Advanced   Chapter 189 · 30 min read · Module 15: Career and Interview Preparation

Data Structures Interview Questions

Learning objectives
  • After this chapter you can pick the right built-in data structure for a task and explain why.
  • You can state the time cost of common list, dict and set operations.
  • You can build a stack and a queue the efficient way with `list` and `collections.deque`.
  • You can use `Counter`, `defaultdict` and `heapq` to solve typical interview problems.
  • You can explain how sorting works in Python and what makes a sort stable.

Data structure questions are the core of most coding interviews. The interviewer wants to see that you can choose a tool that fits the problem and that you know what each operation costs. Python gives you lists, tuples, dictionaries and sets out of the box, and the standard library adds deque, Counter, defaultdict and heapq.

This chapter covers the structures and the questions that go with them. For each one you will see how it is stored, what is fast, what is slow, and a short example. Knowing the cost of an operation lets you say things like 'a set lookup is constant time on average, so I will use a set here'.

Read the examples, run them, and then change them. Interview answers feel natural when you have tried the code yourself.

Lists and tuples

A list is an ordered, mutable sequence stored as a dynamic array. Reading or writing an item by index is constant time. Appending to the end is fast on average. Inserting or deleting at the front or middle is slow because the items after it must shift, which costs time proportional to the length. Searching with in checks items one by one, so it is linear. A tuple is an ordered, immutable sequence. It is lighter than a list and its items can act as dictionary keys when every item is hashable.

Example 1: List operations
nums = [5, 3, 8]
nums.append(1)
nums.insert(0, 9)
print(nums)
print(nums.pop())
print(nums.pop(0))
print(nums[-1], nums[1:3])
print(8 in nums)
[9, 5, 3, 8, 1] 1 9 8 [3, 8] True

Dictionaries and sets

A dictionary maps keys to values using a hash table. Looking up, adding or removing a key takes constant time on average. Keys must be hashable, which means immutable types such as strings, numbers and tuples of hashable items. Since Python 3.7 a dict remembers insertion order. A set stores unique hashable items, also in a hash table, so membership tests with in are constant time on average. Sets support union, intersection and difference.

StructureIndex / lookupAdd at endInsert at frontMembership (in)
listO(1)O(1) averageO(n)O(n)
dictO(1) averageO(1) averagenot applicableO(1) average
setnot applicableO(1) averagenot applicableO(1) average
dequeO(n) in middleO(1)O(1)O(n)
Example 2: Dict and set basics
stock = {'apple': 3, 'pear': 0}
stock['plum'] = 7
print(stock.get('kiwi', -1))
print(list(stock))

a = {1, 2, 3}
b = {3, 4}
print(sorted(a | b), a & b, sorted(a - b))
-1 ['apple', 'pear', 'plum'] [1, 2, 3, 4] {3} [1, 2]

Stacks and queues

A stack is last in, first out. A Python list works well: append pushes and pop removes the top, both fast. A queue is first in, first out. Using list.pop(0) for a queue is slow because every other item shifts. The right tool is collections.deque, which adds and removes at both ends in constant time. Interviewers often ask for a balanced-brackets check using a stack, or a breadth-first search using a queue.

Example 3: Stack and queue
from collections import deque

stack = []
stack.append('a')
stack.append('b')
print(stack.pop())

queue = deque(['x', 'y'])
queue.append('z')
print(queue.popleft())
print(list(queue))
b x ['y', 'z']
Example 4: Balanced brackets with a stack
def balanced(text):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in text:
        if ch in '([{':
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

print(balanced('{[()]}'))
print(balanced('(]'))
print(balanced('(('))
True False False

Counter, defaultdict and heapq

Counter counts hashable items and is perfect for frequency questions. defaultdict creates a missing value automatically, which removes the need for an if key not in d check when grouping. heapq gives a min-heap on top of a list: heappush and heappop take logarithmic time, and nlargest or nsmallest find the top few items. A heap is the standard answer for 'find the k largest items' or 'always take the smallest next'.

Example 5: Counting and grouping
from collections import Counter, defaultdict

words = ['tea', 'eat', 'cat', 'ate', 'act']
print(Counter('banana').most_common(2))

groups = defaultdict(list)
for w in words:
    groups[''.join(sorted(w))].append(w)
print(list(groups.values()))
[('a', 3), ('n', 2)] [['tea', 'eat', 'ate'], ['cat', 'act']]
Example 6: A heap
import heapq

scores = [42, 7, 19, 88, 3]
heapq.heapify(scores)
print(heapq.heappop(scores))
print(heapq.nlargest(2, [42, 7, 19, 88, 3]))
3 [88, 42]

Sorting and complexity

Python's sorted() and list.sort() use an algorithm called Timsort. It takes O(n log n) time in the worst case and is stable, which means items that compare equal keep their original order. Stability lets you sort by several keys by sorting in steps, or by returning a tuple from the key function. sorted() returns a new list, while sort() changes the list in place and returns None. Big-O notation describes how the running time grows with the input size, and interviewers expect you to state it for your solution.

Example 7: Sorting with keys
people = [('Ravi', 30), ('Asha', 25), ('Meena', 30)]
print(sorted(people, key=lambda p: p[1]))
print(sorted(people, key=lambda p: (-p[1], p[0])))
[('Asha', 25), ('Ravi', 30), ('Meena', 30)] [('Meena', 30), ('Ravi', 30), ('Asha', 25)]
Tip: say the cost of your plan out loud. 'I will turn the list into a set first, which is O(n), and then each lookup is O(1).'

Typical interview patterns

  • Two-sum: store seen numbers in a dict so each lookup is constant time instead of a nested loop.
  • Remove duplicates: use a set, or dict.fromkeys(items) to keep the order.
  • Find the most common item: use Counter.most_common.
  • Check anagrams: compare sorted strings or two Counter objects.
  • Reverse or palindrome checks: slicing with [::-1] is short and clear.
Example 8: Two-sum and ordered duplicates
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return seen[target - n], i
        seen[n] = i
    return None

print(two_sum([2, 7, 11, 15], 9))
print(list(dict.fromkeys([3, 1, 3, 2, 1])))
(0, 1) [3, 1, 2]

Python syntax

Syntax
from collections import deque, Counter, defaultdict
q = deque()
q.append(x); q.popleft()
Syntax
import heapq
heapq.heappush(h, x)
heapq.heappop(h)
Syntax
sorted(items, key=lambda x: (x[1], x[0]), reverse=False)

Real-world applications

  • Counting words and events in logs with Counter
  • Using a deque as a work queue in a breadth-first search
  • Using a dict for fast lookups in caches and indexes
  • Using a heap for scheduling and top-k results
  • Using sets to remove duplicates and compare groups

Common mistakes

Mistake: Using list.pop(0) as a queue
Fix: Use collections.deque and popleft() for constant-time removal from the front.
Mistake: Checking membership in a large list inside a loop
Fix: Convert the list to a set once, then use in on the set.
Mistake: Using a list as a dictionary key
Fix: Lists are not hashable. Use a tuple instead.
Mistake: Writing x = nums.sort() and getting None
Fix: sort() works in place and returns None. Use sorted(nums) if you need a new list.
Mistake: Modifying a list while looping over it
Fix: Loop over a copy or build a new list with a comprehension.

Important tips

  • Name the structure and its cost when you explain a choice.
  • Start with a simple brute-force idea, then improve it with a dict or set.
  • Use Counter and defaultdict to keep code short and readable.
  • Test with an empty input and a single item before saying you are done.

Key points summary

  • List: ordered, mutable, fast index and append, slow insert at front.
  • Dict and set: hash tables with constant average lookup.
  • Keys and set items must be hashable.
  • Use deque for queues and a list for stacks.
  • heapq gives a min-heap; Timsort is stable and O(n log n).

Exam and interview points

  • Give the average cost of list append, list insert at index 0, dict lookup and set membership.
  • Explain why dict keys must be hashable.
  • Show how to implement a queue efficiently.
  • Explain what makes Timsort stable and why it matters.
  • Describe how to find the k largest items.

Quick revision

  • List insert at front is O(n); dict and set lookup is O(1) average.
  • Stack: list append/pop. Queue: deque append/popleft.
  • Counter counts, defaultdict groups, heapq gives smallest first.
  • sorted() returns new; sort() returns None.
  • Lists cannot be dict keys; tuples can.

Frequently asked questions

Why is a set lookup faster than a list lookup?

A set uses a hash table, so Python jumps straight to where the item should be. A list must compare items one at a time until it finds a match.

Are dictionaries ordered?

Yes. Since Python 3.7 dictionaries remember the order in which keys were inserted. This is part of the language.

What is the difference between a list and a tuple?

A list can change after creation, a tuple cannot. Tuples are lighter and can be dictionary keys if their items are hashable.

What does stable sorting mean?

If two items compare equal, they stay in the same relative order after sorting. This is useful when sorting by one key after another.

How do I get a max-heap with heapq?

heapq only gives a min-heap. A common trick is to push the negative of each number and negate again when popping.

Practise this chapter

16 practice questions Take the chapter quiz

Related chapters