← Questions

Smallest number from an increase and decrease pattern

0
AirbnbCodingLast asked Feb 2026

A coding interview question asked in Airbnb's technical phone screen, last asked Feb 2026. It tests greedy, stacks and strings.

You get a pattern of I (increase) and D (decrease) characters of length n. Build the smallest number with n + 1 distinct digits from 1 to 9 where each pair of neighboring digits follows the pattern: I means the next digit is larger, D means it is smaller.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • smallest_number(pattern: str) -> str

Example

"IIDDD"     ->  "126543"
"DDIDDIID"  ->  "321654798"
"IDID"      ->  "13254"
"D"         ->  "21"

Constraints

  • 1 <= len(pattern) <= 8, so the digits 1 to 9 always suffice.
  • Each digit is used at most once.

Clarifying questions

  • Must the digits be distinct, and from 1 to 9 only?
  • Is a pattern longer than 8 possible? Then what?

What a strong answer covers

  • The greedy stack: for i from 0 to n, push i + 1; when the pattern has I at i or i == n, pop everything onto the result. Each run of Ds gets reversed. O(n).
  • Why it is the smallest: digits are used in increasing order, reversed only as much as each D run forces.
  • The alternative: backtracking over permutations, and why the greedy is better.
  • Tests: all I, all D, alternating.

Follow-ups

  • Return the largest such number.
  • Allow digits 0 to 9, or longer patterns using numbers instead of digits.
  • Count how many numbers fit the pattern.

Where it's asked

What it tests

greedy · stacks · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding