Find the Smallest Element in an Array
Solve this ProblemEasy5 min
Topics
BasicsArrays
Companies
TCSInfosysWipro
Given an array
nums, return its smallest element.
This is the mirror image of finding the largest element. The scanning version keeps a running minimumRunning MinimumThe smallest value seen so far while walking through a sequence. and updates it whenever something smaller appears; the sorting version is shorter but does far more work than necessary. Starting the running minimum at the first element (not at 0) keeps the answer correct for all-positive arrays.
Test Case 1:
Input:nums = [12, 4, 19, 7]
Output:4
Explanation:4 is smaller than every other value.
Test Case 2:
Input:nums = [-3, -9, 0]
Output:-9
Explanation:Negative values count too; −9 is the smallest.
Constraints
- ◆
1 ≤ nums.length ≤ 1000 - ◆
-1000000 ≤ nums[i] ≤ 1000000
Try the Dry Run
Approach & Solutions
Sort a Copy, Take the FirstGood
Sort a copy of the array in ascending order; the smallest value then sits at index 0. Short to write, but sorting puts every element in order when only one value is needed.
Time
O(n log n)Space
O(n)Java
class Solution {
public int smallestElement(int[] nums) {
int[] sorted = nums.clone();
Arrays.sort(sorted);
return sorted[0];
}
}Single ScanOptimal
Remember the smallest value seen so far, starting with the first element. Walk through the rest and replace it whenever a smaller value appears. One pass, one extra variable.
Time
O(n)Space
O(1)Java
class Solution {
public int smallestElement(int[] nums) {
int smallest = nums[0];
for (int value : nums) {
if (value < smallest) {
smallest = value;
}
}
return smallest;
}
}