Make Array Empty Problem
Description
LeetCode Problem 2659.
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.
Example 1:
Input: nums = [3,4,-1]
Output: 5
| Operation | Array |
|---|---|
| 1 | [4, -1, 3] |
| 2 | [-1, 3, 4] |
| 3 | [3, 4] |
| 4 | [4] |
| 5 | [] |
Example 2:
Input: nums = [1,2,4,3]
Output: 5
| Operation | Array |
|---|---|
| 1 | [2, 4, 3] |
| 2 | [4, 3] |
| 3 | [3, 4] |
| 4 | [4] |
| 5 | [] |
Example 3:
Input: nums = [1,2,3]
Output: 3
| Operation | Array |
|---|---|
| 1 | [2, 3] |
| 2 | [3] |
| 3 | [] |
Constraints:
1 <= nums.length <= 10^5-10^9<= nums[i] <= 10^9- All values in
numsare distinct.
Solution
Approach: Hash Table + Sorting + Fenwick Tree
Remember each value's position in a hash table, then sort the values. Removing the values in increasing order, the cost of getting from one value a to the next larger b is the distance between their positions, minus the positions already removed in between (counted with a Fenwick tree). If b lies before a, the pass wraps around, adding n - k extra operations, where k is the number of values already removed. The first value costs its position plus 1.
Complexity: O(n log n) time and O(n) space.
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countOperationsToEmptyArray(self, nums: List[int]) -> int:
pos = {x: i for i, x in enumerate(nums)}
nums.sort()
n = len(nums)
tree = BinaryIndexedTree(n)
ans = pos[nums[0]] + 1
for k in range(n - 1):
i, j = pos[nums[k]], pos[nums[k + 1]]
d = j - i - (tree.query(j + 1) - tree.query(i + 1))
ans += d + (n - k) * int(i > j)
tree.update(i + 1, 1)
return ans