Check whether a given array is a k sorted array or not
Last Updated :
16 Jan, 2023
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++
// C++ implementation to check whether the given array
// is a k sorted array or not
#include <bits/stdc++.h>
using namespace std;
// function to find index of element 'x' in sorted 'arr'
// uses binary search technique
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;
}
}
// function to check whether the given array is
// a 'k' sorted array or not
string isKSortedArray(int arr[], int n, int k)
{
// auxiliary array 'aux'
int aux[n];
// copy elements of 'arr' to 'aux'
for (int i = 0; i<n; i++)
aux[i] = arr[i];
// sort 'aux'
sort(aux, aux + n);
// for every element of 'arr' at index 'i',
// find its index 'j' in 'aux'
for (int i = 0; i<n; i++)
{
// index of arr[i] in sorted array 'aux'
int j = binarySearch(aux, 0, n-1, arr[i]);
// if abs(i-j) > k, then that element is
// not at-most k distance away from its
// target position. Thus, 'arr' is not a
// k sorted array
if (abs(i - j) > k)
return "No";
}
// 'arr' is a k sorted array
return "Yes";
}
// Driver program to test above
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
// Java implementation to check whether the given array
// is a k sorted array or not
import java.util.Arrays;
class Test
{
// Method to check whether the given array is
// a 'k' sorted array or not
static String isKSortedArray(int arr[], int n, int k)
{
// auxiliary array 'aux'
int aux[] = new int[n];
// copy elements of 'arr' to 'aux'
for (int i = 0; i<n; i++)
aux[i] = arr[i];
// sort 'aux'
Arrays.sort(aux);
// for every element of 'arr' at index 'i',
// find its index 'j' in 'aux'
for (int i = 0; i<n; i++)
{
// index of arr[i] in sorted array 'aux'
int j = Arrays.binarySearch(aux,arr[i]);
// if abs(i-j) > k, then that element is
// not at-most k distance away from its
// target position. Thus, 'arr' is not a
// k sorted array
if (Math.abs(i - j) > k)
return "No";
}
// 'arr' is a k sorted array
return "Yes";
}
// Driver method
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
# Python 3 implementation to check
# whether the given array is a k
# sorted array or not
# function to find index of element
# 'x' in sorted 'arr' uses binary
# search technique
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
# function to check whether the given
# array is a 'k' sorted array or not
def isKSortedArray(arr, n, k):
# auxiliary array 'aux'
aux = [0 for i in range(n)]
# copy elements of 'arr' to 'aux'
for i in range(0, n, 1):
aux[i] = arr[i]
# sort 'aux'
aux.sort(reverse = False)
# for every element of 'arr' at
# index 'i', find its index 'j' in 'aux'
for i in range(0, n, 1):
# index of arr[i] in sorted
# array 'aux'
j = binarySearch(aux, 0, n - 1, arr[i])
# if abs(i-j) > k, then that element is
# not at-most k distance away from its
# target position. Thus, 'arr' is not a
# k sorted array
if (abs(i - j) > k):
return "No"
# 'arr' is a k sorted array
return "Yes"
# Driver Code
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))
# This code is contributed by
# Shashank_Sharma
C#
// C# implementation to check
// whether the given array is a
// k sorted array or not
using System;
using System.Collections;
class GFG {
// Method to check whether the given
// array is a 'k' sorted array or not
static String isKSortedArray(int []arr, int n, int k)
{
// auxiliary array 'aux'
int []aux = new int[n];
// copy elements of 'arr' to 'aux'
for (int i = 0; i<n; i++)
aux[i] = arr[i];
// sort 'aux'
Array.Sort(aux);
// for every element of 'arr' at index
// 'i', find its index 'j' in 'aux'
for (int i = 0; i<n; i++)
{
// index of arr[i] in sorted array 'aux'
int j = Array.BinarySearch(aux,arr[i]);
// if abs(i-j) > k, then that element is
// not at-most k distance away from its
// target position. Thus, 'arr' is not a
// k sorted array
if (Math.Abs(i - j) > k)
return "No";
}
// 'arr' is a k sorted array
return "Yes";
}
// Driver method
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));
}
}
// This code is contributed by Sam007
JavaScript
<script>
// Javascript implementation to check whether the given array
// is a k sorted array or not
// function to find index of element 'x' in sorted 'arr'
// uses binary search technique
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 to check whether the given array is
// a 'k' sorted array or not
function isKSortedArray(arr, n, k)
{
// auxiliary array 'aux'
var aux = Array(n);
// copy elements of 'arr' to 'aux'
for (var i = 0; i<n; i++)
aux[i] = arr[i];
// sort 'aux'
aux.sort((a,b)=> a-b)
// for every element of 'arr' at index 'i',
// find its index 'j' in 'aux'
for (var i = 0; i<n; i++)
{
// index of arr[i] in sorted array 'aux'
var j = binarySearch(aux, 0, n-1, arr[i]);
// if abs(i-j) > k, then that element is
// not at-most k distance away from its
// target position. Thus, 'arr' is not a
// k sorted array
if (Math.abs(i - j) > k)
return "No";
}
// 'arr' is a k sorted array
return "Yes";
}
// Driver program to test above
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>
OutputIs 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)
{
// creating an array to store value, index of the original array
vector<pair<int, int>> aux;
for(int i=0;i<n;i++){
aux.push_back({arr[i], i}); // pushing the elements and index of arr to aux
}
// sorting the aux array
sort(aux.begin(), aux.end());
// for every element, check if the absolute value of (currIndex-originalIndex) <= k
// if not, then return "NO"
for(auto i=0;i<n;i++){
if(abs(i-aux[i].second)>k) return "No";
}
// If all elements satisfy the condition, the loop will terminate and
// "Yes" will be returned.
return "Yes";
}
int main() {
int arr[] = {3, 2, 1, 5, 6, 4}; // input array
int n = sizeof(arr)/sizeof(int); // number of elements in array(arr)
int k = 2; // value to check is array is "k" sorted
cout<<isKSortedArray(arr, n, k); // prints "Yes" since the input array is k-sorted
return 0;
}
Java
/*package whatever //do not write package name here */
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)
{
// creating an array to store value,
// index of the original array
List<Pair> aux = new ArrayList<>();
for(int i=0;i<n;i++){
aux.add(new Pair(arr[i], i)); // pushing the elements and index of arr to aux
}
// sorting the aux array
Collections.sort(aux,(a,b)->a.key-b.key);
// for every element, check if the absolute
// value of (currIndex-originalIndex) <= k
// if not, then return "NO"
for(int i=0;i<n;i++){
if(Math.abs(i-aux.get(i).val)>k) return "No";
}
// If all elements satisfy the condition,
// the loop will terminate and
// "Yes" will be returned.
return "Yes";
}
public static void main (String[] args) {
int arr[] = {3, 2, 1, 5, 6, 4}; // input array
int n =arr.length; // number of elements in array(arr)
int k = 2; // value to check is array is "k" sorted
System.out.println(isKSortedArray(arr, n, k)); // prints "Yes" since the input array is k-sorted
}
}
// This code is contributed by aadityaburujwale.
Python3
# Python code for the same approach
def isKSortedArray(arr, n, k):
# creating an array to store value, index of the original array
aux = []
for i in range(n):
aux.append([arr[i], i]) # pushing the elements and index of arr to aux
# sorting the aux array
aux.sort()
# for every element, check if the absolute value of (currIndex-originalIndex) <= k
# if not, then return "NO"
for i in range(n):
if(abs(i-aux[i][1])>k):
return "No"
# If all elements satisfy the condition, the loop will terminate and
# "Yes" will be returned.
return "Yes"
# driver code
arr = [3, 2, 1, 5, 6, 4] # input array
n = len(arr) # number of elements in array(arr)
k = 2 # value to check is array is "k" sorted
print(isKSortedArray(arr, n, k)) # prints "Yes" since the input array is k-sorted
# This code is contributed by shinjanpatra
C#
using System;
using System.Collections;
class GFG {
static string isKSortedArray(int[] arr, int n, int k)
{
// creating an array to store value, index of the
// original array
SortedList aux = new SortedList();
for (int i = 0; i < n; i++) {
aux.Add(arr[i], i); // pushing the elements and
// index of arr to aux
}
// for every element, check if the absolute value
// of (currIndex-originalIndex) <= k if not, then
// return "NO"
for (int i = 0; i < aux.Count; i++) {
int x = (int)aux.GetByIndex(i);
if (Math.Abs(i - x) > k)
return "No";
}
// If all elements satisfy the condition, the loop
// will terminate and "Yes" will be returned.
return "Yes";
}
public static void Main()
{
int[] arr = { 3, 2, 1, 5, 6, 4 }; // input array
int n = 6; // number of elements in array(arr)
int k = 2; // value to check is array is "k" sorted
Console.Write(isKSortedArray(
arr, n, k)); // prints "Yes" since the input
// array is k-sorted
}
}
// This code is contributed by garg28harsh.
JavaScript
// Javascript code Addition
class Pair {
constructor(k, v) {
this.key = k;
this.val = v;
}
}
function isKSortedArray(arr, n, k) {
// creating an array to store value,
// index of the original array
let aux = [];
for (let i = 0; i < n; i++) {
aux.push(new Pair(arr[i], i)); // pushing the elements and index of arr to aux
}
// sorting the aux array
aux.sort((a, b) => a.key - b.key);
// for every element, check if the absolute
// value of (currIndex-originalIndex) <= k
// if not, then return "NO"
for (let i = 0; i < n; i++) {
if (Math.abs(i - aux[i].val) > k) return "No";
}
// If all elements satisfy the condition,
// the loop will terminate and
// "Yes" will be returned.
return "Yes";
}
let arr = [3, 2, 1, 5, 6, 4]; // input array
let n = arr.length; // number of elements in array(arr)
let k = 2; // value to check is array is "k" sorted
console.log(isKSortedArray(arr, n, k)); // prints "Yes" since the input array is k-sorted
// This code is contributed by lokesh.
Time Complexity: O(nlogn)
Space Complexity: O(n)
Similar Reads
Check whether the given array is perfect or not
There is an array containing some non-negative integers. Check whether the array is perfect or not. An array is called perfect if it is first strictly increasing, then constant and finally strictly decreasing. Any of the three parts can be empty. Examples: Input : arr[] = {1, 8, 8, 8, 3, 2}Output :
5 min read
Check whether the given String is good for any ascending Array or not
Given a string S of length N. Consider any ascending array A[] such that each A[i] > 0 for all (1 <= i <= N) and some conditions, the task is to output YES/NO, by checking that the above-given conditions are true for all possible ascending A[]'s or not with given S. Sum up all the elements
7 min read
Check if a given array is pairwise sorted or not
An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements. Examples: Input : arr[] = {10, 15, 9, 9, 1, 5}; Output : Yes Pairs are (10, 15), (
5 min read
Check if a given array is sorted in Spiral manner or not
Given an array arr[] of size N, the task is to check if the array is spirally sorted or not. If found to be true, then print "YES". Otherwise, print "NO". Note: An array is spirally sorted if arr[0] ? arr[N - 1] ? arr[1] ? arr[N - 2] ... Examples: Input: arr[] = { 1, 10, 14, 20, 18, 12, 5 } Output:
5 min read
Check if reversing a sub array make the array sorted
Given an array of n distinct integers. The task is to check whether reversing any one sub-array can make the array sorted or not. If the array is already sorted or can be made sorted by reversing any one subarray, print "Yes", else print "No". Examples: Input : arr [] = {1, 2, 5, 4, 3}Output : YesBy
15+ min read
Check whether K times of a element is present in array
Given an array arr[] and an integer K, the task is to check whether K times of any element are also present in the array. Examples : Input: arr[] = {10, 14, 8, 13, 5}, K = 2 Output: Yes Explanation: K times of 5 is also present in an array, i.e. 10. Input: arr[] = {7, 8, 5, 9, 11}, K = 3 Output: No
8 min read
Check if a sorted array can be divided in pairs whose sum is k
Given a sorted array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair k.Expected time complexity O(n) and extra space O(1). This problem is a variation of below problem, but has a different interesting solution that r
11 min read
Check whether Array represents a Fibonacci Series or not
Given an array arr[] consisting of N integers, the task is to check whether a Fibonacci series can be formed using all the array elements or not. If possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = { 8, 3, 5, 13 } Output: Yes Explanation: Rearrange given array as {3, 5, 8, 13}
9 min read
Check if an array is Wave Array
Given an array of N positive integers. The task is to check if the array is sorted in wave form. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: NO Input: arr[] = {1, 5, 3, 7, 2, 8, 6}Output: YES Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: First c
14 min read
Check if all elements of the array are palindrome or not
Given an array arr[]. The task is to check if the array is PalinArray or not i.e., if all elements of array are palindrome or not. Examples: Input: arr[] = [21, 131, 20] Output: falseExplanation: For the given array, element 20 is not a palindrome so false is the output.Input: arr[] = [111, 121, 222
3 min read