Arrays and Hashing Array basics
46. Linear Search
You are given an array of integers nums and an integer target. Return the index of the first position in
nums that holds target. If target does not appear in nums, return -1.
Indexes start at 0, so the first element is at index 0 and the last is at index nums.length − 1. The array
can be in any order, and the same value can appear more than once.
Example 1
Input: nums = [4, 9, -2, 9, 7], target = 9
1Explanation: 9 appears twice, at index 1 and at index 3. The first of them counts, so the answer is 1.
Example 2
Input: nums = [3, 8, 1], target = 5
-1Explanation: No element of nums equals 5, so the answer is −1.
Example 3
Input: nums = [-5, 0, 5, -5, 10], target = 10
4Explanation: 10 is the last element. Its index is nums.length − 1, which is 4.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109-109 ≤ target ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.