Magicsheet logo

Find K-Length Substrings With No Repeated Characters

Medium
25%
Updated 8/1/2025

Asked by 1 Company

Find K-Length Substrings With No Repeated Characters

What is this problem about?

In the Find K-Length Substrings With No Repeated Characters coding problem, you are given a string and an integer kk. You need to count how many substrings of length kk consist of entirely unique characters. If kk is larger than the length of the string or the alphabet size (26), the answer is zero.

Why is this asked in interviews?

Amazon frequently uses this to test a candidate's proficiency with the Sliding Window interview pattern. It evaluations whether you can efficiently maintain a character frequency state as you slide through a string. It’s a "clean" problem that checks if you can avoid O(nimesk)O(n imes k) brute force by using a Hash Table or a frequency array to perform updates in O(1)O(1) per character.

Algorithmic pattern used

This problem uses a Fixed-size Sliding Window with a Hash Table (or frequency array).

  1. Initialize a frequency array of size 26 and a uniqueCount variable.
  2. Build the first window of size kk.
  3. If uniqueCount == k, the window is valid.
  4. Slide the window one character at a time:
    • Add the incoming character: update frequency and uniqueCount.
    • Remove the outgoing character: update frequency and uniqueCount.
    • Check if the window is valid.

Example explanation

s = "havefunonleetcode", k = 5

  1. Window 1: "havef". All unique. Count = 1.
  2. Window 2: "avefu". All unique. Count = 2.
  3. ...
  4. Window "unonl": 'n' is repeated. Not valid. ... and so on.

Common mistakes candidates make

  • Re-calculating uniqueness: Using a Set to check every substring from scratch (O(nimesk)O(n imes k)).
  • Alphabet Constraint: Not realizing that if k>26k > 26, the result must be 0 (Pigeonhole Principle).
  • Hash Map overhead: Using a heavy Map object when a simple int[26] array would be much more performant.

Interview preparation tip

Always look for the "fixed-size" hint in sliding window problems. If the window size is constant, the logic is simpler than dynamic windows, but you must be precise with adding/removing elements simultaneously.

Similar Questions