All challenges
Easy 0 solved 0% acceptance

First Negative Index

Find where the first negative number appears.

What you'll learn

  • Search a list from the start
  • Return as soon as you find a match
  • Return -1 when nothing matches

Problem

Find the position (counting from 0) of the first negative number in the list.

Implement first_negative_index(numbers).

Input

numbers: The list of integers.

Output

Return the index, or -1 if there are no negative numbers.

Constraints

0 ≤ length ≤ 100,000

Examples

Example 1
Input:
numbers = [4, 0, -2, -7]

Expected output:
expected = 2
Input:
std::vector<long long> numbers = {4, 0, -2, -7};

Expected output:
long long expected = 2;
Input:
long[] numbers = new long[] {4, 0, -2, -7};

Expected output:
long expected = 2;

Explanation

-2 at index 2 is the first negative value.

Example 2
Input:
numbers = [1, 2, 3]

Expected output:
expected = -1
Input:
std::vector<long long> numbers = {1, 2, 3};

Expected output:
long long expected = -1;
Input:
long[] numbers = new long[] {1, 2, 3};

Expected output:
long expected = -1;

Explanation

There are no negative numbers, so the answer is -1.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

You only need the first position where a value is below zero.

Hint 2

Scan from left to right and stop as soon as you find one.

Hint 3

If no negative value appears, be sure to return the missing-case value.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.