Skip to content

Commit 2ff17f6

Browse files
Merge pull request #16 from codewithme-py/feat/find-all-anagrams-in-a-string-0438
problem solution & test 0438
2 parents 3c39eed + d949239 commit 2ff17f6

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

problems_cache.json

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19293,5 +19293,35 @@
1929319293
"Count Subarrays With K Distinct Integers",
1929419294
"Hard",
1929519295
"count-subarrays-with-k-distinct-integers"
19296+
],
19297+
"4241": [
19298+
"Unique Email Groups",
19299+
"Medium",
19300+
"unique-email-groups"
19301+
],
19302+
"4247": [
19303+
"Minimum Capacity Box",
19304+
"Easy",
19305+
"minimum-capacity-box"
19306+
],
19307+
"4240": [
19308+
"Find the Smallest Balanced Index",
19309+
"Medium",
19310+
"find-the-smallest-balanced-index"
19311+
],
19312+
"4220": [
19313+
"Minimum Operations to Sort a String",
19314+
"Medium",
19315+
"minimum-operations-to-sort-a-string"
19316+
],
19317+
"4192": [
19318+
"Minimum Cost to Partition a Binary String",
19319+
"Hard",
19320+
"minimum-cost-to-partition-a-binary-string"
19321+
],
19322+
"4261": [
19323+
"Reverse K Subarrays",
19324+
"Medium",
19325+
"reverse-k-subarrays"
1929619326
]
1929719327
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from collections import Counter
2+
3+
4+
class Solution:
5+
def findAnagrams(self, s: str, p: str) -> list[int]:
6+
"""
7+
Finds all the initial anagram indexes of the p line in the s line.
8+
An anagram is a permutation of the letters of the string p.
9+
For example, 'ab' and 'ba' are anagrams.
10+
The algorithm uses a sliding window of fixed size len(p)
11+
And a dictionary for counting characters in the current window
12+
and in the reference line p.
13+
This allows you to compare the window with p for O(1) (on average),
14+
reaching Total time O(n), where n is the length of the string s.
15+
"""
16+
if len(p) > len(s):
17+
return []
18+
p_count, window_count, result = Counter(p), Counter(), []
19+
for i in range(len(s)):
20+
window_count[s[i]] += 1
21+
if i >= len(p):
22+
window_count[s[i - len(p)]] -= 1
23+
if window_count[s[i - len(p)]] == 0:
24+
del window_count[s[i - len(p)]]
25+
if window_count == p_count:
26+
result.append(i - len(p) + 1)
27+
return result
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
3+
from solutions.find_all_anagrams_in_a_string_0438 import Solution
4+
5+
6+
@pytest.mark.parametrize('s, p, expected', [
7+
('cbaebabacd', 'abc', [0, 6]),
8+
('abab', 'ab', [0, 1, 2]),
9+
('ab', 'ab', [0]),
10+
])
11+
def test_solution(s: str, p: str, expected: list[int]) -> None:
12+
sol = Solution()
13+
assert sol.findAnagrams(s, p) == expected

0 commit comments

Comments
 (0)