Minimum common element in all subarrays of size K

Given an array arr[] consisting of N distinct integers and a positive integer K, the task is to find the minimum element that occurs in all subarrays of size K. If no such element exists, then print “-1”.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}, K = 4
Output: 2
Explanation:
The subarrays of size 4 are {1, 2, 3, 4} and {2, 3, 4, 5}.
The common elements in the above subarrays are {2, 3, 4}.
The minimum of the above common element is 2.

Input: arr[] = {1, 2, 3, 4, 5}, K = 2
Output: -1
Explanation: 
The subarrays of size 2 are {1, 2}, {2, 3}, {3, 4}, {4, 5}. Since there is no common element, print -1.

Naive Approach: The idea is to generate all possible subarrays of the given array of size K and find the common elements in all the subarrays formed. After, finding the common elements, print the minimum among them. If no element is found to be common in all the subarrays, then print “-1”



Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The idea is to first check the condition for the common element in all the subarrays and if such an element exists, then it should be within the range [N – K, K], in the given array. Below are the conditions where we can’t find any such minimum element:

  • If N is odd and K ≥ (N + 1)/2.
  • If N is even and K ≥ ((N + 1)/2) + 1.

If the above conditions don’t satisfy, then the minimum element lies in the range [N – K, K]. Therefore, iterate over the given array in this range and print the value of the minimum element in it.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum common
// among all the subarray of size K
// from the given array arr[]
void minCommonElementInSubarrays(
    int arr[], int N, int K)
{
    int c;
 
    // If N is odd then update
    // C as K >= (N + 1)/2
    if ((N + 1) % 2 == 0) {
        c = (N + 1) / 2;
    }
 
    // If N is even then update
    // C as K >= (N + 1)/2 + 1
    else {
        c = (N + 1) / 2 + 1;
    }
 
    // If K < C, return "=1"
    if (K < c) {
        cout << -1;
    }
 
    // Otherwise
    else {
 
        // Initialize result variable
        int ar = INT_MAX;
 
        // Find minimum element
        for (int i = N - K; i < K; i++) {
            ar = min(arr[i], ar);
        }
 
        // Print the minimum value
        cout << ar;
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4, 5 };
 
    // Given K
    int K = 4;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    minCommonElementInSubarrays(arr, N, K);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.io.*;
 
class GFG{
   
// Function to find the minimum common
// among all the subarray of size K
// from the given array arr[]
static void minCommonElementInSubarrays(int arr[],
                                        int N, int K)
{
    int c;
   
    // If N is odd then update
    // C as K >= (N + 1)/2
    if ((N + 1) % 2 == 0)
    {
        c = (N + 1) / 2;
    }
   
    // If N is even then update
    // C as K >= (N + 1)/2 + 1
    else
    {
        c = (N + 1) / 2 + 1;
    }
   
    // If K < C, return "=1"
    if (K < c)
    {
        System.out.print(-1);
    }
   
    // Otherwise
    else
    {
         
        // Initialize result variable
        int ar = Integer.MAX_VALUE;
   
        // Find minimum element
        for(int i = N - K; i < K; i++)
        {
            ar = Math.min(arr[i], ar);
        }
   
        // Print the minimum value
        System.out.print(ar);
    }
}
   
// Driver Code
public static void main (String[] args)
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4, 5 };
   
    // Given K
    int K = 4;
   
    int N = arr.length;
   
    // Function call
    minCommonElementInSubarrays(arr, N, K);
}
}
 
// This code is contributed by sanjoy_62

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import sys
 
# Function to find the minimum common
# among all the subarray of size K
# from the given array arr[]
def minCommonElementInSubarrays(arr, N, K):
     
    c = 0
 
    # If N is odd then update
    # C as K >= (N + 1)/2
    if ((N + 1) % 2 == 0):
        c = (N + 1) // 2
 
    # If N is even then update
    # C as K >= (N + 1)/2 + 1
    else:
        c = (N + 1) / 2 + 1
 
    # If K < C, return "=1"
    if (K < c):
        print(-1)
 
    # Otherwise
    else:
         
        # Initialize result variable
        ar = sys.maxsize
 
        # Find minimum element
        for i in range(N - K, K):
            ar = min(arr[i], ar)
 
        # Print the minimum value
        print(ar)
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr = [ 1, 2, 3, 4, 5 ]
 
    # Given K
    K = 4
 
    N = len(arr)
 
    # Function call
    minCommonElementInSubarrays(arr, N, K)
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
   
// Function to find the minimum common
// among all the subarray of size K
// from the given array arr[]
static void minCommonElementInSubarrays(int[] arr,
                                        int N, int K)
{
    int c;
   
    // If N is odd then update
    // C as K >= (N + 1)/2
    if ((N + 1) % 2 == 0)
    {
        c = (N + 1) / 2;
    }
   
    // If N is even then update
    // C as K >= (N + 1)/2 + 1
    else
    {
        c = (N + 1) / 2 + 1;
    }
   
    // If K < C, return "=1"
    if (K < c)
    {
        Console.Write(-1);
    }
   
    // Otherwise
    else
    {
         
        // Initialize result variable
        int ar = Int32.MaxValue;
   
        // Find minimum element
        for(int i = N - K; i < K; i++)
        {
            ar = Math.Min(arr[i], ar);
        }
         
        // Print the minimum value
        Console.Write(ar);
    }
}
   
// Driver Code
public static void Main ()
{
     
    // Given array arr[]
    int[] arr = { 1, 2, 3, 4, 5 };
   
    // Given K
    int K = 4;
   
    int N = arr.Length;
   
    // Function call
    minCommonElementInSubarrays(arr, N, K);
}
}
 
// This code is contributed by sanjoy_62

chevron_right


Output: 

2



 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


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.



Improved By : mohit kumar 29, sanjoy_62