You are given two strings s1
and s2
, both of the same length. You can perform the following operation any number of times:
Return true
if you can make the strings s1
and s2
equal, and false
otherwise.
Example:
s1 = "abcd", s2 = "cdab"
true
s1[1]
with s1[3]
results in "adcb"
s1[0]
with s1[2]
results in "cdab"
To determine if we can make s1
equal to s2
using the allowed operations, let’s break it down:
s1
to s2
using the allowed operations; otherwise, we cannot.Here’s the implementation of the described strategy:
def canBeMadeEqual(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
even_indices_s1 = sorted(s1[i] for i in range(0, len(s1), 2))
odd_indices_s1 = sorted(s1[i] for i in range(1, len(s1), 2))
even_indices_s2 = sorted(s2[i] for i in range(0, len(s2), 2))
odd_indices_s2 = sorted(s2[i] for i in range(1, len(s2), 2))
return even_indices_s1 == even_indices_s2 and odd_indices_s1 == odd_indices_s2
# Example usage:
s1 = "abcd"
s2 = "cdab"
print(canBeMadeEqual(s1, s2)) # Output: True
O(n)
where n
is the length of the strings.O(n log n)
for both even and odd indices.O(n)
.Overall, the time complexity is dominated by the sorting step, so it is O(n log n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?