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 K Adjacent Swaps INPUT Original String: num 4 3 2 1 idx 0 idx 1 idx 2 idx 3 Input Values: num = "4321" k = 4 (max swaps) GOAL: Find smallest number using at most k swaps of adjacent digits ALGORITHM STEPS 1 Find Smallest Digit Within k positions ahead "4321": smallest='1' at idx=3 Need 3 swaps (3 <= k=4) OK 2 Swap to Front Move '1' to position 0 4321 --> 4312 (swap 1,2) 4312 --> 4132 (swap 1,3) 4132 --> 1432 (swap 1,4) 3 Update k k = 4 - 3 = 1 remaining 4 Repeat for Next Position Find smallest in "432" From "1432": check idx 1-2 '3' at idx 2 (cost=1, k=1) OK 1432 --> 1342 (k=0 done) FINAL RESULT Minimum Integer Obtained: 1 3 4 2 Output: "1342" Total swaps used: 4 Swap Trace: 4321 --> 4312 (k=3) 4312 --> 4132 (k=2) 4132 --> 1432 (k=1) 1432 --> 1342 (k=0) OK - Minimum Found! Key Insight: The Greedy approach works because placing the smallest available digit at each position from left to right guarantees the minimum result. We search within k positions ahead since each position needs (index - current) swaps. Use a BIT/Fenwick tree for O(n log n) complexity to track actual positions after previous swaps. TutorialsPoint - Minimum Possible Integer After at Most K Adjacent Swaps On Digits | Greedy Approach
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