Check If a String Can Break Another String — LeetCode 1433 Python Solution
- Problem
- #1433
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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. In other words s2 can break s1 or vice-versa.
Example
- Input
- s1 = "abc", s2 = "xya"
- Output
- true
- Explanation
- "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".
Python solution
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
cs1 = sorted(s1)
cs2 = sorted(s2)
return all(a >= b for a, b in zip(cs1, cs2)) or all(
a <= b for a, b in zip(cs1, cs2)
)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1433. Check If a String Can Break Another String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1433. Check If a String Can Break Another String?
- LeetCode 1433. Check If a String Can Break Another String is rated Medium on LeetCode.
- What topics does LeetCode 1433. Check If a String Can Break Another String cover?
- LeetCode 1433. Check If a String Can Break Another String is tagged Greedy, String and Sorting on LeetCode.