Check if Strings Can be Made Equal With Operations II Problem
Description
LeetCode Problem 2840.
You are given two strings s1 and s2, both of length n, consisting of lowercase English letters.
You can apply the following operation on any of the two strings any number of times:
- Choose any two indices
iandjsuch thati < jand the differencej - iis even, then swap the two characters at those indices in the string.
Return true if you can make the strings s1 and s2 equal, and false otherwise.
Example 1:
Input: s1 = "abcdba", s2 = "cabdab"
Output: true
Explanation: We can apply the following operations on s1:
- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbadba".
- Choose the indices i = 2, j = 4. The resulting string is s1 = "cbbdaa".
- Choose the indices i = 1, j = 5. The resulting string is s1 = "cabdab" = s2.
Example 2:
Input: s1 = "abe", s2 = "bea"
Output: false
Explanation: It is not possible to make the two strings equal.
Constraints:
n == s1.length == s2.length1 <= n <= 10^5s1ands2consist only of lowercase English letters.
Solution
Approach: Counting by Index Parity
An operation swaps two characters whose indices differ by an even amount, so characters at even indices can be rearranged freely among the even positions, and likewise for odd indices. The characters never change parity.
So the strings can be made equal exactly when the multiset of letters at even indices matches, and the multiset at odd indices matches. We count letters per parity in s1, subtract the counts from s2, and check that everything is zero.
Complexity: Time O(n), space O(1) (26 letters per parity).
class Solution:
def checkStrings(self, s1: str, s2: str) -> bool:
return Counter(s1[::2]) == Counter(s2[::2]) and Counter(s1[1::2]) == Counter(
s2[1::2]
)