Break Adjacent Duplicate Characters
IBMSoftware Engineer · Online AssessmentLast updated
Tests string traversal, run-length counting, and greedy optimization to determine the minimum character replacements needed to eliminate adjacent identical characters across a list of words.
Break Adjacent Duplicate Characters
Given an array of strings words consisting solely of lowercase English letters, determine the minimum number of character replacements required for each word so that no two adjacent characters are identical. In one operation, you may replace any character with any other lowercase English letter.
Return an array of integers where the i-th integer represents the minimum number of operations required for words[i].
Function Signature
def min_replacements(words: list[str]) -> list[int]:
pass
Input
words: A list of strings, where each string contains only lowercase English letters ('a'-'z').
Output
- Returns a list of integers containing the minimum replacements for each corresponding string in
words.
Constraints
1 <= len(words) <= 10^51 <= len(words[i]) <= 10^5- The total length of all strings in
wordsdoes not exceed2 * 10^5. - Each
words[i]consists only of lowercase English letters.
Examples
Example 1
Input: words = ["ab", "aaa", "bookkeeper"]
Output: [0, 1, 3]
Explanation:
"ab"already has no adjacent duplicates:0changes."aaa"can be changed to"aba":1change.- In
"bookkeeper", adjacent pairs are'oo','kk', and'ee'. Replacing one letter in each pair (e.g.,"bo1ke2pe3r") requires3changes.
Example 2
Input: words = ["baaaa", "c"]
Output: [2, 0]
Explanation:
- In
"baaaa", the run of'a's has length 4. Changing 2 of them (e.g., indices 2 and 4 to'b') yields"baba", which has no adjacent duplicates:2changes. "c"has length 1:0changes.
Edge Cases
- Single-character strings require
0replacements. - Strings with all identical characters of length
krequirek // 2replacements.
Hints
Hint 1
Consider contiguous runs of identical characters independently.
Hint 2
For a run of identical characters of length k, think about how many changes are needed to prevent any two identical characters from touching.
Hint 3
Because the alphabet has 26 letters, you can always choose a substitute character that does not conflict with its immediate neighbors; thus, a run of length k requires floor(k / 2) replacements.
Follow-up questions
- What if the alphabet size were restricted to only 2 characters (e.g., binary strings '0' and '1') instead of 26?
- How would you reconstruct the lexicographically smallest valid string using the minimum number of replacements?
- How would you solve the problem if each character replacement had a distinct associated cost?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.