Problem Summary
You are given two strings s1 and s2, both of length 4.
You can perform the following operation any number of times:
- Swap characters at indices:
0 โ 21 โ 3
Return true if you can make s1 equal to s2, otherwise false.
๐ Key Observation
The allowed swaps create two independent groups of indices:
- Group 1:
{0, 2} - Group 2:
{1, 3}
Within each group, characters can be freely swapped, but cannot move between groups.
๐ That means:
- Characters at indices
{0, 2}ins1must match those ins2 - Characters at indices
{1, 3}ins1must match those ins2
๐ก Core Idea
Instead of simulating swaps, we:
- Compare characters in the same groups
- Sort or count them
- Check if both groups match between
s1ands2
โ Approach
Step-by-step:
- Extract characters:
group1_s1 = [s1[0], s1[2]]group2_s1 = [s1[1], s1[3]]
- Do the same for
s2 - Sort both groups and compare
๐ง Why Sorting Works
Since we can swap freely inside a group, only the multiset (frequency) mattersโnot order.
๐งพ Code Implementation
Python
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
return (
sorted([s1[0], s1[2]]) == sorted([s2[0], s2[2]]) and
sorted([s1[1], s1[3]]) == sorted([s2[1], s2[3]])
)
Java
class Solution {
public boolean canBeEqual(String s1, String s2) {
char[] g1_s1 = {s1.charAt(0), s1.charAt(2)};
char[] g1_s2 = {s2.charAt(0), s2.charAt(2)};
char[] g2_s1 = {s1.charAt(1), s1.charAt(3)};
char[] g2_s2 = {s2.charAt(1), s2.charAt(3)}; Arrays.sort(g1_s1);
Arrays.sort(g1_s2);
Arrays.sort(g2_s1);
Arrays.sort(g2_s2); return Arrays.equals(g1_s1, g1_s2) && Arrays.equals(g2_s1, g2_s2);
}
}
C++
class Solution {
public:
bool canBeEqual(string s1, string s2) {
vector<char> g1_s1 = {s1[0], s1[2]};
vector<char> g1_s2 = {s2[0], s2[2]};
vector<char> g2_s1 = {s1[1], s1[3]};
vector<char> g2_s2 = {s2[1], s2[3]}; sort(g1_s1.begin(), g1_s1.end());
sort(g1_s2.begin(), g1_s2.end());
sort(g2_s1.begin(), g2_s1.end());
sort(g2_s2.begin(), g2_s2.end()); return g1_s1 == g1_s2 && g2_s1 == g2_s2;
}
};
โฑ๏ธ Complexity Analysis
- Time Complexity: O(1)
(Only 4 characters โ constant work) - Space Complexity: O(1)
๐งช Example
Input
s1 = "abcd"
s2 = "cdab"
Explanation
- Group1:
a, cโ matchesc, a - Group2:
b, dโ matchesd, b
โ
Output: true
๐ Takeaway
This problem is not about simulating swapsโitโs about recognizing index grouping constraints.
Once you see the pattern:
โSwaps only within fixed index setsโ
๐ It reduces to a simple group comparison problem.