Array Search

easy

You are given an array arr of n integers and a single integer x. Your job is to find out where x lives in the array.

Return the index of the first occurrence of x in arr. If x is not present at all, return -1.

The array is not sorted, so you have no shortcuts — x could be hiding anywhere. Indices are 0-based: the first element is at index 0.

Hints

You're really just asking one question of every element: "are you the one I'm looking for?"
The array is unsorted — you cannot skip ahead or binary-search, so what's the simplest way to guarantee you don't miss it?
Walk from index 0 and return the moment you find x; if you fall off the end, it isn't there.

Common doubts

Binary search needs a sorted array. Here arr is unsorted, so the target could be anywhere and you must be able to inspect every element — O(n) is optimal.
Return the index of the first (leftmost) occurrence. Scanning left to right and returning on the first match handles this automatically.
Return -1. It's the agreed sentinel meaning "not found".

Interview follow-ups

Then you could use binary search to find x in O(log n) time — but to return the FIRST occurrence you'd binary-search for the leftmost boundary.
Keep scanning to the end and increment a counter on each match instead of returning early — still O(n) but a single full pass.

Fun facts

  • Linear search is the very first algorithm most people invent on their own — it's exactly how you scan a shopping receipt for one item.
  • The 'stop as soon as you know the answer' idea powers short-circuit evaluation (&&, ||) in nearly every programming language.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 2, 3, 4], x = 3
Output: 2
3 sits at index 2, so we return 2.
Example 2
Input: arr = [10, 8, 30, 4, 5], x = 5
Output: 4
5 is the last element, at index 4.
Example 3
Input: arr = [10, 8, 30], x = 6
Output: -1
6 never appears, so we return -1.
Constraints

- 1 <= arr.size <= 10^6 - 0 <= arr[i] <= 10^6 - 0 <= x <= 10^5

Solve this problem →