Skip to content

Commit eed8a9a

Browse files
Merge pull request #16 from mihirs16/master
added leetcode questions
2 parents 3464565 + 70e886b commit eed8a9a

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# word pattern | leetcode 290 | https://leetcode.com/problems/word-pattern/
2+
# create a vocabulary to match pattern and a seen hashset to record seen words
3+
4+
class Solution:
5+
def wordPattern(self, pattern: str, s: str) -> bool:
6+
vocab = dict()
7+
seens = dict()
8+
sent = s.split(" ")
9+
10+
if len(sent) != len(pattern):
11+
return False
12+
13+
for i in range(len(pattern)):
14+
i_patt = pattern[i]
15+
i_sent = sent[i]
16+
17+
if vocab.get(i_patt):
18+
if vocab[i_patt] != i_sent:
19+
return False
20+
else:
21+
if seens.get(i_sent):
22+
return False
23+
vocab[i_patt] = i_sent
24+
seens[i_sent] = True
25+
26+
return True
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# top k frequency elements | leetcode 347 | https://leetcode.com/problems/top-k-frequent-elements/
2+
# use buckets with each bucket being the frequency of an element
3+
4+
from collections import Counter
5+
6+
class Solution:
7+
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
8+
freq = Counter(nums)
9+
N = len(nums)
10+
11+
# create buckets where index = frequency of element
12+
buckets = [[] for x in range(N + 1)]
13+
for f in freq:
14+
buckets[freq[f]].append(f)
15+
16+
# get k elements starting from the end of the bucket
17+
k_mf = []
18+
for x in buckets[::-1]:
19+
if k > 0:
20+
if x != []:
21+
k_mf += x
22+
k -= len(x)
23+
else:
24+
return k_mf
25+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# group anagrams | leetcode 49 | https://leetcode.com/problems/group-anagrams/
2+
# method: dictionary with char counter as key
3+
4+
from collections import defaultdict
5+
6+
class Solution:
7+
def groupAnagrams(self, strs):
8+
grouped = defaultdict(list)
9+
10+
for each_word in strs:
11+
count_of_ch = [0] * 26
12+
for each_ch in each_word:
13+
count_of_ch[ord(each_ch) - ord("a")] += 1
14+
grouped[tuple(count_of_ch)].append(each_word)
15+
16+
return grouped.values()

0 commit comments

Comments
 (0)