The Wayback Machine - https://web.archive.org/web/20220111163128/https://www.geeksforgeeks.org/find-indices-having-at-least-k-non-increasing-elements-before-and-k-non-decreasing-elements-after-them/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find indices having at least K non-increasing elements before and K non-decreasing elements after them

  • Last Updated : 11 Jan, 2022

Given an array arr[] of size N and an integer K, the task is to find all the indices in the given array having at least K non-increasing elements before and K non-decreasing elements after them.

Examples:

Input: arr[] = {1, 1, 1, 1, 1}, K = 0
Output: 0 1 2 3 4
Explanation: Since K equals 0, every index satisfies the condition.

Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 2
Output: -1
Explanation: No index has 2 non-increasing before it and 2 non-decreasing elements after it.

 

Approach: The solution can be found by using the concept of prefix and suffix array. Follow the steps mentioned below:



  1. Form the prefix[] array where prefix[i] represents the number of elements before i which obeys non-increasing order.
  2. Form the suffix[] array where suffix[i] represents the number of elements after i which obeys non-decreasing order.
  3. Now only that indexes should be included in answer for which, both prefix[i] and suffix[i] are greater than or equal to K.

Below is the implementation of the above approach.

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find all the indices
vector<int> findIndices(int arr[], int K,
                        int N)
{
    vector<int> prefix(N), suffix(N);
    vector<int> ans;
  
    prefix[0] = 0;
    for (int i = 1; i < N; i++) {
        if (arr[i] <= arr[i - 1])
            prefix[i] = prefix[i - 1] + 1;
        else
            prefix[i] = 0;
    }
  
    suffix[N - 1] = 0;
    for (int i = N - 2; i >= 0; i--) {
        if (arr[i] <= arr[i + 1])
            suffix[i] = suffix[i + 1] + 1;
        else
            suffix[i] = 0;
    }
  
    for (int i = 0; i < N; i++) {
        if (prefix[i] >= K && suffix[i] >= K)
            ans.push_back(i);
    }
  
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 1, 1, 1, 1 };
    int K = 0;
    int N = sizeof(arr) / sizeof(arr[0]);
    vector<int> ans = findIndices(arr, K, N);
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    if (ans.size() == 0)
        cout << "-1";
    return 0;
}
Output
0 1 2 3 4 

Time Complexity: O(N)
Auxiliary Space: O(N) 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!