Parse Compact Duration Strings Like 1h30m15s Into Seconds
Last updated: November 29, 2026
Quick Overview
Given a duration string made of number-unit pairs such as "1h30m15s" or "2d", using units d, h, m, and s, return the total number of seconds, rejecting malformed input such as repeated or out-of-order units and trailing numbers.
0
0
0 solved
Given a duration string made of number-unit pairs such as "1h30m15s" or "2d", using units d, h, m, and s, return the total number of seconds, rejecting malformed input such as repeated or out-of-order units and trailing numbers.
A Google phone screen parsing exercise in the style of timeout flags in Borg configs or gcloud command-line options. The interviewer wants a single-pass tokenizer, explicit validation rules agreed up front, and good error messages rather than silently wrong totals.
What the Interviewer Expects
- Agrees on the grammar, including whether order matters and units may repeat
- Accumulates multi-digit numbers in a single left-to-right scan
- Converts with a unit table rather than a chain of if statements
- Raises clear errors for dangling numbers, bare units, and unknown characters
- States O(n) time
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Support fractional values like 1.5h and milliseconds (ms) without ambiguity against minutes.
- Format a number of seconds back into the shortest canonical string.
- How would you share this parser between a CLI and a config validator so error messages stay consistent?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: a string like
1h30m15s,2d,90s. Units ared,h,m,s; case-insensitive. - Output: total seconds as an integer.
- Each unit appears at most once and in decreasing size order (`1...
High-Level Design
Scan characters once with a tiny state machine. Digits extend the current number buffer. A unit character closes the buffer: check that the buffer is non-empty and that the unit ranks strictly after t...