Minimum Possible Integer After at Most K Adjacent Swaps On Digits - Problem
You're given a string of digits representing a very large integer and an integer k representing the maximum number of adjacent swaps you can perform.
Your goal is to find the lexicographically smallest integer possible by strategically using at most k adjacent digit swaps. Think of it like rearranging digits in a number to make it as small as possible, but you can only swap neighboring digits!
Key Points:
- You can swap any two adjacent digits
- You can perform at most k swaps (you don't have to use all k)
- Goal: minimize the resulting integer
- Return the result as a string
Example: If you have "4321" and k=4, you could transform it to "1234" by strategically moving the smallest digits to the front.
Input & Output
example_1.py โ Basic case
$
Input:
num = "4321", k = 4
โบ
Output:
"1234"
๐ก Note:
We can transform 4321 โ 3421 โ 3241 โ 2341 โ 1234 using exactly 4 swaps to get the minimum possible result.
example_2.py โ Limited swaps
$
Input:
num = "100", k = 1
โบ
Output:
"010"
๐ก Note:
With only 1 swap allowed, we can swap the first two digits: 100 โ 010. This gives us the lexicographically smallest result.
example_3.py โ Already optimal
$
Input:
num = "1234", k = 4
โบ
Output:
"1234"
๐ก Note:
The string is already in its optimal form, so no swaps are needed even though k=4 swaps are available.
Constraints
- 1 โค num.length โค 3 ร 104
- num consists of only digits and does not have leading zeros
- 0 โค k โค 109
- k can be larger than the number of swaps needed
Visualization
Tap to expand
Understanding the Visualization
1
Identify Target
For each position, find the smallest digit reachable with remaining swaps
2
Calculate Cost
Determine how many swaps needed to move target digit to current position
3
Execute Swaps
Perform adjacent swaps to bubble the digit forward
4
Update State
Decrease swap budget and move to next position
Key Takeaway
๐ฏ Key Insight: Greedy approach works because placing smaller digits at earlier positions always leads to a lexicographically smaller result, and we should use our swap budget optimally by prioritizing the most impactful moves first.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code