Repository: TheAlgorithms/Java
Pull request #5756 (2024-10-13 06:57:00)

feat: Add `CelebrityFinder` new algorithm with Junit 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/5756?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `77.77778%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 63.95%. Comparing base [(`6682c7c`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/6682c7c76e2bf016e2e7b51a6027ac30d354b13e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`77f2e9c`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/77f2e9c465e65a8005f0249d979c5a5c978d018f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5756?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...java/com/thealgorithms/stacks/CelebrityFinder.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5756?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstacks%2FCelebrityFinder.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdGFja3MvQ2VsZWJyaXR5RmluZGVyLmphdmE=) | 77.77% | [0 Missing and 2 partials :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5756?src=pr&el=tree&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    #5756      +/-   ##
============================================
- Coverage     63.96%   63.95%   -0.01%     
- Complexity     4172     4176       +4     
============================================
  Files           583      584       +1     
  Lines         16320    16329       +9     
  Branches       3150     3154       +4     
============================================
+ Hits          10439    10444       +5     
- Misses         5456     5457       +1     
- Partials        425      428       +3     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5756?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).

alxkm: Could you please provide link to some description of this algorithm, because now it looks like some leetcode
Hardvan: Here are a list of resources that explain the Celebrity Finding algorithm using Stacks:
- [Scaler - The Celebrity Problem](https://www.scaler.in/the-celebrity-problem/)
- [Unraveling the Celebrity Problem: A Solution Using Stacks](https://blogs.brain-mentors.com/unraveling-the-celebrity-problem-a-solution-using-stacks/)

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index cb26c292..11ce5b74 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -607,6 +607,7 @@
             * [WiggleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/WiggleSort.java)
           * stacks
             * [BalancedBrackets](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java)
+            * [CelebrityFinder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/CelebrityFinder.java)
             * [DecimalToAnyUsingStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java)
             * [DuplicateBrackets](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java)
             * [InfixToPostfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java)
@@ -1163,6 +1164,7 @@
             * [WiggleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java)
           * stacks
             * [BalancedBracketsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java)
+            * [CelebrityFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java)
             * [DecimalToAnyUsingStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/DecimalToAnyUsingStackTest.java)
             * [DuplicateBracketsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/DuplicateBracketsTest.java)
             * [InfixToPostfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/CelebrityFinder.java b/src/main/java/com/thealgorithms/stacks/CelebrityFinder.java
new file mode 100644
index 00000000..67ac861e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/CelebrityFinder.java
@@ -0,0 +1,52 @@
+package com.thealgorithms.stacks;
+
+import java.util.Stack;
+
+/**
+ * Solves the celebrity problem using a stack-based algorithm.
+ *
+ * <p>Celebrity is someone known by everyone but doesn't know anyone else.
+ * <p>Applications: Graph theory and social network analysis.
+ *
+ * @author Hardvan
+ */
+public final class CelebrityFinder {
+    private CelebrityFinder() {
+    }
+
+    /**
+     * Finds the celebrity in the given party matrix using a stack-based algorithm.
+     *
+     * @param party A 2D matrix where party[i][j] is 1 if i knows j, otherwise 0.
+     * @return The index of the celebrity, or -1 if there is no celebrity.
+     */
+    public static int findCelebrity(int[][] party) {
+
+        // Push all people onto the stack
+        Stack<Integer> stack = new Stack<>();
+        for (int i = 0; i < party.length; i++) {
+            stack.push(i);
+        }
+
+        // Find the potential celebrity by comparing pairs
+        while (stack.size() > 1) {
+            int person1 = stack.pop();
+            int person2 = stack.pop();
+
+            if (party[person1][person2] == 1) {
+                stack.push(person2); // person1 knows person2, so person2 might be the celebrity
+            } else {
+                stack.push(person1); // person1 doesn't know person2, so person1 might be the celebrity
+            }
+        }
+
+        // Verify the candidate
+        int candidate = stack.pop();
+        for (int i = 0; i < party.length; i++) {
+            if (i != candidate && (party[candidate][i] == 1 || party[i][candidate] == 0)) {
+                return -1;
+            }
+        }
+        return candidate;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java b/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java
new file mode 100644
index 00000000..da021794
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java
@@ -0,0 +1,41 @@
+package com.thealgorithms.stacks;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class CelebrityFinderTest {
+
+    @ParameterizedTest
+    @MethodSource("providePartyMatrices")
+    public void testCelebrityFinder(int[][] party, int expected) {
+        assertEquals(expected, CelebrityFinder.findCelebrity(party));
+    }
+
+    private static Stream<Arguments> providePartyMatrices() {
+        return Stream.of(
+            // Test case 1: Celebrity exists
+            Arguments.of(new int[][] {{0, 1, 1}, {0, 0, 1}, {0, 0, 0}}, 2),
+
+            // Test case 2: No celebrity
+            Arguments.of(new int[][] {{0, 1, 0}, {1, 0, 1}, {1, 1, 0}}, -1),
+
+            // Test case 3: Everyone knows each other, no celebrity
+            Arguments.of(new int[][] {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}}, -1),
+
+            // Test case 4: Single person, they are trivially a celebrity
+            Arguments.of(new int[][] {{0}}, 0),
+
+            // Test case 5: All know the last person, and they know no one
+            Arguments.of(new int[][] {{0, 1, 1, 1}, {0, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}}, 3),
+
+            // Test case 6: Larger party with no celebrity
+            Arguments.of(new int[][] {{0, 1, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 1}, {1, 1, 1, 0}}, -1),
+
+            // Test case 7: Celebrity at the start of the matrix
+            Arguments.of(new int[][] {{0, 0, 0}, {1, 0, 1}, {1, 1, 0}}, 0));
+    }
+}