Skip to content

added leetcode questions #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions 14. Questions/leetcode 290 - word pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# word pattern | leetcode 290 | https://leetcode.com/problems/word-pattern/
# create a vocabulary to match pattern and a seen hashset to record seen words

class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
vocab = dict()
seens = dict()
sent = s.split(" ")

if len(sent) != len(pattern):
return False

for i in range(len(pattern)):
i_patt = pattern[i]
i_sent = sent[i]

if vocab.get(i_patt):
if vocab[i_patt] != i_sent:
return False
else:
if seens.get(i_sent):
return False
vocab[i_patt] = i_sent
seens[i_sent] = True

return True
25 changes: 25 additions & 0 deletions 14. Questions/leetcode 347 - top k frequent elements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# top k frequency elements | leetcode 347 | https://leetcode.com/problems/top-k-frequent-elements/
# use buckets with each bucket being the frequency of an element

from collections import Counter

class Solution:
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
freq = Counter(nums)
N = len(nums)

# create buckets where index = frequency of element
buckets = [[] for x in range(N + 1)]
for f in freq:
buckets[freq[f]].append(f)

# get k elements starting from the end of the bucket
k_mf = []
for x in buckets[::-1]:
if k > 0:
if x != []:
k_mf += x
k -= len(x)
else:
return k_mf

16 changes: 16 additions & 0 deletions 14. Questions/leetcode 49 - group anagrams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# group anagrams | leetcode 49 | https://leetcode.com/problems/group-anagrams/
# method: dictionary with char counter as key

from collections import defaultdict

class Solution:
def groupAnagrams(self, strs):
grouped = defaultdict(list)

for each_word in strs:
count_of_ch = [0] * 26
for each_ch in each_word:
count_of_ch[ord(each_ch) - ord("a")] += 1
grouped[tuple(count_of_ch)].append(each_word)

return grouped.values()