-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_the_difference_btwn_str(merge_sort).py
More file actions
50 lines (40 loc) · 1.34 KB
/
find_the_difference_btwn_str(merge_sort).py
File metadata and controls
50 lines (40 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def mergesort(arr):
if len(arr)<=1:
return arr
mid=len(arr)//2
left_half = mergesort(arr[:mid])
right_half = mergesort(arr[mid:])
sorted_arr =[]
i=j=0
while i<len(left_half) and j <len(right_half):
if left_half[i] < right_half[j]:
sorted_arr.append(left_half[i])
i+=1
else:
sorted_arr.append(right_half[j])
j+=1
while i<len(left_half):
sorted_arr.append(left_half[i])
i+=1
while j <len(right_half):
sorted_arr.append(right_half[j])
j+=1
return sorted_arr
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
sorted_s = mergesort(list(s))
sorted_t = mergesort(list(t))
for i in range(len(sorted_s)):
if sorted_s[i] != sorted_t[i]:
return sorted_t[i]
return sorted_t[-1]
if __name__ == "__main__":
s = "abcd"
t = "abcde"
solution = Solution()
print(solution.findTheDifference(s, t))
# Output: e
# Explanation: The character 'e' is the extra character in string t.
# Time Complexity: O(n log n) due to the mergesort algorithm
# Space Complexity: O(n) for the sorted arrays
# Note: This implementation uses mergesort to sort the characters in both strings