HackerRank Plus Minus

Dustin Kingen's photoDustin Kingen

published a story

6 days ago


Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.


In the general case, the input can be assumed to be an iterable collection.

The best case time complexity an algorithm can have is O(N) linear time because every input must be visited at least once.

The best case space complexity an algorithm can have is O(1) constant time because only four values are needed:

  1. Total number of elements
  2. Number of positive values
  3. Number of negative values
  4. Number of zero values

Plus Minus in Python 3

Time = O(N) Space = O(1)

def plusMinus(arr):
    length = 0
    elements = [0, 0, 0]
    for n in arr:
        length += 1
        if n > 0:
            elements[0] += 1
        elif n < 0:
            elements[1] += 1
            elements[2] += 1
    for e in elements:
        print("%.6f" % (e/length))

No Comments Yet

Add a comment