Replace the Substring for Balanced String - Complete Solution Guide
Replace the Substring for Balanced String is LeetCode problem 1234, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given a string s of length n containing only four kinds of characters: 'Q' , 'W' , 'E' , and 'R' . A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced . If s is already balanced , return 0 . Example 1: Input: s = "QWER" Output: 0 Explanation: s is already balanced. Example 2: Input: s = "QQWE" Output: 1
Detailed Explanation
The problem asks us to find the minimum length of a substring within a given string `s` (containing only 'Q', 'W', 'E', 'R' characters) that needs to be replaced with any other string of the same length, such that the resulting string becomes 'balanced'. A string is considered 'balanced' if each of the four characters ('Q', 'W', 'E', 'R') appears exactly `n/4` times, where `n` is the length of the string `s`. The constraint is that `n` is always a multiple of 4. If the input string is already balanced, the function should return 0.
Solution Approach
The provided solution employs a sliding window technique. First, it calculates the required count `k = n/4` for each character. Then, it identifies the characters that have counts exceeding `k` and stores the excess counts in a `needed` counter. The sliding window expands and contracts to find the minimum window size that contains at least the number of excess characters needed to make the overall string balanced. The `formed` variable keeps track of how many of the needed characters' counts are satisfied within the current window.
Step-by-Step Algorithm
- Step 1: Calculate `n = len(s)` and `k = n // 4`. `k` represents the ideal count for each character.
- Step 2: Count the occurrences of each character in `s` using a `Counter` (or HashMap).
- Step 3: Create a `needed` `Counter` (or HashMap) to store characters that have counts greater than `k`. The values in `needed` represent the number of extra occurrences of each character that need to be replaced.
- Step 4: Initialize `left = 0`, `min_len = n`, `required = len(needed)`, and `formed = 0`. `left` is the left boundary of the sliding window, `min_len` stores the minimum window size found so far, `required` is the number of characters that have counts greater than k (number of keys in `needed`), and `formed` tracks how many of those character's needs are met within the window.
- Step 5: Iterate through the string with the `right` pointer (right boundary of the sliding window).
- Step 6: Update the `window_counts` `Counter` (or HashMap) with the character at the `right` pointer.
- Step 7: If the character at the `right` pointer is in `needed` and its count in `window_counts` matches its count in `needed`, increment `formed`.
- Step 8: While `left <= right` and `formed == required`, update `min_len` with the minimum of `min_len` and `right - left + 1`. Shrink the window from the left.
- Step 9: Decrement the count of the character at the `left` pointer in `window_counts`.
- Step 10: If the character at the `left` pointer is in `needed` and its count in `window_counts` is now less than its count in `needed`, decrement `formed`.
- Step 11: Increment `left` to shrink the window.
- Step 12: Return `min_len`.
Key Insights
- Insight 1: The core idea is to use a sliding window approach. We aim to find the smallest window such that replacing the characters within that window will balance the entire string.
- Insight 2: We don't actually replace the substring. We just identify the substring that, if removed, would leave us with at most n/4 occurrences of each character. Then, the length of the substring is the answer.
- Insight 3: Using a `Counter` (or equivalent hash map) is crucial for efficiently tracking the frequency of each character both in the overall string and within the sliding window.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: String, Sliding Window.
Companies
Asked at: Accolite.