Warm Up · Loops 02
Count Negative Numbers in an Array
Problem Statement
Write a function that returns the number of negative numbers in an array.
Example
Input: arr = [2, -6, 4, 8, 1, -9]
Process: -6 and -9 are below 0 → count = 2
Output: 2
Approach
- Initialize a counter to 0.
- Loop through the array.
- If the element is less than 0, increment the counter.
- Return the final count after the loop ends.
Time & Space Complexity
Time Complexity: O(n) - where n is the number of elements in the array.
Space Complexity: O(1) - only a counter variable is used.
Visualisation
1Start with the array
[2, -6, 4, 8, 1, -9]2Set the counter
let count = 0;3For each element, is it negative?
arr[i] < 0 ? count++4Negative count
2Explanation
countstarts at 0 and only goes up when a negative number is found.arr[i] < 0is true for -6 and -9, socountbecomes 2.- The function returns
countinstead of printing it, so the caller decides what to do with it.
Your solution
Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.
// Write your solution in JavaScript // Print the answer with console.log()
Console
No output yet. Use console.log() to print values here.
Write your own solution and press Submit once to unlock the answer.