Check If a String Can Break Another String — LeetCode 1433 Python Solution

MediumGreedyStringSorting
Problem
#1433
Pattern
Greedy
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview