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 a String Can Break Another String

Difficulty: Medium


Problem Description

Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.


Key Insights

  • A string can break another string if, when sorted, each character in the first string is greater than or equal to the corresponding character in the second string.
  • Sorting both strings allows for a straightforward comparison of their characters.
  • If one string can break the other, then the reverse must also be true; hence, we only need to check one direction.

Space and Time Complexity

Time Complexity: O(n log n) due to sorting both strings.
Space Complexity: O(n) for storing the sorted strings.


Solution

To determine if one string can break another, we can follow these steps:

  1. Sort both strings.
  2. Compare the sorted versions character by character.
  3. If all characters in the first string are greater than or equal to the corresponding characters in the second string, then the first string can break the second string.
  4. If not, check the reverse condition (i.e., if the second string can break the first).

Code Solutions

def canBreak(s1: str, s2: str) -> bool:
    s1_sorted = sorted(s1)
    s2_sorted = sorted(s2)
    
    def canBreakHelper(a, b):
        for i in range(len(a)):
            if a[i] < b[i]:
                return False
        return True
    
    return canBreakHelper(s1_sorted, s2_sorted) or canBreakHelper(s2_sorted, s1_sorted)

# Example usage
print(canBreak("abc", "xya"))  # Output: True
print(canBreak("abe", "acd"))  # Output: False
← Back to All Questions