• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 23:25
CEST 05:25
KST 12:25
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
Team TLMC #5: Winners Announced!0[ASL20] Ro8 Preview Pt2: Holding On9Maestros of the Game: Live Finals Preview (RO4)5TL.net Map Contest #21 - Finalists4Team TLMC #5: Vote to Decide Ladder Maps!0
Community News
5.0.15 Patch Balance Hotfix (2025-10-8)18Weekly Cups (Sept 29-Oct 5): MaxPax triples up3PartinG joins SteamerZone, returns to SC2 competition245.0.15 Balance Patch Notes (Live version)118$2,500 WardiTV TL Map Contest Tournament 152
StarCraft 2
General
5.0.15 Patch Balance Hotfix (2025-10-8) 5.0.15 Balance Patch Notes (Live version) The New Patch Killed Mech! Weekly Cups (Sept 29-Oct 5): MaxPax triples up Team TLMC #5: Winners Announced!
Tourneys
Tenacious Turtle Tussle Sea Duckling Open (Global, Bronze-Diamond) $2,500 WardiTV TL Map Contest Tournament 15 RSL Offline Finals Dates + Ticket Sales! Stellar Fest
Strategy
Custom Maps
External Content
Mutation # 494 Unstable Environment Mutation # 493 Quick Killers Mutation # 492 Get Out More Mutation # 491 Night Drive
Brood War
General
Question regarding recent ASL Bisu vs Larva game [BSL21] - How to Qualify to Each League ? ASL20 General Discussion BW General Discussion RepMastered™: replay sharing and analyzer site
Tourneys
[Megathread] Daily Proleagues [ASL20] Ro8 Day 4 Small VOD Thread 2.0 [ASL20] Ro8 Day 3
Strategy
Current Meta TvZ Theorycraft - Improving on State of the Art Proposed Glossary of Strategic Uncertainty 9 hatch vs 10 hatch vs 12 hatch
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread ZeroSpace Megathread Dawn of War IV Path of Exile
Dota 2
Official 'what is Dota anymore' discussion LiquidDota to reintegrate into TL.net
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
SPIRED by.ASL Mafia {211640} TL Mafia Community Thread
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread UK Politics Mega-thread The Games Industry And ATVI
Fan Clubs
The herO Fan Club! The Happy Fan Club!
Media & Entertainment
Movie Discussion! Anime Discussion Thread [Manga] One Piece
Sports
2024 - 2026 Football Thread Formula 1 Discussion MLB/Baseball 2023 NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
Recent Gifted Posts The Automated Ban List BarCraft in Tokyo Japan for ASL Season5 Final
Blogs
What your "aura" says about…
Peanutsc
Mental Health In Esports: Wo…
TrAiDoS
Try to reverse getting fired …
Garnet
[ASL20] Players bad at pi…
pullarius1
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1217 users

Logic/Programming Interview Questions

Blogs > Oracle
Post a Reply
Normal
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-26 19:53:15
June 24 2011 21:43 GMT
#1
So we all know all the big names ask hard questions on interviews so I've made it a hobby to look for the challenging ones and time myself solving them.

Most of the ones on the internet are fairly well known so I'm not going to bother posting any of those. In fact, I'll post precisely those which I found the most challenging, and feel free to share yours.

After each question I will attempt to provide an origination for the question. (I have not interviewed at all these companies, but friends have)

In order of increasing difficulty,

1) Implement an integer Median Priority queue. That is, Peek has O(1) and Insert/Delete Median has O(logn). (Data structures course).

+ Show Spoiler [Hint] +
Too easy for a hint


+ Show Spoiler [Solved] +
http://www.teamliquid.net/blogs/viewblog.php?topic_id=237090&currentpage=2#26


2) Suppose there is a street-race, with a total of k contestants. You start at intersection A, and finish at intersection C. For safety, you want to plan this so that no two contestants can possibly be on the same road together. (Their routes are unique) There are exactly k unique routes from A to B (by unique I mean no roads in any two routes are the same) and exactly k unique routes from B to C. Describe a method to find k unique A-C routes. (Graph theory course)

+ Show Spoiler [Hint] +
Observe that this scenario can be modeled as a undirected unweighted graph, with intersections being vertices, and roads being edges. You want to k pairwise edge-disjoint paths from A to C. Transitivity of Mengers (edge) theorem


3) In OOP, how would you create/modify a class such that it can ONLY be allocated on the heap. That is, allocation onto the stack will error or fail. (Bloomberg)

+ Show Spoiler [Hint] +
No hint or else this would be too easy


+ Show Spoiler [Solved] +
http://www.teamliquid.net/blogs/viewblog.php?topic_id=237090#11


4) Given an array of size n, implement a function which will find the kth largest element in O(n) time and O(1) space. Be careful to note that elements are not necessarily integers, but have the standard comparison operators (ie <=, <) defined, all of which are transitive. (Data structures course)

+ Show Spoiler [Hint] +
Related to median priority queue


5) Given an integer array of size 2n+1 (odd length), where every element exists in pairs except for one unique element, find the unique element in O(n) time and O(1) space. (Google)

+ Show Spoiler [Hint] +
Associativity, Commutativity


+ Show Spoiler [Solved] +
http://www.teamliquid.net/blogs/viewblog.php?topic_id=237090&currentpage=2#22


6) Find the start of a cycle in a C++ linked list in O( n ) where n is the number of nodes, and space complexity O(1). Elements in the array are not necessarily distinct, so searching for the first recurrence of an element does not work. You do not know n. (IBM)

Example of a cycle in a linked list

+ Show Spoiler [Hint] +
Pointers. Make sure your understanding of them is most up-to-date with recent gcc C++ compilers. More specifically, 0xabf points to the same place as 0xabc.


+ Show Spoiler [Additional Hint] +
We know we can use two pointers, lets label them A and B. A simple algorithm which, in every iteration, increments A = A->Next and B=B->Next->Next (with NULL checkers) will eventually yield A=B if there is a loop or B=NULL if there is no loop. This algorithm is trivial, also known as "The turtle and the hare algorithm." Now, try to do this using only ONE pointer


7) Given a standard 52 card deck, you pull out 4 arbitrary cards. Now, you pull out the next card and memorize it before putting it back in the deck. Describe a method to arrange the first four cards in any order on a table so that someone who knows your system will be able to identify the 5th card you pulled. There is only enough space on the table to arrange the cards vertically, side by side. All four cards must be at the table and cannot be re-ordered once set.

Clarification: You may flip cards upside down, but note that the observer will not be able to see what the upside down cards are.

+ Show Spoiler [Hint] +
In mathematical terms, you are to find an onto mapping M: A -> B where A is {a, b, c, d} (the first four cards you pulled) to B = {all 52 cards} \ A. So |B| = 48. Note that rearranging the cards in any order only leaves 4! = 24 permutations. So M may not be one-to-one.


+ Show Spoiler [Solved] +
http://www.teamliquid.net/forum/viewpost.php?post_id=9964122


Horuku
Profile Blog Joined August 2010
United States405 Posts
Last Edited: 2011-06-24 21:56:02
June 24 2011 21:48 GMT
#2
#1. Never heard of a MEDIAN priority-queue and don't feel like googling the difference between it and a regular priority queue. Otherwise, like you said this is also a relatively easy question. The difficulty could be increased based on the underlying data-structure used for the queue (dynamic array, heap, etc.) Then it just comes down to arranging the data-structure each time an element is inserted based on its priority classification so the higher priority gets popped off first.

#2. This is probably a good one to study. CBA to do it at the moment.

#3. I imagine this is answered by saying have a watcher that triggers if data tries to be put on the stack? Not sure in what context it is being refered to, to be honest. Is it talking about the default operating system stack or a custom user built one in an OO language?

#4. This is way to easy for O(n). Just do a linear search comparing each element to each other and storing the current largest in a variable. A better question would be concerning binary search after you ask them what sort method they would use. And give a dataset size, because some sort methods are crappy for small data sets while others are obviously better.

#5. Again, O(n) is too easy. A linear search and you're good to go.

#6. Not sure about the cycle syntax, but based on the hint and how you should build a linked-list in C++ (where each node connects to another node through a pointer to that node), I'd image it is a simple memory search.

#7. CBA for this one either. I'd say in the interview though that I would google the trick to solving this and then implement that trick with an algorithm to do it :D
d<^^>b
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-24 22:03:31
June 24 2011 21:49 GMT
#3
#1 A median priority queue is a regular priority queue where priority is given to the median element.

#3 Sounds fine but what exactly is the watcher? Youre skipping the essence of the question.

#4 We want kth largest not max

#5 O(1) space so you cant store elements which have occured

#6 Not so simple actually. A cycle is simply whenever node->next points to an element which you have previously traversed.
jdseemoreglass
Profile Blog Joined July 2010
United States3773 Posts
June 24 2011 21:57 GMT
#4
Hmm... I stopped reading at "Transitivity of Mengers (edge) theorem."

It depresses me to read things like this because I plan on learning programming and suddenly I realize how much of my life I have to spend learning this shit just to be on par with an average programmer.

Meh. Maybe I should just figure out a way to take stupid people's money and get rich. Like offering people enlightenment and then charging them for copy-pasted sections of the Tao Te Ching.
"If you want this forum to be full of half-baked philosophy discussions between pompous faggots like yourself forever, stay the course captain vanilla" - FakeSteve[TPR], 2006
Horuku
Profile Blog Joined August 2010
United States405 Posts
June 24 2011 21:57 GMT
#5
On June 25 2011 06:49 Oracle wrote:
Show nested quote +
On June 25 2011 06:48 Horuku wrote:
#4 is way to easy for O(n). Just do a linear search comparing each element to each other and storing the current largest in a variable. A better question would be concerning binary search after you ask them what sort method they would use. And give a dataset size, because some sort methods are crappy for small data sets while others are obviously better.


Sorry, youre right, i forgot to add that you have O( 1 ) space complexity.
but also, your solution finds the largest, not the kth largest.


Well still, for kth largest then you would just sort the array and then choose the element [k-1] lol
d<^^>b
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 24 2011 22:02 GMT
#6
On June 25 2011 06:57 Horuku wrote:
Show nested quote +
On June 25 2011 06:49 Oracle wrote:
On June 25 2011 06:48 Horuku wrote:
#4 is way to easy for O(n). Just do a linear search comparing each element to each other and storing the current largest in a variable. A better question would be concerning binary search after you ask them what sort method they would use. And give a dataset size, because some sort methods are crappy for small data sets while others are obviously better.


Sorry, youre right, i forgot to add that you have O( 1 ) space complexity.
but also, your solution finds the largest, not the kth largest.


Well still, for kth largest then you would just sort the array and then choose the element [k-1] lol


Comparison based sort is lower bound nlogn
Radix/Counting sort are O(k) where k is the largest element in the array. But those work for integers (or some equivalent hashing function). Still if k > n then this doesn't work. In this problem you are not allowed to assume n <= k.
Siniyas
Profile Joined January 2011
Germany66 Posts
Last Edited: 2011-06-24 22:38:10
June 24 2011 22:35 GMT
#7
For the cycle

If the list is n elements long, isnt the n+1 element always the start of the cycle?


For the cards thing.
We could just have an order for the cards,that card a is bigger than b
depending on the value ex. K>Q and also for the suits if cards are double.
We start with cards 1>2>3>4, for the first highest remaining card in the deck.
then change 3 and 4 then go 1 further and change 2 and 4, 3 and 4 and then 3 and 4 again and so on and so on.
Also if we can leave an empty space we get enough permutations, so that we can distinctly map each element.


for 4

We can just copy the array and run through it k times, picking out the biggest element and deleting it from the array.


For 2.

I dont see the difficulty here. First route from A to B goes with first route from B to C or any other as long as we dont use the chosen routes after that.


Let it rip
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-24 22:55:26
June 24 2011 22:46 GMT
#8
On June 25 2011 07:35 Siniyas wrote:
For the cycle

If the list is n elements long, isnt the n+1 element always the start of the cycle?


For the cards thing.
We could just have an order for the cards,that card a is bigger than b
depending on the value ex. K>Q and also for the suits if cards are double.
We start with cards 1>2>3>4, for the first highest remaining card in the deck.
then change 3 and 4 then go 1 further and change 2 and 4, 3 and 4 and then 3 and 4 again and so on and so on.
Also if we can leave an empty space we get enough permutations, so that we can distinctly map each element.


for 4

We can just copy the array and run through it k times, picking out the biggest element and deleting it from the array.


For 2.

I dont see the difficulty here. First route from A to B goes with first route from B to C or any other as long as we dont use the chosen routes after that.





Clarification for the cycle, it doesnt have to loop back to the beginning. The cycle can contain only a subset of the elements. So the first portion doesnt have to be contained in the cycle.

And you do not know the value of 'n', sorry i should have explicitly said that.

#7 You cant re-order the cards multiple times. Pick a configuration, set it on the table, and someone should know which card you are mapping to. Empty spaces aren't allowed, sorry forgot to mention. You must use all 4 cards.

#4 That is O(kn) and not O(n)

#2 What if the routes from B to C are not pairwise edge disjoint from the A to B paths? That is, routes frmo B to C intersect some roads which are part of routes from A to B.
Siniyas
Profile Joined January 2011
Germany66 Posts
June 24 2011 23:01 GMT
#9
On June 25 2011 07:46 Oracle wrote:
Show nested quote +
On June 25 2011 07:35 Siniyas wrote:
For the cycle

If the list is n elements long, isnt the n+1 element always the start of the cycle?


For the cards thing.
We could just have an order for the cards,that card a is bigger than b
depending on the value ex. K>Q and also for the suits if cards are double.
We start with cards 1>2>3>4, for the first highest remaining card in the deck.
then change 3 and 4 then go 1 further and change 2 and 4, 3 and 4 and then 3 and 4 again and so on and so on.
Also if we can leave an empty space we get enough permutations, so that we can distinctly map each element.


for 4

We can just copy the array and run through it k times, picking out the biggest element and deleting it from the array.


For 2.

I dont see the difficulty here. First route from A to B goes with first route from B to C or any other as long as we dont use the chosen routes after that.





For the cycle, it doesnt have to loop back to the beginning. The cycle can contain only a subset of the elements. So the first portion doesnt have to be contained in the cycle.

#7 You cant re-order the cards multiple times. Pick a configuration, set it on the table, and someone should know which card you are mapping to.

#4 That is O(kn) and not O(n)

#2 What if the routes from B to C are not pairwise edge disjoint from the A to B paths? That is, routes frmo B to C intersect some roads which are part of routes from A to B.


It doesnt matter if the cycle loops back to the beginning or any other element.
But to loop back we need to have gone through all n elements of the list once.
Example.
A->B->C->D->B
4 elements 5 element is the start of the cycle.

7
Dont understand your point exactly. Do we need to to pick a fixed ordering for the 4 cards based on certain characteristics that never change?
Doesnt really make sense to me. If we cant change the order of the cards in accordance to the 5 card that we drew, than it would be totally random. Unless the scheme that the 4 cards are ordered buy have conditions in it that pertain to the 5 card. Is that what you mean?

4
Okay usually constants are not factored into O Notation, but if you want it exactly n or less, then i will think about it again.

2
If thats the case, is there even a garantuee that we can find k A to C paths that dont cross?

Let it rip
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-24 23:17:15
June 24 2011 23:07 GMT
#10
On June 25 2011 08:01 Siniyas wrote:
Show nested quote +
On June 25 2011 07:46 Oracle wrote:
On June 25 2011 07:35 Siniyas wrote:
For the cycle

If the list is n elements long, isnt the n+1 element always the start of the cycle?


For the cards thing.
We could just have an order for the cards,that card a is bigger than b
depending on the value ex. K>Q and also for the suits if cards are double.
We start with cards 1>2>3>4, for the first highest remaining card in the deck.
then change 3 and 4 then go 1 further and change 2 and 4, 3 and 4 and then 3 and 4 again and so on and so on.
Also if we can leave an empty space we get enough permutations, so that we can distinctly map each element.


for 4

We can just copy the array and run through it k times, picking out the biggest element and deleting it from the array.


For 2.

I dont see the difficulty here. First route from A to B goes with first route from B to C or any other as long as we dont use the chosen routes after that.





For the cycle, it doesnt have to loop back to the beginning. The cycle can contain only a subset of the elements. So the first portion doesnt have to be contained in the cycle.

#7 You cant re-order the cards multiple times. Pick a configuration, set it on the table, and someone should know which card you are mapping to.

#4 That is O(kn) and not O(n)

#2 What if the routes from B to C are not pairwise edge disjoint from the A to B paths? That is, routes frmo B to C intersect some roads which are part of routes from A to B.


It doesnt matter if the cycle loops back to the beginning or any other element.
But to loop back we need to have gone through all n elements of the list once.
Example.
A->B->C->D->B
4 elements 5 element is the start of the cycle.

7
Dont understand your point exactly. Do we need to to pick a fixed ordering for the 4 cards based on certain characteristics that never change?
Doesnt really make sense to me. If we cant change the order of the cards in accordance to the 5 card that we drew, than it would be totally random. Unless the scheme that the 4 cards are ordered buy have conditions in it that pertain to the 5 card. Is that what you mean?

4
Okay usually constants are not factored into O Notation, but if you want it exactly n or less, then i will think about it again.

2
If thats the case, is there even a garantuee that we can find k A to C paths that dont cross?



I misunderstood some of your points so I edited my explanation, see above.

#7 You can assign a "value" to each of the four cards you drew. (ie a=1, b=2, c=3, d=4) But your scheme doesn't work if we do not allow the empty space. (Its close though, i definitely tried that) The fifth card (and also first four) are completely arbitrary and unrelated.

#4 k is not a constant (it is in terms of n). k is chosen by the algorithm. Of course k<=n, but k changes based on what value we choose. For example, if we want k= n-1, then we have to do n*(n-1) loops! thats definitely not linear.

#2 There sure is (Q3)
HowitZer
Profile Joined February 2003
United States1610 Posts
June 24 2011 23:22 GMT
#11
3.)

class HeapOnly
{
private:
HeapOnly(){}

public:
static HeapOnly* Allocate() { return new HeapOnly(); }
};

int main()
{
HeapOnly p; // error

HeapOnly * p = HeapOnly::Allocate(); // ok

return 0;
}
Human teleportation, molecular decimation, breakdown and reformation is inherently purging. It makes a man acute.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 24 2011 23:26 GMT
#12
On June 25 2011 08:22 HowitZer wrote:
3.)

class HeapOnly
{
private:
HeapOnly(){}

public:
static HeapOnly* Allocate() { return new HeapOnly(); }
};

int main()
{
HeapOnly p; // error

HeapOnly * p = HeapOnly::Allocate(); // ok

return 0;
}


That works. Of course there are many ways to implement it, but the gist is to make the constructor private (hence no stack allocation) and a public function (or friend to constructor or w.e) which returns a heap pointer.
Siniyas
Profile Joined January 2011
Germany66 Posts
Last Edited: 2011-06-24 23:30:45
June 24 2011 23:29 GMT
#13
Oh for 3. Only make a private constructor and have a static method that gives back a pointer to an object on the heap?

Edit: Meh. Just saw it was already posted.
Let it rip
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 24 2011 23:34 GMT
#14
Ive added an additional hint to Q6
aphorism
Profile Joined February 2011
United States226 Posts
Last Edited: 2011-06-24 23:50:13
June 24 2011 23:47 GMT
#15
On June 25 2011 06:43 Oracle wrote:
7) Given a standard 52 card deck, you pull out 4 arbitrary cards. Now, you pull out the next card and memorize it before putting it back in the deck. Describe a method to arrange the first four cards in any order on a table so that someone who knows your system will be able to identify the 5th card you pulled. There is only enough space on the table to arrange the cards vertically, side by side. All four cards must be at the table and cannot be re-ordered at any time.

+ Show Spoiler [Hint] +
In mathematical terms, you are to find an onto mapping M: A -> B where A is {a, b, c, d} (the first four cards you pulled) to B = {all 52 cards} \ A. So |B| = 48. Note that rearranging the cards in any order only leaves 4! = 24 permutations. So M may not be one-to-one.


So for this question, is our friend only allowed to observe the cards? I have ideas for an encoding that places cards face up/down, but I'm not sure if our observer is allowed to flip them face-up or not.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-24 23:57:27
June 24 2011 23:54 GMT
#16
Yes the friend is only allowed to observe the cards. Face up/face down is fine, but note that your friend cannot know which card is which if there is more than one upside down card. So essentially, just think you can only label the face side with an 'a', 'b', 'c', or 'd'.

You're on the right track though. This isnt really an interview question, but a question a friend gave to me at lunch once. He said he didnt know the solution, and he heard it months back.

I encourage you to really think about it and then post, to ensure youre not missing any cases.
aphorism
Profile Joined February 2011
United States226 Posts
Last Edited: 2011-06-25 00:25:47
June 25 2011 00:24 GMT
#17
Here's a sketch of a solution to 7, I hope it works...

First, let's define an 'order' for cards of each color: Hearts < Diamonds < Spades < Clubs. This plus numerical order gives a mapping of cards of each color to the integers 1-26 by value, and it also gives us a strictly less-than operator for cards, so the lowest card can be called A, the next lowest can be called B, etc.

In your 4 cards, you will have either a majority color, or 2 red & 2 black cards. In this case, you will leave all cards face up, and use the 24 permutations of the face-up cards to correspond to 1-24, which correspond to the (at most 24) cards of the majority color (use red as the majority in the case of a 2/2 split). Our friend knows which cards in the majority color to leave out of the sorted list (because they're face-up on the table), so he can just map permutations (by lexicographic order or something) to the correct card.

For the remaining 24-26 cards, we turn some cards face-down (at most 2, so we never turn down a card in the minority color), and map the permutations of the face-up cards to cards in the minority color as follows (F = face-down card):

F A B C = 6 permutations of A, B, and C
A F B C = 6 more.
A B F C = 6 more
A B C F = 6 more
F F A B = 2 more, for 26 total permutations.

We turn at most 2 face-down, so we always leave our minority color cards face-up, and again our friend knows which ones to leave out of the sorted list.

Here's an example, because it's kinda sketchy just explaining it...


Let's say I pull the following 4 cards:
Ace of Hearts
Seven of Spades
Ten of Spades
Six of Diamonds.

In order, they are
Ace of Hearts = A
Six of Diamonds = B
Seven of Spades = C
Ten of Spades = D

Let's say the 5th card is the King of Spades.

It's in our minority color, and it's the 11th card out of 24, because we don't count the seven/ten of spades.

We thus give it the following mapping, where F is D, face-down.:
C F A B.

Our friend sees the 11th permutation for the minority color, and also sees the seven/ten of spades, so he knows to skip those. The 11th smallest black card, not counting the seven/ten of spades, is the King of Spades.


Let's say the fifth card is the Ace of Diamonds instead. Not counting the 4 cards we have on the table, it's the 13th smallest red card. We thus put down the 13th red permutation, CABD (all face up). Our friend sees the 13th permutation, and all cards face up, so he counts up to the 13th smallest red card, skipping the Ace of Hearts, because it's already on the table. This gives the Ace of Diamonds.


That post was far longer than I expected it would be, so much for a solution sketch...
Anyway, feel free to point out any terrible flaws in my system, I think works okay.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 25 2011 00:32 GMT
#18
I didnt read the example, and as soon as you mentioned "majority element" I knew what was going to come next. Looks right, and its completely different from my solution.

Here's mine:

We think of a card as a {0,1}-bit. A card represents 0 if it is face up and 1 if it is face-down.

So then we get a binary string of length four. So we can represent 2^4 - 1 = 15 possibly values with a string of 4 bits. But there are really only 13 distinct values. Hence we will never get the string 1111. So we will always have a face-up card.

So we assign 'a' = Hearts, 'b' = Diamonds, 'c' = Spades, 'd' = Clubs. The card which is face-up and leftmost denotes the suit.


So for example A F F F can be read as 0111 = 7. The A says its the 7 of Hearts.
FBDF can be read as 1001 = 9. The B says its the 9 of Diamonds.
ptell
Profile Joined October 2009
United States103 Posts
June 25 2011 00:33 GMT
#19
Solution to 7) :

First note that every card can be mapped to a number in the range of 1 to 52. Using the convention in bridge, the map is (from smallest to highest):

01 <--> Ace of Spades
02 <--> Ace of Hearts
03 <--> Ace of Diamonds
04 <--> Ace of Clubs
05 <--> Deuce of Spades
.
.
.
51 <--> King of Diamonds
52 <--> King of Clubs

Then the first four cards corresponds to a set of four number, e.g. {04, 13, 17, 31}. Then reindex the remaining 48 cards so that it starts from 01 and ends at 48.

Now there are 4! = 24 ways to arrange four distinct cards so we can map to indices 01 to 24. Next to represent the indices 25 to 48, flip the card with the smallest value.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 25 2011 00:45 GMT
#20
On June 25 2011 09:33 ptell wrote:
Solution to 7) :

First note that every card can be mapped to a number in the range of 1 to 52. Using the convention in bridge, the map is (from smallest to highest):

01 <--> Ace of Spades
02 <--> Ace of Hearts
03 <--> Ace of Diamonds
04 <--> Ace of Clubs
05 <--> Deuce of Spades
.
.
.
51 <--> King of Diamonds
52 <--> King of Clubs

Then the first four cards corresponds to a set of four number, e.g. {04, 13, 17, 31}. Then reindex the remaining 48 cards so that it starts from 01 and ends at 48.

Now there are 4! = 24 ways to arrange four distinct cards so we can map to indices 01 to 24. Next to represent the indices 25 to 48, flip the card with the smallest value.

Yup, can't find a problem with it. I came across this solution too but didn't like it because most likely the observer would need a coding grammar to lookup which permutation refers to which.
athief
Profile Joined November 2010
United States85 Posts
Last Edited: 2011-06-25 02:05:30
June 25 2011 01:37 GMT
#21
On June 25 2011 09:45 Oracle wrote:
Show nested quote +
On June 25 2011 09:33 ptell wrote:
Solution to 7) :

First note that every card can be mapped to a number in the range of 1 to 52. Using the convention in bridge, the map is (from smallest to highest):

01 <--> Ace of Spades
02 <--> Ace of Hearts
03 <--> Ace of Diamonds
04 <--> Ace of Clubs
05 <--> Deuce of Spades
.
.
.
51 <--> King of Diamonds
52 <--> King of Clubs

Then the first four cards corresponds to a set of four number, e.g. {04, 13, 17, 31}. Then reindex the remaining 48 cards so that it starts from 01 and ends at 48.

Now there are 4! = 24 ways to arrange four distinct cards so we can map to indices 01 to 24. Next to represent the indices 25 to 48, flip the card with the smallest value.

Yup, can't find a problem with it. I came across this solution too but didn't like it because most likely the observer would need a coding grammar to lookup which permutation refers to which.




Ok, non math person here, but I think the posted #7 solution relies too heavily on knowledge of Bridge convention. Mine (if I even understand your post correctly) hinges on knowledge of the alphabet, but I'd wager that's a far greater set of people.
[image loading]

I haven't got the best draw of four determining cards here, but the fifth card is + Show Spoiler +
the Six of Spades
.

Here's how you can tell.
[spoiler]Two cards are face-up: therefore their faces must contain relevant information. This information is limited to value and suit.

Two are face-down. One of these is oriented counter to everything else: therefore their faces do not contain useful information and are being used to indicate something else. Let's take the most-different card first, in the top-left.

The array of all possible cards (it's invisible, and the table is clear, we're not crazy) ends at the corner of this card. It's differing orientation, face-down-ness, and location outside of the array let us mark it as an origin point. Conversely, we could mark it as a card that has nothing entirely in common with the others- the point is: it's meant to indicate that the locations of the other cards fit into an array. Hopefully either this card or the particular positioning of the other cards will get that to the observer, because it's essential.

The other face-down card is in the array, and it is showing no value (in that it's face-down). It indicates that this is the particular droid we're looking for- it marks a location in the array (which would be filled by our fifth card).

The array itself is a bit more difficult to outline (especially given these cards- ideally we'd have no two cards in the same suit). The information/value contained on the face of the cards is limited to suit and number. In this array, suit is indicated by vertical position, and number by horizontal position. I bold this because it's pretty much the whole solution. In our example we don't get to see the full suit arrangement, which invites the observer to err in determining the fifth card based on it's being the sole member of the set of it's particular suit [Edit: nevermind, the picture is of my second set of cards, sorry. We still don't see the whole suit arrangement, but with anything less than 40 cards that's not a guarantee anyway.].

Hence my alphabet comment: I've elected to order the suits in alphabetical order by name in English. The orthographs for the suit names match those used on the face cards (not that there necessarily are any, but...), and the simplest organization for these letters is the alphabet. Thus, vertically, our array is Clubs>Diamonds>Hearts>Spades.

Summary: the face-up and sideways face-down card indicate the arrangement, and the face-down card indicates the particular location we want to communicate. No math needed, only basic card skills. Sorry for the terrible picture.

EDIT: MOTHER %^&#@* I can't read. >_<
There is only enough space on the table to arrange the cards vertically, side by side. All four cards must be at the table and cannot be re-ordered once set.
"No man yields who flies on my ship" Have [i]you[/i] scanned the island?
DeLoAdEr
Profile Blog Joined July 2003
Japan527 Posts
June 25 2011 11:45 GMT
#22
5)

Let a_1, a_2, b_1, b_2, c_1, c_2, ... be the pairs and x the unique element.

^ = bitwise XOR:
(a_1 ^ a_2) ^ (b_1 ^ b_2) ^ (c_1 ^ c_2) ^ x = x because a ^ a = 0 and 0 ^ a = a. Since ^ is commutative and associative the order doesnt matter and to get the unique element we can just run in a loop over all elements and XOR them. Should work =)
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 25 2011 12:57 GMT
#23
On June 25 2011 20:45 DeLoAdEr wrote:
5)

Let a_1, a_2, b_1, b_2, c_1, c_2, ... be the pairs and x the unique element.

^ = bitwise XOR:
(a_1 ^ a_2) ^ (b_1 ^ b_2) ^ (c_1 ^ c_2) ^ x = x because a ^ a = 0 and 0 ^ a = a. Since ^ is commutative and associative the order doesnt matter and to get the unique element we can just run in a loop over all elements and XOR them. Should work =)


That's exactly correct, good job
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-25 15:24:02
June 25 2011 15:22 GMT
#24
1) I don't think this is possible. List and array-backed queues have linear time inserts, and heap-backed queues have logarithmic extracts. If we don't need constant time extracts, heaps would work fine.

4) Median of medians algorithm. God I love this one.
Compilers are like boyfriends, you miss a period and they go crazy on you.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 25 2011 16:04 GMT
#25
On June 26 2011 00:22 BottleAbuser wrote:
1) I don't think this is possible. List and array-backed queues have linear time inserts, and heap-backed queues have logarithmic extracts. If we don't need constant time extracts, heaps would work fine.

4) Median of medians algorithm. God I love this one.


#1 Oops, youre right I mistyped the question. Should be possible now.

#4 Median of Medians can be generalized to k-select, but the tricky part is how
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-25 16:15:09
June 25 2011 16:14 GMT
#26
6) Initialize a counter k as 1, and save your current location as x. Go to the next node k times and check if its the same as your current location. Until it is, continue to save your current location as x, and increment k, and check if k hops ahead is the same as the current location.

This is O(n) because if we enter a loop, it is at most size of n. When k reaches a multiple of n, we are done, so it is O(n).

1) A min and a max heap of equal sizes. Ta-da.
Compilers are like boyfriends, you miss a period and they go crazy on you.
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
June 25 2011 16:39 GMT
#27
Median of medians: group the elements into groups of 5, and sort the groups of 5 (n/5*5log5)=O(n). Take the median of these recursively (O(n), ok, that's cheating, because I don't remember and can't understand Wikipedia's proof... should do that ... later...).

Now you can split the array into an upper and lower half by comparison with our pivot. If the upper half's size is k-1, then we can return the median. If k>size/2-1, then k-=size/2+1, and we do it again for the lower half. If k<size/2-1, then we do it again for the upper half. This recursion is also O(n), somehow.
Compilers are like boyfriends, you miss a period and they go crazy on you.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 25 2011 16:41 GMT
#28
On June 26 2011 01:14 BottleAbuser wrote:
6) Initialize a counter k as 1, and save your current location as x. Go to the next node k times and check if its the same as your current location. Until it is, continue to save your current location as x, and increment k, and check if k hops ahead is the same as the current location.

This is O(n) because if we enter a loop, it is at most size of n. When k reaches a multiple of n, we are done, so it is O(n).

1) A min and a max heap of equal sizes. Ta-da.


#1 correct. Theres also another method using AVL trees and keeping the median at the root.

#6 Im actually not sure how when k reaches a multiple of n we are done. Is it not when k reaches the length of the cycle we are done? My understanding of that algorithm is O(pn) where p is the size of the cycle. Either way, try to find precisely where the cycle begins (i know the hint algorithm I gave doesnt do this, but the question asks for this)
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-25 16:58:12
June 25 2011 16:49 GMT
#29
Yar, I forgot about that requirement and fixated on the hint algorithm. Shit me. And you're right, it's O(pn) or O(n^2) if the whole damn thing is a cycle. I have to go back to school.

I can still fix the algorithm I gave (O(n^2) still); you backtrack by k-1 steps, see if k steps ahead is the same as that node, and continue (backtrack by k-2, k-3, and so on and see if k steps ahead of that node is the same) until you reach one that isn't.

But then again, that only works for doubly linked lists. Grr.
Compilers are like boyfriends, you miss a period and they go crazy on you.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-25 17:01:21
June 25 2011 16:57 GMT
#30
On June 26 2011 01:39 BottleAbuser wrote:
Median of medians: group the elements into groups of 5, and sort the groups of 5 (n/5*5log5)=O(n). Take the median of these recursively (O(n), ok, that's cheating, because I don't remember and can't understand Wikipedia's proof... should do that ... later...).

Now you can split the array into an upper and lower half by comparison with our pivot. If the upper half's size is k-1, then we can return the median. If k>size/2-1, then k-=size/2+1, and we do it again for the lower half. If k<size/2-1, then we do it again for the upper half. This recursion is also O(n), somehow.


Heh, im not entirely convinced


On June 26 2011 01:49 BottleAbuser wrote:
Yar, I forgot about that requirement and fixated on the hint algorithm. Shit me. And you're right, it's O(pn) or O(n^2) if the whole damn thing is a cycle. I have to go back to school.

I can still fix the algorithm I gave (O(n^2) still); you backtrack by k-1 steps, see if k steps ahead is the same as that node, and continue (backtrack by k-2, k-3, and so on and see if k steps ahead of that node is the same) until you reach one that isn't.

But then again, that only works for doubly linked lists. Grr.


Dont worry, these are meant to be challenging... Really focus on the first hint, the solution is actually very very simple to implement, and not even that conceptually complex.

Also, this solution assumes that the start of the cycle has its backward pointer to the linear list, and not to the cycle
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-25 17:08:56
June 25 2011 17:07 GMT
#31
If it is a doubly linked list, then my solution still works in O(n^2), because you're guaranteed to find the place where you jumped into the cycle. From there, you have at most k-1 nodes in between a definite non-cycle node and a definite cycle node, and you can check each one to see which is the first. I'll give these another crack tomorrow, it's drinkin time. And what the heck is 0xabc and 0xabf? Those are different values, unless C++ has some really weird quirks...
Compilers are like boyfriends, you miss a period and they go crazy on you.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-25 17:24:36
June 25 2011 17:15 GMT
#32
On June 26 2011 02:07 BottleAbuser wrote:
If it is a doubly linked list, then my solution still works in O(n^2), because you're guaranteed to find the place where you jumped into the cycle. From there, you have at most k-1 nodes in between a definite non-cycle node and a definite cycle node, and you can check each one to see which is the first. I'll give these another crack tomorrow, it's drinkin time.

And what the heck is 0xabc and 0xabf? Those are different values, unless C++ has some really weird quirks...


Yes but what if the backwards pointer points to the previous element of the cycle instead of the linear list? Ie A<->B->C<->D<->E<->C (Notice that C doesnt point back to B, but instead to E)

To answer the second part,

they are hexidecimal values, so the address at 0xabf is exactly the same as the address at 0xabc according to the C++ interpreter.

http://www.wolframalpha.com/input/?i=0xabf

http://www.wolframalpha.com/input/?i=0xabc

(Really because C++ assumes every address must be a multiple of four, and hence it takes the lowest multiple of four in any address)

Also, it might be helpful to forget what you know about pointer arithmetic
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
June 26 2011 08:42 GMT
#33
If the back pointer is different that makes it too easy so ill discount comparing self and self.next.previous.

2) Give each edge unity weight and run a shortest path k times, removing traversed edges as you go. This works because if we find that start and end disconnect after x iterations, we can remove x edges from G to cut it by umm really carefully selecting an edge from each found parh and Mengers says that thats that. Hah.
Compilers are like boyfriends, you miss a period and they go crazy on you.
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-26 14:16:41
June 26 2011 14:07 GMT
#34
Proof of median of medians linear runtime

Finding the median of medians takes a recursive call on the sets of 5, or T(n/5).

Partitioning into "this group of 5's median is less than/greater than median of set" takes linear time or O(n).

We are guaranteed that the elements of each goup of 5 in the groups whose median is less than set median are also less than the set median (transitivity of less than operator). Therefore, at least 3/5 of 1/2 of the set is less than the set median, and no more than 1-3/10. In the wost case, T(n*7/10).

Now, T(n*7/10)+T(n/5) <= T(n*9/10). Thus, worst case is T(n) <= O(n) + O(n*9/10) + O(n*(9/10)^2 + ...) = O(n) * (1 + 9/10 + (9/10)^2 + ...) which is O(n)*c for some constant c. Power series of 9/10^n for n in Z converges on 10, so c is truly asymptotically constant.
Compilers are like boyfriends, you miss a period and they go crazy on you.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 26 2011 14:59 GMT
#35
On June 26 2011 23:07 BottleAbuser wrote:
Proof of median of medians linear runtime

Finding the median of medians takes a recursive call on the sets of 5, or T(n/5).

Partitioning into "this group of 5's median is less than/greater than median of set" takes linear time or O(n).

We are guaranteed that the elements of each goup of 5 in the groups whose median is less than set median are also less than the set median (transitivity of less than operator). Therefore, at least 3/5 of 1/2 of the set is less than the set median, and no more than 1-3/10. In the wost case, T(n*7/10).

Now, T(n*7/10)+T(n/5) <= T(n*9/10). Thus, worst case is T(n) <= O(n) + O(n*9/10) + O(n*(9/10)^2 + ...) = O(n) * (1 + 9/10 + (9/10)^2 + ...) which is O(n)*c for some constant c. Power series of 9/10^n for n in Z converges on 10, so c is truly asymptotically constant.


Ok so now you have the median element, and id assume you want to partition the array around it, which clearly takes O(n). Now what? Recursively pivoting the section with k in it isn't O(n), in fact it is o(nlogn) (think binary search/quicksort)

For #2,
Using Prims algorithm or Djistkras algorithm to find an AC-path may work, and removing the path each iteration, but I am not so sure how we are guaranteed to find k of them, since a shortest path may intersect an edge of another path, and removing it may reduce remaining number of AC paths.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 26 2011 19:53 GMT
#36
On June 25 2011 09:33 ptell wrote:
Solution to 7) :

First note that every card can be mapped to a number in the range of 1 to 52. Using the convention in bridge, the map is (from smallest to highest):

01 <--> Ace of Spades
02 <--> Ace of Hearts
03 <--> Ace of Diamonds
04 <--> Ace of Clubs
05 <--> Deuce of Spades
.
.
.
51 <--> King of Diamonds
52 <--> King of Clubs

Then the first four cards corresponds to a set of four number, e.g. {04, 13, 17, 31}. Then reindex the remaining 48 cards so that it starts from 01 and ends at 48.

Now there are 4! = 24 ways to arrange four distinct cards so we can map to indices 01 to 24. Next to represent the indices 25 to 48, flip the card with the smallest value.


I've given this a little more thought and actually came to a flaw; how would the observer know how to do an index shift if the final card is upside down?
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
June 27 2011 03:18 GMT
#37
The recursive calls sum to O(n). If we're generous and say that each call cuts the size in half, then we take O(current size) time for each recursion. So we get T = n*(1 + 1/2 + 1/4 + 1/8 + 1/16 + ...) = 2n. However, even if we're not generous our power series is of 9/10 instead of the much nicer 1/2, but it still converges on 10n, instead of nlogn.

Put another way, the recursion stack depth is indeed dependent on n, ie it's log(n). However, the sum of the lengths that we are actually looking at is linear to n.
Compilers are like boyfriends, you miss a period and they go crazy on you.
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2011-06-27 08:28:08
June 27 2011 07:57 GMT
#38
1) Implement an integer Median Priority queue. That is, Peek has O(1) and Insert/Delete Median has O(logn). (Data structures course).

I vaguely remember something from Wikipedia about a heap that alternates between min and max heap at every level that has the desirable properties.

2) Suppose there is a street-race, with a total of k contestants. You start at intersection A, and finish at intersection C. For safety, you want to plan this so that no two contestants can possibly be on the same road together. (Their routes are unique) There are exactly k unique routes from A to B (by unique I mean no roads in any two routes are the same) and exactly k unique routes from B to C. Describe a method to find k unique A-C routes. (Graph theory course)

I think I'm missing something here.

3) In OOP, how would you create/modify a class such that it can ONLY be allocated on the heap. That is, allocation onto the stack will error or fail. (Bloomberg)

Private constructor and a named constructor idiom is the classic way to do it, but a nicer way to do it is to use a private destructor (or a protected one if you still want inheritance), and explicitly deleting via the base class:

class Base
{
public:
explicit Base () {}
virtual ~Base () {}
};

class Derived :
public Base
{
public:
explicit Derived () {}
protected:
virtual ~Derived () {}
};

int main (int argc, char* argv[])
{
// Derived x; // fails
Base* base = new Derived();
delete base;
Derived* derived = new Derived();
delete dynamic_cast<Base*>(derived);
}


Edit: This is possible as well:


class Test
{
public:
explicit Test () {}
void destroy ()
{
delete this;
}
protected:
virtual ~Test () {}
};

int main (int argc, char* argv[])
{
Test* test = new Test();
test->destroy();
}


There is a related concept I call pseudo abstract classes, where the base class has protected constructors and destructors to prevent instantiation, and you can only create objects of the derived class.

4) Given an array of size n, implement a function which will find the kth largest element in O(n) time and O(1) space. Be careful to note that elements are not necessarily integers, but have the standard comparison operators (ie <=, <) defined, all of which are transitive. (Data structures course)

Median of medians can find the median in O(n) time, you can recurse on the left or right half of the vector to find the desired element. Equal elements can mess things up, but you can work around them by wrapping them in an std:: pair, with the second element being an arbitrary ordering of the elements.

5) Given an integer array of size 2n+1 (odd length), where every element exists in pairs except for one unique element, find the unique element in O(n) time and O(1) space. (Google)

Nice, the solution for this one eluded me. Should clarify that the elements in pairs are the same.

6) Find the start of a cycle in a C++ linked list in O( n ) where n is the number of nodes, and space complexity O(1). Elements in the array are not necessarily distinct, so searching for the first recurrence of an element does not work. You do not know n. (IBM)

I've heard this puzzle before. All you have to do is start two search, the first one steps one at a time, the second one steps two at a time. If they ever point to the same element, that element is in the cycle (or is the start of the cycle?). Ah yes, it is in the hints. Well, it is possible with only one pointer if we assume that all pointed objects are aligned, so we can store extra information in the pointers like mark bits, and that these mark bits are unset; we simply walk through the linked list, marking visited pointers until we encounter an already marked pointer.

7) Given a standard 52 card deck, you pull out 4 arbitrary cards. Now, you pull out the next card and memorize it before putting it back in the deck. Describe a method to arrange the first four cards in any order on a table so that someone who knows your system will be able to identify the 5th card you pulled. There is only enough space on the table to arrange the cards vertically, side by side. All four cards must be at the table and cannot be re-ordered once set.

Clarification: You may flip cards upside down, but note that the observer will not be able to see what the upside down cards are.


Well, if you define an (otherwise arbitrary) ordering on the cards, you can convey a lot of information with arranging cards, and flipping some of them upside down:

0 upside down card in 4 choose 0 positions and 4! possible ordering of visible cards = 4 choose 0 * 4! = 24
1 upside down card in 4 choose 1 positions and 3! possible ordering of visible cards = 4 choose 1 * 3! = 4 * 6 = 24
2 upside down card in 4 choose 2 positions and 2! possible ordering of visible cards = 4 choose 2 * 2! = 6 * 2 = 12
3 upside down card in 4 choose 3 positions and 1! possible ordering of visible cards = 4 choose 3 * 1! = 4

24 + 24 + 12 + 4 = 64 possible arrangements, more than enough to identify that 5th card.
http://www.fimfiction.net/user/Treasure_Chest
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-27 10:23:13
June 27 2011 10:16 GMT
#39
Frigo, I don't agree with your solution for 6. If you use 2 pointers, you can know when you're in the loop, but you don't know where the loop starts. If you use a marker on each node, you're using O(n) space, not O(1). The hint actually makes me think this is the answer the OP was looking for, but you have no guarantees about the starting pointer values at all: for any valid address, there are 4 values that will resolve to that address (n, n+1, n+2, n+3), but which one indicates that this was already visited, and what guarantees that this one didn't just start with that value?
Compilers are like boyfriends, you miss a period and they go crazy on you.
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2011-06-27 11:01:23
June 27 2011 10:51 GMT
#40
Well, the space requirement is dubious. Either O(1) if we assume that the unused space is already given, or O(n) if we don't. I don't see how could you use only one pointer without exploiting this. I am sure the OP was thinking about this approach as well, the hint is a giveaway; most C++ compilers align objects and won't return non-aligned address that could screw up the algorithm.

Determining where the loop starts is trivial if you know any multiple of the loop length. This requires an additional counter though.
http://www.fimfiction.net/user/Treasure_Chest
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
June 27 2011 14:05 GMT
#41
Frigo, the O(1) space requirement implies that the additional space we need isn't dependent on how large the input is. If you are using 1 extra bit for every node, that could theoretically be 2^100 more bits. That's why there is a significant difference between in-place and non in-place sorting algorithms: If you have a petabyte of data and a petabyte of storage space, you're not going anywhere without an in-place algorithm.

But given the way the question is worded, we have no guarantee about the current state of the pointers, as an adversary could defeat you every time on the first node.
Compilers are like boyfriends, you miss a period and they go crazy on you.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-27 20:44:45
June 27 2011 20:42 GMT
#42
Sorry I havent checked this in a while, here's some clarifications:

I will post a diagram for Q2 soon

BottleAbuser, your proof of the O(n) running time of k-select is fine with me now

I have a different solution:
You turn the array into a heap and then find the k-th largest. I'll post a detailed solution soon.

For Q6:
You can assume that node->next modulo 4 == 0 for every node in the list. You guys are actually really close to the answer.

Frigo, your answer to Q7 doesn't seem right with me, you can refer to the post I made before regarding a similar method.
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-27 22:42:40
June 27 2011 21:26 GMT
#43
heapify(A)
A: an array

1. n ← size(A) − 1
2. for i ← floor(n/2) to 0 do
3. bubble−up(A, i)

Builds a max-heap in linear-time, given the assumption that the 2i'th index is the left child, and 2i+1'th index is the right child of an element.

Then its a simple o(k) time to find the kth largest
Hamster1800
Profile Blog Joined August 2008
United States175 Posts
June 27 2011 22:02 GMT
#44
Could you elaborate more on how to select once you've heapified the array? I'm not familiar with a linear time method to do k-select in a heap. BottleAbuser's method (recurse on median-of-medians) I believe is the standard method for k-select.
D is for Diamond, E is for Everything Else
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-27 22:37:46
June 27 2011 22:09 GMT
#45
You do sort of a breadth first search on the heap, giving priority to the greatest element and traverse that node. It comes out to O(k)
Hamster1800
Profile Blog Joined August 2008
United States175 Posts
June 27 2011 22:19 GMT
#46
That shouldn't work. The relative size of two nodes says nothing about the relative sizes of their children. For example, just because the top of the (min-)heap is 1 with children 10 and 100, the 20th smallest element might be the 100. It also could be some deep descendent of the 10 or a deep descendent of the 100. I don't understand how you're going to determine which is the case.
D is for Diamond, E is for Everything Else
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-27 22:44:38
June 27 2011 22:22 GMT
#47
A max heap is a left-justified binary tree. The invariant on the tree is that a node's key is strictly greater than or equal to each of its children nodes' key.

We traverse only k-1 edges, and every time we traverse an edge we will effectively be eliminating a greater element than k. But we only traverse the edge with the child with the greatest key.

Hence we place each key in a priority queue, and traverse the greatest key out of all the "active" nodes.

But since we only traverse k-1 edges, we are done at the kth iteration.


In Pseudocode,

activenode <- root
initialize Maxheap Q

for 0 to k-1
put children of activenode into Q
activenode <- get max of Q

return activenode

Actually i guess this is O(klogk) but I believe theres an analysis which shows its within n so i'll think about it for a bit. (Something to do with Q's size being at most n/2 iirc, guess I shouldve done the problems before posting them )

Hamster1800
Profile Blog Joined August 2008
United States175 Posts
Last Edited: 2011-06-27 22:27:47
June 27 2011 22:27 GMT
#48
Let me be more clear: I'm not worried about the runtime of your algorithm. I'm worried about what it is and that it gets the correct answer. If you could explain your k-select method in full and explain how it gets the kth largest element, that would answer my question.
D is for Diamond, E is for Everything Else
Oracle
Profile Blog Joined May 2007
Canada411 Posts
June 27 2011 22:38 GMT
#49
Ive edited my post above to be more clear
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2011-06-28 03:02:28
June 28 2011 02:59 GMT
#50
On June 28 2011 05:42 Oracle wrote:
For Q6:
You can assume that node->next modulo 4 == 0 for every node in the list. You guys are actually really close to the answer.

Well it's settled then. We just need to set a bit in the "next" pointer to mark a node visited. And technically, the algorithm uses only an O(1) space overhead, not O(n), made possible by the special structure of the list.

Frigo, your answer to Q7 doesn't seem right with me, you can refer to the post I made before regarding a similar method.

Well, I have only shown that we convey enough information to tell the 5th card, I left the ordering and indexing of the cards, and the method to calculate the index of the 5th from the possible arrangements, implicit.

Other than that, I forgot the case when all cards are upside down:
0 upside down, 4 visible: 4 choose 0 * 4! = 1 * 24 = 24
1 upside down, 3 visible: 4 choose 1 * 3! = 4 * 6 = 24
2 upside down, 2 visible: 4 choose 2 * 2! = 6 * 2 = 12
3 upside down, 1 visible: 4 choose 3 * 1! = 4 * 1 = 4
4 upside down, 0 visible: 4 choose 4 * 0! = 1 * 1 = 1
65 possible arrangements
http://www.fimfiction.net/user/Treasure_Chest
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-06-28 11:17:25
June 28 2011 11:15 GMT
#51
Well, we can simply increment each traversed node's next pointer to mark it as visited then. If the next node'spointer mod 4 is 1 then that's the start of the loop.

Should read whole thread heh. I meant "what frigo said"
Compilers are like boyfriends, you miss a period and they go crazy on you.
iaretehnoob
Profile Joined June 2004
Sweden741 Posts
June 28 2011 12:15 GMT
#52
On June 25 2011 09:32 Oracle wrote:
Here's mine:

We think of a card as a {0,1}-bit. A card represents 0 if it is face up and 1 if it is face-down.

So then we get a binary string of length four. So we can represent 2^4 - 1 = 15 possibly values with a string of 4 bits. But there are really only 13 distinct values. Hence we will never get the string 1111. So we will always have a face-up card.

So we assign 'a' = Hearts, 'b' = Diamonds, 'c' = Spades, 'd' = Clubs. The card which is face-up and leftmost denotes the suit.


So for example A F F F can be read as 0111 = 7. The A says its the 7 of Hearts.
FBDF can be read as 1001 = 9. The B says its the 9 of Diamonds.

Maybe I'm just misunderstanding your method, but doesn't this assume you actually get at least one other card of the same suit as the fifth card? For example how would you represent the 7 of Hearts if the other 4 cards are black?
Oracle
Profile Blog Joined May 2007
Canada411 Posts
Last Edited: 2011-06-28 15:02:31
June 28 2011 15:01 GMT
#53
On June 28 2011 21:15 iaretehnoob wrote:
Show nested quote +
On June 25 2011 09:32 Oracle wrote:
Here's mine:

We think of a card as a {0,1}-bit. A card represents 0 if it is face up and 1 if it is face-down.

So then we get a binary string of length four. So we can represent 2^4 - 1 = 15 possibly values with a string of 4 bits. But there are really only 13 distinct values. Hence we will never get the string 1111. So we will always have a face-up card.

So we assign 'a' = Hearts, 'b' = Diamonds, 'c' = Spades, 'd' = Clubs. The card which is face-up and leftmost denotes the suit.


So for example A F F F can be read as 0111 = 7. The A says its the 7 of Hearts.
FBDF can be read as 1001 = 9. The B says its the 9 of Diamonds.

Maybe I'm just misunderstanding your method, but doesn't this assume you actually get at least one other card of the same suit as the fifth card? For example how would you represent the 7 of Hearts if the other 4 cards are black?

The 1st card I pulled out is mapped to hearts, regardless if it is a black-suited card. So we map the ordering not the suit.


On June 28 2011 20:15 BottleAbuser wrote:
Well, we can simply increment each traversed node's next pointer to mark it as visited then. If the next node'spointer mod 4 is 1 then that's the start of the loop.

Should read whole thread heh. I meant "what frigo said"



Right, I love this one
Normal
Please log in or register to reply.
Live Events Refresh
Next event in 6h 35m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Nathanias 162
StarCraft: Brood War
Noble 76
Sharp 36
KwarK 13
Icarus 12
Dota 2
monkeys_forever476
LuMiX1
Counter-Strike
Stewie2K356
Other Games
summit1g9629
shahzam840
JimRising 737
C9.Mang0720
Maynarde180
ViBE172
Organizations
Other Games
gamesdonequick1081
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Doublelift4472
• Lourlo584
• Rush458
• Stunt183
Upcoming Events
The PondCast
6h 35m
Map Test Tournament
7h 35m
OSC
12h 35m
SKillous vs Krystianer
GgMaChine vs Demi
ArT vs Creator
INexorable vs TBD
ReBellioN vs TriGGeR
UedSoldier vs Iba
sOs vs Moja
Map Test Tournament
1d 7h
OSC
1d 9h
Korean StarCraft League
1d 23h
CranKy Ducklings
2 days
Map Test Tournament
2 days
OSC
2 days
[BSL 2025] Weekly
2 days
[ Show More ]
Safe House 2
2 days
Sparkling Tuna Cup
3 days
Map Test Tournament
3 days
OSC
3 days
IPSL
3 days
Bonyth vs Art_Of_Turtle
Razz vs rasowy
Liquipedia Results

Completed

Acropolis #4 - TS2
Maestros of the Game
HCC Europe

Ongoing

BSL 21 Points
ASL Season 20
CSL 2025 AUTUMN (S18)
C-Race Season 1
IPSL Winter 2025-26
WardiTV TLMC #15
EC S1
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025

Upcoming

SC4ALL: Brood War
BSL Season 21
BSL 21 Team A
RSL Offline Finals
RSL Revival: Season 3
Stellar Fest
SC4ALL: StarCraft II
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.