#2826

Sorting Three Groups

Medium
ArrayBinary SearchDynamic ProgrammingCounting SortPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach involves counting how many 1s, 2s, and 3s are in the array and then calculating the minimum removals needed to create a non-decreasing sequence. This is done using prefix sums to keep track of the counts efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the total number of 1s, 2s, and 3s in the array.
  2. 2Step 2: Use prefix sums to track how many 1s and 2s are before each index.
  3. 3Step 3: For each possible partition, calculate the number of removals needed and update the minimum removals.
solution.py15 lines
1def min_operations(nums):
2    count1 = nums.count(1)
3    count2 = nums.count(2)
4    count3 = nums.count(3)
5    min_removals = float('inf')
6    prefix1 = 0
7    prefix2 = 0
8    for num in nums:
9        if num == 1:
10            prefix1 += 1
11        elif num == 2:
12            prefix2 += 1
13        removals = (count2 - prefix2) + (count3 - (count2 + count3 - prefix1))
14        min_removals = min(min_removals, removals)
15    return min_removals

Complexity note: This complexity is linear because we only pass through the array a couple of times, counting elements and calculating removals.

  • 1Understanding the distribution of numbers (1, 2, 3) helps in optimizing the solution.
  • 2Using prefix sums allows us to efficiently calculate the number of removals needed for each partition.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.