|
| 1 | +/** |
| 2 | + * 1625. Lexicographically Smallest String After Applying Operations |
| 3 | + * https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a string s of even length consisting of digits from 0 to 9, and two integers a |
| 7 | + * and b. |
| 8 | + * |
| 9 | + * You can apply either of the following two operations any number of times and in any order on s: |
| 10 | + * - Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, |
| 11 | + * if s = "3456" and a = 5, s becomes "3951". |
| 12 | + * - Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345". |
| 13 | + * |
| 14 | + * Return the lexicographically smallest string you can obtain by applying the above operations any |
| 15 | + * number of times on s. |
| 16 | + * |
| 17 | + * A string a is lexicographically smaller than a string b (of the same length) if in the first |
| 18 | + * position where a and b differ, string a has a letter that appears earlier in the alphabet than |
| 19 | + * the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" |
| 20 | + * because the first position they differ is at the third letter, and '5' comes before '9'. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string} s |
| 25 | + * @param {number} a |
| 26 | + * @param {number} b |
| 27 | + * @return {string} |
| 28 | + */ |
| 29 | +var findLexSmallestString = function(s, a, b) { |
| 30 | + const visited = new Set(); |
| 31 | + let smallestString = s; |
| 32 | + const queue = [s]; |
| 33 | + |
| 34 | + const addOperation = str => { |
| 35 | + const chars = str.split(''); |
| 36 | + for (let i = 1; i < str.length; i += 2) { |
| 37 | + chars[i] = String((parseInt(chars[i]) + a) % 10); |
| 38 | + } |
| 39 | + return chars.join(''); |
| 40 | + }; |
| 41 | + |
| 42 | + const rotateOperation = str => { |
| 43 | + return str.slice(-b) + str.slice(0, -b); |
| 44 | + }; |
| 45 | + |
| 46 | + while (queue.length) { |
| 47 | + const current = queue.shift(); |
| 48 | + if (visited.has(current)) continue; |
| 49 | + visited.add(current); |
| 50 | + if (current < smallestString) smallestString = current; |
| 51 | + |
| 52 | + const added = addOperation(current); |
| 53 | + const rotated = rotateOperation(current); |
| 54 | + |
| 55 | + queue.push(added); |
| 56 | + queue.push(rotated); |
| 57 | + } |
| 58 | + |
| 59 | + return smallestString; |
| 60 | +}; |
0 commit comments