Practice: Data Structures Interview Questions

« Read the chapter

Q1. Count characters

BeginnerCoding

Use Counter to print the two most common letters of 'mississippi' as a list of pairs.

Goal: Use Counter.

Q2. Remove duplicates keep order

BeginnerCoding

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

IntermediateCoding

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

IntermediateCoding

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

IntermediateCoding

Print the three largest numbers of [10, 50, 20, 40, 30] using heapq.

Goal: Use heapq.

Q6. Two-sum

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
nums = [3, 1, 2]
result = nums.sort()
print(result)
print(nums)

Goal: Know sort versus sorted.

Q8. Set operations

BeginnerOutput

What does this print?

Code
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a & b))
print(sorted(a - b))

Goal: Use set operations.

Q9. Stable sort

IntermediateOutput

What does this print?

Code
pairs = [('b', 1), ('a', 1), ('c', 0)]
print(sorted(pairs, key=lambda p: p[1]))

Goal: Understand stable sorting.

Q10. Dictionary get

BeginnerOutput

What does this print?

Code
d = {'a': 1}
print(d.get('b'))
print(d.get('b', 0))
print(len(d))

Goal: Use dict.get.

Q11. Deque rotate

IntermediateOutput

What does this print?

Code
from collections import deque
d = deque([1, 2, 3, 4])
d.rotate(1)
print(list(d))

Goal: Know deque methods.

Q12. Counter arithmetic

AdvancedOutput

What does this print?

Code
from collections import Counter
a = Counter('aab')
b = Counter('abc')
print(sorted((a + b).items()))

Goal: Combine Counters.

Q13. Fix the list key

IntermediateDebugging

This code fails because a list is used as a dict key. Fix it so it prints 5.

Code
grid = {}
grid[[1, 2]] = 5
print(grid[[1, 2]])

Goal: Know hashable keys.

Q14. Fix the queue

IntermediateDebugging

This queue removes from the front with pop(0), which is slow for big queues. Rewrite it with deque so it prints 1.

Code
queue = [1, 2, 3]
print(queue.pop(0))

Goal: Choose deque for queues.

Q15. Choosing a structure

IntermediateConceptual

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

AdvancedApplication

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.