HackerRank Min Max Sum solution with JavaScript

Learn how to solve the making anagrams problem from the HackerRank challenges by using JavaScript.
May 02, 2023JavaScript
2 min read

Let's learn how to solve the Min Max Sum challenge from the HackerRank website.

To solve this problem, we must find the minimum and maximum values that can be calculated by summing exactly four integers from an array of five integers. Then, we must print the respective minimum and maximum values separated by a space.

Example

arr = [1, 3, 5, 7, 9];

The minimum sum is 1+3+5+7, or 16. The maximum sum is 3+5+7+9, or 24. For this example, we should print 16 24.

Pseudo code solution

  1. Sort the input array so that the numbers are in increasing order.
  2. Define numeric min and max variables to compute the sum of each.
  3. Loop over the input array
    • Sum all array elements, except the last one, and assign the sum to the min variable.
    • Sum all array elements, except the first one, and assign the sum to the max variable.
  4. Log the min and max to the console.

Code solution

function minMaxSum(arr) {
  const sortedArray = arr.sort();

  let min = 0;
  let max = 0;

  for (let i = 0; i < sortedArray.length; i++) {
    if (i < sortedArray.length - 1) {
      min += sortedArray[i];
    }

    if (i > 0) {
      max += sortedArray[i];
    }
  }

  console.log(`${min} ${max}`);
}

Test cases

minMaxSum([2, 3, 4, 1, 5]);

The min sum for this array should be 10 by summing 1+2+3+4. The max sum for this array should be 14 by summing 2+3+4+5.

10 14

The result is indeed what we expected.

Time and space complexity

The Big O time complexity of the solution is comprised of the following.

  • O(n log n) for the sorting with the JavaScript sort method.
  • O(n) for iterating over the input array, where n is the length of the input array.

When adding both together, we get a time complexity of O(2n log n), which is essentially just O(n log n), or logarithmic time complexity.

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.