Open In App

Check if it is possible to sort an array with conditional swapping of elements at distance K

Last Updated : 29 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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>


Output: 

no

 

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 : arr[] = {1, 0, 3, 2} Output : yes Explanation:- W
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: Swap arr[0] and arr[3], so arr[] becomes {4, 3,
5 min read
Sorting array with conditional swapping
Given an array arr containing elements from [1...to n]. Each element appears exactly once in the array arr. Given an string str of length n-1. Each character of the string is either 0 or 1. In the array, swapping of the i-th element with (i + 1)-th element can be done as many times as we want, if the i-th character of the string is 1. Our task is t
6 min read
Maximize X such that Array can be sorted by swapping elements X distance apart
Given an input arr[] of length N, Which contains integers from 1 to N in unsorted order. You can apply only one type of operation on arr[] elements': Choose an index i and an integer X and swap Ai with an element that is X distance apart and both the indices are within the boundary of the array. Then the task is to find the maximum value of X by wh
10 min read
Maximize maximum possible subarray sum of an array by swapping with elements from another array
Given two arrays arr[] and brr[] consisting of N and K elements respectively, the task is to find the maximum subarray sum possible from the array arr[] by swapping any element from the array arr[] with any element of the array brr[] any number of times. Examples: Input: N = 5, K = 4, arr[] = { 7, 2, -1, 4, 5 }, brr[] = { 1, 2, 3, 2 }Output : 21Exp
7 min read
Sort an array by swapping elements of different type specified by another array
Given two arrays a[] and b[] which contain the integer elements and their respective types (either type 0 or type 1) respectively, the task is to check if it is possible to sort the array in non-decreasing order by swapping elements of different types only. Examples: Input: a[] = {30, 20, 20, 10}, b[] = {1, 1, 1, 1} Output: No Explanation: Since al
9 min read
C++ Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14, x = 12, y = 20 Output:
5 min read
C Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14, x = 12, y = 20 Output:
4 min read
Java Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14, x = 12, y = 20 Output:
6 min read
Python Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14, x = 12, y = 20 Output:
5 min read
Article Tags :
Practice Tags :