
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 input_list[i] is not same as temp_list[i], then
- 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
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
- Related Articles
- Check if the array can be sorted using swaps between given indices only in Python
- Check if a sorted array can be divided in pairs whose sum is k in Python
- Check if an array is sorted and rotated in Python
- Check if a queue can be sorted into another queue using a stack in Python
- Check if reversing a sub array make the array sorted in Python
- Check if given array is almost sorted (elements are at-most one position away) in Python
- Check if any square (with one colored cell) can be divided into two equal parts in Python
- Previous Permutation With One Swap in Python
- Check if characters of one string can be swapped to form other in Python
- Check If a Number Is Majority Element in a Sorted Array in Python
- Meta Strings (Check if two strings can become same after a swap in one string) in C++
- Program to check whether one string swap can make strings equal or not using Python
- Check if array sum can be made K by three operations on it in Python
- Check if elements of an array can be arranged satisfying the given condition in Python
- Check if an array of 1s and 2s can be divided into 2 parts with equal sum in Python

Advertisements