#3634
Minimum Removals to Balance Array
MediumArrayBinary SearchSliding WindowSortingTwo PointersSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
Sort the array and use a two-pointer technique to find the largest balanced window. The difference between the total length and this window gives the minimum removals.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array.
- 2Step 2: Initialize two pointers, i and j, both at the start of the array.
- 3Step 3: Expand j while nums[j] <= k * nums[i]; calculate removals as n - (j - i + 1).
solution.py11 lines
1def min_removals_optimal(nums, k):
2 nums.sort()
3 n = len(nums)
4 i, j, max_removals = 0, 0, 0
5 while j < n:
6 if nums[j] <= k * nums[i]:
7 j += 1
8 else:
9 i += 1
10 max_removals = max(max_removals, j - i)
11 return n - max_removalsℹ
Complexity note: The sorting step dominates the complexity, followed by a linear scan with two pointers.
- 1Sorting helps in efficiently finding the range of valid elements.
- 2Using two pointers reduces the need for nested loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.