#2375

Construct Smallest Number From DI String

Medium
StringBacktrackingStackGreedyStackGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a greedy approach by constructing the result string based on the pattern directly. We can use a stack to manage the digits and ensure that we maintain the required order without generating all permutations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty stack and a result string.
  2. 2Step 2: Iterate through the pattern, pushing digits onto the stack.
  3. 3Step 3: When encountering 'I', pop from the stack to the result to maintain the increasing order.
  4. 4Step 4: At the end, pop any remaining digits in the stack to the result.
solution.py10 lines
1def smallestNumber(pattern):
2    stack = []
3    result = ''
4    n = len(pattern)
5    for i in range(n + 1):
6        stack.append(str(i + 1))
7        if i == n or pattern[i] == 'I':
8            while stack:
9                result += stack.pop()
10    return result

Complexity note: The time complexity is O(n) because we iterate through the pattern and push/pop from the stack, which takes constant time. The space complexity is O(n) due to the stack storing up to n elements.

  • 1Using a stack allows us to efficiently manage the order of digits based on the pattern.
  • 2Greedy approaches can often yield optimal solutions without the need for exhaustive search.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.