Back to Arrays
Q5Question 5 of 109

Find the smallest element in an array

Key Concepts
  • Seed a min variable with the first element, then scan the rest of the array once and update min whenever a smaller value appears.
  • The algorithm runs in O(n) time and O(1) extra space, mirroring the find-maximum pattern.
  • For money always use BigDecimal and compare with compareTo, where a negative result means the left value is smaller.
  • Seeding with the first real element avoids the trap of using Integer.MAX_VALUE, which is not valid for BigDecimal.
  • Guard the empty array by throwing IllegalArgumentException rather than returning a misleading zero.
  • This pattern is the building block for finding both min and max in a single pass.

Definition

Assume the first element is the smallest, then walk the array once and downgrade min whenever something smaller appears.
  • Linear scan – visit each element exactly once from left to right, giving O(n) time.
  • Tracking variable – a single variable min remembers the smallest value seen so far, giving O(1) extra space.
  • Seeding – initialise min with the first element, not with a large constant, because that is always correct.
  • Comparison – for BigDecimal use compareTo where a negative result means the left value is smaller.
  • Mirror of max – the logic is identical to finding the largest element, with the comparison direction flipped.

Priya runs a shop with current account CUR3001 at National Bank of India and wants to know her smallest single sale of the day so she can decide a minimum order value. She points at her first sale and says "smallest so far." She reads each later sale, and every time a sale is smaller than the one her finger is on, she moves to that smaller one. At the end her finger rests on the smallest sale.

Understanding the Concepts

What is the problem?

Given an array of numbers, find the single smallest element. In a banking context, Priya runs a shop on current account CUR3001 at National Bank of India and wants to know her smallest sale amount of the day to set a minimum order threshold.

Why use a linear scan?

Just like finding the maximum, you cannot skip any element because any skipped element might be the smallest. Sorting first costs O(n log n), which is unnecessary when a single O(n) pass suffices.

How does the algorithm work?

Seed a variable min with the first element. Iterate from the second element to the end. For each element, if it is smaller than min, assign it to min. When the loop finishes, min holds the smallest value.

JAVA
package com.bank.service;

import java.math.BigDecimal;

public class SaleAnalyzer {

    public static BigDecimal findSmallestSale(BigDecimal[] sales) {
        if (sales == null || sales.length == 0) {
            throw new IllegalArgumentException("No sales to analyze");
        }
        BigDecimal min = sales[0];
        for (int i = 1; i < sales.length; i++) {
            if (sales[i].compareTo(min) < 0) {
                min = sales[i];
            }
        }
        return min;
    }

    public static void main(String[] args) {
        BigDecimal[] dailySales = {
            new BigDecimal("1250.00"),
            new BigDecimal("340.50"),
            new BigDecimal("8900.00"),
            new BigDecimal("125.75"),
            new BigDecimal("4600.00")
        };
        BigDecimal smallest = findSmallestSale(dailySales);
        System.out.println("Smallest sale for CUR3001: Rs." + smallest);
    }
}
TEXT
Smallest sale for CUR3001: Rs.125.75

Why seed with the first element?

Seeding with a large constant like Integer.MAX_VALUE does not work for BigDecimal because BigDecimal has no predefined maximum constant. Seeding with the first real element is always correct and avoids guessing an upper bound that might be too small for very large banking amounts.

Why use BigDecimal and compareTo?

BigDecimal stores the exact decimal value and avoids the rounding errors of double. The compareTo method returns a negative number when the left value is smaller, zero when equal, and a positive number when larger. Two BigDecimal values with different scales, such as 340.5 and 340.50, are correctly treated as equal by compareTo.

JAVA
BigDecimal a = new BigDecimal("340.50");
BigDecimal b = new BigDecimal("125.75");
int result = a.compareTo(b); // positive, meaning a > b

What about the empty array edge case?

An empty array has no smallest element. Returning zero would mislead the caller into thinking a zero-rupee sale occurred. Throwing IllegalArgumentException makes the absence explicit.

JAVA
if (sales == null || sales.length == 0) {
    throw new IllegalArgumentException("No sales to analyze");
}

What is the time and space complexity?

  • Time: O(n) because each element is visited exactly once.
  • Space: O(1) because only one tracking variable is used.
  • The lower bound is O(n) because any skipped element could be the smallest.

What are common mistakes?

The most common mistake is initializing min with zero, which gives a wrong answer when all values are positive. Another mistake is using the > comparison direction instead of <, which would find the maximum instead of the minimum.

JAVA
// Wrong: seeding with zero when all sales are positive
BigDecimal min = BigDecimal.ZERO; // stays 0, wrong answer

// Wrong: comparing in the wrong direction
if (sales[i].compareTo(min) > 0) { min = sales[i]; } // finds max, not min

// Correct
BigDecimal min = sales[0];
if (sales[i].compareTo(min) < 0) { min = sales[i]; }

How is this different from finding the maximum?

The logic is identical except the comparison direction is flipped. For finding the maximum you check compareTo > 0; for finding the minimum you check compareTo < 0. Both share the same O(n) time, O(1) space, same seeding strategy, and same edge case handling. They can be combined into a single pass that tracks both min and max simultaneously.

| Aspect | Find Max | Find Min |
|---|---|---|
| Comparison | compareTo > 0 | compareTo < 0 |
| Seed | First element | First element |
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |

What should a senior engineer know?

A senior engineer combines finding both min and max into a single pass to avoid scanning the array twice. The pairwise comparison technique processes elements in pairs, comparing them with each other first, then comparing the smaller against min and the larger against max. This reduces comparisons from 2n to roughly 1.5n. For a Priya's merchant dashboard that needs both the smallest and largest sale, one pass through the day's transactions gives both answers.

Visual Overview

DIAGRAM
  sales[]:  1250  340.50  8900  125.75  4600
              │
              ▼
  min = 1250.00  (seed with first element)
              │
        ┌─────┴─────┐
        │  i = 1     │  340.50 < 1250?  YES → min = 340.50
        │  i = 2     │   8900 < 340.50? NO
        │  i = 3     │  125.75 < 340.50? YES → min = 125.75
        │  i = 4     │   4600 < 125.75? NO
        └─────┬─────┘
              ▼
  Result: min = 125.75

Key Takeaway

Finding the smallest element in an array is the mirror image of finding the largest, and I solve it with a single linear pass using constant extra space. I seed a minimum variable with the first element, then I iterate through the remaining elements, and whenever I find a value smaller than my current minimum I downgrade the minimum to that value. When the loop finishes, the minimum variable holds the smallest element.

In my banking project at National Bank of India, I used this to power a merchant dashboard feature for Priya, who runs a shop on current account CUR3001. She wanted to know her smallest sale of the day to decide a minimum order value, so I scan the list of today's sale amounts and return the smallest. Every amount is a BigDecimal, and I compare using the compareTo method where a negative result means the current value is smaller.

I always seed the minimum with the first real element rather than a giant constant, because seeding with an actual element is guaranteed correct and I never have to guess an upper bound. I also guard the empty list: if the merchant had no sales today, there is no smallest sale, so I throw an IllegalArgumentException instead of returning a misleading zero.

Remember one sentence: seed min with the first element, scan once, and update whenever you find something smaller.

---

Share
Use ← → arrow keys to navigate