Make Array Empty — LeetCode 2659 Python Solution

HardGreedyBinary Indexed TreeSegment TreeArrayBinary SearchOrdered SetSorting
Problem
#2659
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview