Created
January 2, 2026 08:46
-
-
Save rtsoy/630865b48b08f4a2f361fb9dfad87a6b to your computer and use it in GitHub Desktop.
438. Find All Anagrams in a String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/find-all-anagrams-in-a-string/ | |
| // | |
| // Time: O(n) | |
| // Space: O(1) | |
| // | |
| // n - number of elements in array | |
| // .................... // | |
| func findAnagrams(s string, p string) []int { | |
| n := len(s) | |
| m := len(p) | |
| if n < m { | |
| return nil | |
| } | |
| target := [26]int{} | |
| for i := range m { | |
| idx := p[i] - 'a' | |
| target[idx]++ | |
| } | |
| key := [26]int{} | |
| res := make([]int, 0) | |
| for i := range m { | |
| idx := s[i] - 'a' | |
| key[idx]++ | |
| } | |
| if key == target { | |
| res = append(res, 0) | |
| } | |
| l, r := 0, m | |
| for r < n { | |
| key[s[l]-'a']-- | |
| key[s[r]-'a']++ | |
| l++ | |
| r++ | |
| if key == target { | |
| res = append(res, l) | |
| } | |
| } | |
| return res | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment