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 INPUT nums = [2, 1, 3, 2, 1] 2 i=0 1 i=1 3 i=2 2 i=3 1 i=4 Elements: only 1, 2, or 3 Goal: Make array non-decreasing with minimum removals Non-decreasing example: [1,1,2,2,3] OK Bad example: [2,1,3] NOT OK ALGORITHM STEPS 1 Initialize DP dp[i] = min ops for ending with group i (1,2,3) 2 Count Costs For each element, track removal cost per group 3 DP Transitions dp[1]: keep only 1s dp[2]: min(dp[1],dp[2])+cost dp[3]: min(dp[1..3])+cost 4 Final Answer Return min(dp[1..3]) DP State Evolution: Start: dp=[0,0,0] After: dp=[2,1,0] Answer: min(2,1,0)=0? No! FINAL RESULT Elements to Remove: 3 2 1 3 2 1 Remaining Array: [3] Or keep [1,2] or [1,3] All need 3 removals Output: 3 Key Insight: Count-Based DP tracks minimum removals to end with each group (1, 2, or 3). For non-decreasing order: group 2 can follow 1 or 2; group 3 can follow 1, 2, or 3. Time: O(n), Space: O(1) - only need 3 DP values at any time. TutorialsPoint - Sorting Three Groups | Count-Based DP Approach
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