Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Every place an anagram begins

Medium · Target 20 minutes · Sliding window· Type asked at

Given lowercase strings s and p, return every index i such that the substring of s starting at i with length |p| is an anagram of p: the same letters, each the same number of times. Return the indices in increasing order.

Examples

InputOutputWhy
s = "cbaebabacd", p = "abc"[0, 6]"cba" at 0 and "bac" at 6.
s = "abab", p = "ab"[0, 1, 2]"ab", "ba", "ab".
s = "hello", p = "xyz"[]No window matches.

Constraints

  • 1 ≤ |s|, |p| ≤ 3 × 10⁴
  • s and p are lowercase English letters

Hints

Hint 1

Two strings are anagrams exactly when their letter counts agree. Every window has the same length as p.

Hint 2

Moving the window changes two counts. Comparing all 26 counts each time works; can you avoid even that?

Hint 3

Keep need[c] = count of c in p minus count of c in the window, and the number of letters where need[c] ≠ 0. The window matches when that number is 0.

Where people lose marks

  • Returning early when p is longer than s is correct, but forgetting it makes some languages index out of range.
  • Updating off after changing the count instead of comparing the old and new values.
  • Sorting every window: O(|s| · |p| log |p|).
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.