Ask a question the code can answer.
Define behaviour for empty inputs, duplicates, absence, and invalid values.
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.
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.
SCAN positions from left to right
RETURN the first matching index
RETURN None if no position matches03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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))0 None
- 1
The contract promises the first matching index, so scanning from the left and stopping immediately is appropriate.
- 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
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
O(n)
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
Test the first-index contract on duplicates and a missing target.
Reveal one possible solution +
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
Why is if index a poor found/not-found check here?
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.