NeetCode #861LC-389EasyBit Manipulation
← Back to All Problems#861 · #389 · Find the Difference(找不同)
📌 Problem Statement & Constraints
You are given two strings
s and t. String t is produced by shuffling s and then inserting one extra lowercase letter at a random position. Return that extra letter. Constraints: 0 <= s.length <= 1000, t.length == s.length + 1, and both contain only lowercase English letters.💡 Core Algorithmic Approaches
- Every character of
salso appears int, plus exactly one extra character. - XOR-ing the character codes of all of
sand all oftcancels the shared characters, leaving only the extra one. - This mirrors the single-number trick and avoids any extra data structure.
- An equally valid alternative is to compare the sums of the character codes, or to use a 26-entry count array.
💻 Benchmark Python3 Implementation
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
res = 0
for ch in s:
res ^= ord(ch) # shared characters cancel out
for ch in t:
res ^= ord(ch)
return chr(res)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass over each string.
💾 Space Complexity
O(1): a single accumulator.
⚠️ Interview Pitfalls & Follow-ups
- Using a set difference: sets discard duplicates, so a repeated extra character would be lost; e.g.
s = a, t = aa. - Sorting both strings and comparing: O(n log n) and more code than the XOR pass.
- Forgetting the empty-string case:
smay be empty, in which case the single character oftis the answer; the loops handle it. - XOR-ing characters instead of their codes: in Python you must call
ordexplicitly, since strings are not integers.