k sorted array | Practice | GeeksforGeeks

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 distance away from its target position in the sorted array.

Example 1:
Input:
N=6
arr[] = {3, 2, 1, 5, 6, 4} 
K = 2
Output: Yes
Explanation:
Every element is at most 2 distance 
away from its target position in the
sorted array.  

Example 2:
Input:
N=7
arr[] = {13, 8, 10, 7, 15, 14, 12}
K = 1
Output: No


Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function isKSortedArray() that takes array arr, integer n and integer k as parameters and return "Yes" if the array is a k sorted array else return "No".

Expected Time Complexity: O(NlogN).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ N ≤ 105
0 ≤ K ≤ N
0
lindan1232 months ago
 string isKSortedArray(int arr[], int n, int k)
    {
        vector<pair<int,int> > comp;
        vector<pair<int,int> > rev;
        
        for(int i=0;i<n;i++)
        {
            rev.push_back({arr[i],i});
        }
        sort(rev.begin(),rev.end());
        
        for(int i=0;i<n;i++)
        {
            comp.push_back({rev[i].first,i});
        }
        
        for(int i=0;i<n;i++)
        {
            int num = abs(rev[i].second-comp[i].second);
            if(num>k)
            {
                return "No";
            }
        }
        return "Yes";
    }
Time Taken : 0.5
Cpp
 
0
kake13372 months ago
       vector<pair<int,int>> vp;
       for(int i=0;i<n;i++)
       vp.push_back({arr[i],i});
       sort(vp.begin(),vp.end());
       for(int i=0;i<n;i++)
       {
           if(!(i>=vp[i].second-k && i<=vp[i].second+k))
           return "No";
       }
       return "Yes";
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N*log(N)) and space complexity as O(N) is as follows :-
 
Note :- Max value of arr[i] can be assumed to be 1e6.
 
Execution Time :- 0.3 / 1.4 sec
 
string isKSortedArray(int arr[], int n, int k){       int temp[n];       for(int i = 0; i < n; i++)           temp[i] = arr[i];              sort(temp,temp+n);       int cor[1000001];       for(int i = 0; i < n; i++){           cor[temp[i]] = i;       }              for(int i = 0; i < n; i++){           int diff = abs(i - cor[arr[i]]);           if(diff > k) return ("No");        }              return ("Yes");   }
+1
rishabh21cse3 months ago
easy c++ sol :
int bs(int arr[],int l,int h,int x){     while(l<=h){         int mid = (l+h)/2;                  if(arr[mid] == x){             return mid;         }else if(arr[mid] > x){             h = mid - 1;         }else{             l = 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 = bs(aux,0,n-1,arr[i]);               if(abs(i - j) > k)               return "No";           }           return "Yes";
+1
hariomjoshi3 months ago
// solution with binary search onlyclass Solution{     static String isKSortedArray(int[] arr, int n, int k){       int[] oldArr = new int[n];       // assigning old array to new one       for (int i=0; i<n; i++){           oldArr[i] = arr[i];       }       Arrays.sort(arr);       int count = 0;       for(int i = 0; i<n; i++){           int sortedIndex = binarySearch(arr, oldArr[i]);           // System.out.println(i);           // System.out.println(sortedIndex);           if(Math.abs(sortedIndex - i) <=k){               count++;           }       }       if(count == arr.length){           return "Yes";       }       else{           return "No";       }   }
   static int binarySearch(int[] arr, int target){
       int start = 0;       int end = arr.length -1;       while(start<=end){           int mid = start + (end -start)/2;           if(arr[mid] == target){               return mid;           }           else if(arr[mid]< target){               start = mid+1;           }else{               end = mid-1;           }       }       return -1; // the code mustn't reach here   }}
0
chessnoobdj4 months ago
C++ without maps
string isKSortedArray(int arr[], int n, int k)
    {
        vector <int> res(arr, arr+n);
        sort(res.begin(), res.end());
        for(int i=0; i<n; i++){
            int idx = lower_bound(res.begin(), res.end(), arr[i])-res.begin();
            if(abs(idx-i)>k)
                return "No";
        }
        return "Yes";
    }
0
jagdishpadeliya5 months ago
static String isKSortedArray(int arr[], int n, int k) 
    { 
        HashMap<Integer,Integer> hmap = new HashMap<>();
        for(int i=0;i<n;i++)
        {
            hmap.put(arr[i],i);
        }
        Arrays.sort(arr);
        for(int i=0;i<n;i++)
        {
            if(Math.abs(hmap.get(arr[i])-i)>k)
            return "No";
        }
        return "Yes";
    }
0
imranwahid6 months ago
Easy C++ solution
0
ritikshrivastava6645
This comment was deleted.
0
badgujarsachin836 months ago
string isKSortedArray(int arr[], int n, int k)
    {
        //code here.
        vector<pair<int,int>> v;
        for(int i=0;i<n;i++){
            v.push_back(make_pair(arr[i],i));
        }
        sort(v.begin(),v.end());
        for(int i=0;i<n ;i++){
            if(abs(i-v[i].second)>k){
                return "No";
            }
        }
        return "Yes";
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.