2914. Minimum Number of Changes to Make Binary String Beautiful
EasyView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Minimum string changes to make string good (each character has even count).
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;
}
}Was this solution helpful?
Related Problems
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 22. Generate Parentheses(Medium)
- 30. Substring with Concatenation of All Words(Hard)