Python Course · Data structures lesson
Python Coding Interview Basics: Data Structures and Complexity
Compare Python lists, sets, dictionaries and strings with a runnable membership example and complexity table.
Learn the pattern, trace runnable code, and test an edge case.
Core idea
Choose the collection by the operation you perform most.
set: membership
dict: key → value
The direct answer
Choose a Python structure by its operations and constraints.
Lists preserve order and support indexed access. Sets hold distinct hashable values and are useful for membership. Dictionaries associate hashable keys with values. Strings are immutable sequences. In an interview, the right choice follows the operations and output contract.
This lesson compares list and set membership, traces a small example, and names the assumptions behind Big-O statements. It uses Python’s data-structures tutorial and the Python complexity reference. Course pricing follows the introduction.
Course access
Choose your next step in Python.
Review the current course options and access details here.
Heycademy Courses · Coming Soon
Master Python with Heycademy
We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.
We’re putting the finishing touches on this course. Please check back for updates.
Four structures
What changes, stays ordered and can be a key.
| Structure | Typical use | Constraint |
|---|---|---|
| list | Ordered values, indexing, repeats. | Mutable; membership may scan. |
| set | Distinct values and membership. | Elements must be hashable. |
| dict | Lookup from key to value. | Keys must be hashable. |
| str | Text as sequence. | Immutable. |
A tuple can serve as a composite key if its contents are hashable. A list cannot. Clarify whether the output must be sorted, preserve input order or allow any valid order.
Time and space
State average-case hashing assumptions.
| Operation | Typical time | Reason |
|---|---|---|
| list positional access | O(1) | Direct index. |
| list membership | O(n) | May scan n values. |
| set membership | O(1) average | Hash lookup. |
| dict key lookup | O(1) average | Hash lookup. |
| copy n values | O(n) | All values copied. |
| sort n values | O(n log n) | Comparison sorting. |
Hash collisions and adversarial inputs can worsen set/dict behavior. The duplicate-detection set may hold n values, so the complete function uses O(n) extra space. One O(1) operation does not make the entire loop O(1).
Membership example
Find the first repeated ID.
Input ["A", "C", "B", "A"] has four hashable strings. Comparing each new ID against all earlier IDs can take O(n²) time; a set approach takes O(n) expected time and O(n) extra space.
def contains_duplicate(values):
seen = set()
for value in values:
if value in seen:
return True
seen.add(value)
return False| Step | Value | seen before | Decision |
|---|---|---|---|
| 1 | A | {} | Add. |
| 2 | C | {A} | Add. |
| 3 | B | {A,C} | Add. |
| 4 | A | {A,B,C} | Return True. |
The invariant: before each iteration, seen holds precisely the earlier values. It returns false for an empty list and all-distinct list.
Keep building this skill
Turn the example into a tested solution.
Return to the course options whenever you are ready.
When hashing fails
State the hashability contract.
Input [[1], [2], [1]] contains unhashable inner lists. The current set function fails. If each inner list represents an immutable ordered sequence, convert to a tuple. If order should not matter, define a different canonical form. The right normalization depends on the equality rule.
If the task asks for counts rather than a Boolean, a dictionary or Counter fits better. If it requires preserving every occurrence in input order, a list remains useful. Choose by result, operations and constraints.
Transfer task
Count colours and justify space.
For ["red", "blue", "red", "green"], return a mapping from colour to count.
Show the answer
A dictionary or Counter gives red→2, blue→1, green→1. Expected time O(n) under average hashing; extra space O(k), where k is the number of distinct colours. A set loses counts.
Now change the requirement to “does any colour repeat?” A set suffices. Explain why a list-only method can be correct but slower on long all-distinct input.
Common mistakes
Analyze the whole function.
| Mistake | Correction |
|---|---|
| Calling list membership O(1). | It can scan the list. |
| Ignoring set storage. | It may grow to O(n). |
| Using a mutable dict key. | Use hashable keys or a documented normalization. |
| Assuming output order does not matter. | Clarify contract and ties. |
The two-sum method lesson applies a dictionary to a pair-search problem.
A second worked choice
Counts need a dictionary, not a set.
Suppose an event stream contains ["open", "close", "open", "open"] and you need counts. A set answers only which distinct events appeared: {open, close}. It discards multiplicity. A dictionary accumulates the count for each key. The invariant is that after processing i events, each stored count equals the number of occurrences among the first i items.
def count_events(events):
counts = {}
for event in events:
counts[event] = counts.get(event, 0) + 1
return counts
assert count_events(["open", "close", "open", "open"]) == {"open": 3, "close": 1}Expected time is O(n) with average hash-table operations and O(k) auxiliary space for k distinct event values. An empty stream returns an empty dictionary. This differs from duplicate detection even though both problems read the same data shape: the requested output determines the structure.
Derive a full-function bound
Count loops, copies and sorting.
Consider a function that converts a list to a set, sorts the distinct values, and returns the sorted list. Building the set is O(n) expected time and O(k) space for k distinct values. Sorting k values costs O(k log k) time. The whole function is O(n + k log k) expected time, not simply O(1) because set membership is fast. Its output itself holds k values.
Now compare value in values inside a loop over every value. Each membership test can scan n elements, making the total O(n²) in the worst case. State whether an early exit is possible; it can improve some inputs without changing the worst-case bound. This method of accounting prevents a common interview mistake: quoting the complexity of one operation as if it described the whole algorithm.
Strings and sequence costs
An immutable value changes how you build.
Strings support indexing and slices, but they are immutable. Repeatedly appending to a string in a loop can allocate intermediate strings. When building many fragments, collect them in a list and join at the end. The exact performance depends on implementation details, but the interview explanation should identify that creating a new string is different from mutating a list in place.
For a palindrome check, clarify whether case and punctuation matter. The tested is_palindrome solution is exact: "Level" is false because uppercase L and lowercase l differ. If the task asks to ignore case and nonalphanumeric characters, normalization or pointer-skipping becomes part of the algorithm. Do not silently add that behavior because a familiar palindrome exercise used it.
| Contract | “Level” result | Required work |
|---|---|---|
| Exact character equality | False | Compare original characters. |
| Case-insensitive letters | True | Normalize case before or during comparison. |
| Ignore punctuation and spaces | Depends on remaining characters. | Define what to skip. |
Now consider "aab". Its first unique character is b at index 2. A set would tell you which characters exist but not their frequency. A Counter plus an ordered scan matches the task. This connects strings back to dictionary-like counting without confusing existence with multiplicity.
Indexing and slicing
Clarify whether a slice creates a new outer list.
For values = [10,20,30,40], values[1] is 20 and values[1:3] is a new list [20,30]. The stop index is excluded. A slice copies references to elements, not necessarily nested objects. If elements are mutable lists, changing an inner object through the slice can also change what the original outer list points to. The debugging lesson explores that aliasing case.
Indexing by position is a different operation from searching for a value. values[2] is direct positional access, while 30 in values may scan. A common complexity error is to hear “list” and assign one cost to every list operation. State the operation first. Similarly, values.pop() and values.pop(0) have different movement costs; a deque is designed for efficient operations at both ends, as Python’s collections documentation explains.
FAQ
Questions about this skill.
Is set membership always O(1)?
It is normally O(1) on average; the hashing assumptions matter.
Can a list be a dictionary key?
No. Lists are mutable and unhashable.
Does a set preserve duplicates?
No.
Continue with the course
Build reliable Python interview skills.
Review the course options and choose your next learning step.