Longest subarray with only one value greater than k

Given an array of N numbers, find length of the longest subarray such that K is the second largest element on insertion.

Examples:

Input: a[] = {9, 5, 5, 6, 8}, K = 7
Output: 4
The longest subarray is {9, 5, 5, 6}, in which if K is inserted it becomes {9, 5, 5, 6, 7}, and
7 is the second largest element in the array

Input: a[] = {9, 5, 5, 6, 8}, K = 10
Output: 0
Since the maximum number in the array is less than that of K, hence it is not possible.

Input: a[] = {8, 5, 10, 10, 8}, K = 9
Output: 5
9 is the second largest element of whole array



A naive approach is to iterate for every possible subarray and check if on insertion of K, it becomes the second largest element or not. Naively we can store the length of the longest of all such subarrays possible.

Time Complexity: O(N^2)

An efficient solution is to to use the two pointer technique to solve the above problem. Below is the algorithm to solve the above problem.

  • Initialize two pointers front and end as 0, and a visited array which marks the index has been visited or not.
  • We need a set container so that we can the second largest element in any range front-end in O(log N) and a unordered_map to count the frequencies of the elements in the array to decide on the deletion from the set.
  • Initially check if an element exists or not which is greater than K or not, if there is no such element, then subarray is not possible.
  • Insert the element at a[end] in the set and increase its frequency in the map if the index end has not been visited before to avoid multiple insertions of same index.
  • If the set contains only one element then insertion of K is possible as we have only elements and since we know there exists at least one element > k, then this subarray can be a part of the longest subarray, hence we count it and move forward the end pointer.
  • If the set contains more then one element, then the s.end() pointer points after the last element, hence decreasing it twice will give us our second largest element in the range front-end.
  • If the second largest element is greater than K, then this subarray is not possible, hence we need to move the first pointer ahead, but before doing this, check if the frequency of a[front] is 1 or not, if it is so, then delete it from the set, else just decrease the frequency in map by 1, since the element will be existing in any index>front. Increase the front pointer by one.
  • If the second largest element is not greater than K, then simply increase the end pointer by one.
  • Store the largest of lengths of end-front and return it.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the length of the longest
// subarray such that K is the second largest element
// on insertion
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the length of longest subarray
int lengthOfLongestSubarray(int a[], int n, int k)
{
    bool flag = 0;
  
    // Check if any element exists which is
    // greater than k or not
    for (int i = 0; i < n; i++) {
        if (a[i] > k)
            flag = 1;
    }
  
    if (!flag) {
        return 0;
    }
  
    // two pointers used
    int front = 0;
    int end = 0;
  
    // find the maximum length
    int maxi = 0;
  
    // Map used to count frequencies
    unordered_map<int, int> mpp;
  
    // set used to find the second largest
    // element in range front-end
    set<int> s;
  
    // initialize all index of array as 0
    bool vis[n];
    memset(vis, 0, sizeof vis);
  
    // iterate till any of the pointer exceeds N
    while (front < n && end < n) {
  
        // length of longest subarray
        maxi = max(maxi, end - front);
  
        // if the current index has not been
        // visited previously then insert it
        // in the set and increase the frequency
        // and mark it as visited.
        if (!vis[end]) {
            mpp[a[end]]++;
            s.insert(a[end]);
            vis[end] = 1;
        }
  
        // find the largest element in the set
        auto it = s.end();
  
        // if only one element is there in set,
        // then insertion of K is possible which
        // will include other elements
        if (s.size() == 1) {
  
            // increase the second pointer in order
            // to include more elements in the subarray
            end++;
            continue;
        }
  
        // twice decrease the
        // iterator as s.end() points to
        // after the last element
        it--;
  
        // second largest element in set
        it--;
        int el = *it;
  
        // if the second largest element is greater than the
        // K, then it is not possible to insert element
        // in range front-end, and thus decrease the
        // frequency of a[front] and remove from set
        // accordingly
        if (el > k) {
            if (mpp[a[front]] == 1) {
                s.erase(a[front]);
                mpp[a[front]]--;
            }
            else
                mpp[a[front]]--;
  
            // move ahead the first pointer
            front++;
        }
        else {
  
            // increase the second pointer
            // if the second largest element is smaller
            // than or equals to K
            end++;
        }
    }
  
    // at then end also check for last subarray length
    maxi = max(maxi, end - front);
  
    return maxi;
}
  
// Driver Code
int main()
{
    int a[] = { 9, 5, 5, 6, 8 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 7;
  
    cout << lengthOfLongestSubarray(a, n, k);
  
    return 0;
}

chevron_right


Output:

4

Time Complexity: O(N * log N)



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.