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 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:
C++
// 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; } |
Python3
# Python3 program to find the length of # the longest subarray such that K is # the second largest element on insertion # Function to find the length of longest subarray def lengthOfLongestSubarray(a, n, k): flag = 0 # Check if any element exists which is # greater than k or not for i in range (n): if (a[i] > k): flag = 1 if (flag = = 0 ): return 0 # two pointers used front = 0 end = 0 # find the maximum length maxi = 0 # Map used to count frequencies mpp = dict () # set used to find the second largest # element in range front-end s = dict () # initialize all index of array as 0 vis = [ 0 ] * n # iterate till any of the pointer exceeds N while (front < n and 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] = = 0 ): mpp[a[end]] = mpp.get(a[end], 0 ) + 1 s[a[end]] = s.get(a[end], 0 ) + 1 vis[end] = 1 # find the largest element in the set iit = sorted ( list (s)) it = len (iit) # if only one element is there in set, # then insertion of K is possible which # will include other elements if ( len (s) = = 1 ): # increase the second pointer in order # to include more elements in the subarray end + = 1 continue # twice decrease the # iterator as s.end() points to # after the last element it - = 1 # second largest element in set it - = 1 el = iit[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 ): del s[a[front]] mpp[a[front]] - = 1 else : mpp[a[front]] - = 1 # move ahead the first pointer front + = 1 else : # increase the second pointer # if the second largest element is # smaller than or equals to K end + = 1 # at then end also check for # last subarray length maxi = max (maxi, end - front) return maxi # Driver Code a = [ 9 , 5 , 5 , 6 , 8 ] n = len (a) k = 7 print (lengthOfLongestSubarray(a, n, k)) # This code is contributed by Mohit Kumar |
4
Time Complexity: O(N * log N)
Recommended Posts:
- Longest subarray in which all elements are greater than K
- Smallest subarray such that all elements are greater than K
- Longest subarray having maximum sum
- Longest subarray with sum divisible by k
- Longest subarray not having more than K distinct elements
- Length of the longest Subarray with only Even Elements
- Longest subarray having difference in the count of 1's and 0's equal to k
- Longest subarray having count of 1s one more than count of 0s
- Maximum difference between frequency of two elements such that element having greater frequency is also greater
- Longest Increasing Subsequence using Longest Common Subsequence Algorithm
- Find if there is a subarray with 0 sum
- Subarray whose sum is closest to K
- Maximum subarray sum modulo m
- Maximum sum subarray of even length
- Subarray with no pair sum divisible by K
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.