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
Greedy Strategy VisualizationInitial: "4321" with k=4 swaps4321Step 1: Move '1' to front (costs 3 swaps)1432k=1 remainingStep 2: Move '2' forward (costs 1 swap)1243k=0, done!๐ŸŽฏ Key StrategyAlways prioritize moving smaller digitsto earlier positions within swap budgetResult: "1243" - optimal with k=4
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.
Asked in
Google 45 Amazon 38 Microsoft 28 Meta 22
52.0K Views
Medium-High Frequency
~25 min Avg. Time
1.9K 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