Leetcode 1433: Check If a String Can Break Another String

grid47
grid47
Exploring patterns and algorithms
Jun 16, 2024 5 min read

You are given two strings s1 and s2 of the same length. You need to check if some permutation of s1 can ‘break’ some permutation of s2, or vice-versa. A string x can break string y if for every character at position i, x[i] >= y[i] when sorted alphabetically.
Problem
Approach
Steps
Complexity
Input: The input consists of two strings `s1` and `s2`, both containing only lowercase English letters.
Example: s1 = 'cat', s2 = 'abc'
Constraints:
• 1 <= s1.length == s2.length <= 10^5
• All strings consist of lowercase English letters.
Output: The output is a boolean indicating whether one permutation of `s1` can break some permutation of `s2`, or vice-versa.
Example: true
Constraints:
• The output is 'true' if one permutation can break the other, otherwise 'false'.
Goal: To determine if one permutation of `s1` can break some permutation of `s2` or vice-versa.
Steps:
• Step 1: Sort both strings `s1` and `s2`.
• Step 2: Compare the characters of the sorted strings. If at any position, a character from `s1` is less than the corresponding character from `s2`, return 'false'.
• Step 3: If no such position is found, return 'true'.
Goal: The solution should efficiently handle strings of length up to 10^5.
Steps:
• Both strings are of equal length.
• The strings consist only of lowercase English letters.
Assumptions:
• Both input strings are valid and consist of lowercase English letters.
• The strings are of equal length.
Input: s1 = 'cat', s2 = 'abc'
Explanation: After sorting both strings, we have 'act' and 'abc'. Since each character in 'act' is greater than or equal to the corresponding character in 'abc', 's1' can break 's2'.

Input: s1 = 'dog', s2 = 'god'
Explanation: After sorting both strings, we have 'dgo' and 'dgo'. Since the strings are identical, neither can break the other.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus