|
| 1 | +/** |
| 2 | + * 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits |
| 3 | + * https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a string num representing the digits of a very large integer and an integer k. You |
| 7 | + * are allowed to swap any two adjacent digits of the integer at most k times. |
| 8 | + * |
| 9 | + * Return the minimum integer you can obtain also as a string. |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * @param {string} num |
| 14 | + * @param {number} k |
| 15 | + * @return {string} |
| 16 | + */ |
| 17 | +var minInteger = function(num, k) { |
| 18 | + const digits = num.split(''); |
| 19 | + const n = digits.length; |
| 20 | + const fenwick = new Array(n + 1).fill(0); |
| 21 | + const digitQueues = Array.from({ length: 10 }, () => []); |
| 22 | + const result = []; |
| 23 | + |
| 24 | + for (let i = 0; i < n; i++) { |
| 25 | + digitQueues[digits[i]].push(i); |
| 26 | + } |
| 27 | + |
| 28 | + for (let i = 0; i < n; i++) { |
| 29 | + for (let digit = 0; digit <= 9; digit++) { |
| 30 | + if (digitQueues[digit].length === 0) continue; |
| 31 | + const pos = digitQueues[digit][0]; |
| 32 | + const swapsNeeded = pos - fetchValue(pos); |
| 33 | + if (swapsNeeded <= k) { |
| 34 | + k -= swapsNeeded; |
| 35 | + result.push(digit); |
| 36 | + update(pos); |
| 37 | + digitQueues[digit].shift(); |
| 38 | + break; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return result.join(''); |
| 44 | + |
| 45 | + function update(index) { |
| 46 | + for (let i = index + 1; i <= n; i += i & -i) { |
| 47 | + fenwick[i]++; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + function fetchValue(index) { |
| 52 | + let sum = 0; |
| 53 | + for (let i = index + 1; i > 0; i -= i & -i) { |
| 54 | + sum += fenwick[i]; |
| 55 | + } |
| 56 | + return sum; |
| 57 | + } |
| 58 | +}; |
0 commit comments