InterviewLegend

Find All Anagrams in a String

Alex Chen25 min readMedium

Slide a length-three window across "cbaebabacd" and only two of its eight stops spell an anagram of "abc". The one new idea here is what rides inside that window: a character frequency map instead of a running sum. Get that map to update in O(1) as the window moves and the whole problem falls out of the mechanics you already have.

Problem: Given a string s and a pattern p, find all starting indices where an anagram of p exists in s.

Example: s = "cbaebabacd", p = "abc" → [0, 6] because "cba" and "bac" are anagrams of "abc".
What's inside
  • 1 problem, worked step by step
  • 2 diagrams
  • about 25 min

Premium lessonData Structures & Algorithms

Keep going with Premium.

All 78 lessons and 103 worked problems in this course, plus what 100 companies ask, pulled from 20,000+ candidate reports.

100 companies. Checked every month.

Unlock the full course

$49 a year · less than $1 a week · Cancel anytime