703436. First and Second Smallests

Basic

First and Second Smallests

Slug: find-the-smallest-and-second-smallest-element-in-an-array3226

Difficulty: Basic

Id: 703436

Topic Tags: Arrays, Data Structures

Company Tags: Amazon, Goldman Sachs

Summary

Find the first and second smallest elements in an array. This problem involves basic array manipulation and finding the minimum and maximum values in an array.

Detailed Explanation

To solve this problem, we can iterate through the array once to find the smallest element and then again to find the next smallest element that is not equal to the previous one.

Here's a step-by-step breakdown of the solution:

  1. Initialize two variables min and second_min to store the smallest and second smallest elements respectively.
  2. Iterate through the array from left to right.
  3. In each iteration, check if the current element is smaller than min. If it is, update min with the current element.
  4. Continue iterating until the end of the array.
  5. After the first pass, min will store the smallest element and second_min will be updated to the second smallest element (which could be equal to min if there are duplicate elements).
  6. Return min and second_min as the first and second smallest elements.

Time complexity: O(n) where n is the number of elements in the array. Space complexity: O(1) since we only use a constant amount of space to store the minimum and second minimum values.

Optimized Solutions

Java

View on GeeksforGeeks
public class FirstAndSecondSmallest {
    public static int[] find(int[] arr) {
        int min = arr[0];
        int second_min = Integer.MAX_VALUE;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < min) {
                second_min = min;
                min = arr[i];
            } else if (arr[i] < second_min && arr[i] != min) {
                second_min = arr[i];
            }
        }
        return new int[]{min, second_min};
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.