↓Skip to main content
  1. LeetCode/

LeetCode 389: Find the Difference

·1 min· ·
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted → Runtime Error → Accepted

Approach
#

As in LC 136 (Bit Manipulation): across s and t every character except the extra one appears an even number of times, so XOR-ing them all leaves it. sum(ord(t)) - sum(ord(s)) also works.

My Attempts
#

The first version sorted and compared position by position and passed; a rewrite then had a syntax error, and the final version subtracted sums of character codes.

Solution
#

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        x = 0
        for c in s + t:
            x ^= ord(c)
        return chr(x)

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • XOR the ord values and convert back with chr.

Interview Explanation
#

Across both strings every character but the extra one appears an even number of times, so XOR-ing all character codes leaves the answer. Time O(n), space O(1).

Related

LeetCode 242: Valid Anagram
·2 mins
LeetCode Easy Hash-Table String Sorting
LeetCode 242 note: two strings are anagrams exactly when their character counts match; compare Counters or sorted strings
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes
LeetCode 383: Ransom Note
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 383 note: every character’s demand in ransomNote must not exceed its supply in magazine; an empty Counter difference means yes
LeetCode 387: First Unique Character in a String
·1 min
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 note: count first, then scan left to right for the first character with count 1
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 409: Longest Palindrome
·2 mins
LeetCode Easy Hash-Table String Greedy
LeetCode 409 note: use an even number of each character on the two sides, plus one in the middle if any count is odd