Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/java/com/thealgorithms/strings/FindTheDifference.java
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>Example: s = "abcd", t = "abcde" -> 'e'
*
* <p>Uses XOR to cancel out matching characters in O(n) time and O(1) space.
*
* @see <a href="https://leetcode.com/problems/find-the-difference/">LeetCode #389</a>
*/
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;
}
}
Original file line number Diff line number Diff line change
@@ -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"));
}
}
Loading