Find All Anagrams in a String

Quick Overview

Given strings s and p, find all start indices of p's anagrams in s. Tests sliding window with character frequency counting, a common Google phone screen question.

Google
Coding & Algorithms
Software Engineer
Google
Software Engineer
Phone Screen
Coding & Algorithms
Medium

0


Given strings s and p, find all start indices of p's anagrams in s. Tests sliding window with character frequency counting, a common Google phone screen question.

This is a common Google phone screen question that checks whether you can maintain a fixed-size sliding window with character counts instead of re-sorting every substring. The interviewer is watching for an O(n) solution, correct window bookkeeping and clean code in a shared editor.

What the Interviewer Expects
  • Recognize that anagrams share the same character frequency counts
  • Keep a fixed-length window over s and update counts in O(1) per step
  • Compare window counts with p's counts (or track a match counter) to detect anagrams
  • State O(n) time and O(1) space for a fixed alphabet
  • Handle len(p) > len(s) and repeated characters correctly
Key Topics to Cover
Sliding window
Character frequency counting
Hash maps
Anagram detection
String processing
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you avoid comparing two full count maps at every step?
  • What changes if the alphabet is all of Unicode?
  • How would you handle a stream where s arrives one character at a time?
  • How would you return the anagram substrings grouped by the distinct permutation they match?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

To solve the problem of finding all start indices of anagrams of string p in string s, we can utilize the sliding window technique combined with character frequency counting. This approach...

Approach
  1. Initialize: Create a frequency count for the string p using a dictionary (or array) to store the count of each character.
  2. Setup Sliding Window: Create a sliding window of the same leng...

Submit Your Answer
Markdown supported