2840. Check if Strings Can be Made Equal With Operations II
On This Page
You are given two strings
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?
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
j - iis 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.
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.
- Initialize two empty lists for
s2, each to store characters at even and odd positions.
- Populate these lists with characters from
- Sort these lists.
- Compare the sorted lists for equality.
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