#2914

Minimum Number of Changes to Make Binary String Beautiful

Medium
StringTwo PointersGreedy Algorithms
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 grouping the string into pairs of characters and counting how many pairs need to be changed to be uniform (either '00' or '11'). This reduces the problem to a linear scan of the string.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter for changes needed.
  2. 2Step 2: Iterate through the string in pairs (0,1), (2,3), ..., (n-2,n-1).
  3. 3Step 3: For each pair, check if they are the same. If not, increment the changes counter.
solution.py7 lines
1def minChanges(s):
2    changes = 0
3    for i in range(0, len(s), 2):
4        if s[i] != s[i + 1]:
5            changes += 1
6    return changes
7

Complexity note: The time complexity is O(n) because we only make a single pass through the string. The space complexity is O(1) since we use a constant amount of extra space.

  • 1Each substring must be of even length and consist of the same character.
  • 2Pairs of characters can be treated independently to minimize changes.

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