Problem Description
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 at most k times. The goal is to return the minimum integer possible (as a string) by performing at most k adjacent swaps.
Key Insights
- Only adjacent swaps are allowed so the cost to move a digit from index j to index i is (j - i).
- A greedy strategy works: for each position, choose the smallest digit within the next reachable range (i.e. positions [i, i+k]).
- Once a digit is selected, update k to account for the swaps used.
- Efficient implementations for large input sizes may employ data structures like a Binary Indexed Tree or Segment Tree to account for swaps in a more optimal manner.
- Leading zeros in the result are acceptable even though the input has no leading zeros.
Space and Time Complexity
Time Complexity: O(n^2) in the worst-case greedy approach, though it can be optimized to O(n log n) using advanced data structures. Space Complexity: O(n), where n is the number of digits.
Solution
The solution is based on a greedy approach. Iterate over the digits of the number and for each position, look ahead as far as the current remaining swaps (i.e. positions i to min(n-1, i+k)). Identify the smallest digit in that range which can be swapped to the current position. The cost to bring a digit from its current position j to the target i is (j-i) swaps. Deduct that cost from k and continue to the next position. This ensures that at each step we are placing the best possible digit that can be brought from the right while staying within the swap limit.
Data structures used are basic array operations; no extra advanced structures are strictly necessary for this greedy solution. However, for performance improvements on larger inputs, one might use a Binary Indexed Tree (Fenwick Tree) or Segment Tree.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java with line-by-line comments.