Arrange the shuffled cards
1 Answer
Arrange the shuffled cards
| Flag | PURGE
You have a pack of cards. Each one is a plain card with a number on it. They are all shuffled. You are provided with an algorithm move(int cardNo). This method will pick the card (you passed as param) and put it at the top of all cards. i.e, push back all cards one step down and make your card at the top. Write an algorithm to sort all the cards so that No 1 is at the top and say No.52 is at the bottom. Your algorithm should order it in minimum number of moves. Use the method move(cardNo) in your code. Solution time complexity should be O(n). Assume move(cardNo) as O(1).
Eg :[k 3 4 2 1 5 ] – your move should be to move 2 first and then 1. – No. of moves – 2 . Result : [ 1 2 3 4 5]
[ 1 2 4 5 3 ] – No. of moves – 3
Email me when people comment.
Email me when people comment.
Loading...
An error occurred in subscribing you.
Email me when people comment.
Email me when people comment.
Loading...
An error occurred in subscribing you.
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
We need to find the highest card which has higher cards before it.
- Miguel Oliveira August 26, 2013[3, 4, 2, 1, 5] -> 2 is the highest misplaced card (3,4,5 are in the right order)
[1, 2, 4, 5, 3] -> 3 (has 4 and 5 before it)
Finding this card can be done in O(n): traverse the array from left to right and keep the highest card seen so far. If the current card is smaller than the highest seen so far, then it is misplaced.
Afterwards, we need to place this card correctly. To do so, we need to put it on top of all cards. Hence, all cards smaller than this card will be misplaced as well.
So we need to put all cards smaller of equal to the highest misplaced card on top of the pile. Do this in decreasing order and we are done. The number of moves is equal to the highest misplaced card.
[3, 4, 2, 1, 5] -> 2. Move 2 = [2,3,4,1,5]. Move 1 = [1,2,3,4,5]
[1, 2, 4, 5, 3] -> 3. Move 3 = [3,1,2,4,5]. Move 2 = [2,3,1,4,5]. Move 1 = [1,2,3,4,5]