Skip to contentKEEP THE CRAFTTHE SANCTUARY

Linear Search

Inspect an unsorted sequence in input order and stop only when its occurrence contract is decided. Track inspected positions, duplicates, the missing sentinel and the cost of building an index.

2 practice exercises1 interview problem

Recognize it when One lookup has no useful existing ordering.

Checking your account…

Linear Search Code Labs

Scan Until the Contract Is Decided

Linear search inspects items in order and stops as soon as the requested occurrence is determined. It needs no ordering or preprocessing.

Return the Required Occurrence

First, last, any, and all matches are different contracts. First match returns immediately; last match must scan the entire input while updating a candidate index.

Trace Linear Decisions

Reference
def linear_trace(values,target):
    trace=[]
    for index,value in enumerate(values):
        matched=value==target;trace.append([index,value,matched])
        if matched:break
    return trace
Practice

Implement linear_trace(values,target). Return [index,value,matched] for inspected items through the first match.

Public tests

  • Stop exactly when decided

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

Trace Linear Decisions

def linear_trace(values,target):
    trace=[]
    for index,value in enumerate(values):
        matched=value==target;trace.append([index,value,matched])
        if matched:break
    return trace

Stop Before the Second Duplicate

Predict both calls to the existing decision trace. The first stops at the earliest 5; the second has no stopping match and records every input position.

Step Executed statement State Why
Reject index 0 matched=value==target;trace.append([index,value,matched]) [0, 8, False] A failed comparison rules out exactly one position.
Accept index 1 matched=value==target;trace.append([index,value,matched]) [1, 5, True] Every earlier position is known not to match.
Stop if matched:break indexes 2 and 3 uninspected The second 5 is irrelevant to a first-occurrence question.
Absent call return trace two False decisions Exhaustion proves absence only because the whole sequence was inspected.
Print Output
print(linear_trace([8, 5, 5, 2], 5)) [[0, 8, False], [1, 5, True]]
print(linear_trace([8, 2], 5)) [[0, 8, False], [1, 2, False]]

Decide first/last/all before writing the loop. A hash index can speed later queries, but duplicate-position lists and original-index semantics must still match the question.

Use a Sentinel Deliberately

Choose a missing result that cannot be confused with a valid answer, commonly -1 or None. Do not use truthiness for index zero.

Find the First Match

Reference
def find_first(values,target):
    for index,value in enumerate(values):
        if value==target:return index
    return -1
Practice

Implement find_first(values,target). Return the first matching index, or -1.

Public tests

  • Return first occurrence or sentinel

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

Find the First Match

def find_first(values,target):
    for index,value in enumerate(values):
        if value==target:return index
    return -1

Choose Linear Search or an Index

Use a scan for one or few queries over unsorted data. Build a dictionary, set, or sorted index when many queries justify O(n) preprocessing and extra space. A single scan is O(n) time and O(1) auxiliary space.

Explain It in an Interview

Say: “I inspect in input order, and returning here proves this is the first match. If the loop ends, no item satisfies the predicate.” Cover empty input, duplicates, equality semantics, and the missing sentinel.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
One equality scanO(n)O(n)Best case O(1); assumes equality is constant cost.

Space

O(1) scan state; the decision-trace Lab stores O(n) inspected rows.

Assumptions

  • Equality on long strings or nested objects can cost more than O(1).
  • Building a sorted or hashed index has its own time and storage cost.

Invariants Worth Saying Aloud

  1. Before inspecting index i, no earlier position satisfies the first-match predicate.
  2. A -1 result is returned only after every candidate has been checked.

When To Use Or Avoid Linear Search

Use It When

  • Scan for one or few queries when preprocessing would cost as much as the lookup.
  • Continue through the whole input when asking for all matches, a count, or the last match.

Choose Another Tool When

  • Repeated membership queries may justify a set or dictionary built once.
  • A first-match loop cannot answer a last-match contract without changing its stopping rule.

Common Pitfalls

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

Treating index zero as absent

The first valid position is 0, which is falsy. A truthiness check reports a present match as missing.

Prevent it: Compare the sentinel explicitly.

Avoid

found = bool(index)

Use instead

found = index != -1

Overwriting the first occurrence

Repeated assignment without stopping leaves the last index 2 for target 4 in [4,1,4].

Prevent it: Break as soon as the first match is found.

Avoid

for i, v in enumerate(values):
    if v == target: answer = i

Use instead

for i, v in enumerate(values):
    if v == target:
        answer = i
        break

Dereferencing the missing sentinel

In Python values[-1] is a real last element. It does not mean there is no result.

Prevent it: Check the sentinel before indexing.

Avoid

value = values[index]

Use instead

value = None if index == -1 else values[index]

Reviewed References

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