Make Array Empty — LeetCode 2659 Python Solution
- Problem
- #2659
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- nums = [3,4,-1]
- Output
- 5
Python solution
class Solution:
def countOperationsToEmptyArray(self, nums: List[int]) -> int:
pos = {x: i for i, x in enumerate(nums)}
nums.sort()
sl = SortedList()
ans = pos[nums[0]] + 1
n = len(nums)
for k, (a, b) in enumerate(pairwise(nums)):
i, j = pos[a], pos[b]
d = j - i - sl.bisect(j) + sl.bisect(i)
ans += d + (n - k) * int(i > j)
sl.add(i)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2659. Make Array Empty is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2659. Make Array Empty?
- LeetCode 2659. Make Array Empty is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2659. Make Array Empty?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2659. Make Array Empty?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2659. Make Array Empty cover?
- LeetCode 2659. Make Array Empty is tagged Greedy, Binary Indexed Tree, Segment Tree, Array, Binary Search, Ordered Set and Sorting on LeetCode.