Easy
Find the First Occurrence of a Target
- Time limit
- 1 s
- Memory limit
- 128 MB
- Estimated
- 15 min
- Arrays and Strings
Description
Given an array of integers and a target value, return the index of the target's first occurrence.
Use zero-based indexing. If the target does not appear in the array, return -1. If it appears multiple times, return the smallest index at which it occurs.
For example, in [4, 2, 7, 2] with target = 2, the answer is 1.
Implement firstOccurrence(nums, target) to return the required index.
Constraints
1 <= nums.length <= 1000 -1000000 <= nums[i] <= 1000000 -1000000 <= target <= 1000000
Sample cases
3Sample 1
Input
nums = [4,2,7,2] target = 2
Expected output
1
Sample 2
Input
nums = [1,3,5] target = 4
Expected output
-1
Skills and languages
Concepts
- Arrays
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer