Minimum Chnanges for Beautiful String
XXX.Minimum Changes to Make Adjacent Characters Equal
String
Problem Statement:
Given a string s
consisting of lowercase English letters, determine the minimum number of changes needed to make every pair of adjacent characters equal. You can only modify one character at a time.
Algorithm:
- Initialize a counter variable
count
to track the required changes. - Iterate through the string in steps of 2 (checking pairs).
- If the two characters in the pair are different, increment the counter.
- Return the final count as the minimum number of changes needed.
Complexity:
Time: O(n), where n
is the length of the string, as we iterate through the string once. | Space: O(1), as no additional data structures are used.
Java Implementation:
public int minChanges(String s) {
int count = 0; // Tracks the number of changes needed
for (int i = 0; i < s.length() - 1; i += 2) {
if (s.charAt(i) != s.charAt(i + 1)) // If adjacent characters differ
count++; // Increment change count
}
return count; // Return the total changes required
}
Python Implementation:
def min_changes(s):
count = 0 # Tracks the number of changes needed
for i in range(0, len(s) - 1, 2):
if s[i] != s[i + 1]: # If adjacent characters differ
count += 1 # Increment change count
return count # Return the total changes required
C++ Implementation:
int minChanges(string s) {
int count = 0; // Tracks the number of changes needed
for (int i = 0; i < s.length() - 1; i += 2) {
if (s[i] != s[i + 1]) // If adjacent characters differ
count++; // Increment change count
}
return count; // Return the total changes required
}