Given an array arr of n elements, we have to swap an index i with another index i + k any number of times and check whether it is possible to sort the given array arr. If it is then print “yes” otherwise print “no”.
Input: K = 2, arr = [4, 3, 2, 6, 7]
Choose index i = 0 and swap index i with i + k then the array becomes [2, 3, 4, 6, 7] which is sorted hence the output is “yes”.
Input : K = 2, arr = [4, 2, 3, 7, 6]
Output : No
It is not possible to obtain sorted array.
To solve the problem mentioned above we have to take the elements starting from index 0 and add the multiples of K to it, that is 0, 0 + k, 0 + (2*k), and so on. Swap these positions for all the indexes from 0 to K-1 and check if the final array is sorted. If it is, then return “yes” otherwise “no”.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if it is possible to sort an array with conditional swapping of adjacent allowed
- Sorting array with conditional swapping
- Sort an array by swapping elements of different type specified by another array
- Check whether we can sort two arrays by swapping A[i] and B[i]
- Insertion Sort by Swapping Elements
- Sort 1 to N by swapping adjacent elements
- Sort an array with swapping only with a special element is allowed
- Minimum cost to sort an Array such that swapping X and Y costs XY
- Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array
- Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
- Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array
- Maximize Array sum by swapping at most K elements with another array
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array
- Number of swaps to sort when only adjacent swapping allowed
- Recursive selection sort for singly linked list | Swapping node links
- Bubble Sort for Linked List by Swapping nodes
- Smallest number possible by swapping adjacent even odd pairs
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Print the lexicographically smallest array by swapping elements whose sum is odd
- Generate an Array such with elements maximized through swapping bits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.