Skip to content

Instantly share code, notes, and snippets.

View rejoycesong's full-sized avatar
🤗
just peachy

Joyce Song rejoycesong

🤗
just peachy
  • San Francisco
View GitHub Profile
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
seen = {}
for s in strs:
word = ''.join(sorted(s))
if word in seen:
seen[word].append(s)
# no runtime given, but O(n)
class Solution:
def countElements(self, arr: List[int]) -> int:
seen = set(arr)
return sum([1 if n+1 in seen else 0 for n in arr])
# 28ms with reduce; also O(n)
class Solution:
def countElements(self, arr: List[int]) -> int:
seen = set(arr)
# Recurse downwards with helper function, counting the number of nodes as you go
# Go back up the call stack, when you're at the middle, return the node.
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
def helper(head, count):
if not head:
return count
rest = helper(head.next, count + 1)
# stupid 10-minute, O(n) space solution bc andrew was hounding me for trying to go straight for the O(1) space solution
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
return self.process(S) == self.process(T)
# return the list of characters that are typed out in the end
def process(self, s: str) -> list:
curr_index, string = 0, []
for char in s:
# 56ms
class MinStack:
def __init__(self):
self.minHistory = [float('inf')]
self.stack = []
def push(self, x: int) -> None:
self.stack += [x]
if x <= self.minHistory[-1]:
self.minHistory.append(x)
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
shifted_amount = sum(i[1] if i[0] else -i[1] for i in shift) % len(s)
if shifted_amount == 0:
return s
else:
return s[-shifted_amount:] + s[:-shifted_amount]
# cleaner
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
num_rows, num_cols = binaryMatrix.dimensions()[0], binaryMatrix.dimensions()[1]
x, y, last_seen_1 = 0, num_cols-1, "butts"
while x < num_rows and y >= 0:
if binaryMatrix.get(x, y) == 1:
last_seen_1 = y
y -= 1
elif binaryMatrix.get(x, y) == 0:
@rejoycesong
rejoycesong / day1.py
Created December 1, 2021 05:17
aoc 2021 - day 1
input = open('input/day1.txt', 'r').readlines()
numbers = [int(line) for line in input]
# O(n)
def partOne(numbers=numbers):
count = 0
for i in range(1, len(numbers)):
if numbers[i] > numbers[i-1]:
count += 1
return count
input = open('input/day2.txt', 'r').readlines()
directions = [line for line in input]
# O(n)
def partOne(directions=directions):
horizontal = 0
depth = 0
for step in directions:
direction, val = step.split(" ", 1)
input = open('input/day3.txt', 'r').readlines()
strings = [list(line)[:-1] for line in input]
def partOne(strings=strings):
transposed = [*zip(*strings)]
gamma_string = ''.join([max(digit, key=digit.count) for digit in transposed])
epsilon_string = gamma_string.replace('0', 'q').replace('1', '0').replace('q', '1')
return int(gamma_string, 2)*int(epsilon_string, 2)
def partTwo(strings=strings):