class Solution:
# main idea: find first comparable (non equal) char in two sorted string and start compare if bigger string breaks the rule
# time O(O) space O(1)
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
length = len(s1)
s1 = sorted(s1)
s2 = sorted(s2)
for i in range(length):
if s1[i] < s2[i]:
big, small = s2, s1
start = i
break
elif s1[i] == s2[i]:
continue
else:
big, small = s1, s2
start = i
break
for j in range(start+1,length):
if big[j] < small[j]:
return False
return True
optimal version
class Solution:
# main idea:check for all char in alphabet, if count for all char s1 >= s2, or vise versa
# time O(O) space O(1)
def check(self,d1,d2):
s = 0
for c in string.ascii_lowercase:
s += d1[c] - d2[c]
if s < 0:
return False
return True
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
d1 = collections.Counter(s1)
d2 = collections.Counter(s2)
return self.check(d1,d2) | self.check(d2,d1)