Skip to contentKEEP THE CRAFTTHE SANCTUARY

Array

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…

Array Code Labs

Mental Model

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 List Representation and Ownership

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).

Update One Indexed Position

Reference
def replace_at(values, index, item):
    previous = values[index]
    values[index] = item
    return previous
Practice

Implement replace_at(values, index, item). Return the previous item and mutate exactly the requested list position without changing its length.

Public tests

  • Verify one indexed mutation
  • Preserve Python negative indexing

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Update One Indexed Position

def replace_at(values, index, item):
    previous = values[index]
    values[index] = item
    return previous

Indexed Access, Mutation, and Copying

Choose 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.

Separate a Copy from an Alias

Reference
def changed_copy(values, index, item):
    result = values.copy()
    result[index] = item
    return result
Practice

Implement changed_copy(values, index, item). Return a shallow outer copy with one replacement while leaving the original list unchanged.

Public tests

  • Verify copy ownership

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Separate a Copy from an Alias

def changed_copy(values, index, item):
    result = values.copy()
    result[index] = item
    return result

Predict Which List Changes

Before 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:

Print 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.

Use an Index as State

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.

Mark a Dense Value Domain

Reference
def mark_seen_indices(values):
    seen = [False] * len(values)
    for value in values:
        seen[value - 1] = True
    return seen
Practice

Implement 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.

Public tests

  • Verify dense index mapping
  • Verify duplicates do not toggle

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Mark a Dense Value Domain

def mark_seen_indices(values):
    seen = [False] * len(values)
    for value in values:
        seen[value - 1] = True
    return seen

Trace Repeated Labels into Stable Positions

The 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.
Print 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.

Choose an Array or a Different Structure

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.

Array Ownership and Index Mistakes

  • 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.
  • Negative indices wrap from the end, so an accidental -1 can return a plausible but wrong value.

Explain It in an Interview

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 Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Indexed read or replacementO(1)O(1)The position must already exist; a negative index counts from the end.
Append one elementO(1)O(n)The average is amortized in CPython; occasional capacity growth copies existing references.
Copy n outer referencesO(n)O(n)Nested objects are still shared unless separately copied.
Scan and mark n bounded labelsO(n)O(n)Allocate n booleans and perform one constant-time indexed write per input.

Space

O(n) for an n-slot presence buffer or an outer copy; indexed replacement alone adds O(1) auxiliary space.

Assumptions

  • Labels lie in 1..n before value - 1 is used as a position.
  • CPython list operations are counted by references moved; deep object copying is a separate cost.

Invariants Worth Saying Aloud

  1. After a prefix is scanned, seen[i] is true exactly when label i + 1 has appeared in that prefix.
  2. Replacing one indexed slot preserves the list's length; aliases observe that replacement.
  3. A shallow copy separates the outer list but retains references to its nested objects.

When To Use Or Avoid Array

Use It When

  • Use a list when positions are dense and ordered, and the algorithm must retain or update those positions.
  • Use a boolean output buffer when labels are proven to lie in 1..n and only presence is required.

Choose Another Tool When

  • Use a dictionary for sparse or noninteger labels; allocating through the largest label can waste space.
  • Use deque for repeated front removal, and preserve a separate copy when input ownership forbids mutation.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using a one-based label as its index

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.

Avoid

for value in values:
    seen[value] = True

Use instead

for value in values:
    seen[value - 1] = True

Toggling a presence fact on duplicates

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.

Avoid

for value in values:
    seen[value - 1] = not seen[value - 1]

Use instead

for value in values:
    seen[value - 1] = True

Expecting an outer copy to clone rows

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.

Avoid

copied = original.copy()
copied[0].append(7)

Use instead

copied = [row.copy() for row in original]
copied[0].append(7)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.