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 - Mathematical Formula INPUT Array nums with distinct numbers 3 idx 0 1 idx 1 4 idx 2 2 idx 3 Sorted Values: 1 2 3 4 Original Positions: 1-->idx1, 2-->idx3 3-->idx0, 4-->idx2 nums = [3, 1, 4, 2] ALGORITHM STEPS 1 Sort by Value Track original indices 2 Process in Sorted Order Calculate moves for each 3 Count Operations Add rotations + removals 4 Use Fenwick Tree Track removed elements Operations Count: Remove 1 (idx1): 2 ops Remove 2 (idx3): 2 ops Remove 3 (idx0): 2 ops Remove 4 (idx2): 1 op Total: 2+2+2+1 = 7 ops += (currIdx - prevIdx + n) % n FINAL RESULT Execution Trace: Step 1: [3,1,4,2] --> move 3 Step 2: [1,4,2,3] --> remove 1 Step 3: [4,2,3] --> move 4 Step 4: [2,3,4] --> remove 2 Step 5: [3,4] --> remove 3 Step 6: [4] --> remove 4 Step 7: [] --> EMPTY! OUTPUT 7 OK - 7 operations Time: O(n log n) Space: O(n) Key Insight: Instead of simulating each operation, process elements in sorted order. For each element, calculate how many positions we need to rotate from the previous removed element's position. Use a Fenwick Tree to track removed indices and count remaining elements efficiently. TutorialsPoint - Make Array Empty | Mathematical Formula Approach
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