2840. Check if Strings Can be Made Equal With Operations II
On This Page
Problem Statement
You are given two strings s1
and s2
, both of length n
, consisting of lowercase English letters. You can apply certain operations to make them equal. The question is, is it possible?
Naive Solution
A naive approach would be to try all possible swap operations and compare the two strings at each step, which would be highly inefficient.
Hints & Tips
- Observe that swapping can only occur at indices
i
andj
wherej - i
is even. - Separate the string into two different sequences, one containing characters at even indices and the other at odd indices.
- Check the frequency of characters in both sequences.
Approach
The efficient approach involves separating characters at even and odd positions into two different sequences for each string and then comparing the frequency of characters in these sequences.
Steps
- Initialize two empty lists for
s1
ands2
, each to store characters at even and odd positions. - Populate these lists with characters from
s1
ands2
. - Sort these lists.
- Compare the sorted lists for equality.
Solution
from collections import Counter
def checkStrings(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