2375. Construct Smallest Number From DI String #1330
-
Topics: You are given a 0-indexed string A 0-indexed string
Return the lexicographically smallest possible string Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to construct the lexicographically smallest possible number string based on a given pattern of 'I' (increasing) and 'D' (decreasing) characters. The solution must ensure that each digit from 1 to 9 is used exactly once and that the sequence adheres to the given pattern. ApproachThe key insight is to recognize that consecutive 'D' characters in the pattern require a decreasing sequence of digits. By reversing segments of an initially increasing sequence of digits whenever a group of consecutive 'D's is encountered, we can efficiently generate the required sequence. This approach ensures that we produce the lexicographically smallest sequence by leveraging the properties of reversing segments to handle decreasing sequences. Let's implement this solution in PHP: 2375. Construct Smallest Number From DI String <?php
/**
* @param String $pattern
* @return String
*/
function smallestNumber($pattern) {
$n = strlen($pattern);
$result = range(1, $n + 1);
$i = 0;
while ($i < $n) {
if ($pattern[$i] == 'D') {
$j = $i;
while ($j < $n && $pattern[$j] == 'D') {
$j++;
}
$m = $j - $i;
$start = $i;
$end = $i + $m;
reverseSubarray($result, $start, $end);
$i = $j;
} else {
$i++;
}
}
return implode('', $result);
}
/**
* @param $arr
* @param $start
* @param $end
* @return void
*/
function reverseSubarray(&$arr, $start, $end) {
while ($start < $end) {
$temp = $arr[$start];
$arr[$start] = $arr[$end];
$arr[$end] = $temp;
$start++;
$end--;
}
}
// Example cases
echo smallestNumber("IIIDIDDD") . "\n"; // Output: "123549876"
echo smallestNumber("DDD") . "\n"; // Output: "4321"
?> Explanation:
This approach efficiently constructs the required sequence by reversing only the necessary segments, ensuring the solution is both optimal and runs in linear time relative to the length of the pattern. |
Beta Was this translation helpful? Give feedback.
We need to construct the lexicographically smallest possible number string based on a given pattern of 'I' (increasing) and 'D' (decreasing) characters. The solution must ensure that each digit from 1 to 9 is used exactly once and that the sequence adheres to the given pattern.
Approach
The key insight is to recognize that consecutive 'D' characters in the pattern require a decreasing sequence of digits. By reversing segments of an initially increasing sequence of digits whenever a group of consecutive 'D's is encountered, we can efficiently generate the required sequence. This approach ensures that we produce the lexicographically smallest sequence by leveraging the properties of reversi…