Skip to content

Commit ecd74b1

Browse files
committed
solve Find the Difference
1 parent e7a8f1f commit ecd74b1

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

problems/find_the_difference.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution:
2+
# Time Complexity: O(n), where n is the length of t or s.
3+
# Space Complexity: O(1)
4+
def findTheDifference(self, s: str, t: str) -> str:
5+
counts = [0] * 26
6+
for ch in s:
7+
counts[ord(ch) - ord("a")] += 1
8+
for ch in t:
9+
if counts[ord(ch) - ord("a")] == 0:
10+
return ch
11+
counts[ord(ch) - ord("a")] -= 1
12+
return ""
13+
14+
15+
class OfficialSolution:
16+
"""
17+
First approach is sorting and comparing character by character.
18+
Time Complexity: O(nlgn).
19+
Space Complexity: O(1).
20+
21+
Second approach is using hash map of 26 keys, which is same as my solution above.
22+
Time Complexity: O(n).
23+
Space Complexity: O(1).
24+
25+
Third approach is bit manipulation. Please check the doc string of the function
26+
below.
27+
"""
28+
29+
def findTheDifferenceApproach3(self, s: str, t: str) -> str:
30+
"""
31+
To use bitwise XOR operation on all elements. XOR would help to eliminate the
32+
alike and only leave the odd duckling.
33+
Thus, the left over bits after XORing all the characters from string s and
34+
string t would be from the extra character of string t.
35+
36+
Time Complexity: O(n), where N is the length of s or t.
37+
Space Complexity: O(1).
38+
"""
39+
xored = 0
40+
for ch in s:
41+
xored ^= ord(ch)
42+
for ch in t:
43+
xored ^= ord(ch)
44+
return chr(xored)

tests/test_find_the_difference .py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import unittest
2+
3+
from find_the_difference import Solution, OfficialSolution
4+
5+
6+
class TestFindTheDifference(unittest.TestCase):
7+
def test_example_1(self):
8+
assert Solution().findTheDifference(s="abcd", t="abcde") == "e"
9+
assert OfficialSolution().findTheDifferenceApproach3(s="abcd", t="abcde") == "e"

0 commit comments

Comments
 (0)