DEV Community

averagealloy
averagealloy

Posted on

challenge gauntlet #003

The problem

Given a string of space-separated numbers, return the highest and lowest values in that string.

The breakdown

let's look at the examples:

highAndLow("1 2 3 4 5");  // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"

Alright, so what do we need to return? Two integers, one the maximum and one the minimum. The max will be first followed by the minimum. It also looks like the return statement is a string so let's get down to brass tax!

let's set a variable to an empty string.
let str = "";

Then I would need a variable that takes the numbers in the string and splits them on the spaces putting them into an array.

It would look like this:
let arr = numbers.split(" ");

Then for the return statement what we want to do is spread over the array getting the max value, then add a space and then doing the same for the minimum value. This is good but looking back at the examples we need those values in a string. So before we do that we need to add it to a string. It would look like this:

return str + Math.max(...arr) + " " + Math.min(...arr);

Here is it all together:



function highAndLow(numbers){
let str = "";

let arr = numbers.split(" ");

return str + Math.max(...arr) + " " + Math.min(...arr);
}




#O-Zone

Alright so let's talk about time and space!


Disclaimer: I am new at tackling big O in relation to problems. If There stuff that I need to work on let me know in the comments below!

The first two lines I am not to concerned with but the third, that where it gets interesting. From my understanding (mostly a really smart friend), it would be O(n) for one of the operations. Because there are two of them (operations regarding the array (spread operator))it would be 2 but we would drop the 2 and look at the base. Long story short it will be O(n) or linear time and space. This means as the input grows the amount of computation would grow the same or in lockstep. 


#What to work on

Ok, some progress. Big O has been put into the fold but, the variables have slipped a bit this week but it is about progress, not perfection. 


thanks, Mike









Top comments (0)