Approach
Segment tree or range structure
For Minimum Possible Integer After at Most K Adjacent Swaps on Digits, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.
- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 45 lines of Python from the credited upstream file minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 7class BIT(object): 8 def __init__(self, n):9 self.__bit = [0] * n10 11 def add(self, i, val):12 while i < len(self.__bit):13 self.__bit[i] += val14 i += (i & -i)15 16 def sum(self, i):17 result = 018 while i > 0:19 result += self.__bit[i]20 i -= (i & -i)21 return result22 23 24class Solution(object):25 def minInteger(self, num, k):26 """27 :type num: str28 :type k: int29 :rtype: str30 """31 lookup = collections.defaultdict(list)32 bit = BIT(len(num)+1)33 for i in reversed(xrange(len(num))):34 bit.add(i+1, 1)35 lookup[int(num[i])].append(i+1)36 result = []37 for _ in xrange(len(num)):38 for d in xrange(10):39 if lookup[d] and bit.sum(lookup[d][-1]-1) <= k:40 k -= bit.sum(lookup[d][-1]-1)41 bit.add(lookup[d].pop(), -1)42 result.append(d)43 break44 return "".join(map(str, result))45