Arrays and Hashing Array basics

46. Linear Search

Easy

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

Output: 1

Explanation: 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

Output: -1

Explanation: No element of nums equals 5, so the answer is −1.

Example 3

Input: nums = [-5, 0, 5, -5, 10], target = 10

Output: 4

Explanation: 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.

nums = [2, 2, 2], target = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • -109 ≤ target ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.