Skip to content

Commit 5646e68

Browse files
committed
adding algo
1 parent 80ec3ae commit 5646e68

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
from collections import Counter
4+
5+
class Solution:
6+
def minimumKeypresses(self, s: str) -> int:
7+
"""
8+
Greedy approach: Assign most frequent characters to 1-press slots
9+
10+
Example: s = "apple"
11+
Frequency: {'p': 2, 'a': 1, 'l': 1, 'e': 1}
12+
13+
Assignment:
14+
- 'p' (freq=2) → position 0 → 1 press → total: 2 * 1 = 2
15+
- 'a' (freq=1) → position 1 → 1 press → total: 1 * 1 = 1
16+
- 'l' (freq=1) → position 2 → 1 press → total: 1 * 1 = 1
17+
- 'e' (freq=1) → position 3 → 1 press → total: 1 * 1 = 1
18+
19+
Total: 2 + 1 + 1 + 1 = 5
20+
"""
21+
22+
# Count character frequencies
23+
freq = Counter(s)
24+
print(freq)
25+
26+
# Sort by frequency (descending) - greedy choice
27+
counts = sorted(freq.values(), reverse=True)
28+
print(counts)
29+
30+
total_presses = 0
31+
32+
# Calculate presses based on position
33+
for position, frequency in enumerate(counts):
34+
# Positions 0-8: 1 press (9 slots)
35+
# Positions 9-17: 2 presses (9 slots)
36+
# Positions 18-26: 3 presses (9 slots)
37+
presses_per_char = (position // 9) + 1
38+
total_presses += presses_per_char * frequency
39+
40+
return total_presses
41+
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def numberOfWays(self, s: str) -> int:
6+
"""
7+
Count valid 3-building selections forming "010" or "101" patterns.
8+
9+
Key insight: Track how many 2-character patterns we can form,
10+
then extend them with the appropriate third character.
11+
12+
Time: O(n), Space: O(1)
13+
"""
14+
count_0 = 0 # Count of '0' seen so far
15+
count_1 = 0 # Count of '1' seen so far
16+
count_01 = 0 # Count of "01" patterns (0 followed by 1)
17+
count_10 = 0 # Count of "10" patterns (1 followed by 0)
18+
19+
result = 0
20+
21+
for char in s:
22+
if char == '0':
23+
# Current '0' can complete "010": we need "01" before this '0'
24+
result += count_01
25+
26+
# Current '0' can start new "01" patterns: pair with each previous '0'
27+
# Wait no, "01" means 0 then 1, so we can't create "01" with another 0
28+
29+
# Current '0' extends all previous '1' to form "10" pattern
30+
count_10 += count_1
31+
32+
count_0 += 1
33+
else: # char == '1'
34+
# Current '1' can complete "101": we need "10" before this '1'
35+
result += count_10
36+
37+
# Current '1' extends all previous '0' to form "01" pattern
38+
count_01 += count_0
39+
40+
count_1 += 1
41+
42+
return result

0 commit comments

Comments
 (0)