Check if array can be sorted with one swap in Python


Suppose, we are provided with an array that contains integer elements. We have to find out if the values in the array can be sorted in a non-decreasing order if we can perform only one swap operation. If possible, we say it can be done, otherwise not.

So, if the input is like input_list = [7, 8, 12, 10, 11, 9], then the output will be “Can be done”

To solve this, we will follow these steps −

  • temp_list := a copy of the list input_list
  • sort the list temp_list
  • swap_count := 0
  • for i in range 0 to size of input_list, do
    • if input_list[i] is not same as temp_list[i], then
      • swap_count := swap_count + 1
  • if swap_count is same as 0 or swap_count is same as 2, then
    • return True
  • otherwise,
    • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

from copy import deepcopy
def solve(input_list):
   temp_list = deepcopy(input_list)
   temp_list.sort()
   swap_count = 0
   for i in range(len(input_list)):
      if input_list[i] != temp_list[i]:
         swap_count += 1
   if swap_count == 0 or swap_count == 2:
      print("Can be done")
   else:
      print("Can't be done")
input_list = [7, 8, 12, 10, 11, 9] 
solve(input_list)

Input

[7, 8, 12, 10, 11, 9]

Output

Can be done

Updated on: 30-Dec-2020

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements