Warm Up · Loops 02
Find Smallest Number in an Array
Problem Statement
Write a function that returns the smallest number in an array.
Example
Input: arr = [2, -6, 4, 8, 1, -9]
Process: smallest goes 2 → -6 → -9
Output: -9
Approach
- Initialize a variable
smallesttoInfinity. - Loop through the array.
- If the current element is less than
smallest, updatesmallest. - Return
smallestafter the loop ends.
Time & Space Complexity
Time Complexity: O(n) - where n is the number of elements in the array.
Space Complexity: O(1) - only a single variable is used.
Visualisation
1Start with the array
[2, -6, 4, 8, 1, -9]2Assume nothing is smaller yet
let smallest = Infinity;3Smaller than current smallest? Replace it
arr[i] < smallest4Smallest number
-9Explanation
- Starting at
Infinityguarantees the first element always becomes the newsmallest. - Each time a smaller value appears,
smallestis updated: 2, then -6, then -9. - After one pass through the array,
smallestholds the minimum value.
Your solution
Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.
// Write your solution in JavaScript // Print the answer with console.log()
Console
No output yet. Use console.log() to print values here.
Write your own solution and press Submit once to unlock the answer.