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
Sorting Three Groups: Minimum Removals21321Input: [2,1,3,2,1]Strategy: Keep longest non-decreasing subsequence12Keep: [1,2] (length 2)Remove 3 elements: 2, 3, 1Answer: 3 operations✓ Keep✗ Remove
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
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen