Minimum Possible Integer After at Most K Adjacent Swaps On Digits Problem
Description
LeetCode Problem 1505.
You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:

Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 10^4numconsists of only digits and does not contain leading zeros.1 <= k <= 10^9
Solution
Approach: Greedy With a Fenwick Tree
To make the number as small as possible, make its first digit as small as possible, then the second, and so on. For the current position, try digits 0 to 9 in order and take the first one that can be brought here with the swaps we have left. For a given digit, the cheapest copy to move is its leftmost unused copy, since any other copy has at least as many digits in front of it.
Bringing a digit to the front with adjacent swaps costs exactly the number of digits still in front of it. Digits we have already moved out no longer count, because they now sit before the current position. So if the copy is at original index j, its cost is
j - (number of already used original indices below j)
Rather than updating positions after every move, keep a Fenwick tree (binary indexed tree) over the original indices with a 1 at every index already used. The count of used indices below j is a prefix sum, which the tree answers in O(log n). For each digit, keep a queue of its original indices in increasing order, so the leftmost unused copy is at the front.
For each output position: for d = 0..9, take the front j of queue d and compute its cost. If the cost is at most k, subtract it from k, pop j, mark j used in the tree and append d. Once k runs out, every remaining digit costs 0 only when it is the next unused digit, so the rest of the number is copied in its original order, as it should be.
The answer may begin with zeros ("100", k = 1 gives "010"), and we return it as a string without stripping them.
Complexity: O(10 · n log n) = O(n log n) time and O(n) space.
from collections import deque
class Solution:
def minInteger(self, num: str, k: int) -> str:
n = len(num)
pos = [deque() for _ in range(10)] # pos[d]: original indices of digit d not used yet
for i, c in enumerate(num):
pos[int(c)].append(i)
tree = [0] * (n + 1) # Fenwick tree: 1 at every original index already moved out
def used_before(i): # how many of the original indices 0..i-1 are used
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
ans = []
for _ in range(n):
for d in range(10):
if pos[d]:
j = pos[d][0]
cost = j - used_before(j) # unused digits still in front of it
if cost <= k:
k -= cost
pos[d].popleft()
ans.append(str(d))
i = j + 1
while i <= n:
tree[i] += 1
i += i & -i
break
return "".join(ans)