We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Strings Can be Made Equal With Operations I

Difficulty: Easy


Problem Description

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.


Key Insights

  • The operation allows swapping characters at indices that are two positions apart.
  • This means that characters at indices [0, 2] and [1, 3] can be swapped freely.
  • As a result, the characters at even indices can be rearranged independently of the characters at odd indices.
  • To determine if s1 can be transformed into s2, we need to check if the characters at the even indices of s1 match those at the even indices of s2, and similarly for the odd indices.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To solve this problem, we can follow these steps:

  1. Extract characters from the even indices (0 and 2) of both strings and check if they are the same when sorted.
  2. Extract characters from the odd indices (1 and 3) of both strings and check if they are the same when sorted.
  3. If both checks pass, return true; otherwise, return false.

This approach uses simple string operations and sorting, which are efficient given the constant length of 4.


Code Solutions

def canBeEqual(s1: str, s2: str) -> bool:
    # Extract and sort characters at even indices
    even_s1 = sorted([s1[0], s1[2]])
    even_s2 = sorted([s2[0], s2[2]])
    
    # Extract and sort characters at odd indices
    odd_s1 = sorted([s1[1], s1[3]])
    odd_s2 = sorted([s2[1], s2[3]])
    
    # Compare sorted characters
    return even_s1 == even_s2 and odd_s1 == odd_s2
← Back to All Questions