MediumNo. 2826
Sorting Three Groups — LeetCode 2826 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search, Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer array nums. Each element in nums is 1, 2 or 3.
Python solution
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
- Time
- O(n)where n is the length of the array
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0300 | Longest Increasing Subsequence | Medium |
| 0354 | Russian Doll Envelopes | Hard |
| 0410 | Split Array Largest Sum | Hard |
| 0902 | Numbers At Most N Given Digit Set | Hard |
| 1187 | Make Array Strictly Increasing | Hard |
| 1235 | Maximum Profit in Job Scheduling | Hard |
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.