2914. Minimum Number of Changes to Make Binary String Beautiful
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Minimum string changes to make string good (each character has even count). Count characters with odd frequency.
Algorithm
- 1Count frequencies. Odd frequency chars must pair up. Min changes = oddCount / 2.
Common Pitfalls
- •Each swap can fix two odd-frequency characters. Minimum changes = floor(oddCount/2).
2914.cs
C#
// Approach: Scan even-indexed pairs; each mismatched pair costs 1 change.
// Time: O(n) Space: O(1)
public class Solution
{
public int MinChanges(string s)
{
int ans = 0;
for (int i = 0; i + 1 < s.Length; i += 2)
{
if (s[i] != s[i + 1])
++ans;
}
return ans;
}
}Advertisement
Was this solution helpful?