Count Good Numbers up to a Limit
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Count positive integers up to a large limit whose decimal digits are nonzero, unique, and contain no internal valley pattern. The task combines an upper bound of 10^18 with a nine-digit structural limit and requires careful handling of prefixes and boundary values.
Read the full Google Software Engineer interview experience this question came from
Constraints
- m_decimal is the canonical decimal representation of 1 <= m <= 10^18.
- Good numbers use only digits 1 through 9 and never repeat a digit.
- For every three consecutive digits a, b, c, the pattern a > b < c is forbidden.
- A good number has at most nine digits.
Examples
Input: ("1",)
Expected Output: 1
Explanation: Only the number one is included.
Input: ("5",)
Expected Output: 5
Explanation: Every positive one-digit number up to five is good.
Hints
- Use digit DP with tight and started flags plus a used-digit bitmask.
- Keep the previous two chosen digits so appending a digit can detect a newly completed valley.
- Leading padding zeroes are not part of the number and must not enter the mask.
Community answers
Answer by Josef420