DSA Factory
Free lessonsArrays · Stage 1 · Traversal · Step 3

Stop when you find it

Return the first position of a value, or −1. About 7 minutes.

Stop as soon as you find it

You're looking for your friend's name on a class list. The moment you spot it, you stop reading. There's no point going through the rest of the list.

A loop can do the same: the moment a box holds what you want, return its box number straight away. Returning ends the function, so the rest of the loop never runs. That also means you always get the first match.

Found it? return the box number right away.
Look for 9target = 9
5
0
3
1
9
2
3
3
8
4
i

5 isn't 9. Keep going.

Move 1 of 3

Saying "it isn't here"

If the loop gets to the end without returning, nothing matched. You still have to return something, and it mustn't look like a real box number. So return −1: no box is ever numbered −1, so nobody can mistake it for an answer.

Returning 0 would be a bug. Box 0 is a real box, the very first one.

After the loop: you know nothing matched.
Not 0: box 0 is a real position.
In code
for i in range(len(nums)):
    if nums[i] == target:
        return i
return -1
Quick check

A loop returns the box number as soon as it finds a 4. The array is 4, 7, 4, 1. What does it return?

  1. A0
  2. B2
  3. C−1
Show the answer

0. Box 0 already holds a 4, so it returns 0 and stops.

Your problem

Find the first position

You get a list and a target. Return the index of the first box that holds the target. If the target isn't in the list, return -1.

Example
nums = [5, 3, 9, 3, 8], target = 3 → 1

0 ≤ n ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding