Problem
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.
Examples
Example 1:
graph LR;
A("4321") --- B("3421") --- C("3412") --- D("3142") --- E("1342")
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Greedy
Here are the key insights:
- The problem revolves around creating the smallest lexicographical sequence possible within adjacent swaps.
- Prioritise moving smaller digits closer to the front while respecting the
kallowed swaps. - This can be achieved using a greedy approach:
- Iterate through the digits of
numand repeatedly bring the smallest digit within thek-range of the current position to the front.
- Iterate through the digits of
Algorithms
- Convert
numinto a list for mutable operations. - Traverse the string and at every step:
- Look at the next
kdigits. - Bring the smallest digit in this range to the current position using minimal swaps.
- Deduct the number of swaps used from
k. - If
kbecomes0, stop as no further swaps can be made.
- Look at the next
- Join the modified list and return it as a string.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n*k). Evaluating the smallest digit in ak-length window takesO(k)for each digit, resulting inO(n*k)wherenis the length of the string. - 🧺 Space complexity:
O(n)due to the mutable list representation ofnum.