Find the index of a target in an unsorted list by checking each element — O(n) linear search — and return -1 when it is missing. Run and time it live.
The problem
Return the index of the first occurrence of target in nums, or -1 if it is not there. Don't use list.index().
Examples
Example 1
Input
linear_search([4, 2, 7, 2], 2)
Expected output
1
Example 2
Input
linear_search([4, 2, 7], 9)
Expected output
-1
+ 2 hidden tests on Submit.
Edge cases to ask about
- Missing target
- Duplicates (first one wins)
- Empty
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Check every element | O(n) | O(1) | Best case O(1), worst case O(n). |
Walkthrough of the optimal approach (try it yourself first)
Walk the list with enumerate and return the first matching index. Best case O(1) (it is first), worst case O(n) (last or missing) — Big-O usually describes the worst case.
On an unsorted list, linear search is optimal. If the list is sorted, binary search (next question) is exponentially faster.
Complexity: O(n) time, O(1) space. In the worst case (missing or last) every element is checked.
Reveal the reference solution
def linear_search(nums, target): for i, x in enumerate(nums): if x == target: return i return -1
Follow-ups interviewers ask
- Return every index of target.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Linear Search in Python?
The optimal solution runs in O(n) time and O(1) auxiliary space. In the worst case (missing or last) every element is checked.
What follow-up questions do interviewers ask about Linear Search in Python?
Return every index of target.
