Sorting Three Groups — LeetCode 2826 Python Solution

MediumArrayBinary SearchDynamic Programming
Problem
#2826
Reading time
3 min

The problem

You are given an integer array nums. Each element in nums is 1, 2 or 3.

Python solution

Python
class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        f = [0] * 3
        for x in nums:
            g = [0] * 3
            if x == 1:
                g[0] = f[0]
                g[1] = min(f[:2]) + 1
                g[2] = min(f) + 1
            elif x == 2:
                g[0] = f[0] + 1
                g[1] = min(f[:2])
                g[2] = min(f) + 1
            else:
                g[0] = f[0] + 1
                g[1] = min(f[:2]) + 1
                g[2] = min(f)
            f = g
        return min(f)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2826. Sorting Three Groups 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 2826. Sorting Three Groups?
LeetCode 2826. Sorting Three Groups is rated Medium on LeetCode.
What is the time complexity of LeetCode 2826. Sorting Three Groups?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2826. Sorting Three Groups?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2826. Sorting Three Groups cover?
LeetCode 2826. Sorting Three Groups is tagged Array, Binary Search and Dynamic Programming 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