[
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 symbolz
only in this word, so total number of times we havez
in string is number of times we have wordzero
inside. So, what we do: we keep global countercnt
and subtract all frequencies, corresponding to lettersz
,e
,r
,o
. - Look at word
two
, we have symbolw
only in this word, remove all wordstwo
. - Look at word
four
, we have symbolu
only in this word, remove all wordsfour
. - Look at word
six
, we have symbolx
only in this word, remove all wordssix
. - Look at word
eight
, we have symbolg
only in this word, remove all wordseight
. - Look at word
one
, we have symbolo
only in this word if we look at words we still have, remove all wordsone
. - Look at word
three
, we have symbolt
only in this word if we look at words we still have, remove all wordsthree
. - Look at word
five
, we have symbolf
only in this word if we look at words we still have, remove all wordsfive
. - Look at word
seven
, we have symbols
only in this word if we look at words we still have, remove all wordsseven
. - Look at word
nine
, we have symboln
only 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