Created
October 19, 2025 17:01
-
-
Save tatsuyax25/73194af4d9bf63afde0cd96bd142add7 to your computer and use it in GitHub Desktop.
You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Add a to all odd indices of s (0-indexed). Digits po
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {string} s | |
| * @param {number} a | |
| * @param {number} b | |
| * @return {string} | |
| */ | |
| var findLexSmallestString = function(s, a, b) { | |
| // Set to keep track of visited strings to avoid revisiting the same state | |
| const visited = new Set(); | |
| // Queue for BFS traversal, starting with the original string | |
| const queue = [s]; | |
| // Initialize result with the original string | |
| let result = s; | |
| // BFS loop: explore all reachable strings | |
| while (queue.length > 0) { | |
| // Get the next string from the queue | |
| const curr = queue.shift(); | |
| // Skip if we've already visited this string | |
| if (visited.has(curr)) continue; | |
| // Mark this string as visited | |
| visited.add(curr); | |
| // Update result if current string is lexicographically smaller | |
| if (curr < result) result = curr; | |
| // --- Operation 1: Add 'a' to all digits at odd indices --- | |
| let chars = curr.split(''); | |
| for (let i = 1; i < chars.length; i += 2) { | |
| // Add 'a' to digit and wrap around using modulo 10 | |
| chars[i] = (parseInt(chars[i]) + a) % 10; | |
| } | |
| const added = chars.join(''); | |
| // If this new string hasn't been visited, add it to the queue | |
| if (!visited.has(added)) queue.push(added); | |
| // --- Operation 2: Rotate the string to the right by 'b' positions --- | |
| const rotated = curr.slice(-b) + curr.slice(0, curr.length - b); | |
| // If this rotated string hasn't been visited, add it to the queue | |
| if (!visited.has(rotated)) queue.push(rotated); | |
| } | |
| // Return the smallest string found | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment