HackerRank Plus Minus solution with JavaScript
Let's learn how to solve the Plus Minus challenge from the HackerRank website.
To solve this problem, we must define a function that receives an array of integers and calculates the ratios of its elements that are positive, negative, and zero.
The function should print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with 6 digits after the decimal. The function should not return a value.
Example
We are given the following example.
arr = [1, 1, 0, -1, -1]
This array has 5
elements, two positive, two negative and one zero. Their ratios are 2/5
, 2/5
, and 1/5
. The function should print these ratios with a precision of 6 decimal places.
0.400000
0.400000
0.200000
Pseudo code solution
- Get the length of the input array.
- Define numeric variables to track the number of positive, negative, and zero values in the array.
- Loop over the Array
- If the
value
is less than0
, increment thenegatives
counter. - If the
value
is greater than0
, increment thepositives
counter. - If the
value
is neither less than or greater than0
, increment thezeros
counter.
- If the
- Divide each counter by the array length.
- Log the result to the console using a precision of 6 decimal places.
Code solution
function plusMinus(arr) {
const length = arr.length;
let negatives = 0;
let zeros = 0;
let positives = 0;
arr.forEach((value) => {
if (value < 0) {
negatives++;
}
else if (value > 0) {
positives++;
}
else {
zeros++;
}
});
console.log((positives / length).toPrecision(6));
console.log((negatives / length).toPrecision(6));
console.log((zeros / length).toPrecision(6));
}
Test case
console.log(plusMinus([-4, 3, -9, 0, 4, 1]));
We should expect this test case to result in 3/6
positives, 2/6
negatives, and 1
zero.
"0.500000"
"0.333333"
"0.166667"
The result is indeed what we expected, with each expected ratio expressed in decimals up to 6 digits of precision.
Time and space complexity
The Big O time complexity of the solution is linear, or O(n)
, where n
is the length of the input array. The solution used one loop that iterated over all the numbers in the input array.
The Big O space complexity of the solution is constant, or O(1)
. Regardless of the length of the input array, we'll always require the same numeric variables to be stored in memory.