Check if Strings Can be Made Equal With Operations I Problem
#2839
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2839.
You are given two strings s1 and s2, both of length 4, 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 thatj - i = 2, 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 = "abcd", s2 = "cdab"
Output: true
Explanation: We can do the following operations on s1:
- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad".
- Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2.
Example 2:
Input: s1 = "abcd", s2 = "dacb"
Output: false
Explanation: It is not possible to make the two strings equal.
Constraints:
s1.length == s2.length == 4s1ands2consist only of lowercase English letters.
Solution
Approach: Counting
A swap only exchanges characters whose indices differ by 2, so a character never changes the parity of its position, and any arrangement within the even positions (and within the odd positions) can be reached. So the strings can be made equal exactly when the characters at even indices match as multisets and the characters at odd indices match.
Complexity: time O(n), space O(|Σ|), where Σ is the alphabet.
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
return Counter(s1[::2]) == Counter(s2[::2]) and Counter(s1[1::2]) == Counter(
s2[1::2]
)