Skip to content
Hello Python
Algorithm2 Practice1 Interview

Linear Search

Inspect candidates sequentially when no exploitable ordering or index is available. Learn the algorithm's preconditions, state transition, correctness argument, Python cost model, and transfer from one focused drill to a full Interview Problem.

Recognize it when

Consider Linear Search when the prompt's constraints and required operations match this shape: Inspect candidates sequentially when no exploitable ordering or index is available.

Pybit demonstrates Linear Search in a professional Python interview workspace.
On this page · Scan Until the Contract Is Decided

Checking your account…

Sign in to save your code and progress across devices. The lesson and problem statement remain public.

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

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

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
Linear Search complete workflowO(n)O(n)Lowercase each character and count membership in the five-vowel set.

Space

O(1) for the focused Count Vowels implementation.

Assumptions

  • The scan adds one exactly for each case-normalized vowel and zero for every other character.
  • The bound counts Python sorting, slicing, hashing, heap, recursion, and container-copy costs rather than treating syntax as free.

Invariants Worth Saying Aloud

  1. State the precise Linear Search invariant before coding and preserve it after every update, traversal step, or recursive return.
  2. The unresolved search region still contains every possible answer.
  3. Each transition inspects or eliminates new work and therefore makes progress.
  4. Scan characters and test normalized membership. Preserve this claim after every transition.

When To Use Or Avoid Linear Search

Use It When

  • Use Linear Search when this precondition is stated or can be proved: The search space and equality or monotone-boundary contract are explicit.
  • Use it when this maintained state removes repeated work: The unresolved search region still contains every possible answer.

Choose Another Tool When

  • Avoid Linear Search when this precondition is absent: The search space and equality or monotone-boundary contract are explicit.
  • Avoid it when a simpler direct scan satisfies the constraints with less implementation risk.

Common Pitfalls

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

Applying the algorithm without its precondition

Verify algorithm preconditions such as sorted input, nonnegative weights, acyclicity, or admissible heuristics before applying it.

Prevent it: State and verify this precondition before coding: The search space and equality or monotone-boundary contract are explicit.

Avoid

def count_vowels(text):
    pass

Use instead

def count_vowels(text):
    return sum(character.lower() in 'aeiou' for character in text)

Breaking the state transition

This implementation ignores uppercase vowels and undercounts mixed-case input.

Prevent it: Preserve this proof obligation: Every discarded candidate or interval is excluded by a direct comparison or monotone predicate.

Avoid

def count_vowels(text):
    return sum(character in 'aeiou' for character in text)

Use instead

def count_vowels(text):
    return sum(character.lower() in 'aeiou' for character in text)

Hiding Python work in the claimed bound

Include visited state, boundary cases, recursion depth, and hidden copying costs in correctness and complexity analysis.

Prevent it: Count every sort, slice, copy, membership check, heap update, and recursive frame before claiming O(n).

Avoid

def count_vowels(text):
    return sum(character in 'aeiou' for character in text)

Use instead

def count_vowels(text):
    return sum(character.lower() in 'aeiou' for character in text)

Reviewed References

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