389. Find the Difference LeetCode Solution

In this guide, you will get 389. Find the Difference LeetCode Solution with the best time and space complexity. The solution to Find the Difference problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find the Difference solution in C++
  4. Find the Difference solution in Java
  5. Find the Difference solution in Python
  6. Additional Resources
389. Find the Difference LeetCode Solution image

Problem Statement of Find the Difference

You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.

Example 1:

Input: s = “abcd”, t = “abcde”
Output: “e”
Explanation: ‘e’ is the letter that was added.

Example 2:

Input: s = “”, t = “y”
Output: “y”

Constraints:

0 <= s.length <= 1000
t.length == s.length + 1
s and t consist of lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

389. Find the Difference LeetCode Solution in C++

class Solution {
 public:
  char findTheDifference(string s, string t) {
    const char sXors = accumulate(s.begin(), s.end(), 0, bit_xor<>());
    const char tXors = accumulate(t.begin(), t.end(), 0, bit_xor<>());
    return sXors ^ tXors;
  }
};
/* code provided by PROGIEZ */

389. Find the Difference LeetCode Solution in Java

class Solution {
  public char findTheDifference(String s, String t) {
    final char sXors = (char) s.chars().reduce(0, (a, b) -> a ^ b);
    final char tXors = (char) t.chars().reduce(0, (a, b) -> a ^ b);
    return (char) (sXors ^ tXors);
  }
}
// code provided by PROGIEZ

389. Find the Difference LeetCode Solution in Python

class Solution:
  def findTheDifference(self, s: str, t: str) -> str:
    sXors = chr(functools.reduce(operator.xor, map(ord, s), 0))
    tXors = chr(functools.reduce(operator.xor, map(ord, t), 0))
    return chr(ord(sXors) ^ ord(tXors))
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.