Find the index of the first occurrence of a value in an unsorted array

Quick Overview

Return the index of the first occurrence of a value in an unsorted integer array, or -1 when the value is absent, without calling a built-in search method. It tests loop control, early exit on a match, and correct handling of repeated and missing values.

Find the index of the first occurrence of a value in an unsorted array

Company: Nokia

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given an integer array `nums` and an integer `key`, perform a linear search to find the first occurrence of `key` in `nums`. Return the index of the first occurrence of `key` in `nums`, or `-1` if `key` does not appear in the array. You must implement the search yourself, without using any built-in search methods. ### Function Signature ```python def linear_search(nums: list[int], key: int) -> int: ``` ### Rules - Indices are 0-based. - If `key` appears more than once, return the smallest index where it appears. - Do not call a built-in search method such as `list.index`. ### Constraints - `1 <= len(nums) <= 10^4` - `-10^9 <= nums[i], key <= 10^9` ### Examples ```text Input: nums = [4, 2, 7, 1, 9, 3], key = 7 Output: 2 ``` The value `7` is at index `2`, and it does not appear anywhere else. ```text Input: nums = [5, 1, 8, 1, 4], key = 1 Output: 1 ``` The value `1` appears at indices `1` and `3`. The first occurrence is at index `1`. ```text Input: nums = [4, 2, 7, 1, 9, 3], key = 5 Output: -1 ``` None of the six values equals `5`, so the result is `-1`.

Overview: Return the index of the first occurrence of a value in an unsorted integer array, or -1 when the value is absent, without calling a built-in search method. It tests loop control, early exit on a match, and correct handling of repeated and missing values.

Nokia logo
Nokia
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given an integer array nums and an integer key, perform a linear search to find the first occurrence of key in nums.

Return the index of the first occurrence of key in nums, or -1 if key does not appear in the array.

You must implement the search yourself, without using any built-in search methods.

Function Signature

def linear_search(nums: list[int], key: int) -> int:

Rules

  • Indices are 0-based.
  • If key appears more than once, return the smallest index where it appears.
  • Do not call a built-in search method such as list.index .

Constraints

  • 1 <= len(nums) <= 10^4
  • -10^9 <= nums[i], key <= 10^9

Examples

Input: nums = [4, 2, 7, 1, 9, 3], key = 7
Output: 2

The value 7 is at index 2, and it does not appear anywhere else.

Input: nums = [5, 1, 8, 1, 4], key = 1
Output: 1

The value 1 appears at indices 1 and 3. The first occurrence is at index 1.

Input: nums = [4, 2, 7, 1, 9, 3], key = 5
Output: -1

None of the six values equals 5, so the result is -1.