LeetCode 2839: Check Strings Equal (Easy Explanation + Code)

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 โ†” 2
    • 1 โ†” 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} in s1 must match those in s2
  • Characters at indices {1, 3} in s1 must match those in s2

๐Ÿ’ก Core Idea

Instead of simulating swaps, we:

  1. Compare characters in the same groups
  2. Sort or count them
  3. Check if both groups match between s1 and s2

โœ… Approach

Step-by-step:

  1. Extract characters:
    • group1_s1 = [s1[0], s1[2]]
    • group2_s1 = [s1[1], s1[3]]
  2. Do the same for s2
  3. 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 โ†’ matches c, a
  • Group2: b, d โ†’ matches d, 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.

Leave a Comment