Return Nth Smallest Element in Java

The challenge

Given an array/list [] of integers, Find the Nth smallest element in this array of integers

Notes

  • Array/list size is at least 3 .
  • Array/list’s numbers could be a mixture of positives , negatives and zeros .
  • Repetition in array/list’s numbers could occur, so don’t Remove Duplications .

Examples

nthSmallest({3,1,2} ,2) ==> return (2) nthSmallest({15,20,7,10,4,3} ,3) ==> return (7) nthSmallest({2,169,13,-5,0,-1} ,4) ==> return (2)
Code language: PHP (php)

The solution in Java code

Option 1:

public class Solution { public static int nthSmallest(final int[] arr, final int n) { java.util.Arrays.sort(arr); for(int i=0; i<arr.length; i++) { if (i==n-1) return arr[i]; } return 0; } }
Code language: Java (java)

Option 2:

import java.util.Arrays; public class Solution { public static int nthSmallest(final int[] arr, final int n) { Arrays.sort(arr); return arr[n - 1]; } }
Code language: Java (java)

Option 3:

import java.util.Arrays; public class Solution { public static int nthSmallest(final int[] arr, final int n) { return Arrays.stream(arr).sorted().skip(n-1).findFirst().getAsInt(); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SampleTest { @Test public void checkPositiveValues() { doTest(new int[]{3, 1, 2}, 2, 2); doTest(new int[]{15, 20, 7, 10, 4, 3}, 3, 7); } @Test public void checkNegativeValues() { doTest(new int[]{-5, -1, -6, -18}, 4, -1); doTest(new int[]{-102, -16, -1, -2, -367, -9}, 5, -2); } @Test public void checkMixedValues() { doTest(new int[]{2, 169, 13, -5, 0, -1}, 4, 2); doTest(new int[]{177, 225, 243, -169, -12, -5, 2, 92}, 5, 92); } private void doTest(final int[] arr, final int n, final int expected) { assertEquals(expected, Solution.nthSmallest(arr, n)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments