Longest Single-Letter Substring After at Most k Character Changes
Company: Pinduoduo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Given a string of uppercase letters and a budget of at most k single-character changes, find the longest run of one repeated letter that can be produced. Tests reasoning about which substrings can be made uniform, efficient counting, and a near-linear solution for strings of up to 100,000 characters.
Read the full Pinduoduo Software Engineer interview experience this question came from
Constraints
- 1 <= len(s) <= 10^5
- s consists only of the uppercase letters 'A' to 'Z'.
- 0 <= k <= len(s)
Examples
Input: ('ABAB', 2)
Expected Output: 4
Explanation: Source example 1: change both B's (or both A's) so the whole string of length 4 is one letter.
Input: ('AABABBA', 1)
Expected Output: 4
Explanation: Source example 2: changing index 3 to B gives BBBB; every length-5 window needs 2 changes, so the window must shrink.
Hints
- Fix one substring. How many changes does it take to turn it into a single repeated letter, and which letter should you keep?
- A substring of length L can be made uniform exactly when L minus the count of its most common letter is at most k.
- Changing characters outside the substring you keep never helps, so you only need to reason about one contiguous range at a time.