1625. Lexicographically Smallest String After Applying Operations #2314
-
|
Topics: You are given a string You can apply either of the following two operations any number of times and in any order on
Return the lexicographically smallest string you can obtain by applying the above operations any number of times on A string 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 by applying two operations:
Since the string length is at most 100, I can use BFS to explore all possible states. Approach
Let's implement this solution in PHP: 1625. Lexicographically Smallest String After Applying Operations <?php
/**
* @param String $s
* @param Integer $a
* @param Integer $b
* @return String
*/
function findLexSmallestString($s, $a, $b) {
$visited = array();
$queue = array();
array_push($queue, $s);
$visited[$s] = true;
$best = $s;
while (!empty($queue)) {
$current = array_shift($queue);
// Update best if current is lexicographically smaller
if (strcmp($current, $best) < 0) {
$best = $current;
}
// Operation 1: Add a to all odd indices
$newStr1 = "";
for ($i = 0; $i < strlen($current); $i++) {
if ($i % 2 == 1) {
$digit = intval($current[$i]);
$newDigit = ($digit + $a) % 10;
$newStr1 .= strval($newDigit);
} else {
$newStr1 .= $current[$i];
}
}
if (!array_key_exists($newStr1, $visited)) {
$visited[$newStr1] = true;
array_push($queue, $newStr1);
}
// Operation 2: Rotate right by b positions
$n = strlen($current);
$newStr2 = substr($current, $n - $b) . substr($current, 0, $n - $b);
if (!array_key_exists($newStr2, $visited)) {
$visited[$newStr2] = true;
array_push($queue, $newStr2);
}
}
return $best;
}
// Test cases
echo findLexSmallestString("5525", 9, 2) . "\n"; // Output: "2050"
echo findLexSmallestString("74", 5, 1) . "\n"; // Output: "24"
echo findLexSmallestString("0011", 4, 2) . "\n"; // Output: "0011"
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to find the lexicographically smallest string by applying two operations:
ato all odd indices (0-indexed), with digits wrapping around (mod 10)bpositionsSince the string length is at most 100, I can use BFS to explore all possible states.
Approach
Let's implement this solution in PHP: 1625. Lexicographically Smallest String After Applying Operations