You are given an integer array nums containing distinct numbers, and you can perform the following operations until the array is empty:

  • If the first element has the smallest value, remove it
  • Otherwise, put the first element at the end of the array

Return an integer denoting the number of operations it takes to make nums empty.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,4,2]
Output: 7
💡 Note: Operations: [3,1,4,2]→[1,4,2,3]→[4,2,3]→[2,3,4]→[3,4]→[4,3]→[4]→[]. Total: 7 operations.
Example 2 — Already Sorted
$ Input: nums = [1,2,3]
Output: 3
💡 Note: Elements are already in ascending order, so each can be removed immediately: 1+1+1 = 3 operations.
Example 3 — Reverse Order
$ Input: nums = [4,3,2,1]
Output: 10
💡 Note: Worst case: need to rotate many times. Remove 1 (pos 3): 4 ops. Remove 2 (pos 2): 3 ops. Remove 3 (pos 1): 2 ops. Remove 4 (pos 0): 1 op. Total: 10.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • All elements in nums are distinct

Visualization

Tap to expand
Make Array Empty: Process Overview3142Initial: [3,1,4,2]FirstMinOperations Process:3≠min(1) → rotate → [1,4,2,3]1=min(1) → remove → [4,2,3]Continue until empty...7 OperationsFinal Result
Understanding the Visualization
1
Input Array
[3,1,4,2] - mixed order elements
2
Operation Rules
Remove if first is minimum, else rotate
3
Result
7 total operations needed
Key Takeaway
🎯 Key Insight: Elements must be removed in ascending order, allowing mathematical calculation instead of simulation
Asked in
Google 15 Microsoft 12 Meta 8
12.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen