Drill

ProblemsPython › dates

Read a duration a human typed

mediumdatesPython

A config file lets people write timeouts as "1h30m" instead of counting seconds, and the loader has to turn that into a number without trusting it.

parse_duration(text: string) → int

Solve it in the editor →

Where you start

def parse_duration(text: str) -> int:
    

Worked examples

CallResult
parse_duration("1h30m")5400
parse_duration("45s")45
parse_duration("2h")7200
parse_duration("90m")5400

Hint

Scan digits, then expect exactly one unit letter. Remember which units you have already taken so order and repeats are both caught by the same check.

Reference solution in Python
def parse_duration(text: str) -> int:
    rank = {'h': 1, 'm': 2, 's': 3}
    mult = {'h': 3600, 'm': 60, 's': 1}
    i = 0
    total = 0
    last = 0
    while i < len(text):
        n = 0
        digits = 0
        while i < len(text) and text[i].isdigit():
            n = n * 10 + int(text[i])
            i += 1
            digits += 1
        if digits == 0 or i >= len(text):
            return -1
        u = text[i]
        if u not in rank or rank[u] <= last:
            return -1
        last = rank[u]
        total += n * mult[u]
        i += 1
    return total

The same problem in another language

More dates problems in Python