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

PythonServer Side ProgrammingProgramming

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

So, if the input is like num = "5432" k = 4, then the output will be 2453 because at first number is 5432. Then after first phase it will be 4532, then 4523, then 4253 and at final phase 2453.

To solve this, we will 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 < size of num, do

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

    • while indx is not same as -1, do

      • if indx - i <= k, then

        • num := num[from index 0 to i-1] concatenate num[indx] concatenate num[from index i to indx-1] concatenate num[from index indx+1 to end]

        • k := k -(indx - i)

        • i := i + 1

        • to_find := 0

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

      • otherwise,

        • come out 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

num = "5432"
k = 4
print(solve(num, k))

Input

"5432", 4

Output

2453
raja
Updated on 06-Oct-2021 08:39:46

Advertisements