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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code