Problem Description
Explanation
To solve this problem, we can approach it by sorting the two strings in non-decreasing order. If for any index i
, s1[i]
is greater than s2[i]
for all indices i
, or if s2[i]
is greater than s1[i]
for all indices i
, then one string can break the other. This is because if one string is in non-decreasing order, and the other is in non-increasing order, the first string can break the second string.
We can achieve this by sorting both strings and then comparing them character by character. If at any point the characters of one string are all greater than the characters of the other string, then one can break the other.
- Time complexity: O(nlogn) where n is the length of the strings
- Space complexity: O(n) for sorting the strings
Solutions
import java.util.Arrays;
class Solution {
public boolean checkIfCanBreak(String s1, String s2) {
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
boolean canBreakS1 = true;
boolean canBreakS2 = true;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] < arr2[i]) {
canBreakS1 = false;
}
if (arr2[i] < arr1[i]) {
canBreakS2 = false;
}
}
return canBreakS1 || canBreakS2;
}
}
Loading editor...