HackerRank: Second Smallest Element

·

1 min read

Given an array of size N, find the second smallest element in the array. (Do not use sort function. Use O(n) approach.)

Input Format

There are two lines in the input:

  1. An integer N (size of array)

  2. N integers (elements of the array)

Constraints

N\> 0

Output Format

A single integer

Sample Input 0

6
5 2 8 12 67 3
Sample Output 0

3
Explanation 0

Smallest Element = 2, Second Smallest Element = 3

Sample Input 1

4 
1 2 3 4
Sample Output 1

2
Explanation 1

Smallest Element = 1, Second Smallest Element = 2
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here */
        Scanner sc = new Scanner(System.in);
        int n= sc.nextInt();
        int[] arr = new int[n];
        for(int i=0; i<n; i++){
            arr[i] = sc.nextInt();
            //sum += arr[i];
        }

        int secsmall = Integer.MAX_VALUE;
        int firsmall = Integer.MAX_VALUE;

        for(int i:  arr){
            if(i < firsmall){
                secsmall = firsmall;
                firsmall = i;
            }else if( i< secsmall && i != firsmall){
                secsmall = i;
            } 
        }

        if(n < 2)
        System.out.println("0");
        else if( secsmall == Integer.MAX_VALUE)
        System.out.println(firsmall);
        else
        System.out.println( secsmall);
    }
}

One test case didn't run :-

1
3