#1433

Check If a String Can Break Another String

Medium
StringGreedySortingSortingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages sorting and a greedy approach. By sorting both strings, we can directly compare their characters in a single pass to determine if one can break the other.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort both strings s1 and s2.
  2. 2Step 2: Check if sorted s1 can break sorted s2 by comparing characters at each index.
  3. 3Step 3: Check if sorted s2 can break sorted s1 in the same manner.
  4. 4Step 4: Return true if either condition is satisfied; otherwise, return false.
solution.py11 lines
1# Full working Python code
2
3def can_break(s1, s2):
4    s1_sorted = sorted(s1)
5    s2_sorted = sorted(s2)
6    def can_break_helper(a, b):
7        return all(x >= y for x, y in zip(a, b))
8    return can_break_helper(s1_sorted, s2_sorted) or can_break_helper(s2_sorted, s1_sorted)
9
10# Example usage
11print(can_break('abc', 'xya'))  # Output: True

Complexity note: The time complexity is O(n log n) due to the sorting step, which is the most time-consuming operation. The space complexity is O(n) because we create sorted copies of the strings.

  • 1Sorting allows for direct comparison of characters.
  • 2Greedy approach is effective when checking conditions across sorted arrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.