Practice: Data Structures Interview Questions
Q1. Count characters
Use Counter to print the two most common letters of 'mississippi' as a list of pairs.
Goal: Use Counter.
Q2. Remove duplicates keep order
Remove duplicates from [4, 1, 4, 2, 1, 3] while keeping the first-seen order and print the list.
Goal: Deduplicate with a dict.
Q3. Queue with deque
Create a deque with 1, 2, 3, add 4 at the end, remove the first item, and print the remaining deque as a list.
Goal: Use deque as a queue.
Q4. Group words by first letter
Group ['apple', 'avocado', 'banana', 'blueberry', 'cherry'] by first letter using defaultdict and print the result as a regular dict.
Goal: Use defaultdict.
Q5. Top three with a heap
Print the three largest numbers of [10, 50, 20, 40, 30] using heapq.
Goal: Use heapq.
Q6. Two-sum
Write two_sum(nums, target) using a dict that returns the indexes of the two numbers adding to target. Print the result for [3, 2, 4] and 6.
Goal: Solve two-sum.
Q7. Sort returns None
What does this print?
nums = [3, 1, 2]
result = nums.sort()
print(result)
print(nums)Goal: Know sort versus sorted.
Q8. Set operations
What does this print?
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a & b))
print(sorted(a - b))Goal: Use set operations.
Q9. Stable sort
What does this print?
pairs = [('b', 1), ('a', 1), ('c', 0)]
print(sorted(pairs, key=lambda p: p[1]))Goal: Understand stable sorting.
Q10. Dictionary get
What does this print?
d = {'a': 1}
print(d.get('b'))
print(d.get('b', 0))
print(len(d))Goal: Use dict.get.
Q11. Deque rotate
What does this print?
from collections import deque
d = deque([1, 2, 3, 4])
d.rotate(1)
print(list(d))Goal: Know deque methods.
Q12. Counter arithmetic
What does this print?
from collections import Counter
a = Counter('aab')
b = Counter('abc')
print(sorted((a + b).items()))Goal: Combine Counters.
Q13. Fix the list key
This code fails because a list is used as a dict key. Fix it so it prints 5.
grid = {}
grid[[1, 2]] = 5
print(grid[[1, 2]])Goal: Know hashable keys.
Q14. Fix the queue
This queue removes from the front with pop(0), which is slow for big queues. Rewrite it with deque so it prints 1.
queue = [1, 2, 3]
print(queue.pop(0))Goal: Choose deque for queues.
Q15. Choosing a structure
You must check millions of times whether a user id already exists in a collection of 100000 ids. Which structure do you choose and why?
Goal: Choose by cost.
Q16. Last N log lines
You need to keep only the last 3 lines read from a stream. Which structure fits and how do you create it?
Goal: Use bounded deque.