Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Think like a problem solver
EXPERIMENT 02 / 66

Ask a question the code can answer.

Define behaviour for empty inputs, duplicates, absence, and invalid values.

BY NAVAN SAMI◷ 7 MIN READSTARTERCONCEPT

01 Model the idea

An algorithm is correct relative to a contract. Does a search return an index, a value, or a boolean? If duplicates exist, is any match acceptable or must it be the first? What happens when nothing matches? These questions change both implementation and tests. Writing them down prevents a fast answer to the wrong problem.

THE THING THAT MUST STAY TRUE

No earlier inspected position matches the target.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
SCAN positions from left to right
RETURN the first matching index
RETURN None if no position matches

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

algorithm_contracts.py
def first_index(values, target):
    for index, value in enumerate(values):
        if value == target: return index
    return None
print(first_index([4, 7, 4], 4))
print(first_index([], 4))
↳ EXPECTED OUTPUT
0
None
  1. 1

    The contract promises the first matching index, so scanning from the left and stopping immediately is appropriate.

  2. 2

    None means no result. It cannot be confused with index zero; a truthiness check such as if index would incorrectly reject a valid match at zero.

  3. 3

    Choose tests representing separate cases: first match, later match, repeated target, missing target, and empty input. Tests illustrate the contract but do not replace a correctness argument.

04 Count the cost

TIME

O(n)

SPACE

O(1) auxiliary

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Test the first-index contract on duplicates and a missing target.

Reveal one possible solution +
one_possible_solution.py
def first_index(values, target):
    return next((i for i, value in enumerate(values) if value == target), None)
assert first_index([4, 7, 4], 4) == 0
assert first_index([4, 7], 9) is None
assert first_index([], 9) is None
print("Contract checks passed")

06 Check your reasoning

QUICK SIGNAL CHECK

Why is if index a poor found/not-found check here?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.