LeetCode 389: Find the Difference Solution

Master LeetCode problem 389 (Find the Difference), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

389. Find the Difference

Problem Explanation

Explanation

To find the added letter in string t, we can calculate the ASCII value sum of all characters in both strings s and t. The difference between these sums will give us the ASCII value of the added letter. We can then convert this ASCII value back to a character to get the added letter.

  • Initialize a variable sum to 0.
  • Iterate over all characters in both strings s and t and add the ASCII values of the characters to sum.
  • Calculate the difference between the sum of ASCII values of characters in t and the sum of ASCII values of characters in s.
  • Convert this difference back to a character to get the added letter.

Time Complexity: O(n), where n is the length of string t. Space Complexity: O(1)

Solution Code

class Solution {
    public char findTheDifference(String s, String t) {
        int sum = 0;
        for (char c : s.toCharArray()) {
            sum += c;
        }
        for (char c : t.toCharArray()) {
            sum -= c;
        }
        return (char) Math.abs(sum);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 389 (Find the Difference)?

This page provides optimized solutions for LeetCode problem 389 (Find the Difference) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 389 (Find the Difference)?

The time complexity for LeetCode 389 (Find the Difference) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 389 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 389 in Java, C++, or Python.

Back to LeetCode Solutions