Find All Anagrams In A String

Problem statement

Locate every start index in s where a substring is an anagram of p. Return those indices (any order is fine unless a judge checks sorted order).

Example:

Input:

s = "cbaebabacd", p = "abc"

Expected output:

[0, 6]

Why: "cba" and "bac" match p’s letter multiset.

Practice on LeetCode: Find All Anagrams in a String

Golang Solution

func findAnagrams(s string, p string) []int {
    
    var result []int

    if len(p) > len(s) {
        return result
    }
    
    countS := make([]int, 26)
    countP := make([]int, 26)

    for i:=0; i<len(p); i++ {
        countS[int(s[i]-'a')]++
        countP[int(p[i]-'a')]++
    }

    start := 0
    end := len(p)

    if fmt.Sprint(countS) == fmt.Sprint(countP) {
        result = append(result, start)
    }

    for end < len(s) {
        countS[int(s[start]-'a')]--
        countS[int(s[end]-'a')]++

        if fmt.Sprint(countS) == fmt.Sprint(countP) {
            result = append(result, start+1)
        }

        start++
        end++
    }

    return result
}