My this code is not working despite giving right ans on several tes cases.
Code not working
Oh Sorry! it was mistaken. Now I rectified the code according to the condition but is still not working.
For the given sample test case:
1
4
3 2 4 1
Your code gives output as:
2 1 0 0
Which is not correct.
Also there are some test case issues with this question.
So to actually check if your code/appraoch is correct, submit it on https://leetcode.com/problems/pancake-sorting/ and check.
ok will check it. Do we have to stop iteration at the point when the array is sorted.
Yes…because swaps after that are not necessary
code is working, but the approach that was Taught in the course is not the most efficient approach. Can you explain the efficient one.
Refer this.
Input: [3,2,4,1]
Pick highest element so far. Do swaps to bring it to last position.
In the input ,4 is the highest. So subarray from 3 to 4 is reversed.
Swap 1: 4 2 3 1
The whole array is then reversed such that 4 reaches its desired position.
Swap 2: 1 3 2 4
Now the unsorted window is from index 0 to 2.Highest element in this window is 3.So subarray 1 3 is reversed
Swap 3: 3 1 2 4
Swap the whole window such that 3 reaches its desired position.
Swap 4: 2 1 3 4
Now the unsorted window is from index 0 to 1. Highest element in this window is 2.
Swap 5:1 2 3 4
Ans on leetcode takes 4 swaps. Is the solution on leetcode is coincidence and only a way to misguide the coder to find any other solution, or any other way is possible.
By the way, our mentor has also taught the same method as you have explained.
Yes…there can be multiple possible outputs to this question. So not necessary that sample output matches exactly to Leetcode’s output.
Also your solution is fine and efficient enough. It is O(n^2). The solution provided there by leetcode is also O(n^2)
ok, that’s fine. Thanks
My code is showing WA.
Did you try that question on leetcode with the same approach?
There are issues with test cases for this question so it might not give all correct here