-
Notifications
You must be signed in to change notification settings - Fork 21.2k
feat: Add NearestElement stack algorithms and fix Javadoc build warnings #7434
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sabarirajan83
wants to merge
2
commits into
TheAlgorithms:master
Choose a base branch
from
sabarirajan83:nearest-elements-in-array
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
132 changes: 132 additions & 0 deletions
132
src/main/java/com/thealgorithms/datastructures/stacks/NearestElement.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| package com.thealgorithms.datastructures.stacks; | ||
|
|
||
| import java.util.Stack; | ||
|
|
||
| /** | ||
| * The NearestElement class provides implementations for classic stack-based | ||
| * algorithms to find the nearest greater or smaller elements in an array. These | ||
| * algorithms use a Monotonic Stack approach to achieve linear time complexity. | ||
| * For more details, see: | ||
| * https://en.wikipedia.org/wiki/All-nearest-smaller-values | ||
| */ | ||
| public final class NearestElement { | ||
|
|
||
| private NearestElement() { | ||
| } | ||
|
|
||
| /** | ||
| * For each element in an array, finds the first element to its right that | ||
| * is greater. | ||
| * | ||
| * @param arr the input array of integers | ||
| * @return an array where each index i contains the nearest greater element | ||
| * to the right of arr[i], or -1 if none exists | ||
| * @throws IllegalArgumentException if the input array is null | ||
| */ | ||
| public static int[] nearestGreaterToRight(int[] arr) { | ||
| if (arr == null) { | ||
| throw new IllegalArgumentException("Input array cannot be null"); | ||
| } | ||
| int n = arr.length; | ||
| int[] result = new int[n]; | ||
| Stack<Integer> stack = new Stack<>(); | ||
|
|
||
| for (int i = n - 1; i >= 0; i--) { | ||
| // Safety Check 1: Short-circuit && prevents peek() on empty stack | ||
| while (!stack.isEmpty() && stack.peek() <= arr[i]) { | ||
| stack.pop(); | ||
| } | ||
| // Safety Check 2: Ternary operator handles empty stack case | ||
| result[i] = stack.isEmpty() ? -1 : stack.peek(); | ||
| stack.push(arr[i]); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * For each element in an array, finds the first element to its left that is | ||
| * greater. | ||
| * | ||
| * @param arr the input array of integers | ||
| * @return an array where each index i contains the nearest greater element | ||
| * to the left of arr[i], or -1 if none exists | ||
| * @throws IllegalArgumentException if the input array is null | ||
| */ | ||
| public static int[] nearestGreaterToLeft(int[] arr) { | ||
| if (arr == null) { | ||
| throw new IllegalArgumentException("Input array cannot be null"); | ||
| } | ||
| int n = arr.length; | ||
| int[] result = new int[n]; | ||
| Stack<Integer> stack = new Stack<>(); | ||
|
|
||
| for (int i = 0; i < n; i++) { | ||
| // Safety Check 3: Short-circuit && prevents peek() on empty stack | ||
| while (!stack.isEmpty() && stack.peek() <= arr[i]) { | ||
| stack.pop(); | ||
| } | ||
| // Safety Check 4: Ternary operator handles empty stack case | ||
| result[i] = stack.isEmpty() ? -1 : stack.peek(); | ||
| stack.push(arr[i]); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * For each element in an array, finds the first element to its right that | ||
| * is smaller. | ||
| * | ||
| * @param arr the input array of integers | ||
| * @return an array where each index i contains the nearest smaller element | ||
| * to the right of arr[i], or -1 if none exists | ||
| * @throws IllegalArgumentException if the input array is null | ||
| */ | ||
| public static int[] nearestSmallerToRight(int[] arr) { | ||
| if (arr == null) { | ||
| throw new IllegalArgumentException("Input array cannot be null"); | ||
| } | ||
| int n = arr.length; | ||
| int[] result = new int[n]; | ||
| Stack<Integer> stack = new Stack<>(); | ||
|
|
||
| for (int i = n - 1; i >= 0; i--) { | ||
| // Safety Check 5: Short-circuit && prevents peek() on empty stack | ||
| while (!stack.isEmpty() && stack.peek() >= arr[i]) { | ||
| stack.pop(); | ||
| } | ||
| // Safety Check 6: Ternary operator handles empty stack case | ||
| result[i] = stack.isEmpty() ? -1 : stack.peek(); | ||
| stack.push(arr[i]); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * For each element in an array, finds the first element to its left that is | ||
| * smaller. | ||
| * | ||
| * @param arr the input array of integers | ||
| * @return an array where each index i contains the nearest smaller element | ||
| * to the left of arr[i], or -1 if none exists | ||
| * @throws IllegalArgumentException if the input array is null | ||
| */ | ||
| public static int[] nearestSmallerToLeft(int[] arr) { | ||
| if (arr == null) { | ||
| throw new IllegalArgumentException("Input array cannot be null"); | ||
| } | ||
| int n = arr.length; | ||
| int[] result = new int[n]; | ||
| Stack<Integer> stack = new Stack<>(); | ||
|
|
||
| for (int i = 0; i < n; i++) { | ||
| // Safety Check 7: Short-circuit && prevents peek() on empty stack | ||
| while (!stack.isEmpty() && stack.peek() >= arr[i]) { | ||
| stack.pop(); | ||
| } | ||
| // Safety Check 8: Ternary operator handles empty stack case | ||
| result[i] = stack.isEmpty() ? -1 : stack.peek(); | ||
| stack.push(arr[i]); | ||
| } | ||
| return result; | ||
| } | ||
| } | ||
11 changes: 0 additions & 11 deletions
11
src/main/java/com/thealgorithms/searches/InterpolationSearch.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 0 additions & 13 deletions
13
src/main/java/com/thealgorithms/searches/LinearSearch.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 110 additions & 0 deletions
110
src/test/java/com/thealgorithms/datastructures/stacks/NearestElementTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| package com.thealgorithms.datastructures.stacks; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertArrayEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| /** | ||
| * Comprehensive JUnit 5 tests for NearestElement algorithms. | ||
| * These tests cover standard cases, edge cases, negative numbers, and exceptions. | ||
| */ | ||
| public class NearestElementTest { | ||
|
|
||
| // --- Standard Test Cases --- | ||
|
|
||
| @Test | ||
| void testStandardInput() { | ||
| int[] input = {4, 5, 2, 10, 8}; | ||
|
|
||
| // Nearest Greater to Right: For 4->5, 5->10, 2->10, 10->none, 8->none | ||
| assertArrayEquals(new int[]{5, 10, 10, -1, -1}, NearestElement.nearestGreaterToRight(input)); | ||
|
|
||
| // Nearest Greater to Left: For 4->none, 5->none, 2->5, 10->none, 8->10 | ||
| assertArrayEquals(new int[]{-1, -1, 5, -1, 10}, NearestElement.nearestGreaterToLeft(input)); | ||
|
|
||
| // Nearest Smaller to Right: For 4->2, 5->2, 2->none, 10->8, 8->none | ||
| assertArrayEquals(new int[]{2, 2, -1, 8, -1}, NearestElement.nearestSmallerToRight(input)); | ||
|
|
||
| // Nearest Smaller to Left: For 4->none, 5->4, 2->none, 10->2, 8->2 | ||
| assertArrayEquals(new int[]{-1, 4, -1, 2, 2}, NearestElement.nearestSmallerToLeft(input)); | ||
| } | ||
|
|
||
| // --- Edge Cases: Empty and Single Element --- | ||
|
|
||
| @Test | ||
| void testEmptyArray() { | ||
| int[] input = {}; | ||
| int[] expected = {}; | ||
| // An empty array should return an empty array for all variations[cite: 1065]. | ||
| assertArrayEquals(expected, NearestElement.nearestGreaterToRight(input)); | ||
| assertArrayEquals(expected, NearestElement.nearestSmallerToLeft(input)); | ||
| } | ||
|
|
||
| @Test | ||
| void testSingleElementArray() { | ||
| int[] input = {10}; | ||
| int[] expected = {-1}; | ||
| // A single element has no neighbors, so it should always return the sentinel -1. | ||
| assertArrayEquals(expected, NearestElement.nearestGreaterToRight(input)); | ||
| assertArrayEquals(expected, NearestElement.nearestSmallerToLeft(input)); | ||
| } | ||
|
|
||
| // --- Edge Cases: Uniform and Monotonic Sequences --- | ||
|
|
||
| @Test | ||
| void testAllIdenticalElements() { | ||
| int[] input = {5, 5, 5, 5}; | ||
| int[] expected = {-1, -1, -1, -1}; | ||
| // Since elements are equal, none are strictly greater or smaller. | ||
| assertArrayEquals(expected, NearestElement.nearestGreaterToRight(input)); | ||
| assertArrayEquals(expected, NearestElement.nearestSmallerToRight(input)); | ||
| } | ||
|
|
||
| @Test | ||
| void testStrictlyIncreasing() { | ||
| int[] input = {1, 2, 3, 4}; | ||
| // Greater to Right: each element has a successor | ||
| assertArrayEquals(new int[]{2, 3, 4, -1}, NearestElement.nearestGreaterToRight(input)); | ||
| // Smaller to Right: no element has a smaller value to its right | ||
| assertArrayEquals(new int[]{-1, -1, -1, -1}, NearestElement.nearestSmallerToRight(input)); | ||
| } | ||
|
|
||
| @Test | ||
| void testStrictlyDecreasing() { | ||
| int[] input = {4, 3, 2, 1}; | ||
| // Smaller to Right: each element has a smaller successor | ||
| assertArrayEquals(new int[]{3, 2, 1, -1}, NearestElement.nearestSmallerToRight(input)); | ||
| // Greater to Right: no element has a larger value to its right | ||
| assertArrayEquals(new int[]{-1, -1, -1, -1}, NearestElement.nearestGreaterToRight(input)); | ||
| } | ||
|
|
||
| // --- Negative Numbers and Large Values --- | ||
|
|
||
| @Test | ||
| void testNegativeNumbers() { | ||
| int[] input = {-10, -5, -2, -8}; | ||
| // Nearest Greater to Right: -10 -> -5, -5 -> -2, -2 -> none, -8 -> none | ||
| assertArrayEquals(new int[]{-5, -2, -1, -1}, NearestElement.nearestGreaterToRight(input)); | ||
| // Nearest Smaller to Left: -10 -> none, -5 -> -10, -2 -> -5, -8 -> -10 | ||
| assertArrayEquals(new int[]{-1, -10, -5, -10}, NearestElement.nearestSmallerToLeft(input)); | ||
| } | ||
|
|
||
| @Test | ||
| void testExtremeValues() { | ||
| int[] input = {Integer.MAX_VALUE, 0, Integer.MIN_VALUE}; | ||
| // Smaller to Right: MAX -> 0, 0 -> MIN, MIN -> none | ||
| assertArrayEquals(new int[]{0, Integer.MIN_VALUE, -1}, NearestElement.nearestSmallerToRight(input)); | ||
| // Greater to Left: MAX -> none, 0 -> MAX, MIN -> 0 | ||
| assertArrayEquals(new int[]{-1, Integer.MAX_VALUE, 0}, NearestElement.nearestGreaterToLeft(input)); | ||
| } | ||
|
|
||
| // --- Exception Handling --- | ||
|
|
||
| @Test | ||
| void testNullInput() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great test coverage for null input edge case! |
||
| // Verifies that an IllegalArgumentException is thrown for null input[cite: 1065, 1068]. | ||
| assertThrows(IllegalArgumentException.class, () -> { | ||
| NearestElement.nearestGreaterToRight(null); | ||
| }); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using ArrayDeque instead of Stack class,
it is faster and recommended in Java docs.