Leetcode 2375: Construct Smallest Number From DI String

grid47
grid47
Exploring patterns and algorithms
Mar 14, 2024 5 min read

You are given a string pattern consisting of the characters ‘I’ and ‘D’, where ‘I’ indicates that the next number in a sequence should be greater, and ‘D’ means the next number should be smaller. You need to construct the lexicographically smallest string num of length n + 1 such that the digits in num follow the conditions set by the pattern. The digits in num must be distinct and range from ‘1’ to ‘9’.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `pattern` of length `n`, where each character is either 'I' or 'D'.
Example: pattern = 'IIDID'
Constraints:
• 1 <= pattern.length <= 8
• pattern consists only of 'I' and 'D'.
Output: Return the lexicographically smallest string `num` that satisfies the pattern.
Example: Output: '123549876'
Constraints:
Goal: The goal is to construct the smallest lexicographical string `num` by following the constraints defined by the pattern.
Steps:
• 1. Traverse through the pattern and push the smallest available digits to a stack whenever encountering 'I'.
• 2. When encountering 'D', push digits into the stack and reverse them once 'I' is encountered or the end of the string is reached.
• 3. Append the digits from the stack to form the final number.
Goal: The string `pattern` contains only 'I' and 'D' characters and can be at most 8 characters long.
Steps:
• The pattern will always contain at least 1 character.
• The number of digits in `num` will be one greater than the length of the pattern.
Assumptions:
• The string `pattern` will always be valid, containing only 'I' and 'D'.
• The length of the string `num` will be equal to the length of the pattern plus one.
Input: Input: pattern = 'IIDID'
Explanation: In this case, we need to create a string such that at positions with 'I', the next number is greater, and at positions with 'D', the next number is smaller. The smallest valid string satisfying the pattern is '123549876'.

Input: Input: pattern = 'DIDI'
Explanation: Here, the smallest number satisfying the conditions is '4321'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus