Sorting Three Groups - Problem
You are given an integer array nums. Each element in nums is 1, 2 or 3.
In each operation, you can remove an element from nums. Return the minimum number of operations to make nums non-decreasing.
A non-decreasing array means that for all valid indices i, nums[i] <= nums[i+1].
Input & Output
Example 1 — Mixed Values
$
Input:
nums = [2,1,3,2,1]
›
Output:
3
💡 Note:
One optimal non-decreasing subsequence is [1,2] or [1,3]. We keep 2 elements and remove 3: operations = 5 - 2 = 3
Example 2 — Already Sorted
$
Input:
nums = [1,3,2,1,3,3]
›
Output:
2
💡 Note:
Longest non-decreasing subsequence could be [1,1,3,3] with length 4. Remove 2 elements: operations = 6 - 4 = 2
Example 3 — All Same
$
Input:
nums = [2,2,2,2]
›
Output:
0
💡 Note:
Array is already non-decreasing (all elements equal), so no operations needed
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is 1, 2, or 3
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Mixed array with values 1, 2, 3 that needs sorting
2
Find LIS
Identify longest non-decreasing subsequence to keep
3
Remove Rest
Remove all elements not in optimal subsequence
Key Takeaway
🎯 Key Insight: Instead of thinking about sorting, find the longest subsequence that's already sorted and remove everything else
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code