The challenge

Given an array of integers your solution should find the smallest integer.

For example:

  • Given [34, 15, 88, 2] your solution will return 2
  • Given [34, -345, -1, 100] your solution will return -345

You can assume, for the purpose of this challenge, that the supplied array will not be empty.

The solution in Java

Option 1 (using Arrays.sort):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.Arrays;

public class SmallestIntegerFinder {
    public static int findSmallestInt(int[] args) {

        Arrays.sort(args);
      
        return args[0];
    }
}

Option 2 (using streams):

1
2
3
4
5
6
7
import java.util.stream.IntStream;

public class SmallestIntegerFinder {
    public static int findSmallestInt(int[] args) {
        return IntStream.of(args).min().getAsInt();
    }
}

Test cases to validate the solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class SmallestIntegerFinderTest {

    @Test
    public void example1(){
        int expected = 11;
        int actual = SmallestIntegerFinder.findSmallestInt(new int[]{78,56,232,12,11,43});
        assertEquals(expected, actual);
    }


    @Test
    public void example2(){
        int expected = -33;
        int actual = SmallestIntegerFinder.findSmallestInt(new int[]{78,56,-2,12,8,-33});
        assertEquals(expected, actual);
    }
    
    @Test
    public void example3(){
        int expected = Integer.MIN_VALUE;
        int actual = SmallestIntegerFinder.findSmallestInt(new int[]{0,Integer.MIN_VALUE,Integer.MAX_VALUE});
        assertEquals(expected, actual);
    }
}