2434. Using a Robot to Print the Lexicographically Smallest String #1774
-
Topics: You are given a string
Return the lexicographically smallest string that can be written on the paper. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the lexicographically smallest string that can be written on the paper by a robot using two operations: moving the first character of the string Approach
Let's implement this solution in PHP: 2434. Using a Robot to Print the Lexicographically Smallest String <?php
/**
* @param String $s
* @return String
*/
function robotWithString($s) {
$n = strlen($s);
if ($n == 0) {
return "";
}
$min_right = array_fill(0, $n + 1, '');
$min_right[$n] = chr(ord('z') + 1);
for ($i = $n - 1; $i >= 0; $i--) {
$min_right[$i] = min($s[$i], $min_right[$i + 1]);
}
$stack = array();
$res = array();
for ($i = 0; $i < $n; $i++) {
array_push($stack, $s[$i]);
while (!empty($stack)) {
$top = end($stack);
if ($top <= $min_right[$i + 1]) {
array_pop($stack);
$res[] = $top;
} else {
break;
}
}
}
return implode('', $res);
}
// Test Cases
echo robotWithString("zza") . "\n"; // Output: "azz"
echo robotWithString("bac") . "\n"; // Output: "abc"
echo robotWithString("bdda") . "\n"; // Output: "addb"
?> Explanation:
This approach efficiently leverages preprocessing and stack operations to construct the desired result in linear time and space, meeting the problem constraints optimally. |
Beta Was this translation helpful? Give feedback.
We need to find the lexicographically smallest string that can be written on the paper by a robot using two operations: moving the first character of the string
s
to the robot's stringt
(stack), or moving the last character oft
to the paper. The challenge is to determine the optimal sequence of operations that results in the smallest possible string.Approach
s
onto a stack (t
) or pop the top character from the stack to the result string (p
). The goal is to arrange these operations such that the resulting stringp
is lexicographically smallest.