2839. Check if Strings Can be Made Equal With Operations I
On This Page
You are given two strings
s2, both of length 4, consisting of lowercase English letters. The objective is to find out if it’s possible to make the two strings equal by swapping certain pairs of characters.
A naive approach would be to try out all possible swap combinations. However, this can be very inefficient, especially when the strings have a large number of characters.
Hints & Tips
- Observe that the swapping condition is quite specific:
j - i = 2.
- The strings should be permutations of each other.
The efficient solution for this problem involves sorting the characters at even and odd positions separately for both strings and then comparing them.
- Sort the characters at even indices for
- Sort the characters at odd indices for
- Compare the sorted characters at even indices for both strings and the sorted characters at odd indices for both strings.
class Solution: def canBeEqual(self, s1: str, s2: str) -> bool: even_s1 = sorted(s1[::2]) odd_s1 = sorted(s1[1::2]) even_s2 = sorted(s2[::2]) odd_s2 = sorted(s2[1::2]) return even_s1 == even_s2 and odd_s1 == odd_s2