Find All Anagrams in a String
Updated
Problem statement
Given two strings s and p, return the start indices (0-based) of every substring of s that is an anagram of p, in increasing order.
An anagram uses exactly the same letters with the same counts, in any order. A substring is a run of characters that are next to each other in s, so each answer is a window of length p.length. Windows may overlap. If there are none, return an empty array.
Function
findAnagrams(s: String, p: String) → List<Integer>Examples
Example 1
s = "cbaebabacd"p = "abc"return = [0,6]The window starting at 0 is cba and the window starting at 6 is bac; both use the letters a, b and c once each. No other window of length 3 does, so the answer is [0, 6].
Example 2
s = "abab"p = "ab"return = [0,1,2]The windows are ab (start 0), ba (start 1) and ab (start 2). All three are anagrams of ab, and windows may overlap.
Example 3
s = "ab"p = "abc"return = []p is longer than s, so no window fits and the answer is empty.
Constraints
1 <= s.length, p.length <= 2 * 10^4sandpconsist of lowercase English letters.
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Longest Substring Without Repeating CharactersSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Shortest Deletion for Distinct CharactersOracle · ONSITE INTERVIEWOracle interview questions
- Longest Substring Without Repeating CharactersGoogle · ONSITE INTERVIEWGoogle interview questions
- Longest Substring Without Repeating CharactersAmazon · ONSITE INTERVIEW
- Longest Substring Without Repeating CharactersInfosys · ONSITE INTERVIEWInfosys interview questions
- Longest Substring Without Repeating CharactersOmnissa · ONSITE INTERVIEWOmnissa interview questions
- Longest Substring with At Most K Distinct CharactersGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Longest Substring Without Repeating CharactersBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Sliding-Window Rate LimiterStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions
- Longest Substring Without Repeated CharactersDatadog · ONSITE INTERVIEWDatadog interview questions