Find Smallest
Given an array of integers, find the smallest element. Return the minimum value. If the array is empty, return 0.
For example, the smallest in [5, 2, 8, 1, 9] is 1. In [-3, -7, -1] it is -7. In [10] it is 10. An empty array returns 0.
Finding the minimum is a fundamental array operation. It teaches the linear scan pattern: initialize a candidate with the first element, then compare each subsequent element and update if a smaller value is found.
The solution initializes min to the first element, iterates through the rest, and updates min whenever a smaller element is encountered. After the loop, return min.
Edge cases include an empty array (return 0), a single element (return it), all equal values (return that value), and negative numbers (the minimum is the most negative value).
Example Input & Output
Example 1: The smallest value in [10, 5, 8, 3, 12] is 3
Example 2: The smallest value in [0, -1, -5, 2] is -5
Example 3: With a single element, that element is the smallest
Algorithm Flow
Solution Approach
Iterate through the array while tracking the smallest value seen so far.
Handle empty array by returning 0. Set min to the first element. Loop from the second element onward; if the current element is smaller than min, update min. Return min after examining all elements.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int find_smallest(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int min = nums[0];
for (int num : nums) {
if (num < min) min = num;
}
return min;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
