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
|
class Solution:
def match_pairs(self, nuts: List[str], bolts: List[str]) -> None:
def partition(arr: List[str], low: int, high: int, pivot: str) -> int:
i = low
for j in range(low, high):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
elif arr[j] == pivot:
arr[j], arr[high] = arr[high], arr[j]
j -= 1
arr[i], arr[high] = arr[high], arr[i]
return i
def match_pairs_util(nuts: List[str], bolts: List[str], low: int, high: int) -> None:
if low < high:
pivot_index = partition(bolts, low, high, nuts[high])
partition(nuts, low, high, bolts[pivot_index])
match_pairs_util(nuts, bolts, low, pivot_index - 1)
match_pairs_util(nuts, bolts, pivot_index + 1, high)
match_pairs_util(nuts, bolts, 0, len(nuts) - 1)
# Example usage
sol = Solution()
nuts = ['@', '#', '$', '%', '^', '&']
bolts = ['$', '%', '&', '^', '@', '#']
sol.match_pairs(nuts, bolts)
print("Matched nuts and bolts:")
print("Nuts: ", nuts)
print("Bolts: ", bolts)
|