438 Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams ins.
Strings consists of lowercase English letters only and the length of both stringssandpwill not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".Example 2:
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".The Idea
This is probably the most creative solution I've come up with for a leetcode problem. I also think it has the potential to beat top submissions given a few optimizations, and perhaps no account on the preprocessing step of performing a uniform distribution.
My first thought was simply iterate through the string, and sum together the integers. e.g.
This works because of the associative property of addition.
But the main problem with this is that multiple permutation sums can produce the same key identifier. Consider:
So to avoid this, why won't develop our own random mapping for the alphabet? The greater our bounds for a random number, the less likely it is that the sum of a word will equal the sum of another word, unless every single character in the word hashes the exact location. We can produce use a uniform distribution to that every number without the bounds of our range has an equal probability of becoming selected. Finally, we perform the same algorithm as above.
solution with constant space. (too slow)
Last updated
Was this helpful?