Last Updated: June 7, 2026
Scan the array and return the smallest value. The detail to be careful about is where you start the comparison from.
The values can be negative or zero, so you cannot assume the answer is positive or begin the search at zero. If you seeded a running minimum with 0 and the array were all positive, like [4, 2, 7], you would wrongly return 0 even though 0 is not in the array. Seed the running minimum with the first element instead, which is always a real value in the array.
The array can also contain duplicates of the smallest value. That changes nothing, since the smallest value is still the smallest no matter how many times it appears.
-2^31 <= nums[i] <= 2^31 - 1 → Full 32-bit signed range. Values can be negative or zero, so never seed the running minimum with 0. Seed it with nums[0] instead, an actual element of the array. For an all-positive array like [4, 2, 7], starting at 0 would return 0, which is wrong. Starting at nums[0] = 4 and then scanning gives the correct answer 2.1 <= nums.length → The array is non-empty, so nums[0] always exists and is a safe starting value.Finding the smallest value means looking at every element at least once, since any one of them could be the minimum. Keep a single variable holding the smallest value seen so far. Start it at nums[0], then walk the rest of the array, updating the variable each time you find a smaller element. When the scan finishes, the variable holds the smallest element. Because the seed is a real element rather than 0, the result is guaranteed to be one of the inputs.
smallest = nums[0].nums[i], if nums[i] < smallest, set smallest = nums[i].smallest.Input:
Start with smallest = nums[0] = 4. Compare against nums[1] = 2. Since 2 < 4, update smallest = 2. Compare against nums[2] = 7. Since 7 > 2, leave smallest unchanged. The scan ends with smallest = 2.
Notice that even though every value in the array is positive, seeding with the first element gives the right answer. A 0 seed would have returned 0, which is not in the array.