My Golang solution to the find all anagrams in a string problem.

438. Find All Anagrams in a String

https://leetcode.com/problems/find-all-anagrams-in-a-string/

Description

Given two strings s and target, return an array of all the start indices of target’s anagrams in s. You may return the answer in any order.

Example 1:

Input: s = "cbaebabacd", target = "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", target = "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".

Solution - Sliding Window with HashMap

func findAnagrams(s string, target string) []int {
sLen := len(s)
targetLen := len(target)
anagramIndexes := []int{}
if sLen < targetLen {
return anagramIndexes
}
targetCount := map[rune]int{}
for _, r := range target {
targetCount[r] = targetCount[r] + 1
}
sCount := map[rune]int{}
for i, r := range s {
sCount[r] = sCount[r] + 1
if i >= targetLen {
ch := rune(s[i-targetLen])
if sCount[ch] == 1 {
delete(sCount, ch)
} else {
sCount[ch] = sCount[ch] - 1
}
}
isAnagram := true
for c, numChars := range targetCount {
if numChars != sCount[c] {
isAnagram = false
break
}
}
if isAnagram {
anagramIndexes = append(anagramIndexes, i - targetLen + 1)
}
}
return anagramIndexes
}

Comments