Skip to content

Instantly share code, notes, and snippets.

@jsgoller1
Last active May 4, 2018 06:53
Show Gist options
  • Save jsgoller1/887e77e44107f2e652fb0a3322200837 to your computer and use it in GitHub Desktop.
Save jsgoller1/887e77e44107f2e652fb0a3322200837 to your computer and use it in GitHub Desktop.
Examples (not completely tested) of places where I'd use collections during an interview
#!/usr//bin/python
from collections import *
"""
Question: "Write a function that left-shifts (or right-shifts) an array arr by n places."
Answer: Use a deque. Note that you can do this too with normal arrays, but when you get
asked about performance, deques have O(1) performance for popping or appending from
either side, and are as easy to use as normal arrays.
"""
def left_shift(arr, n):
d = deque(arr)
for i in range(n):
d.append(d.popleft())
return list(d)
def right_shift(arr, n):
d = deque(arr)
for i in range(n):
d.appendleft(d.pop())
return list(d)
"""
Question: "Given two words a and b, calculate the minimum number
of deletions required to make a and b anagrams; e.g. if a = 'aabbcc'
and b = 'ccddee', return 8 (remove 'aabb' from a and 'ddee' from b,
leaving both as 'bb')."
Answer: Use a counter. This question has a O(N^2) answer involving
comparing every letter in a to every letter in b, but by using hashing
you can create a O(N) solution, and counters make counting with hashable
objects super easy.
In the answer below, we count the number of chars a and b have in
common via the intersection operator &, and then we subtract that
from the length of a and the length of b, determining how many chars
they don't have in common and must be deleted.
"""
def min_deletions(a, b):
c = Counter(a)
d = Counter(b)
shared = sum((c & d).values())
return (len(a) - shared) + (len(b) - shared)
"""
Question: "Given a string S, and a list of letters L, return the indices in S at which
the letters in L occur."
Answer: This question can be answered in O(N^2) time by checking each letter in L against each
char in the string, but in O(N) with a defaultdict; a defaultdict is a dictionary
that uses a user-supplied type as the value to which keys are mapped.
"""
def indices(string, letters):
d = defaultdict(list)
for i in range(len(string)):
d[string[i]].append(i)
indices_dict = {}
for letter in letters:
indices_dict[letter] = d[letter]
return indices_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment