<p>You are given a string <code>num</code> representing <strong>the digits</strong> of a very large integer and an integer <code>k</code>. You are allowed to swap any two adjacent digits of the integer <strong>at most</strong> <code>k</code> times.</p>

<p>Return <em>the minimum integer you can obtain also as a string</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" style="width: 500px; height: 40px;" />
<pre>
<strong>Input:</strong> num = &quot;4321&quot;, k = 4
<strong>Output:</strong> &quot;1342&quot;
<strong>Explanation:</strong> The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> num = &quot;100&quot;, k = 1
<strong>Output:</strong> &quot;010&quot;
<strong>Explanation:</strong> It&#39;s ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> num = &quot;36789&quot;, k = 1000
<strong>Output:</strong> &quot;36789&quot;
<strong>Explanation:</strong> We can keep the number without any swaps.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= num.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>num</code> consists of only <strong>digits</strong> and does not contain <strong>leading zeros</strong>.</li>
	<li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution:
    def minInteger(self, num: str, k: int) -> str:
        # prior idea: kind of worked, but not quite:
        #     move as many 1s to front as possible, then 2s, etc.
        # but it gets stuck if we can't move things to the front


        # idea: what digit do we take next?
        #    the smallest one possible!

        # suppose we have digits d0, d1, .. d{r-1} labeled by their distance from the current front
        # we'll take the best digit within k, then reduce k by the label of the one we took

        # how do we update labels?
        #  if we take di, then i+1..r-1 are all decremented by one because they get one closer
        #  to the next position we swap into

        # segment or fenwick tree? we can record the original indices of each digit
        # and in log(N) get the cumulative offset that accounts for swaps made thus far
        
        # then for each digit, we'd find the best/only in 0..9 we can move, move it by i-o(i), then decrement k
        # do this while k, then take all the remaining digits

        N = len(num)

        # Fenwick tree for cumulative offsets
        f = [0]*(N+1)

        def incrOffset(i: int, by: int) -> None:
            """modifies the cumulative offset of i.. by `by`"""
            i += 1
            while i <= N:
                f[i] += by
                i += i & (-i)

        def getOffset(i: int) -> int:
            i += 1
            ans = 0
            while i:
                ans += f[i]
                i &= i-1
            return ans

        # record nominal indices of all digits, use a deque for easy pop left
        #   to improve speed: use a list, and also store a pointer to the next index
        idxs = [deque() for d in range(10)]
        for i, d in enumerate(num): idxs[int(d)].append(i)

        taken = [False]*N # nominal indices we've taken thus far

        out = [] # digits we've taken already
        while k and len(out) < N:
            # TODO: we can optimize away duplicate getOffset calls at the cost of illegibility

            # find the lowest digit we can take next: it must be within k swaps
            # "within k" meaning it's *adjusted* index to account for earlier numbers swapped out
            m = min(d for d, iq in enumerate(idxs) if iq and iq[0]+getOffset(iq[0]) <= k)

            # take m:
            #    add to output (ofc), mark as taken
            #    and since we moved the number at index i, all nums at i+1 are
            #      one closer to the front of the untaken numbers
            out.append(m)
            i = idxs[m].popleft()
            taken[i] = True
            k -= i + getOffset(i)
            # when we take the digit at i, digits at higher nominal indices
            # move 1 closer to the next digit to take
            incrOffset(i+1, by=-1)

        if len(out) < N:
            # out of swaps: take remaining numbers in their original order;
            # we didn't change the relative order of untaken numbers
            out.extend(num[i] for i in range(N) if not taken[i])

        return ''.join(map(str, out))




        
20700