Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array.
For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array.
Examples:
Input : arr[] = {3, 2, 1, 5, 6, 4}, k = 2
Output : Yes
Every element is at most 2 distance away
from its target position in the sorted array.
Input : arr[] = {13, 8, 10, 7, 15, 14, 12}, k = 3
Output : No
13 is more than k = 3 distance away
from its target position in the sorted array.
Copy elements of the original array arr[] to an auxiliary array aux[].
Sort aux[]. Now, for each element at index i in arr[], find its index j in aux[] using Binary Search. If for any element k < abs(i-j), then arr[] is not a k sorted array. Else it is a k sorted array. Here abs are the absolute value.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int binarySearch( int arr[], int low, int high, int x)
{
while (low <= high)
{
int mid = (low + high) / 2;
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
high = mid - 1;
else
low = mid + 1;
}
}
string isKSortedArray( int arr[], int n, int k)
{
int aux[n];
for ( int i = 0; i<n; i++)
aux[i] = arr[i];
sort(aux, aux + n);
for ( int i = 0; i<n; i++)
{
int j = binarySearch(aux, 0, n-1, arr[i]);
if ( abs (i - j) > k)
return "No" ;
}
return "Yes" ;
}
int main()
{
int arr[] = {3, 2, 1, 5, 6, 4};
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
cout << "Is it a k sorted array?: "
<< isKSortedArray(arr, n, k);
return 0;
}
|
Java
import java.util.Arrays;
class Test
{
static String isKSortedArray( int arr[], int n, int k)
{
int aux[] = new int [n];
for ( int i = 0 ; i<n; i++)
aux[i] = arr[i];
Arrays.sort(aux);
for ( int i = 0 ; i<n; i++)
{
int j = Arrays.binarySearch(aux,arr[i]);
if (Math.abs(i - j) > k)
return "No" ;
}
return "Yes" ;
}
public static void main(String args[])
{
int arr[] = { 3 , 2 , 1 , 5 , 6 , 4 };
int k = 2 ;
System.out.println( "Is it a k sorted array ?: " +
isKSortedArray(arr, arr.length, k));
}
}
|
Python3
def binarySearch(arr, low, high, x):
while (low < = high):
mid = int ((low + high) / 2 )
if (arr[mid] = = x):
return mid
elif (arr[mid] > x):
high = mid - 1
else :
low = mid + 1
def isKSortedArray(arr, n, k):
aux = [ 0 for i in range (n)]
for i in range ( 0 , n, 1 ):
aux[i] = arr[i]
aux.sort(reverse = False )
for i in range ( 0 , n, 1 ):
j = binarySearch(aux, 0 , n - 1 , arr[i])
if ( abs (i - j) > k):
return "No"
return "Yes"
if __name__ = = '__main__' :
arr = [ 3 , 2 , 1 , 5 , 6 , 4 ]
n = len (arr)
k = 2
print ( "Is it a k sorted array?:" ,
isKSortedArray(arr, n, k))
|
C#
using System;
using System.Collections;
class GFG {
static String isKSortedArray( int []arr, int n, int k)
{
int []aux = new int [n];
for ( int i = 0; i<n; i++)
aux[i] = arr[i];
Array.Sort(aux);
for ( int i = 0; i<n; i++)
{
int j = Array.BinarySearch(aux,arr[i]);
if (Math.Abs(i - j) > k)
return "No" ;
}
return "Yes" ;
}
public static void Main()
{
int []arr = {3, 2, 1, 5, 6, 4};
int k = 2;
Console.WriteLine( "Is it a k sorted array ?: " +
isKSortedArray(arr, arr.Length, k));
}
}
|
Javascript
<script>
function binarySearch(arr, low, high, x)
{
while (low <= high)
{
var mid = parseInt((low + high) / 2);
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
high = mid - 1;
else
low = mid + 1;
}
}
function isKSortedArray(arr, n, k)
{
var aux = Array(n);
for ( var i = 0; i<n; i++)
aux[i] = arr[i];
aux.sort((a,b)=> a-b)
for ( var i = 0; i<n; i++)
{
var j = binarySearch(aux, 0, n-1, arr[i]);
if (Math.abs(i - j) > k)
return "No" ;
}
return "Yes" ;
}
var arr = [3, 2, 1, 5, 6, 4];
var n = arr.length;
var k = 2;
document.write( "Is it a k sorted array?: "
+ isKSortedArray(arr, n, k));
</script>
|
Output
Is it a k sorted array?: Yes
Time Complexity: O(nlogn)
Auxiliary space: O(n)
Another Approach can be to store the corresponding indices of elements into the aux array. Then simply check if abs ( i – aux[i].second ) <= k, return “No” if the condition is not satisfied. It is slightly faster than the approach mentioned above as we don’t have to perform binary search to check the distance from original index, though the “O notation” would remain same.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
string isKSortedArray( int arr[], int n, int k)
{
vector<pair< int , int >> aux;
for ( int i=0;i<n;i++){
aux.push_back({arr[i], i});
}
sort(aux.begin(), aux.end());
for ( auto i=0;i<n;i++){
if ( abs (i-aux[i].second)>k) return "No" ;
}
return "Yes" ;
}
int main() {
int arr[] = {3, 2, 1, 5, 6, 4};
int n = sizeof (arr)/ sizeof ( int );
int k = 2;
cout<<isKSortedArray(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class GFG {
static class Pair{
int key;
int val;
Pair( int k, int v){
key = k;
val = v;
}
}
static String isKSortedArray( int arr[], int n, int k)
{
List<Pair> aux = new ArrayList<>();
for ( int i= 0 ;i<n;i++){
aux.add( new Pair(arr[i], i));
}
Collections.sort(aux,(a,b)->a.key-b.key);
for ( int i= 0 ;i<n;i++){
if (Math.abs(i-aux.get(i).val)>k) return "No" ;
}
return "Yes" ;
}
public static void main (String[] args) {
int arr[] = { 3 , 2 , 1 , 5 , 6 , 4 };
int n =arr.length;
int k = 2 ;
System.out.println(isKSortedArray(arr, n, k));
}
}
|
Python3
def isKSortedArray(arr, n, k):
aux = []
for i in range (n):
aux.append([arr[i], i])
aux.sort()
for i in range (n):
if ( abs (i - aux[i][ 1 ])>k):
return "No"
return "Yes"
arr = [ 3 , 2 , 1 , 5 , 6 , 4 ]
n = len (arr)
k = 2
print (isKSortedArray(arr, n, k))
|
C#
using System;
using System.Collections;
class GFG {
static string isKSortedArray( int [] arr, int n, int k)
{
SortedList aux = new SortedList();
for ( int i = 0; i < n; i++) {
aux.Add(arr[i], i);
}
for ( int i = 0; i < aux.Count; i++) {
int x = ( int )aux.GetByIndex(i);
if (Math.Abs(i - x) > k)
return "No" ;
}
return "Yes" ;
}
public static void Main()
{
int [] arr = { 3, 2, 1, 5, 6, 4 };
int n = 6;
int k = 2;
Console.Write(isKSortedArray(
arr, n, k));
}
}
|
Javascript
class Pair {
constructor(k, v) {
this .key = k;
this .val = v;
}
}
function isKSortedArray(arr, n, k) {
let aux = [];
for (let i = 0; i < n; i++) {
aux.push( new Pair(arr[i], i));
}
aux.sort((a, b) => a.key - b.key);
for (let i = 0; i < n; i++) {
if (Math.abs(i - aux[i].val) > k) return "No" ;
}
return "Yes" ;
}
let arr = [3, 2, 1, 5, 6, 4];
let n = arr.length;
let k = 2;
console.log(isKSortedArray(arr, n, k));
|
Time Complexity: O(nlogn)
Space Complexity: O(n)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
16 Jan, 2023
Like Article
Save Article