Check if it is possible to sort an array with conditional swapping of elements at distance K
Last Updated :
29 Jun, 2022
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”.
Examples:
Input: K = 2, arr = [4, 3, 2, 6, 7]
Output: Yes
Explanation:
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
Explanation:
It is not possible to obtain sorted array.
Approach:
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:
C++
// CPP implementation to Check if it is possible to sort an
// array with conditional swapping of elements at distance K
#include <bits/stdc++.h>
using namespace std;
// Function for finding if it possible
// to obtain sorted array or not
bool fun(int arr[], int n, int k)
{
vector<int> v;
// Iterate over all elements until K
for (int i = 0; i < k; i++) {
// Store elements as multiples of K
for (int j = i; j < n; j += k) {
v.push_back(arr[j]);
}
// Sort the elements
sort(v.begin(), v.end());
int x = 0;
// Put elements in their required position
for (int j = i; j < n; j += k) {
arr[j] = v[x];
x++;
}
v.clear();
}
// Check if the array becomes sorted or not
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
// Driver code
int main()
{
int arr[] = { 4, 2, 3, 7, 6 };
int K = 2;
int n = sizeof(arr) / sizeof(arr[0]);
if (fun(arr, n, K))
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}
Java
// Java implementation to check if it
// is possible to sort an array with
// conditional swapping of elements
// at distance K
import java.lang.*;
import java.io.*;
import java.util.*;
class GFG{
// Function for finding if it possible
// to obtain sorted array or not
public static boolean fun(int[] arr, int n,
int k)
{
Vector<Integer> v = new Vector<Integer>();
// Iterate over all elements until K
for(int i = 0; i < k; i++)
{
// Store elements as multiples of K
for(int j = i; j < n; j += k)
{
v.add(arr[j]);
}
// Sort the elements
Collections.sort(v);
int x = 0;
// Put elements in their
// required position
for(int j = i; j < n; j += k)
{
arr[j] = v.get(x);
x++;
}
v.clear();
}
// Check if the array becomes
// sorted or not
for(int i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
{
return false;
}
}
return true;
}
// Driver code
public static void main (String args[])
{
int[] arr = { 4, 2, 3, 7, 6 };
int K = 2;
int n = arr.length;
if (fun(arr, n, K))
{
System.out.println("yes");
}
else
{
System.out.println("no");
}
}
}
// This code is contributed by sayesha
Python3
# Python3 implementation to Check if it is possible to sort an
# array with conditional swapping of elements at distance K
# Function for finding if it possible
# to obtain sorted array or not
def fun(arr, n, k):
v = []
# Iterate over all elements until K
for i in range(k):
# Store elements as multiples of K
for j in range(i, n, k):
v.append(arr[j]);
# Sort the elements
v.sort();
x = 0
# Put elements in their required position
for j in range(i, n, k):
arr[j] = v[x];
x += 1
v = []
# Check if the array becomes sorted or not
for i in range(n - 1):
if (arr[i] > arr[i + 1]):
return False
return True
# Driver code
arr= [ 4, 2, 3, 7, 6 ]
K = 2;
n = len(arr)
if (fun(arr, n, K)):
print("yes")
else:
print("no")
# This code is contributed by apurva raj
C#
// C# implementation to check if it
// is possible to sort an array with
// conditional swapping of elements
// at distance K
using System;
using System.Collections.Generic;
class GFG{
// Function for finding if it possible
// to obtain sorted array or not
public static bool fun(int[] arr,
int n, int k)
{
List<int> v = new List<int>();
// Iterate over all elements until K
for(int i = 0; i < k; i++)
{
// Store elements as multiples of K
for(int j = i; j < n; j += k)
{
v.Add(arr[j]);
}
// Sort the elements
v.Sort();
int x = 0;
// Put elements in their
// required position
for(int j = i; j < n; j += k)
{
arr[j] = v[x];
x++;
}
v.Clear();
}
// Check if the array becomes
// sorted or not
for(int i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
{
return false;
}
}
return true;
}
// Driver code
public static void Main(String []args)
{
int[] arr = {4, 2, 3, 7, 6};
int K = 2;
int n = arr.Length;
if (fun(arr, n, K))
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// JavaScript implementation to
// Check if it is possible to sort an
// array with conditional swapping of
// elements at distance K
// Function for finding if it possible
// to obtain sorted array or not
function fun(arr, n, k)
{
let v = [];
// Iterate over all elements until K
for (let i = 0; i < k; i++) {
// Store elements as multiples of K
for (let j = i; j < n; j += k) {
v.push(arr[j]);
}
// Sort the elements
v.sort();
let x = 0;
// Put elements in their required position
for (let j = i; j < n; j += k) {
arr[j] = v[x];
x++;
}
v = [];
}
// Check if the array becomes sorted or not
for (let i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
// Driver code
let arr = [ 4, 2, 3, 7, 6 ];
let K = 2;
let n = arr.length;
if (fun(arr, n, K))
document.write("yes");
else
document.write("no");
</script>
Time Complexity: O(k*n*log(n))
Auxiliary Space: O(n)
Similar Reads
Check if it is possible to sort an array with conditional swapping of adjacent allowed We are given an unsorted array of integers in the range from 0 to n-1. We are allowed to swap adjacent elements in array many number of times but only if the absolute difference between these element is 1. Check if it is possible to sort the array.If yes then print "yes" else "no". Examples: Input :
5 min read
Check if it is possible to sort the array without swapping adjacent elements Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed. Examples: Input: N = 4, arr[] = {2, 3, 1, 4}Output: YESExplanation
5 min read
Check if an array of pairs can be sorted by swapping pairs with different first elements Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Example
11 min read
Minimize cost to sort an Array by swapping any pair of element (X, Y) with cost as (X + Y) Given an array arr[] consisting of N integers, the task is to find the minimum cost to sort the given array arr[] in ascending order by swapping any pair of elements (X, Y) such that the cost of swapping is (X + Y). Examples: Input: arr[] = {3, 2, 1}Output: 4Explanation:Following are the swapping of
13 min read
Check if the array can be sorted only if the elements on given positions can be swapped Given an array arr[] of length N and another array P[] containing {a1, a2, ... ak} which represents the positions of the given array arr[], the task is to check if the array can be sorted by only swapping the elements' arr[ai], arr[ai+1] where 'i' is some element in the array P[].Examples: Input: ar
8 min read