#2366

Minimum Replacements to Sort the Array

Hard
ArrayMathGreedyGreedyArray
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 solution iterates backward through the array, ensuring each element is less than or equal to the next. By breaking larger elements into smaller parts, we minimize operations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a counter for operations and set a previous bound as infinity.
  2. 2Step 2: Iterate from the second last element to the first element of the array.
  3. 3Step 3: If the current element is greater than the previous bound, calculate how many replacements are needed to ensure it is less than or equal to the previous bound.
  4. 4Step 4: Update the operations counter accordingly.
solution.py14 lines
1# Full working Python code
2
3def min_replacements_optimal(nums):
4    operations = 0
5    prev_bound = float('inf')
6    for i in range(len(nums) - 2, -1, -1):
7        if nums[i] > prev_bound:
8            operations += (nums[i] - 1) // prev_bound
9            nums[i] = prev_bound
10        prev_bound = nums[i]
11    return operations
12
13# Example usage
14print(min_replacements_optimal([3, 9, 3]))

Complexity note: This complexity is achieved because we only traverse the array once, making it efficient for large inputs.

  • 1Breaking larger numbers into smaller parts can help maintain order.
  • 2Always consider the previous element's value when deciding how to break down the current element.

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