2375. Construct Smallest Number From DI String
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Smallest number with pattern where I means increasing, D means decreasing.
Intuition
Smallest number with pattern where I means increasing, D means decreasing. Greedy: use 1-9 with push/pop stack approach.
Algorithm
- 1Stack-based: push digits, pop on I to get increasing sequence.
- 2For i from 0 to n: push i+1. If i==n or pattern[i]==I: pop all stack to result.
Common Pitfalls
- •Classic problem: use stack to reverse decreasing runs. Final digit handles trailing Ds.
2375.cs
C#
// Approach: Stack-based construction; push digits and flush on 'I' to produce lexicographically smallest result.
// Time: O(n) Space: O(n)
public class Solution
{
public string SmallestNumber(string pattern)
{
StringBuilder sb = new StringBuilder();
Stack<char> stack = new Stack<char>();
stack.Push('1');
foreach (char c in pattern)
{
char maxSoFar = stack.Peek();
if (c == 'I')
{
while (stack.Count > 0)
{
maxSoFar = (char)Math.Max(maxSoFar, stack.Peek());
sb.Append(stack.Pop());
}
}
stack.Push((char)(maxSoFar + 1));
}
while (stack.Count > 0)
sb.Append(stack.Pop());
return sb.ToString();
}
}Was this solution helpful?
Related Problems
- 316. Remove Duplicate Letters(Medium)
- 678. Valid Parenthesis String(Medium)
- 921. Minimum Add to Make Parentheses Valid(Medium)
- 1081. Smallest Subsequence of Distinct Characters(Medium)
- 1541. Minimum Insertions to Balance a Parentheses String(Medium)
- 1653. Minimum Deletions to Make String Balanced(Medium)