Check if Strings Can be Made Equal With Operations I - Problem

You are given two strings s1 and s2, both of length 4, consisting of lowercase English letters.

Your task is to determine if you can make these strings identical using a special swap operation. You can perform the following operation any number of times on either string:

  • Choose any two indices i and j such that j - i = 2 (exactly 2 positions apart)
  • Swap the characters at positions i and j

Example: In string "abcd", you can swap positions 0 and 2 (characters 'a' and 'c') or positions 1 and 3 (characters 'b' and 'd').

Return true if you can make the strings equal, false otherwise.

Input & Output

example_1.py — Basic swap case
$ Input: s1 = "abcd", s2 = "cdab"
Output: true
💡 Note: We can swap positions 0↔2 in s1 to get "cbad", then swap positions 1↔3 to get "cdab" which matches s2. Alternatively, both strings have the same characters in even positions [a,c] and odd positions [b,d] when sorted.
example_2.py — No solution case
$ Input: s1 = "abcd", s2 = "dacb"
Output: false
💡 Note: Even positions: s1 has [a,c], s2 has [d,c]. Odd positions: s1 has [b,d], s2 has [a,b]. Since the character sets don't match for both groups, no amount of swapping can make them equal.
example_3.py — Already equal case
$ Input: s1 = "abcd", s2 = "abcd"
Output: true
💡 Note: The strings are already identical, so no swaps are needed. Both have matching even [a,c] and odd [b,d] position characters.

Constraints

  • s1.length == s2.length == 4
  • s1 and s2 consist of lowercase English letters only
  • Only swaps between positions with difference of exactly 2 are allowed

Visualization

Tap to expand
Card Grouping AnalogyHand 1: A♠ B♥ C♦ D♣Position 0A♠Group EvenPosition 1B♥Group OddPosition 2C♦Group EvenPosition 3D♣Group OddHand 2: C♦ D♣ A♠ B♥Position 0C♦Group EvenPosition 1D♣Group OddPosition 2A♠Group EvenPosition 3B♥Group OddEven Group (0 ↔ 2)Hand 1: {A♠, C♦}Hand 2: {C♦, A♠}Sorted: {A♠, C♦} = {A♠, C♦}✓ MATCHOdd Group (1 ↔ 3)Hand 1: {B♥, D♣}Hand 2: {D♣, B♥}Sorted: {B♥, D♣} = {B♥, D♣}✓ MATCHResult: Both groups match - hands can be made equal!Algorithm: Sort each group's cards and compareTime: O(1), Space: O(1) - only 4 cards total!
Understanding the Visualization
1
Initial Setup
You have two hands of 4 cards each, positions 0,1,2,3
2
Swap Rules
You can only swap cards at positions 0↔2 and 1↔3
3
Group Recognition
This creates two independent groups: {0,2} and {1,3}
4
Solution
Check if both hands have the same cards in each group
Key Takeaway
🎯 Key Insight: Swapping positions 2 apart creates two independent groups. Just compare the sorted cards in each group!
Asked in
Microsoft 15 Amazon 12 Google 8 Meta 6
24.5K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen