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'
, thennum[i] < num[i + 1]
. - If
pattern[i] == 'D'
, thennum[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 01:
-
C++
-
Python
#include <stack> #include <string> class Solution { public: std::string smallestNumber(std::string pattern) { std::string result; std::stack<char> numStack{{'1'}}; for (const char direction : pattern) { char maxSoFar = numStack.top(); if (direction == 'I') { // Pop all elements from the stack and add them to result while (!numStack.empty()) { maxSoFar = std::max(maxSoFar, numStack.top()); result += numStack.top(); numStack.pop(); } } numStack.push(maxSoFar + 1); } // Pop remaining elements in the stack while (!numStack.empty()) { result += numStack.top(); numStack.pop(); } return result; } };
class Solution: def smallestNumber(self, pattern: str) -> str: result = "" numStack = ["1"] for direction in pattern: maxSoFar = numStack[-1] if direction == 'I': # Pop all elements from the stack and add them to result while numStack: maxSoFar = max(maxSoFar, numStack[-1]) result += numStack.pop() numStack.append(chr(ord(maxSoFar) + 1)) # Pop remaining elements in the stack while numStack: result += numStack.pop() return result
Time Complexity:
- Processing the Pattern:
We iterate through the
pattern
string of length \( n \), performing operations based on ‘I’ and ‘D’. - Stack Operations:
Each character is pushed and popped from the stack at most once, leading to an amortized \( O(1) \) per operation.
- Total Time Complexity:
The total complexity is \( O(n) \) since each character is processed in constant time.
Space Complexity:
- Stack Storage:
In the worst case, the stack stores all \( n+1 \) digits, leading to \( O(n) \) space.
- Result String:
The result string also stores \( O(n) \) characters.
- Total Space Complexity:
The overall space complexity is \( O(n) \).