Repository: TheAlgorithms/Java
Pull request #5405 (2024-08-26 21:24:10)

refactor: `NextGreaterElement`
Class cleanup.
Readability improvements.
Added tests.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5405?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 48.92%. Comparing base [(`c5b73ec`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c5b73ec742d0522d65331ee02a143f54041845ed?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`02f7553`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/02f7553e3d7d013536a07fdbf6cdea494ab7e23a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5405      +/-   ##
============================================
+ Coverage     48.85%   48.92%   +0.06%     
- Complexity     3039     3043       +4     
============================================
  Files           524      524              
  Lines         15256    15252       -4     
  Branches       2900     2900              
============================================
+ Hits           7454     7462       +8     
+ Misses         7494     7481      -13     
- Partials        308      309       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5405?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java b/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java
index f7cbea71..8b7c9c3e 100644
--- a/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java
+++ b/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java
@@ -1,53 +1,34 @@
 package com.thealgorithms.stacks;
 
-import java.util.Arrays;
 import java.util.Stack;
 
-/*
-    Given an array "input" you need to print the first greater element for each element.
-    For a given element x of an array, the Next greater element of that element is the
-    first greater element to the right side of it. If no such element is present print -1.
-
-    Example
-    input = { 2, 7, 3, 5, 4, 6, 8 };
-    At i = 0
-    Next greater element between (1 to n) is 7
-    At i = 1
-    Next greater element between (2 to n) is 8
-    At i = 2
-    Next greater element between (3 to n) is 5
-    At i = 3
-    Next greater element between (4 to n) is 6
-    At i = 4
-    Next greater element between (5 to n) is 6
-    At i = 5
-    Next greater element between (6 to n) is 8
-    At i = 6
-    Next greater element between (6 to n) is -1
-
-    result : [7, 8, 5, 6, 6, 8, -1]
-
-    1. If the stack is empty Push an element in the stack.
-    2. If the stack is not empty:
-        a.  compare the top element of the stack with next.
-        b.  If next is greater than the top element, Pop element from the stack.
-            next is the next greater element for the popped element.
-        c.  Keep popping from the stack while the popped element is smaller
-            than next. next becomes the next greater element for all such
-            popped elements.
-        d. Finally, push the next in the stack.
-
-    3. If elements are left in stack after completing while loop then their Next greater element is
-   -1.
+/**
+ * Utility class to find the next greater element for each element in a given integer array.
+ *
+ * <p>The next greater element for an element x is the first greater element on the right side of x in the array.
+ * If no such element exists, the result will contain 0 for that position.</p>
+ *
+ * <p>Example:</p>
+ * <pre>
+ * Input:  {2, 7, 3, 5, 4, 6, 8}
+ * Output: {7, 0, 5, 6, 6, 8, 0}
+ * </pre>
  */
-
 public final class NextGreaterElement {
     private NextGreaterElement() {
     }
 
+    /**
+     * Finds the next greater element for each element in the given array.
+     *
+     * @param array the input array of integers
+     * @return an array where each element is replaced by the next greater element on the right side in the input array,
+     * or 0 if there is no greater element.
+     * @throws IllegalArgumentException if the input array is null
+     */
     public static int[] findNextGreaterElements(int[] array) {
         if (array == null) {
-            return array;
+            throw new IllegalArgumentException("Input array cannot be null");
         }
 
         int[] result = new int[array.length];
@@ -62,10 +43,4 @@ public final class NextGreaterElement {
 
         return result;
     }
-
-    public static void main(String[] args) {
-        int[] input = {2, 7, 3, 5, 4, 6, 8};
-        int[] result = findNextGreaterElements(input);
-        System.out.println(Arrays.toString(result));
-    }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java b/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java
new file mode 100644
index 00000000..bf015ddc
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java
@@ -0,0 +1,29 @@
+package com.thealgorithms.stacks;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+class NextGreaterElementTest {
+
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    void testFindNextGreaterElements(int[] input, int[] expected) {
+        assertArrayEquals(expected, NextGreaterElement.findNextGreaterElements(input));
+    }
+
+    static Stream<Arguments> provideTestCases() {
+        return Stream.of(Arguments.of(new int[] {2, 7, 3, 5, 4, 6, 8}, new int[] {7, 8, 5, 6, 6, 8, 0}), Arguments.of(new int[] {5}, new int[] {0}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {2, 3, 4, 5, 0}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {0, 0, 0, 0, 0}),
+            Arguments.of(new int[] {4, 5, 2, 25}, new int[] {5, 25, 25, 0}), Arguments.of(new int[] {}, new int[] {}));
+    }
+
+    @Test
+    void testNullInput() {
+        assertThrows(IllegalArgumentException.class, () -> NextGreaterElement.findNextGreaterElements(null));
+    }
+}