Plus Minus - HackerRank Problem Solving

Featured image

The plus-minus problem is a simple yet challenging programming problem. The goal is to calculate the fraction of positive, negative, and zero numbers in an array. This problem can be solved using a variety of algorithms, including the one presented in this article.

It’s a great exercise for beginners who are looking to hone their programming skills and gain a deeper understanding of Python’s core concepts.

In this post, you will learn how to solve the Plus Minus problem on the Hackerrank website and implement the solution in Python and C++.

Problem Statement and Explanation

In the given array, calculate the ratio of positive, negative and zero. print the decimal value of each fraction on a new line with 6 places after the decimal.

Input Format

The first line contains the n - number of integers The second line contains n space-separated integers describing the array of numbers.

Output Format

Plus Minus Solution in Python

Plus Minus Solution in C++

Explanation of Solution

The function plusMinus() takes an array of integers as input and prints the fraction of positive, negative, and zero numbers in the array.

Here is an example:

Consider the following array:

arr = [-4, 3, -9, 0, 4, 1]

The function will iterate through the array and count the number of positive, negative, and zero numbers. The result will be as follows:

The function will then calculate the fraction of positive, negative, and zero numbers by dividing the corresponding count variable by the total number of elements in the array. The result will be as follows:

Finally, the function will print the three fractions:

Test Case of Plus Minus Problem

Time Complexity of Plus Minus Problem

The time complexity of the above code is O(n), where n is the length of the array. This is because the for loop in the plus_minus() function iterates over the entire array, and each iteration takes a constant amount of time.

Space Complexity of Plus Minus Problem

The space complexity of the plus-minus problem is O(1). This is because the algorithm only uses a constant number of variables, regardless of the size of the input array.

The following are the variables used by the algorithm:

These variables are all of constant size, so the overall space complexity of the algorithm is O(1).