Skip to content

Instantly share code, notes, and snippets.

View kperath's full-sized avatar

Kunju Perath kperath

  • DigitalOcean
  • USA
View GitHub Profile
@kperath
kperath / trie.py
Last active April 23, 2023 19:18
Python Trie class - nicer than using just a map and $
class TrieNode:
def __init__(self):
self.children = {}
self.ref = 0 # number of references (ie. size of each map)
self.end = False
def add_word(self, word):
node = self
node.ref += 1
for c in word:
@kperath
kperath / heap.py
Created April 23, 2023 19:13
MinHeap and MaxHeap class in python so it's easy to use heaps without worry about when to negate the result for max heaps
class MaxHeap(list):
def __init__(self):
self = []
def push(self, n):
heapq.heappush(self, -n)
def pop(self):
return -heapq.heappop(self)
def peek(self):
return -self[0]
@kperath
kperath / wordsearch2.py
Last active April 23, 2023 01:25
My solution to wordsearch 2 on LC: https://leetcode.com/problems/word-search-ii/ a new test case was added that causes TLE for python unless words are removed from the trie which I show here.
class TrieNode:
def __init__(self):
self.children = {}
self.ref = 0 # number of references (ie. size of each map)
self.end = False
def add_word(self, word):
node = self
node.ref += 1
for c in word:
@kperath
kperath / topKFrequent.py
Created March 21, 2023 20:35
My old solutions to the "Top K Frequent Elements" problem on LeetCode: https://leetcode.com/problems/top-k-frequent-elements/
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# sorting
'''
nums_map = collections.Counter(nums)
return sorted(nums_map, key=nums_map.get)[-k:]
# Equivalent to: heapq.nlargest(k, nums_map.keys(), key=count.get)
'''
# heap way (equivalent to above)
'''