๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Data Structures and Algorithms for Python Interviews

Python InterviewCore Conceptsโญ Premium
Python Interview ยท Difficulty: Medium-Hard

The one mental model that carries the whole interview

Every data-structure question in a Python interview eventually reduces to one decision: which built-in container gives you the access pattern the problem needs, and what does that choice cost? Lists give you fast indexed access and slow middle insertions. Dicts and sets give you near-constant lookups at the price of extra memory and unordered iteration. Tuples and strings are immutable, which makes them safe to share but expensive to rebuild. Interviewers are not usually testing whether you can recite Big-O notation โ€” they are watching whether you pick the right container on the first try and then stay consistent about the complexity you claimed.

Prerequisites

  • !Basic Python syntax, loops, and functions
  • !Time complexity basics (O(1), O(n), O(log n))

What You'll Learn

  • 1Explain why a Python list is a dynamic array and what amortization means for append
  • 2Apply the two-pointer and sliding-window patterns to array and string problems
  • 3Choose between dict, set, Counter, and defaultdict under interview pressure
  • 4Implement min-stack, monotonic stack, and BFS/DFS from memory

Lists are dynamic arrays โ€” and that is the whole story

When an interviewer hands you a list problem, the first thing to internalize is that a Python list is a contiguous array of pointers with over-allocation. Appending to the end is amortized O(1): the interpreter usually has spare capacity, and only occasionally pays for a full resize and copy. Inserting or deleting in the middle is O(n) because every later element must shift. Indexing is O(1). Slicing creates a new list, so nums[k:] costs O(nโˆ’k) time and memory โ€” a detail that matters when you recursively slice large inputs.

This mental model immediately rules out bad approaches. If the problem asks you to remove duplicates from a sorted list in place, you should reach for a write-pointer that overwrites earlier positions rather than popping elements, because pop(0) is O(n) per call. If the problem asks you to flatten nested lists, you should decide up front whether you want a fully materialized result or a lazy generator that yields items one at a time โ€” the generator version runs in O(1) extra memory for the result structure, which interviewers love to see.

Two classic array problems share one skeleton. The two-pointer technique walks inward from both ends of a sorted list: if the current sum is too small, advance the left pointer; if too large, retreat the right pointer. Each step eliminates a range of impossible pairs, so the whole scan is O(n) with O(1) extra space. The same idea powers in-place deduplication, palindrome checks, and container-with-most-water style questions. When the list is not sorted, the alternative is a hash map that records each value's index, turning the search for a complement into O(1) lookups โ€” the classic trade of space for time.

python
def two_sum_sorted(nums, target):
    """Two pointers over a sorted list: O(n) time, O(1) space."""
    left, right = 0, len(nums) - 1
    while left < right:
        current = nums[left] + nums[right]
        if current == target:
            return [left, right]
        if current < target:
            left += 1
        else:
            right -= 1
    return []


def dedupe_sorted(nums):
    """Remove duplicates in place from a sorted list."""
    if not nums:
        return 0
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write += 1
    return write

Hash tables: dict, set, Counter, and defaultdict

Dictionaries in CPython are hash tables with open addressing. Average-case lookup, insert, and delete are all O(1); the worst case, when every key collides, degrades to O(n), but you should not worry about that in an interview unless the problem is specifically about adversarial keys. The practical consequences are worth stating out loud: keys must be hashable (strings, numbers, tuples of hashables โ€” never lists or dicts), iteration order follows insertion order since Python 3.7, and membership tests on a set are faster than on a list once the collection grows past a few dozen elements.

Most "count the frequency" problems collapse into collections.Counter. Most "have I seen this before" problems collapse into a set. Most "group things that belong together" problems collapse into a defaultdict(list), which avoids the three-line dance of checking whether a key exists before appending. Interviewers notice when you reach for these tools without hesitation โ€” it signals production experience rather than textbook rehearsal.

A slightly subtler hash-table problem is string encoding and decoding: turn a list of arbitrary strings into one string and back. The robust approach is length-prefix encoding, writing the length, a delimiter, then the payload. It works even when payloads contain the delimiter or span multiple lines, unlike naive joins.

Stacks, queues, and the monotonic-stack trick

Stacks and queues are rarely asked as "implement a stack" questions anymore; instead they appear as the invisible structure inside a harder problem. Valid parentheses is the canonical stack exercise, but the pattern that pays the rent is the monotonic stack: keep the stack sorted so that each element is pushed once and popped once, turning nested loops into a single O(n) pass. The next-greater-element family โ€” daily temperatures, largest rectangle in a histogram, online stock span โ€” is all the same trick with different framing.

The min-stack variant is worth memorizing because it tests whether you understand the cost of scanning for a minimum. Pair every push onto the main stack with a conditional push onto a helper stack that records running minima; popping synchronizes the two. Every operation stays O(1).

python
class MinStack:
    """Stack that reports the current minimum in O(1)."""

    def __init__(self):
        self._data = []
        self._mins = []

    def push(self, value):
        self._data.append(value)
        if not self._mins or value <= self._mins[-1]:
            self._mins.append(value)

    def pop(self):
        value = self._data.pop()
        if value == self._mins[-1]:
            self._mins.pop()
        return value

    def get_min(self):
        return self._mins[-1]


def next_greater(nums):
    """Monotonic stack: index of the next strictly greater element."""
    result = [-1] * len(nums)
    stack = []
    for i, value in enumerate(nums):
        while stack and value > nums[stack[-1]]:
            result[stack.pop()] = value
        stack.append(i)
    return result

Trees and graphs without panicking

Tree and graph problems intimidate candidates because the shape is unfamiliar, but the traversal toolkit is small. Breadth-first search uses a deque and explores level by level โ€” the right choice for shortest-path questions in unweighted graphs and for level-order output. Depth-first search uses an explicit stack or recursion and is the right choice for connectivity, cycle detection, and any problem that asks about paths or subtrees. Both run in O(V + E) time with O(V) space for the visited set.

For binary search trees specifically, remember the invariant: everything in the left subtree is strictly smaller and everything in the right subtree is strictly larger, so validation must carry down a min/max range rather than only checking local parent-child pairs. Lowest common ancestor in a BST is a walk: descend while both targets sit on the same side of the current node; the first node where they diverge is the answer. Topological sort, when courses or tasks have prerequisites, is Kahn's algorithm: compute in-degrees, repeatedly emit nodes with in-degree zero, and fail if you cannot emit every node โ€” that failure is exactly cycle detection.

python
from collections import defaultdict, deque


def bfs(graph, start):
    """Level-by-level traversal: O(V + E) time."""
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return order


def topological_sort(graph):
    """Kahn's algorithm; raises ValueError on a cycle."""
    in_degree = defaultdict(int)
    nodes = set(graph)
    for node in graph:
        for neighbor in graph[node]:
            in_degree[neighbor] += 1
            nodes.add(neighbor)
    queue = deque(n for n in nodes if in_degree[n] == 0)
    result = []
    while queue:
        node = queue.popleft()
        result.append(node)
        for neighbor in graph[node]:
            in_degree[neighbor] -= 1
            if in_degree[neighbor] == 0:
                queue.append(neighbor)
    if len(result) != len(nodes):
        raise ValueError("graph has a cycle")
    return result

Choosing a structure under time pressure

When the interviewer changes the constraint mid-question โ€” "what if the input no longer arrives sorted?" โ€” your container choice may need to change with it. The table below compresses the decision logic most candidates wish they had on the whiteboard.

Problem signalFirst container to reach forTypical complexityWatch out for
Indexed access, append at endlistO(1) amortized appendO(n) middle insert
Frequency countingCounter or dictO(n) time, O(k) spaceunhashable keys
"Seen it before" checkssetO(1) lookuplosing insertion order
Matching pairs, nestinglist used as stackO(n) totalforgetting the empty-stack check
Shortest path, unweighteddict adjacency + dequeO(V + E)marking visited too late
Ordered unique elementsdict keys or sorted listO(n log n) sortset has no order

Follow-up drills that separate strong candidates

Practice explaining your container choice before you type anything. Then drill the mutations: what happens to indices when you insert at the front, what happens to iterators when you modify a dict during iteration, why set and dict membership tests beat list scans, and how you would find the first duplicate in a stream of numbers with a fixed memory budget. Strong candidates also narrate edge cases โ€” empty input, single element, all duplicates, already-sorted versus reverse-sorted โ€” before writing the happy path.

Common Mistakes

Reaching for a list to store a growing set of seen values and scanning it with 'in'

Fix: Use a set; membership tests are O(1) average instead of O(n)

Recursively slicing lists inside a loop and calling it O(n)

Fix: Pass indices or use itertools.islice so you never copy the list

Validating a BST by only comparing each node with its direct parent

Fix: Thread a min/max range down the recursion; distant ancestors constrain distant descendants

Marking a graph node visited when it is dequeued instead of when it is enqueued

Fix: Mark on enqueue in BFS to avoid pushing the same node many times

Best Practices

  • State the complexity of your chosen approach before writing code, then stay honest about it
  • Name the pattern out loud โ€” two pointers, monotonic stack, BFS, topological sort โ€” so the interviewer can steer you
  • Write the empty-input and single-element cases first; they expose off-by-one bugs immediately
  • Prefer the standard library (deque, Counter, defaultdict, bisect) unless the question explicitly asks you to implement the structure yourself

Interview Questions

Q1: Why is appending to a Python list O(1) even though it sometimes has to resize?

CPython over-allocates capacity. Resizes are rare and amortized across many appends, so the average cost per append is constant even though a single resize is O(n).

Q2: Two Sum on an unsorted list versus a sorted list โ€” which structures do you use and why?

Unsorted: one pass with a dict from value to index, O(n) time and space. Sorted: two pointers from both ends, O(n) time and O(1) space, because the sorted order lets each comparison eliminate a whole side.

Q3: How do you detect a cycle in a linked list in O(1) space?

Floyd's tortoise-and-hare: advance a slow pointer by one and a fast pointer by two. If they ever meet, a cycle exists; if the fast pointer falls off the end, it does not.

Q4: When is BFS preferable to DFS?

BFS when edge weights are uniform and you want shortest paths or level-order results; DFS when you need to explore deep paths, detect cycles with colors, or enumerate combinations. Both are O(V + E).

Q5: Explain consistent hashing and why virtual nodes matter.

Keys and nodes are hashed onto a ring; a key belongs to the next node clockwise. Virtual nodes spread each physical node across many ring positions, giving more even load distribution and smaller key movement when a node joins or leaves.

Key Takeaways

  • A Python list is a dynamic array: O(1) indexing and amortized append, O(n) middle insert
  • Two pointers solves sorted-array problems in place; a hash map solves the unsorted versions
  • Counter, defaultdict, and set are the three tools that dissolve most frequency and grouping questions
  • Monotonic stacks turn nested next-greater loops into a single O(n) pass
  • BFS for level order and unweighted shortest paths; DFS for connectivity, cycles, and backtracking
  • Always narrate your container choice and its complexity before you start coding
๐Ÿ”’

Premium Content

Data Structures and Algorithms for Python Interviews

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement