Find minimum operations to make array sorted
Company: IBM
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Take-home Project
Quick Answer: This question evaluates a candidate's competence in array manipulation, algorithmic optimization, and reasoning about deterministic, operation-driven state transitions.
Constraints
- 1 <= n <= 2 * 10^5
- a[i] fits in a 32-bit signed integer
- An empty array and a single-element array are already non-decreasing (answer 0)
- If the array never becomes non-decreasing, return -1
Examples
Input: ([3, 1, 2],)
Expected Output: 1
Explanation: Pop 3, append -> [1,2,3]; 3 stays at the end (1<=2<=3). Array is now sorted after 1 operation.
Input: ([1, 2, 3, 4],)
Expected Output: 0
Explanation: Already non-decreasing, so 0 operations are needed.
Input: ([5],)
Expected Output: 0
Explanation: A single element is trivially non-decreasing.
Input: ([],)
Expected Output: 0
Explanation: An empty array is non-decreasing by definition.
Input: ([2, 1],)
Expected Output: 1
Explanation: Pop 2, append -> [1,2]; sorted after 1 operation.
Input: ([0, 3, 2, 4, 0],)
Expected Output: 4
Explanation: States: [3,2,4,0,0] -> [2,4,0,0,3] -> [4,0,0,2,3] -> [0,0,2,3,4]. Sorted after 4 operations.
Input: ([4, 3, 2, 1],)
Expected Output: 3
Explanation: Reverse-sorted: [3,2,1,4] -> [2,1,3,4] -> [1,2,3,4]. Sorted after 3 operations.
Input: ([0, 4, 2, 3],)
Expected Output: -1
Explanation: The minimum 0 is already at the front; popping it and bubbling sends it back to index 0 unchanged, so the array can never sort. Return -1.
Input: ([2, 2, 2],)
Expected Output: 0
Explanation: All equal elements are already non-decreasing.
Input: ([1, 4, 3, 2],)
Expected Output: -1
Explanation: The trajectory cycles without ever reaching the sorted order, so it is impossible.
Input: ([-1, -3, -2],)
Expected Output: 1
Explanation: Negatives work the same: pop -1, append -> [-3,-2,-1]; sorted after 1 operation.
Input: ([3, 3, 0, 0],)
Expected Output: 2
Explanation: Pop 3 -> [3,0,0,3]; pop 3 -> [0,0,3,3]. Sorted after 2 operations (duplicates and ties handled).
Hints
- Each operation is just: pop the front element and insertion-sort it back in from the right. The relative order of the other elements never changes.
- If the array is solvable, it becomes sorted within n operations. Convince yourself: once the global minimum reaches the front of an unsorted array, it bubbles all the way to index 0 and the array is unchanged, so the process cycles.
- That gives a clean termination rule: simulate at most n operations. If it is sorted at step k, return k; if it is still unsorted after n operations, return -1.