Check If a String Can Break Another String Problem
Description
LeetCode Problem 1433.
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.
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.
Example 1:
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".
Example 2:
Input: s1 = "abe", s2 = "acd"
Output: false
Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
Example 3:
Input: s1 = "leetcodee", s2 = "interview"
Output: true
Constraints:
s1.length == ns2.length == n1 <= n <= 10^5- All strings consist of lowercase English letters.
Solution
Approach: Sort Both Strings
We are free to reorder both strings, so the question is whether we can pair up the characters so that one side is >= in every pair.
Sort both strings and pair them position by position: smallest with smallest, second smallest with second smallest, and so on. If any pairing lets s1 win everywhere, this one does too. Intuitively, the i-th smallest character of s1 has to beat at least i + 1 characters of s2, and pairing it with the i-th smallest of s2 asks for exactly that and nothing more.
So check the sorted strings in both directions: either a[i] >= b[i] for every i, or a[i] <= b[i] for every i. Equal characters count for both, so two identical strings break each other.
Complexity: O(n log n) time for sorting and O(n) extra space. A counting sort over the 26 letters brings this down to O(n).
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
a, b = sorted(s1), sorted(s2)
# pairing the sorted strings is the best chance for either side to win every position
return all(x >= y for x, y in zip(a, b)) or all(x <= y for x, y in zip(a, b))