Construct Smallest Number From DI String - Problem
๐ฏ Construct the Smallest Number From DI String
You're given a pattern string consisting of 'I' (increasing) and 'D' (decreasing) characters. Your mission is to construct the lexicographically smallest number string that follows this pattern perfectly!
The Rules:
- Use digits
1-9, each digit at most once - If
pattern[i] == 'I', thennum[i] < num[i+1](increasing) - If
pattern[i] == 'D', thennum[i] > num[i+1](decreasing) - Return the smallest possible result
Example: Pattern "IIDD" โ Result "12543"
โ
1<2 (I), 2<5 (I), 5>4 (D), 4>3 (D)
Input & Output
example_1.py โ Basic Pattern
$
Input:
pattern = "IIDD"
โบ
Output:
"12543"
๐ก Note:
Start with 1, increase twice (1โ2โ5), then decrease twice (5โ4โ3). This gives us the smallest possible numbers while following the pattern.
example_2.py โ All Decreasing
$
Input:
pattern = "DDD"
โบ
Output:
"54321"
๐ก Note:
Since we need to decrease 4 times starting from the smallest possible number, we start with 5 and go down: 5โ4โ3โ2โ1.
example_3.py โ Single Character
$
Input:
pattern = "I"
โบ
Output:
"12"
๐ก Note:
Simple increase pattern: start with 1, increase to 2. This is the lexicographically smallest solution.
Visualization
Tap to expand
Understanding the Visualization
1
Scan Pattern
Read the DI pattern and identify segments
2
Use Stack
Stack holds positions waiting for number assignment
3
Handle 'I'
Pop stack and assign consecutive numbers
4
Handle 'D'
Push position onto stack (delay assignment)
5
Final Assignment
Assign remaining numbers to positions in stack
Key Takeaway
๐ฏ Key Insight: Use a stack to defer number assignment during decreasing sequences, then assign the smallest possible consecutive numbers when the sequence ends. This guarantees the lexicographically smallest valid result.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the pattern, each element pushed and popped once
โ Linear Growth
Space Complexity
O(n)
Stack can hold up to n elements in worst case (all decreasing)
โก Linearithmic Space
Constraints
- 1 โค pattern.length โค 8
- pattern contains only 'I' and 'D'
- The result will have pattern.length + 1 digits
- Each digit from 1 to 9 can be used at most once
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code