00:00

Problem Statement

Input/Output Examples

Visual Explanation

The letters that are not the most common one are exactly the letters that must be replaced. Keeping that number at or below k is the only condition the window has to satisfy.

Approaches

The first approach handles all letters in one window. The second runs a simpler window once for each possible target letter.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. The single window moves each pointer at most n times; the per-letter version repeats that for 26 letters, which is still linear.

Interview Tips and Recommended Approach

  • State the window rule clearly: windowLength - maxCount <= k.
  • Be ready to defend the stale maxCount. It is the subtle point interviewers ask about.
  • Offer the per-letter version first if unsure. It is easier to prove and still O(n) for a fixed alphabet.
  • Know the family: variable windows with a validity rule also solve the longest substring without repeats and the minimum window problems.

Recommended Approach: Sliding Window With Max Count

Why: it solves the problem in one linear pass with a 26-element array, and the window rule generalises to many other substring questions.