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.

You can apply the following operation on any of the two strings any number of times:

  • Choose any two indices i and j such that j - 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.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "abcd", s2 = "cdab"
Output: true
💡 Note: We can swap positions 0 and 2 in s1 to get "cbad", then swap positions 1 and 3 to get "cdab" which equals s2.
Example 2 — Impossible Case
$ Input: s1 = "abcd", s2 = "dacb"
Output: false
💡 Note: Even positions in s1 are {a,c} but in s2 are {d,c}. Since 'a' and 'd' are different, it's impossible to make them equal.
Example 3 — Already Equal
$ Input: s1 = "abcd", s2 = "abcd"
Output: true
💡 Note: The strings are already equal, so no operations are needed.

Constraints

  • s1.length == s2.length == 4
  • s1 and s2 consist of only lowercase English letters

Visualization

Tap to expand
String Equality with Distance-2 Swapss1 = "abcd"s2 = "cdab"abcdcdabOnly positions with distance 2 can swap: 0↔2, 1↔3Even Group{a,c} = {c,a} ✓Odd Group{b,d} = {d,b} ✓Result: true - Both groups match!
Understanding the Visualization
1
Input Strings
Two strings of length 4 with swap constraint j-i=2
2
Position Groups
Characters can only move within even or odd position groups
3
Compare Groups
Check if both strings have same characters in each group
Key Takeaway
🎯 Key Insight: Characters can only swap within the same position parity group (even or odd indices)
Asked in
Microsoft 15 Amazon 12
25.0K Views
Medium Frequency
~8 min Avg. Time
850 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