Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Array itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Use dense integer positions to read, replace, and scan Python lists. Separate a slot from the object stored there, then choose mutation, copying, or direct value-to-index state deliberately.
20 practice exercises92 interview problems
Recognize it when The answer depends on original positions, a processed prefix, or a dense bounded domain of integer labels.
Checking your account…
An interview “array” in Python is usually a list: an ordered sequence whose integer indices form
a dense range from zero through len(values) - 1. Treat the index as part of the data model. A
loop invariant should say what the processed prefix means, not merely that a loop counter moved.
For example, after processing values[:right], a result array might contain the answer for exactly
those positions. That statement makes an off-by-one error visible: either right is already
processed or it is the next position, but it cannot be both.
Python lists hold references to objects. Assignment creates another name for the same list; it does not copy the elements. A shallow copy creates a new outer list but still shares nested objects. In an interview, say whether the function may mutate its input before using an in-place technique.
The Python list documentation(opens in a new tab) defines the operations. Index reads and writes are constant-time operations. Appending is amortized O(1), while inserting or deleting near the front shifts later references and therefore costs O(n).
def replace_at(values, index, item):
previous = values[index]
values[index] = item
return previousImplement replace_at(values, index, item). Return the previous item and mutate exactly the requested list position without changing its length.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def replace_at(values, index, item):
previous = values[index]
values[index] = item
return previousChoose the operation whose cost matches the proof:
| Operation | Time | Ownership effect |
|---|---|---|
values[index] |
O(1) | Reads the existing object reference |
values[index] = item |
O(1) | Mutates the original list through every alias |
values.append(item) |
Amortized O(1) | Mutates the original list |
values.insert(0, item) |
O(n) | Shifts every existing reference |
values[start:end] |
O(k) | Allocates a new outer list of k references |
values.copy() |
O(n) | Allocates a shallow outer copy |
Slicing inside a loop can turn a linear-looking solution into quadratic work. Repeatedly creating
values[:right] copies a growing prefix; prefer indices or a maintained aggregate when the
algorithm only needs a boundary.
def changed_copy(values, index, item):
result = values.copy()
result[index] = item
return resultImplement changed_copy(values, index, item). Return a shallow outer copy with one replacement while leaving the original list unchanged.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def changed_copy(values, index, item):
result = values.copy()
result[index] = item
return resultBefore reading the output, predict which changes reach rows. Repetition copies object references; it does not run the inner-list expression again. Here both positions point to one row. Copying the outer list creates another container, so appending an outer element stays local. It does not create new inner rows. Read the table from top to bottom as one program.
| Line | Python statement | Observation |
|---|---|---|
| 1 | rows = [[0]] * 2 |
Two slots share one inner list. |
| 2 | copied = rows.copy() |
A new outer list keeps those references. |
| 3 | copied[0].append(1) |
The shared inner list changes. |
| 4 | copied.append([9]) |
Only the copied outer list grows. |
| 5 | print(rows) |
Observe the shared mutation. |
| 6 | print(copied) |
Observe the separate outer length. |
| 7 | separate = [[0] for _ in range(2)] |
Allocate two independent inner lists. |
| 8 | separate[0].append(1) |
Change only the first inner list. |
| 9 | print(separate) |
Compare independent rows. |
Expected printed output:
| Output | |
|---|---|
| 1 | [[0, 1], [0, 1]] |
| 2 | [[0, 1], [0, 1], [9]] |
| 3 | [[0, 1], [0]] |
The first append follows a shared reference, so both displayed rows gain 1. The outer append appears only in copied. The comprehension evaluates [0] separately for each position, so its first row changes alone. A shallow copy of r rows costs O(r) references and still shares their contents; it is not a promise to copy an entire matrix. In an interview, distinguish changing one slot from mutating the object stored there. State which objects the caller expects to remain independent before choosing repetition or copying.
When values come from a known dense domain, a list can replace a hash lookup. If every value is in
1..n, index value - 1 is a collision-free location for that label. The invariant is precise:
after scanning a prefix, seen[i] is true exactly when i + 1 occurred in that prefix. A duplicate
sets the same boolean again; it must not toggle the bit back to false.
def mark_seen_indices(values):
seen = [False] * len(values)
for value in values:
seen[value - 1] = True
return seenImplement mark_seen_indices(values). Values are integers from 1 through len(values). Return a boolean list whose index i is true exactly when i + 1 occurs.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def mark_seen_indices(values):
seen = [False] * len(values)
for value in values:
seen[value - 1] = True
return seenThe adjacent bounded-index-marking Lab uses the label’s value to choose an output position. Trace [2, 2, 1]: the second 2 must preserve the fact already recorded, while label 3 stays absent.
print(mark_seen_indices([2, 2, 1])) followed by print(mark_seen_indices([]))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | seen = [False] * len(values) |
seen = [False, False, False] |
There is one slot for each permitted label, initially with no evidence. |
| 2 | seen[value - 1] = True |
value = 2; seen = [False, True, False] |
One-based label 2 maps to zero-based position 1. |
| 3 | seen[value - 1] = True |
value = 2; seen = [False, True, False] |
A repeat records the same fact without toggling it. |
| 4 | seen[value - 1] = True |
value = 1; seen = [True, True, False] |
The new label fills position 0; no input has established label 3. |
| 5 | return seen |
[True, True, False] |
All input labels were processed, so each boolean now answers presence. |
| Output | |
|---|---|
| 1 | [True, True, False] |
| 2 | [] |
The loop advances through input positions, but writes according to label positions. Setting True is idempotent, so duplicates do not undo earlier evidence. Empty input allocates and returns an empty result without entering the loop.
Use a list when positions are dense, order matters, and indexed access or mutation dominates. Use a dictionary instead when keys are sparse or not integers. Use a deque rather than a list when the hot operation removes from the front. Use a set when only membership matters and no positional answer is required.
Sorting may expose useful order, but it changes positions and costs O(n log n). Before sorting, check whether the required answer includes original indices or whether a one-pass hash map preserves the needed information more directly.
matrix = [[0] * columns] * rows aliases the same inner list; use a comprehension to allocate
independent rows.if target in values is O(n), not O(1); placing it inside a scan can produce O(n squared) work.values = values + [item] allocates a new list, while append mutates the existing list.-1 can return a plausible but wrong value.Before coding, state: “I will use the index as the stable identity of each position, and after each iteration the processed prefix has its final result.” While coding, call out whether the list is an input you may mutate, a fixed-size output buffer, or auxiliary state. At the end, count every full scan, slice, sort, insertion shift, and allocated list before giving time and space bounds.
The focused Mark Seen Indices(opens in a new tab) drill practices direct domain-to-index mapping. Product Except Self(opens in a new tab) then requires two directional invariants over the same dense positions without hiding an extra division or nested scan.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Array itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Indexed read or replacement | O(1) | O(1) | The position must already exist; a negative index counts from the end. |
| Append one element | O(1) | O(n) | The average is amortized in CPython; occasional capacity growth copies existing references. |
| Copy n outer references | O(n) | O(n) | Nested objects are still shared unless separately copied. |
| Scan and mark n bounded labels | O(n) | O(n) | Allocate n booleans and perform one constant-time indexed write per input. |
O(n) for an n-slot presence buffer or an outer copy; indexed replacement alone adds O(1) auxiliary space.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
With values [2, 1, 2], writing seen[value] leaves label 1's slot false and incorrectly marks label 3. A label equal to n would also index past the buffer.
Prevent it: Prove the 1..n domain, then subtract one exactly once when mapping a label to a list position.
for value in values:
seen[value] = Truefor value in values:
seen[value - 1] = TrueWhere you will hit this: Mark Seen Indices(opens in a new tab)
A repeated label remains present. Toggling its boolean makes an even count look absent, so two copies of label 2 undo each other.
Prevent it: Presence is an idempotent update: assign True. Use a numeric count only when multiplicity is required.
for value in values:
seen[value - 1] = not seen[value - 1]for value in values:
seen[value - 1] = TrueWhere you will hit this: Mark Seen Indices(opens in a new tab)
Copying a list of rows duplicates only the outer references. Appending inside one copied row still modifies the caller's row.
Prevent it: For a known two-dimensional list needing independent rows, copy each row and count that additional work.
copied = original.copy()
copied[0].append(7)copied = [row.copy() for row in original]
copied[0].append(7)Where you will hit this: Product Except Self(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27