Medium interview relevanceRoadmap: Beginner
TimeO(n); O(1) if the target is first
SpaceO(1)

Why it costs this much

In the worst case it checks every item exactly once.

Code

def linear_search(items, target):
    for i, x in enumerate(items):    # up to n checks
        if x == target:
            return i                 # best case: first item, O(1)
    return -1

Common pitfalls

Repeating a linear search inside a loop makes O(n²). Build a set or dict first so each lookup is expected O(1).

Operation by operation

OperationBestAverageWorstSpace
Linear searchO(1) if firstO(n)O(n)O(1)

Linear search. Target equally likely to be anywhere, or absent. Works on unsorted data and any sequence, including linked lists.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list