#1505

Minimum Possible Integer After at Most K Adjacent Swaps On Digits

Hard
StringGreedyBinary Indexed TreeSegment TreeGreedy AlgorithmPriority QueueSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a greedy strategy with a priority queue (or min-heap) to efficiently find the smallest digit in the range allowed by k swaps. This reduces unnecessary checks and directly gives the best result.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a min-heap to keep track of the digits within the range of k swaps.
  2. 2Step 2: For each position, extract the smallest digit from the heap and place it in the current position.
  3. 3Step 3: Adjust the heap by adding the next digit from the string and removing the digit that has been placed.
solution.py18 lines
1import heapq
2
3def minInteger(num, k):
4    num = list(num)
5    n = len(num)
6    result = []
7    heap = []
8    for i in range(n):
9        heapq.heappush(heap, (num[i], i))
10        if len(heap) > k + 1:
11            heapq.heappop(heap)
12        if len(heap) > 0:
13            smallest, idx = heapq.heappop(heap)
14            result.append(smallest)
15            k -= (idx - i)
16            if k < 0:
17                break
18    return ''.join(result) + ''.join(num[i:] for i in range(len(result), n))

Complexity note: The time complexity is dominated by the heap operations, which take O(log n) time for each insertion and extraction, leading to O(n log n) overall.

  • 1The goal is to bring the smallest digits to the front, as they contribute most to minimizing the integer.
  • 2Adjacent swaps mean that we can only move digits within a limited range, which requires careful management of positions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.