Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the first index of a target

Return the index of the first occurrence of a target value in an array.

Python practice8 minArrays – Fundamentals & PatternsBeginnerLast updated March 25, 2026

Problem statement

Given an array of integers and a target integer, return the index (0-based) of the first occurrence of the target in the array. If the target does not exist in the array, return -1. Aim for O(n) time and O(1) extra space.

Task

Traverse the array and find the first position where the element equals the target; return -1 if not found.

Examples

Target in middle

Input

arr = [5, 3, 7, 3, 9], target = 3

Output

1

3 first appears at index 1.

Input format

Function call: first_index_of_target(arr, target), where arr is a list of integers and target is an integer.

Output format

An integer index (0-based) or -1 if target not present.

Constraints

0 <= len(arr) <= 10^5. Elements and target are integers. Use O(n) time and O(1) extra space.

Samples

Sample 1

Input

first_index_of_target([1,2,3], 2)

Output

1

2 is at index 1.