Minimum Possible Integer After at Most K Adjacent Swaps On Digits - 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.

Input & Output

Example 1 — Basic Greedy Selection
$ Input: num = "4321", k = 4
Output: "1342"
💡 Note: Move 1 to front (3 swaps: 4321→4312→4132→1432→1342), then move 2 forward (1 swap: 1342→1324 would exceed k), so result is "1342"
Example 2 — Limited Swaps
$ Input: num = "100", k = 1
Output: "010"
💡 Note: Can only make 1 swap. Best option is to swap first two digits: 100→010
Example 3 — No Swaps Needed
$ Input: num = "1234", k = 3
Output: "1234"
💡 Note: Already in minimum order, no swaps needed

Constraints

  • 1 ≤ num.length ≤ 3 × 104
  • num consists only of digits
  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Minimum Integer After At Most K Adjacent SwapsInput:4321k = 4 swapsProcess:1. Find smallest digit within reach2. Bubble it forward using adjacent swaps3. Repeat with remaining swapsSwap Sequence:4321 → 4312 → 4132 → 1432Output:1342Minimum possible!
Understanding the Visualization
1
Input
String of digits and maximum number of adjacent swaps allowed
2
Process
Greedily move smallest digits forward using adjacent swaps
3
Output
Lexicographically smallest possible string
Key Takeaway
🎯 Key Insight: Always move the smallest reachable digit to the front first for optimal results
Asked in
Google 15 Facebook 8 Amazon 6
23.4K Views
Medium Frequency
~45 min Avg. Time
542 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen