Find the smallest and the largest number in an array of integers


Given an array of integers, find the smallest and the largest numbers in the array


Assumptions


- array.length >= 1

- Array is unsorted

- Array can contain duplicate numbers


Example


Input: [2,1,9,4,10,3,7,5,6]

Output: [1,10]

Explanation: 1 is the smallest number in the array, and 10 is the largest number in the given array of numbers


Solution


1. Maintain two int variable - min, max - to hold the smallest and the largest number. Initialize both to first element of array.

2. Traverse array from second element.
- compare element to max, if max is less than element, then set max to element.
- compare element to min, if max is greater than element, then set min to element

3. Add min and max in a new array, and retrun array.


Code



Complexity


Time Complexity O(N)

Space Complexity O(1)

 
Subscribe to our Newsletter

 
 
RECOMMENDED RESOURCES
Behaviorial Interview
Top resource to prepare for behaviorial and situational interview questions.

STAR Interview Example