[
string
math
counter
]
Leetcode 0423. Reconstruct Original Digits from English
https://leetcode.com/problems/reconstruct-original-digits-from-english
Actually what is asked in this problem is to solve linear system of equations: imagine that we have f0, ... f9 frequencies of words zero, ... nine, then we need to solve 10 equations with 10 variables. We can look at this at slightly different angle:
- Let us look at word
zero: we meet symbolzonly in this word, so total number of times we havezin string is number of times we have wordzeroinside. So, what we do: we keep global countercntand subtract all frequencies, corresponding to lettersz,e,r,o. - Look at word
two, we have symbolwonly in this word, remove all wordstwo. - Look at word
four, we have symboluonly in this word, remove all wordsfour. - Look at word
six, we have symbolxonly in this word, remove all wordssix. - Look at word
eight, we have symbolgonly in this word, remove all wordseight. - Look at word
one, we have symboloonly in this word if we look at words we still have, remove all wordsone. - Look at word
three, we have symboltonly in this word if we look at words we still have, remove all wordsthree. - Look at word
five, we have symbolfonly in this word if we look at words we still have, remove all wordsfive. - Look at word
seven, we have symbolsonly in this word if we look at words we still have, remove all wordsseven. - Look at word
nine, we have symbolnonly in this word if we look at words we still have, remove all wordsnine.
Complexity: time complexity is just O(n), where n is length of s, because first we create counter and then we iterate over 10 digits and update cnt in O(1) time. Space complexity is O(n) as well to format our answer.
class Solution:
def originalDigits(self, s):
cnt = Counter(s)
Digits = ["zero","two","four","six","eight","one","three","five","seven","nine"]
Corresp = [0,2,4,6,8,1,3,5,7,9]
Counters = [Counter(digit) for digit in Digits]
Found = [0]*10
for it, C in enumerate(Counters):
k = min(cnt[x]//C[x] for x in C)
for i in C.keys(): C[i] *= k
cnt -= C
Found[Corresp[it]] = k
return "".join([str(i)*Found[i] for i in range(10)])
If you have any question, feel free to ask. If you like the explanations, please Upvote!
If you like the solution, you can upvote it on leetcode discussion section: Problem 0423