Linear Search - Problem

Implement a linear search algorithm to find a specific element in an array.

Given an array of integers nums and a target value target, return the index of the target element if it exists in the array. If the target is not found, return -1.

Linear search checks each element in the array sequentially until it finds the target or reaches the end of the array.

Input & Output

Example 1 — Target Found
$ Input: nums = [4,7,2,9,1], target = 7
Output: 1
💡 Note: The target 7 is found at index 1 in the array
Example 2 — Target Not Found
$ Input: nums = [1,3,5,7,9], target = 4
Output: -1
💡 Note: The target 4 does not exist in the array, so return -1
Example 3 — Target at End
$ Input: nums = [2,4,6], target = 6
Output: 2
💡 Note: The target 6 is found at the last index 2

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • -104 ≤ target ≤ 104

Visualization

Tap to expand
INPUTALGORITHMRESULTArray and TargetLinear Search StepsFound Index47291012347Target1Check nums[0] = 44 ≠ 7, continue2Check nums[1] = 77 = 7, found!3Return index 1Early terminationTarget Found1Index of target 7Key Insight:For unsorted arrays, checking each element sequentially is the most efficient approach possibleTutorialsPoint - Linear Search | Sequential Check Algorithm
Asked in
Google 25 Amazon 30 Microsoft 20 Meta 15
25.0K Views
High Frequency
~10 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen