Skip to main content

Construct Smallest Number From DI String - Solution & Explanation

MediumStringBacktrackingStackGreedy14 min readAsked at: Amazon, Goldman Sachs, Google
Practice this problem

Problem Statement

You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.

A 0-indexed string num of length n + 1 is created using the following conditions:

  • num consists of the digits '1' to '9', where each digit is used at most once.
  • If pattern[i] == 'I', then num[i] < num[i + 1].
  • If pattern[i] == 'D', then num[i] > num[i + 1].

Return the lexicographically smallest possible string num that meets the conditions.

 

Example 1:

Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.

Example 2:

Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.

 

Constraints:

  • 1 <= pattern.length <= 8
  • pattern consists of only the letters 'I' and 'D'.

Approach Overview

Problem Overview: You are given a string consisting of 'D' (decreasing) and 'I' (increasing). The goal is to build the smallest possible number using digits 1–9 without repetition such that the digits follow the pattern. For example, if the pattern contains D, the next digit must be smaller than the previous digit. The challenge is enforcing the pattern while keeping the overall number lexicographically smallest.

Approach 1: Greedy Approach with Stack (O(n) time, O(n) space)

This approach processes the pattern from left to right and uses a stack to temporarily store digits. Push numbers sequentially starting from 1. Whenever you encounter an 'I' or reach the end of the pattern, pop all elements from the stack and append them to the result. This reversal ensures that segments of 'D' automatically produce decreasing sequences while still using the smallest available digits. The key insight: delaying output until an increasing boundary lets you reverse the necessary portion to satisfy multiple consecutive D constraints.

This greedy strategy guarantees the smallest valid number because digits are assigned in increasing order and only reversed when the pattern forces a decrease. Each digit is pushed and popped once, making the algorithm linear. This is the most common interview solution and works well for patterns with long decreasing runs.

Approach 2: Construct from Left to Right (Greedy Pattern Handling) (O(n) time, O(1) extra space)

Another strategy builds the answer array directly while scanning the pattern. Start by filling the digits sequentially. When a 'D' segment appears, identify the full length of that decreasing run and reverse the corresponding portion of the result. For example, if the pattern contains DDD, the next four digits must form a decreasing sequence, so the digits assigned to that segment are reversed after placement.

This method relies on the same greedy observation: the smallest digits should appear as early as possible, but decreasing runs must be reversed to satisfy ordering constraints. Instead of using a stack, the algorithm manipulates segments directly. The logic stays simple and uses constant auxiliary memory.

Approach 3: Backtracking (O(9! ) worst case, O(n) space)

A brute-force method uses backtracking to generate permutations of digits 1–9 and check whether each permutation satisfies the DI pattern. Because the goal is the smallest valid number, the search can stop as soon as a valid candidate appears. While conceptually straightforward, the factorial search space makes this impractical for interviews. It mainly helps illustrate the constraint structure before applying a greedy optimization.

Recommended for interviews: The greedy stack solution is the expected answer. It demonstrates understanding of pattern constraints and efficient use of a greedy strategy with a stack. Explaining the brute-force backtracking approach first shows reasoning about the search space, but implementing the O(n) greedy method signals strong problem-solving skills.

Approach 1: Greedy Approach with Stack

This approach utilizes a stack to construct the number by handling 'I' and 'D' separately. For 'D', we keep adding digits to the stack and for 'I' we release them in reverse order which satisfies the 'D' requirement.

This Python code initiates a result string res and a stack. It iterates over the pattern plus one additional iteration. In each iteration, the next available number is pushed to the stack. When an 'I' or the end of the pattern is reached, the stack is popped to res to fulfill 'D' sequences by reversing the additions.

Code

Python

Java

C++

C

C#

JavaScript

Complexity

Time Complexity: O(n) - where n is the length of the pattern because each element is pushed and popped once.
Space Complexity: O(n) - due to stack storage as needed during computation.

Try this approach in the editor →

Approach 2: Construct from Left to Right

In this approach, we use two pointers and direct calculation of segments using 'D' marks to populate numbers into the result. We fill numbers in reverse order whenever a 'D' is encountered.

This solution adds numbers sequentially and reverses segments during 'I'. At each occurrence of 'I', it reverses the segment from the last 'I' or the start, ensuring minimal lexicographical order through efficient list slicing and reversing.

Code

Python

Java

C++

C

C#

JavaScript

Complexity

Time Complexity: O(n)
Space Complexity: O(n) - storing numbers progressively.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Greedy Approach with Stack

Time Complexity: O(n) - where n is the length of the pattern because each element is pushed and popped once.
Space Complexity: O(n) - due to stack storage as needed during computation.

Construct from Left to Right

Time Complexity: O(n)
Space Complexity: O(n) - storing numbers progressively.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Backtracking (Permutation Search)O(9!)O(n)Understanding the constraint structure or building intuition before optimization
Greedy with StackO(n)O(n)Interview-friendly approach; handles long decreasing sequences cleanly
Construct from Left to Right (Segment Reversal)O(n)O(1)When minimizing auxiliary structures and working directly on the result array

Video Solution

Construct Smallest Number From DI String - Leetcode 2375 - Python • NeetCodeIO • 12,355 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Construct Smallest Number From DI String easy or hard?
Construct Smallest Number From DI String is typically classified as a medium-level problem. The logic becomes straightforward once you recognize that consecutive 'D' segments must be reversed. Identifying the greedy stack strategy is the main challenge.
Construct Smallest Number From DI String Python/Java solution
Most implementations follow the greedy stack pattern: iterate through the pattern, push the next digit, and pop the stack when encountering 'I'. This logic is easy to implement in Python, Java, C++, C, C#, or JavaScript because it only requires basic stack operations and string construction.
How to solve Construct Smallest Number From DI String in O(n)?
Scan the pattern from left to right while assigning digits in increasing order. Use a stack to delay output for 'D' sequences, then pop when an 'I' appears to produce a decreasing segment. Because each digit is processed once, the total complexity stays linear at O(n).
What is the best approach for Construct Smallest Number From DI String?
The greedy stack approach is the most widely used solution. Iterate through the DI pattern, push sequential digits onto a stack, and flush the stack whenever an 'I' appears or the pattern ends. This automatically reverses decreasing segments and produces the smallest valid number. The algorithm runs in O(n) time and O(n) space.
Is Construct Smallest Number From DI String asked at Google/Amazon/Meta?
Greedy pattern construction problems like this frequently appear in interviews at large tech companies. Variants of DI pattern or stack-based sequence construction have been reported in interviews at companies such as Amazon and Google because they test greedy reasoning and stack usage.
What data structure is used in Construct Smallest Number From DI String?
A stack is the primary data structure in the optimal solution. The stack temporarily stores digits until the algorithm determines where a decreasing segment ends, then pops elements to produce the correct order.
What is the time complexity of Construct Smallest Number From DI String?
The optimal greedy solutions run in O(n) time, where n is the length of the DI string. Each digit is pushed and popped at most once when using the stack approach. Space complexity is O(n) for the stack or O(1) for the segment-reversal variant.

Ready to solve this problem?

Practice Construct Smallest Number From DI String with our built-in code editor and test cases.

Practice on FleetCode