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
Check if Strings Can be Made Equal INPUT String s1: a i=0 b i=1 c i=2 d i=3 String s2: c d a b Swap Rule: j - i = 2 Can swap: (0,2) or (1,3) Even indices: 0, 2 Odd indices: 1, 3 ALGORITHM STEPS 1 Group by Position Parity Even: s1[0],s1[2] Odd: s1[1],s1[3] 2 Extract Characters s1 even: {a,c} odd: {b,d} s2 even: {c,a} odd: {d,b} 3 Sort Each Group s1 even sorted: {a,c} s2 even sorted: {a,c} 4 Compare Sorted Groups Even: {a,c} == {a,c} OK Odd: {b,d} == {b,d} OK {a,c} = {a,c} {b,d} = {b,d} Even pos Odd pos FINAL RESULT After applying swaps on s1: Step: Swap s1[0] and s1[2] c b a d Step: Swap s1[1] and s1[3] c d a b s1 becomes "cdab" = s2 Output: true Strings can be made equal! Both groups match - OK Key Insight: Characters at even indices (0, 2) can only swap with each other. Same for odd indices (1, 3). Therefore, we only need to check if sorted characters at even positions match, and sorted characters at odd positions match. Time Complexity: O(1) since string length is fixed at 4. TutorialsPoint - Check if Strings Can be Made Equal With Operations I | Optimal Solution
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