- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Check if it is possible to sort an array with conditional swapping of adjacent allowed in Python

Suppose we have an unordered array of numbers called nums and all elements are in range 0 to n-1. We can swap adjacent elements in nums as many times as required but only when the absolute difference between these element is 1. We have to check whether we can sort the nums or not.

So, if the input is like nums = [1, 0, 3, 2, 5, 4], then the output will be True as we can swap these pairs [(1, 0), (3, 2), (5, 4)] to sort [0, 1, 2, 3, 4, 5].

To solve this, we will follow these steps −

- for i in range 0 to size of nums - 2, do
- if nums[i] > nums[i+1], then
- if nums[i] - nums[i+1] is same as 1, then
- exchange nums[i] and nums[i+1]

- otherwise,
- return False

- if nums[i] - nums[i+1] is same as 1, then

- if nums[i] > nums[i+1], then
- return True

## Example

Let us see the following implementation to get better understanding −

def solve(nums): for i in range(len(nums) - 1): if nums[i] > nums[i+1]: if nums[i] - nums[i+1] == 1: nums[i], nums[i+1] = nums[i+1], nums[i] else: return False return True nums = [1, 0, 3, 2, 5, 4] print(solve(nums))

## Input

[1, 0, 3, 2, 5, 4]

## Output

True

- Related Questions & Answers
- Check if it is possible to sort the array after rotating it in Python
- Check if it is possible to make two matrices strictly increasing by swapping corresponding values only in Python
- Check if it is possible to survive on Island in Python
- Check if array contains contiguous integers with duplicates allowed in Python
- Check if it is possible to serve customer queue with different notes in Python
- Check if it is possible to create a polygon with a given angle in Python
- Check if it is possible to create a polygon with given n sidess in Python
- Check if it is possible to transform one string to another in Python
- Check if it is possible to convert one string into another with given constraints in Python
- Is it possible to resize an array in C#
- Check if it possible to partition in k subarrays with equal sum in Python
- Check if it is possible to draw a straight line with the given direction cosines in Python
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- How to check if an Android app is allowed to show notification?
- Check if it is possible to rearrange rectangles in a non-ascending order of breadths in Python

Advertisements