Program to find minimum possible integer after at most k adjacent swaps on digits in Python

Suppose we have a string called num representing a very large integer number and another value k. We can swap any two adjacent digits at most k times to find the minimum possible value.

So, if the input is like num = "5432" and k = 4, then the output will be 2453. The transformation happens as: 5432 ? 4532 ? 4523 ? 4253 ? 2453.

Algorithm

To solve this problem, we follow these steps:

  • min_num := sort the digits of num

  • i := 0, to_find := 0

  • While num is not same as min_num and k > 0 and i

    • indx := index of item to_find from index i in num

    • While indx is not -1:

      • If indx - i ? k, then:

        • Move digit at indx to position i using adjacent swaps

        • k := k - (indx - i)

        • i := i + 1

        • to_find := 0

      • Otherwise, break from loop

    • to_find := to_find + 1

  • Return num

Example

Let us see the following implementation to get better understanding ?

def solve(num, k):
    min_num = sorted(list(num))
    min_num = ''.join(min_num)
    i = 0
    to_find = 0
    
    while num != min_num and k > 0 and i < len(num):
        indx = num.find(str(to_find), i)
        while indx != -1:
            if indx - i <= k:
                num = num[:i] + num[indx] + num[i:indx] + num[indx+1:]
                k -= (indx - i)
                i += 1
                to_find = 0
                indx = num.find(str(to_find), i)
            else:
                break
        to_find += 1
    
    return num

# Test the function
num = "5432"
k = 4
result = solve(num, k)
print(f"Input: {num}, k = {k}")
print(f"Output: {result}")
Input: 5432, k = 4
Output: 2453

How It Works

The algorithm works by finding the smallest available digit that can be moved to the current position within the remaining swap budget. It starts from position 0 and looks for digit '0', then '1', and so on. When it finds a digit that can be moved to the current position (distance ? remaining swaps), it performs the adjacent swaps to bring that digit forward.

Step-by-Step Example

def solve_with_steps(num, k):
    print(f"Initial: {num}, k = {k}")
    min_num = sorted(list(num))
    min_num = ''.join(min_num)
    i = 0
    to_find = 0
    
    while num != min_num and k > 0 and i < len(num):
        indx = num.find(str(to_find), i)
        if indx != -1 and indx - i <= k:
            print(f"Moving '{to_find}' from position {indx} to {i}")
            num = num[:i] + num[indx] + num[i:indx] + num[indx+1:]
            k -= (indx - i)
            print(f"After move: {num}, remaining swaps: {k}")
            i += 1
            to_find = 0
        else:
            to_find += 1
    
    return num

# Demonstrate with steps
result = solve_with_steps("5432", 4)
print(f"Final result: {result}")
Initial: 5432, k = 4
Moving '2' from position 3 to 0
After move: 2543, remaining swaps: 1
Moving '3' from position 3 to 1
After move: 2345, remaining swaps: 0
Final result: 2345

Conclusion

This greedy algorithm efficiently finds the minimum possible integer by prioritizing the placement of smaller digits at earlier positions. The key insight is to find the smallest digit that can be moved within the available swap budget and bring it forward using adjacent swaps.

---
Updated on: 2026-03-26T14:06:01+05:30

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements