MediumHash TableStringSliding Window

Find All Anagrams in a String

LeetCode
1 approach, code in all languages

Given two strings s and p, report the starting index of every substring of s that is an anagram of p, meaning it uses exactly the same letters with the same multiplicities as p.

The indices can be returned in any order, and an empty list is valid when no such substring exists.

Example 1

Input: s = "cbaebabacd", p = "abc"

Output: [0, 6]

The substrings starting at index 0 ("cba") and index 6 ("bac") are rearrangements of "abc".

Example 2

Input: s = "abab", p = "ab"

Output: [0, 1, 2]

Each window "ab", "ba", and "ab" is an anagram of "ab".

Constraints

  • 1 <= s.length, p.length <= 3 * 10^4
  • s and p consist of lowercase English letters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now