# Find the largest and smallest number in an unsorted array

## Coding Challenge on Data Structure Array.

You have given an input array of integers and your goal is to find both smallest and largest number present in the array with O(n) Time Complexity.

It is also important that your code should be efficient and find out both smallest and largest integer within O(n) Time Complexity

That means you have to find both results by traversing array only one time.

In Javascript, you can directly call sort function and get smallest and largest number. But that is not efficient way to find the results over the Big data. We also want to make sure we achieve O(n) Time Complexity and O(1) Space Complexity.

### First we have to understand the Algorithm we Could use.

Below is the efficient algorithm for doing this. While traversing through the array keep track of maximum and minimum numbers found so far and when you reach the end of the array, then you will get smallest and largest numbers present in the array.

1) Use given array as an Input

2) Define max and min variables to first element of an input array.

3) Traverse through the array

Check if the current element is greater than the max variable, if yes then set max variable to current element.

Check if the current element is less than the min variable , if yes then set min variable to current element.

4) Return the smallest and largest numbers in the input array.

``````const findMinMax = (arr) => {

let max = arr;
let min = arr;

for (let i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
if (min > arr[i]) {
min = arr[i];
}
}

return (`Max: \${max} Min: \${min}`);
}

let arr = [1,5,15,4,7,3];
console.log(findMinMax(arr));

Use this code playground to play with different inputs.
``````