|
| 1 | +package datastructures.stacks; |
| 2 | +import static org.junit.jupiter.api.Assertions.assertArrayEquals; |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | +class NearestElementTest { |
| 5 | + @Test |
| 6 | + void testNearestGreaterToRight_basic() { |
| 7 | + int[] arr = {4, 5, 2, 25}; |
| 8 | + int[] expected = {5, 25, 25, -1}; |
| 9 | + assertArrayEquals(expected, NearestElement.nearestGreaterToRight(arr)); |
| 10 | + } |
| 11 | + @Test |
| 12 | + void testNearestGreaterToLeft_basic() { |
| 13 | + int[] arr = {4, 5, 2, 25}; |
| 14 | + int[] expected = {-1, -1, 5, -1}; |
| 15 | + assertArrayEquals(expected, NearestElement.nearestGreaterToLeft(arr)); |
| 16 | + } |
| 17 | + @Test |
| 18 | + void testNearestSmallerToRight_basic() { |
| 19 | + int[] arr = {4, 5, 2, 25}; |
| 20 | + int[] expected = {2, 2, -1, -1}; |
| 21 | + assertArrayEquals(expected, NearestElement.nearestSmallerToRight(arr)); |
| 22 | + } |
| 23 | + @Test |
| 24 | + void testNearestSmallerToLeft_basic() { |
| 25 | + int[] arr = {4, 5, 2, 25}; |
| 26 | + int[] expected = {-1, 4, -1, 2}; |
| 27 | + assertArrayEquals(expected, NearestElement.nearestSmallerToLeft(arr)); |
| 28 | + } |
| 29 | + @Test |
| 30 | + void testEdgeCases_emptyAndSingle() { |
| 31 | + int[] empty = {}; |
| 32 | + int[] single = {10}; |
| 33 | + assertArrayEquals(new int[]{}, NearestElement.nearestGreaterToRight(empty)); |
| 34 | + assertArrayEquals(new int[]{-1}, NearestElement.nearestGreaterToRight(single)); |
| 35 | + assertArrayEquals(new int[]{-1}, NearestElement.nearestGreaterToLeft(single)); |
| 36 | + assertArrayEquals(new int[]{-1}, NearestElement.nearestSmallerToRight(single)); |
| 37 | + assertArrayEquals(new int[]{-1}, NearestElement.nearestSmallerToLeft(single)); |
| 38 | + } |
| 39 | + @Test |
| 40 | + void testDuplicates() { |
| 41 | + int[] arr = {2, 2, 2}; |
| 42 | + int[] ngr = {-1, -1, -1}; // strictly greater required |
| 43 | + int[] ngl = {-1, -1, -1}; |
| 44 | + int[] nsr = {-1, -1, -1}; // strictly smaller required |
| 45 | + int[] nsl = {-1, -1, -1}; |
| 46 | + assertArrayEquals(ngr, NearestElement.nearestGreaterToRight(arr)); |
| 47 | + assertArrayEquals(ngl, NearestElement.nearestGreaterToLeft(arr)); |
| 48 | + assertArrayEquals(nsr, NearestElement.nearestSmallerToRight(arr)); |
| 49 | + assertArrayEquals(nsl, NearestElement.nearestSmallerToLeft(arr)); |
| 50 | + } |
| 51 | +} |
0 commit comments