Bird
Raised Fist0
Interview Prepsliding-windowmediumAmazonGoogleBloomberg

Longest Repeating Character Replacement

Choose your preparation mode4 modes available
🎯
Longest Repeating Character Replacement
mediumSLIDING_WINDOWAmazonGoogleBloomberg

Imagine you are editing a text and want to find the longest segment where you can replace a few characters to make all characters identical, helping you optimize formatting or compression.

💡 This problem is a classic example of using a sliding window with variable size. Beginners often struggle because they try fixed window sizes or brute force all substrings, missing the insight that the window can expand and shrink dynamically based on character frequency constraints.
📋
Problem Statement

Given a string s and an integer k, you can choose any character of the string and change it to any other uppercase English character at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.

1 ≤ s.length ≤ 10^5s consists of only uppercase English letters0 ≤ k ≤ s.length
💡
Example
Input"s = \"ABAB\", k = 2"
Output4

Replace two 'A's with 'B's or vice versa to get "BBBB" or "AAAA".

Input"s = \"AABABBA\", k = 1"
Output4

Replace one 'B' in the substring "ABAB" to get "AAAA" or "BBBB".

  • All characters are the same and k = 0 → output is length of string
  • k = 0 and string has all distinct characters → output is 1
  • k equals string length → output is string length
  • String length = 1 → output is 1
⚠️
Common Mistakes
Not updating max frequency correctly when shrinking window

Window shrinks incorrectly or max frequency is stale, leading to wrong answer

✅ Do not decrease max frequency when shrinking; keep track of max frequency as max so far

Using a hashmap without considering character set size

Unnecessary overhead and slower performance

✅ Use fixed-size array for uppercase letters to improve speed

Shrinking window too early or too late

Window size is incorrect, resulting in wrong max length

✅ Shrink window only when replacements needed exceed k

Not handling edge cases like k=0 or single character strings

Incorrect output or runtime errors

✅ Test and handle minimal and boundary inputs explicitly

🧠
Brute Force (Check All Substrings)
💡 Starting with brute force helps understand the problem deeply by considering all possible substrings and checking if they can be converted with at most k replacements. It’s inefficient but builds intuition.

Intuition

Try every substring, count the frequency of each character, and check if the substring can be made uniform by replacing at most k characters.

Algorithm

  1. Enumerate all substrings of s using two nested loops.
  2. For each substring, count the frequency of each character.
  3. Calculate the number of replacements needed as substring length minus max frequency.
  4. If replacements needed ≤ k, update the maximum length found.
💡 The nested loops and frequency counting make this approach straightforward but slow, which is why it’s a good starting point to understand the problem.
</>
Code
def characterReplacement(s: str, k: int) -> int:
    max_len = 0
    n = len(s)
    for start in range(n):
        freq = {}
        max_count = 0
        for end in range(start, n):
            freq[s[end]] = freq.get(s[end], 0) + 1
            max_count = max(max_count, freq[s[end]])
            if (end - start + 1) - max_count <= k:
                max_len = max(max_len, end - start + 1)
    return max_len

# Driver code
if __name__ == '__main__':
    print(characterReplacement("ABAB", 2))  # Expected output: 4
Line Notes
for start in range(n):Outer loop picks the start index of substring
freq = {}Reset frequency dictionary for each new start
for end in range(start, n):Inner loop picks the end index of substring
freq[s[end]] = freq.get(s[end], 0) + 1Count frequency of current character in substring
max_count = max(max_count, freq[s[end]])Track the most frequent character count in substring
if (end - start + 1) - max_count <= k:Check if replacements needed are within k
max_len = max(max_len, end - start + 1)Update max length if condition satisfied
import java.util.*;
public class Solution {
    public int characterReplacement(String s, int k) {
        int maxLen = 0;
        int n = s.length();
        for (int start = 0; start < n; start++) {
            Map<Character, Integer> freq = new HashMap<>();
            int maxCount = 0;
            for (int end = start; end < n; end++) {
                char c = s.charAt(end);
                freq.put(c, freq.getOrDefault(c, 0) + 1);
                maxCount = Math.max(maxCount, freq.get(c));
                if ((end - start + 1) - maxCount <= k) {
                    maxLen = Math.max(maxLen, end - start + 1);
                }
            }
        }
        return maxLen;
    }
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.characterReplacement("ABAB", 2)); // Expected output: 4
    }
}
Line Notes
for (int start = 0; start < n; start++) {Outer loop selects substring start
Map<Character, Integer> freq = new HashMap<>();Frequency map reset for each start
for (int end = start; end < n; end++) {Inner loop selects substring end
freq.put(c, freq.getOrDefault(c, 0) + 1);Update frequency of current character
maxCount = Math.max(maxCount, freq.get(c));Track max frequency in current substring
if ((end - start + 1) - maxCount <= k) {Check if replacements needed are within k
maxLen = Math.max(maxLen, end - start + 1);Update max length if valid
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int characterReplacement(string s, int k) {
    int maxLen = 0;
    int n = s.size();
    for (int start = 0; start < n; start++) {
        unordered_map<char, int> freq;
        int maxCount = 0;
        for (int end = start; end < n; end++) {
            freq[s[end]]++;
            maxCount = max(maxCount, freq[s[end]]);
            if ((end - start + 1) - maxCount <= k) {
                maxLen = max(maxLen, end - start + 1);
            }
        }
    }
    return maxLen;
}

int main() {
    cout << characterReplacement("ABAB", 2) << endl; // Expected output: 4
    return 0;
}
Line Notes
for (int start = 0; start < n; start++) {Outer loop for substring start index
unordered_map<char, int> freq;Frequency map reset for each start
for (int end = start; end < n; end++) {Inner loop for substring end index
freq[s[end]]++;Increment frequency of current character
maxCount = max(maxCount, freq[s[end]]);Track max frequency in substring
if ((end - start + 1) - maxCount <= k) {Check if replacements needed are within k
maxLen = max(maxLen, end - start + 1);Update max length if condition met
function characterReplacement(s, k) {
    let maxLen = 0;
    const n = s.length;
    for (let start = 0; start < n; start++) {
        const freq = {};
        let maxCount = 0;
        for (let end = start; end < n; end++) {
            freq[s[end]] = (freq[s[end]] || 0) + 1;
            maxCount = Math.max(maxCount, freq[s[end]]);
            if ((end - start + 1) - maxCount <= k) {
                maxLen = Math.max(maxLen, end - start + 1);
            }
        }
    }
    return maxLen;
}

// Driver code
console.log(characterReplacement("ABAB", 2)); // Expected output: 4
Line Notes
for (let start = 0; start < n; start++) {Outer loop selects substring start
const freq = {};Reset frequency object for each start
for (let end = start; end < n; end++) {Inner loop selects substring end
freq[s[end]] = (freq[s[end]] || 0) + 1;Update frequency of current character
maxCount = Math.max(maxCount, freq[s[end]]);Track max frequency in substring
if ((end - start + 1) - maxCount <= k) {Check if replacements needed are within k
maxLen = Math.max(maxLen, end - start + 1);Update max length if valid
⏱
Complexity
TimeO(n^2)
SpaceO(n)

Two nested loops generate O(n^2) substrings, and frequency counting inside inner loop is O(1) amortized using hashmap. Overall O(n^2).

💡 For n=20, this means about 400 substring checks, which is manageable, but for n=10^5 it becomes impractical.
Interview Verdict: TLE

This approach is too slow for large inputs but is useful to understand the problem and correctness before optimizing.

🧠
Sliding Window with Frequency Map and Max Count Tracking
💡 This approach uses a sliding window that expands and contracts to maintain the condition that the number of replacements needed is at most k. It’s more efficient and introduces the key insight of tracking the most frequent character in the current window.

Intuition

Keep expanding the window and track the count of the most frequent character. If the window size minus this count exceeds k, shrink the window from the left.

Algorithm

  1. Initialize two pointers (left and right) at the start of the string.
  2. Expand right pointer, update frequency of current character and track max frequency in window.
  3. If window size minus max frequency > k, move left pointer forward and update frequencies.
  4. Keep track of the maximum window size seen that satisfies the condition.
💡 The tricky part is maintaining max frequency efficiently and knowing when to shrink the window.
</>
Code
def characterReplacement(s: str, k: int) -> int:
    freq = {}
    left = 0
    max_count = 0
    max_len = 0
    for right in range(len(s)):
        freq[s[right]] = freq.get(s[right], 0) + 1
        max_count = max(max_count, freq[s[right]])
        while (right - left + 1) - max_count > k:
            freq[s[left]] -= 1
            left += 1
        max_len = max(max_len, right - left + 1)
    return max_len

# Driver code
if __name__ == '__main__':
    print(characterReplacement("ABAB", 2))  # Expected output: 4
Line Notes
freq = {}Initialize frequency dictionary for current window
left = 0Left pointer starts at beginning
for right in range(len(s))Right pointer expands window
freq[s[right]] = freq.get(s[right], 0) + 1Update frequency of new character
max_count = max(max_count, freq[s[right]])Track max frequency in window
while (right - left + 1) - max_count > k:Shrink window if replacements exceed k
freq[s[left]] -= 1Decrease frequency of character leaving window
left += 1Move left pointer forward
max_len = max(max_len, right - left + 1)Update max length found
import java.util.*;
public class Solution {
    public int characterReplacement(String s, int k) {
        Map<Character, Integer> freq = new HashMap<>();
        int left = 0, maxCount = 0, maxLen = 0;
        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            freq.put(c, freq.getOrDefault(c, 0) + 1);
            maxCount = Math.max(maxCount, freq.get(c));
            while ((right - left + 1) - maxCount > k) {
                char leftChar = s.charAt(left);
                freq.put(leftChar, freq.get(leftChar) - 1);
                left++;
            }
            maxLen = Math.max(maxLen, right - left + 1);
        }
        return maxLen;
    }
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.characterReplacement("ABAB", 2)); // Expected output: 4
    }
}
Line Notes
Map<Character, Integer> freq = new HashMap<>();Frequency map for current window
int left = 0, maxCount = 0, maxLen = 0;Initialize pointers and trackers
for (int right = 0; right < s.length(); right++) {Expand window from right
freq.put(c, freq.getOrDefault(c, 0) + 1);Update frequency of new character
maxCount = Math.max(maxCount, freq.get(c));Track max frequency in window
while ((right - left + 1) - maxCount > k) {Shrink window if replacements exceed k
freq.put(leftChar, freq.get(leftChar) - 1);Decrease frequency of character leaving window
left++;Move left pointer forward
maxLen = Math.max(maxLen, right - left + 1);Update max length found
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int characterReplacement(string s, int k) {
    unordered_map<char, int> freq;
    int left = 0, maxCount = 0, maxLen = 0;
    for (int right = 0; right < (int)s.size(); right++) {
        freq[s[right]]++;
        maxCount = max(maxCount, freq[s[right]]);
        while ((right - left + 1) - maxCount > k) {
            freq[s[left]]--;
            left++;
        }
        maxLen = max(maxLen, right - left + 1);
    }
    return maxLen;
}

int main() {
    cout << characterReplacement("ABAB", 2) << endl; // Expected output: 4
    return 0;
}
Line Notes
unordered_map<char, int> freq;Frequency map for current window
int left = 0, maxCount = 0, maxLen = 0;Initialize pointers and trackers
for (int right = 0; right < (int)s.size(); right++) {Expand window from right
freq[s[right]]++;Update frequency of new character
maxCount = max(maxCount, freq[s[right]]);Track max frequency in window
while ((right - left + 1) - maxCount > k) {Shrink window if replacements exceed k
freq[s[left]]--;Decrease frequency of character leaving window
left++;Move left pointer forward
maxLen = max(maxLen, right - left + 1);Update max length found
function characterReplacement(s, k) {
    const freq = {};
    let left = 0, maxCount = 0, maxLen = 0;
    for (let right = 0; right < s.length; right++) {
        freq[s[right]] = (freq[s[right]] || 0) + 1;
        maxCount = Math.max(maxCount, freq[s[right]]);
        while ((right - left + 1) - maxCount > k) {
            freq[s[left]]--;
            left++;
        }
        maxLen = Math.max(maxLen, right - left + 1);
    }
    return maxLen;
}

// Driver code
console.log(characterReplacement("ABAB", 2)); // Expected output: 4
Line Notes
const freq = {};Frequency map for current window
let left = 0, maxCount = 0, maxLen = 0;Initialize pointers and trackers
for (let right = 0; right < s.length; right++) {Expand window from right
freq[s[right]] = (freq[s[right]] || 0) + 1;Update frequency of new character
maxCount = Math.max(maxCount, freq[s[right]]);Track max frequency in window
while ((right - left + 1) - maxCount > k) {Shrink window if replacements exceed k
freq[s[left]]--;Decrease frequency of character leaving window
left++;Move left pointer forward
maxLen = Math.max(maxLen, right - left + 1);Update max length found
⏱
Complexity
TimeO(n)
SpaceO(1)

Each character is visited at most twice by left and right pointers. Frequency map size is constant (26 uppercase letters).

💡 For n=10^5, this means roughly 200,000 operations, which is efficient and suitable for interviews.
Interview Verdict: Accepted

This is the standard optimal approach for this problem and is expected in interviews.

🧠
Sliding Window with Fixed-Size Frequency Array
💡 This approach is a variant of the previous one but uses a fixed-size array for frequencies instead of a hashmap, which is more efficient for uppercase English letters.

Intuition

Use an integer array of size 26 to track character counts, improving performance by avoiding hashmap overhead.

Algorithm

  1. Initialize an array of size 26 to zero for character frequencies.
  2. Use two pointers to expand and shrink the window as before.
  3. Update max frequency and shrink window if needed.
  4. Return the maximum window size found.
💡 This approach is almost identical to the previous but uses a more efficient data structure for frequency tracking.
</>
Code
def characterReplacement(s: str, k: int) -> int:
    freq = [0] * 26
    left = 0
    max_count = 0
    max_len = 0
    for right in range(len(s)):
        freq[ord(s[right]) - ord('A')] += 1
        max_count = max(max_count, freq[ord(s[right]) - ord('A')])
        while (right - left + 1) - max_count > k:
            freq[ord(s[left]) - ord('A')] -= 1
            left += 1
        max_len = max(max_len, right - left + 1)
    return max_len

# Driver code
if __name__ == '__main__':
    print(characterReplacement("ABAB", 2))  # Expected output: 4
Line Notes
freq = [0] * 26Initialize fixed-size frequency array for uppercase letters
freq[ord(s[right]) - ord('A')] += 1Increment frequency of current character by index
max_count = max(max_count, freq[ord(s[right]) - ord('A')])Track max frequency in window
while (right - left + 1) - max_count > k:Shrink window if replacements exceed k
freq[ord(s[left]) - ord('A')] -= 1Decrease frequency of character leaving window
left += 1Move left pointer forward
max_len = max(max_len, right - left + 1)Update max length found
public class Solution {
    public int characterReplacement(String s, int k) {
        int[] freq = new int[26];
        int left = 0, maxCount = 0, maxLen = 0;
        for (int right = 0; right < s.length(); right++) {
            freq[s.charAt(right) - 'A']++;
            maxCount = Math.max(maxCount, freq[s.charAt(right) - 'A']);
            while ((right - left + 1) - maxCount > k) {
                freq[s.charAt(left) - 'A']--;
                left++;
            }
            maxLen = Math.max(maxLen, right - left + 1);
        }
        return maxLen;
    }
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.characterReplacement("ABAB", 2)); // Expected output: 4
    }
}
Line Notes
int[] freq = new int[26];Fixed-size frequency array for uppercase letters
freq[s.charAt(right) - 'A']++;Increment frequency of current character
maxCount = Math.max(maxCount, freq[s.charAt(right) - 'A']);Track max frequency in window
while ((right - left + 1) - maxCount > k) {Shrink window if replacements exceed k
freq[s.charAt(left) - 'A']--;Decrease frequency of character leaving window
left++;Move left pointer forward
maxLen = Math.max(maxLen, right - left + 1);Update max length found
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int characterReplacement(string s, int k) {
    vector<int> freq(26, 0);
    int left = 0, maxCount = 0, maxLen = 0;
    for (int right = 0; right < (int)s.size(); right++) {
        freq[s[right] - 'A']++;
        maxCount = max(maxCount, freq[s[right] - 'A']);
        while ((right - left + 1) - maxCount > k) {
            freq[s[left] - 'A']--;
            left++;
        }
        maxLen = max(maxLen, right - left + 1);
    }
    return maxLen;
}

int main() {
    cout << characterReplacement("ABAB", 2) << endl; // Expected output: 4
    return 0;
}
Line Notes
vector<int> freq(26, 0);Fixed-size frequency vector for uppercase letters
freq[s[right] - 'A']++;Increment frequency of current character
maxCount = max(maxCount, freq[s[right] - 'A']);Track max frequency in window
while ((right - left + 1) - maxCount > k) {Shrink window if replacements exceed k
freq[s[left] - 'A']--;Decrease frequency of character leaving window
left++;Move left pointer forward
maxLen = max(maxLen, right - left + 1);Update max length found
function characterReplacement(s, k) {
    const freq = new Array(26).fill(0);
    let left = 0, maxCount = 0, maxLen = 0;
    for (let right = 0; right < s.length; right++) {
        freq[s.charCodeAt(right) - 65]++;
        maxCount = Math.max(maxCount, freq[s.charCodeAt(right) - 65]);
        while ((right - left + 1) - maxCount > k) {
            freq[s.charCodeAt(left) - 65]--;
            left++;
        }
        maxLen = Math.max(maxLen, right - left + 1);
    }
    return maxLen;
}

// Driver code
console.log(characterReplacement("ABAB", 2)); // Expected output: 4
Line Notes
const freq = new Array(26).fill(0);Fixed-size frequency array for uppercase letters
freq[s.charCodeAt(right) - 65]++;Increment frequency of current character
maxCount = Math.max(maxCount, freq[s.charCodeAt(right) - 65]);Track max frequency in window
while ((right - left + 1) - maxCount > k) {Shrink window if replacements exceed k
freq[s.charCodeAt(left) - 65]--;Decrease frequency of character leaving window
left++;Move left pointer forward
maxLen = Math.max(maxLen, right - left + 1);Update max length found
⏱
Complexity
TimeO(n)
SpaceO(1)

Same as previous approach but with slightly better constant factors due to array usage.

💡 This is the most efficient and clean approach for uppercase letters.
Interview Verdict: Accepted

This is the preferred approach in interviews when input constraints allow it.

📊
All Approaches - One-Glance Tradeoffs
💡 In interviews, always aim to code the sliding window approach with frequency tracking (Approach 2 or 3) as it balances clarity and efficiency.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute ForceO(n^2)O(n)NoN/AMention only - never code due to inefficiency
2. Sliding Window with HashMapO(n)O(1)NoN/ACode this if input alphabet is unknown or large
3. Sliding Window with Frequency ArrayO(n)O(1)NoN/APreferred approach for uppercase letters due to simplicity and speed
💼
Interview Strategy
💡 Use this guide to understand the problem deeply and practice explaining each approach clearly before coding. Focus on sliding window intuition and how to maintain constraints efficiently.

How to Present

Step 1: Clarify the problem and constraints with the interviewer.Step 2: Describe the brute force approach to show understanding.Step 3: Explain why brute force is inefficient and introduce sliding window.Step 4: Present the sliding window approach with frequency tracking.Step 5: Code the optimal solution and test with examples.

Time Allocation

Clarify: 2min → Approach: 5min → Code: 10min → Test & Optimize: 3min. Total ~20min

What the Interviewer Tests

Interviewer tests your ability to identify sliding window patterns, maintain frequency counts efficiently, and optimize time complexity from brute force to linear.

Common Follow-ups

  • What if the string contains lowercase letters or all ASCII? → Use a larger frequency array or hashmap.
  • Can you optimize space further? → Frequency array is already minimal; hashmap is needed for larger alphabets.
💡 These follow-ups test your adaptability to input variations and understanding of data structures.
🔍
Pattern Recognition

When to Use

1) Problem asks for longest substring or subarray; 2) You can replace or remove up to k elements; 3) The substring must satisfy a uniformity or frequency condition; 4) Input size is large, requiring efficient solution.

Signature Phrases

'longest substring containing the same letter''replace at most k characters'

NOT This Pattern When

Fixed-size window problems or problems requiring exact substring matching without replacements

Similar Problems

Longest Substring Without Repeating Characters - sliding window to find longest substring with unique charsMinimum Window Substring - sliding window with character frequency constraintsLongest Substring with At Most K Distinct Characters - variable window size based on distinct count

Practice

(1/5)
1. You are given a binary array and an integer k. You want to find the length of the longest contiguous subarray containing only 1s after flipping at most k zeros to 1s. Which algorithmic approach guarantees an optimal solution with linear time complexity?
easy
A. Sliding window with two pointers maintaining a window that contains at most k zeros
B. Brute force nested loops checking all subarrays and counting zeros each time
C. Dynamic programming with memoization over subarray indices and zero counts
D. Greedy approach flipping zeros as soon as encountered without shrinking window

Solution

  1. Step 1: Understand problem constraints

    The problem requires the longest subarray with at most k zeros flipped to ones, which suggests a variable-size window approach.
  2. Step 2: Identify suitable algorithm

    Sliding window with two pointers efficiently tracks the window boundaries and zero count, allowing linear time complexity.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sliding window with two pointers is the classic optimal approach for this problem [OK]
Hint: Longest subarray with constraints -> sliding window [OK]
Common Mistakes:
  • Assuming greedy flipping without window shrink works
  • Using DP unnecessarily
  • Brute force is too slow
2. You are given two strings s1 and s2. You need to determine if any substring of s2 is a rearrangement (permutation) of s1. Which algorithmic approach guarantees an optimal solution in terms of time complexity?
easy
A. Greedy approach that tries to match characters from s1 in s2 sequentially.
B. Brute force checking all substrings of s2 and comparing frequency maps with s1.
C. Dynamic programming to build a table of substring matches based on character counts.
D. Sliding window with frequency map and a match count optimization to track when all characters match.

Solution

  1. Step 1: Understand problem constraints

    The problem requires checking if any substring of s2 is a permutation of s1, which means the substring must have the same character counts as s1.
  2. Step 2: Identify optimal approach

    Brute force (checking all substrings) is O(n*m) and inefficient. Dynamic programming is not suitable here as the problem is about frequency matching, not overlapping subproblems. Greedy fails because character order can differ. Sliding window with frequency map and match count optimization efficiently tracks character matches in O(n) time.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Sliding window with match count tracks matches in O(n) time [OK]
Hint: Sliding window with match count is O(n) and optimal [OK]
Common Mistakes:
  • Believing greedy or DP solves this efficiently
  • Thinking brute force is acceptable for large inputs
3. The following code attempts to count the number of subarrays with at most k odd numbers using a sliding window. Identify the line containing the subtle bug that causes incorrect results or inefficiency.
def countAtMost(nums, k):
    count = 0
    left = 0
    odd_count = 0
    for right in range(len(nums)):
        if nums[right] % 2 == 1:
            odd_count += 1
        while odd_count > k:
            if nums[left] % 2 == 1:
                odd_count -= 1
            left += 1
        count += right - left
    return count
medium
A. Line 14: count += right - left
B. Line 10: while odd_count > k:
C. Line 12: left += 1
D. Line 6: if nums[right] % 2 == 1: odd_count += 1

Solution

  1. Step 1: Understand counting formula

    Count should add number of subarrays ending at right with at most k odds, which is right - left + 1, not right - left.
  2. Step 2: Identify off-by-one error

    Using right - left misses counting the subarray where left == right, causing undercount.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct counting formula is right - left + 1 [OK]
Hint: Count subarrays ending at right = right - left + 1 [OK]
Common Mistakes:
  • Off-by-one in counting subarrays
  • Not breaking early when odd_count > k
  • Incorrectly updating odd_count
4. What is the time complexity of the optimal sliding window with count matching algorithm for finding all anagrams of p in s, where n = len(s) and m = len(p)?
medium
A. O(n), because the window slides once over s and frequency counts are updated in constant time.
B. O(n * m), because each window requires comparing frequency maps of size m.
C. O(n * 26), because frequency arrays of fixed size 26 are compared at each step.
D. O(n log m), due to sorting substrings during comparison.

Solution

  1. Step 1: Identify main loop operations

    The window slides over s once, so O(n) iterations.
  2. Step 2: Check frequency updates and comparisons

    Frequency counts are arrays of fixed size 26, updated in O(1) time; matches count updated in O(1).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sliding window with count matching is linear time [OK]
Hint: Fixed alphabet size makes frequency updates O(1) [OK]
Common Mistakes:
  • Assuming frequency map comparison is O(m)
  • Confusing n*m with n
  • Thinking sorting is involved
5. What is the time complexity of the optimal sliding window solution that uses a queue to track zero positions for the Max Consecutive Ones III problem, given an input array of length n and integer k?
medium
A. O(n * k) because each zero can cause multiple window shifts
B. O(n) because each element is visited at most twice by the two pointers
C. O(n^2) because the queue operations inside the loop cause nested behavior
D. O(k) because the queue size is limited to k zeros only

Solution

  1. Step 1: Identify loop behavior

    The right pointer iterates over all n elements once, and the left pointer only moves forward when zeros exceed k.
  2. Step 2: Analyze queue operations and pointer moves

    Each zero index is enqueued once and dequeued once, so total operations are O(n). However, each zero can cause the left pointer to move multiple times in worst case, leading to O(n * k) complexity.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    While the queue operations are O(n), the window shifts can multiply by k in worst cases [OK]
Hint: Consider worst-case window shifts caused by zeros [OK]
Common Mistakes:
  • Assuming strictly linear without considering multiple shifts
  • Confusing queue size with total operations
  • Ignoring worst-case scenarios
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard