diff --git a/src/main/java/com/thealgorithms/strings/FindTheDifference.java b/src/main/java/com/thealgorithms/strings/FindTheDifference.java new file mode 100644 index 000000000000..ebb228efe7c7 --- /dev/null +++ b/src/main/java/com/thealgorithms/strings/FindTheDifference.java @@ -0,0 +1,27 @@ +package com.thealgorithms.strings; + +/** + * Finds the extra character added to string t, which is string s with one + * additional random character shuffled in. + * + *
Example: s = "abcd", t = "abcde" -> 'e' + * + *
Uses XOR to cancel out matching characters in O(n) time and O(1) space. + * + * @see LeetCode #389 + */ +public final class FindTheDifference { + private FindTheDifference() { + } + + public static char findTheDifference(String s, String t) { + char result = 0; + for (char c : s.toCharArray()) { + result ^= c; + } + for (char c : t.toCharArray()) { + result ^= c; + } + return result; + } +} diff --git a/src/test/java/com/thealgorithms/strings/FindTheDifferenceTest.java b/src/test/java/com/thealgorithms/strings/FindTheDifferenceTest.java new file mode 100644 index 000000000000..1d0ac2220e8b --- /dev/null +++ b/src/test/java/com/thealgorithms/strings/FindTheDifferenceTest.java @@ -0,0 +1,28 @@ +package com.thealgorithms.strings; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class FindTheDifferenceTest { + + @Test + public void testExample() { + assertEquals('e', FindTheDifference.findTheDifference("abcd", "abcde")); + } + + @Test + public void testEmptyS() { + assertEquals('a', FindTheDifference.findTheDifference("", "a")); + } + + @Test + public void testSameCharAdded() { + assertEquals('a', FindTheDifference.findTheDifference("a", "aa")); + } + + @Test + public void testShuffled() { + assertEquals('y', FindTheDifference.findTheDifference("ae", "eay")); + } +}