HackerRank Plus Minus solution with JavaScript

Learn how to solve the plus minus problem from the HackerRank challenges by using JavaScript.
April 28, 2023JavaScript
3 min read

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

  1. Get the length of the input array.
  2. Define numeric variables to track the number of positive, negative, and zero values in the array.
  3. Loop over the Array
    • If the value is less than 0, increment the negatives counter.
    • If the value is greater than 0, increment the positives counter.
    • If the value is neither less than or greater than 0, increment the zeros counter.
  4. Divide each counter by the array length.
  5. 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.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.