Minimum common element in subarrays of all possible lengths

Given an array arr[] consisting of N integers from the range [1, N]( repetition allowed ), the task is to find the minimum common element for each possible subarray length. If no such element exists for any particular length of the subarray, then print -1.
Examples:
Input: arr[] = {1, 3, 4, 5, 6, 7}
Output: -1 -1 -1 4 3 1
Explanation:Â
K = 1: No common element exists. Therefore, print -1.Â
K = 2: No common element exists. Therefore, print -1.Â
K = 3: No common element exists. Therefore, print -1.Â
K = 4: Since 4 is common in all subarrays of size 4, print 4.Â
K = 5: Since 3 and 4 is common in all subarrays of size 5, print 3 as it is the minimum.Â
K = 6: Print 1 as it is the minimum element in the array.
ÂInput: arr[]: {1, 2, 2, 2, 1}
Output: -1 2 2 1 1
Approach: Follow the steps below to solve the problem:Â
- Traverse the array and store the last occurrence of every element in a Map.
- Initialize an array temp[] and store in it for each value, the maximum distance between any pair of consecutive repetitions of it in the array.
- Once the above step is completed, update temp[] by comparing temp[i] with the distance of the last occurrence of i from the end of the array.
- Now, store the minimum comment element for all subarrays of length 1 to N one by one and print them.
Below is the implementation of the above approach:
Â
C++
// C++ Program to implement the// above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find maximum distance// between every two elementvoid max_distance(int a[], int temp[], int n){    // Stores index of last occurrence    // of each array element    map<int, int> mp;Â
    // Initialize temp[] with -1    for (int i = 1; i <= n; i++) {        temp[i] = -1;    }Â
    // Traverse the array    for (int i = 0; i < n; i++) {Â
        // If array element has        // not occurred previously        if (mp.find(a[i]) == mp.end())Â
            // Update index in temp            temp[a[i]] = i + 1;Â
        // Otherwise        elseÂ
            // Compare temp[a[i]] with distance            // from its previous occurrence and            // store the maximum            temp[a[i]] = max(temp[a[i]],                             i - mp[a[i]]);Â
        mp[a[i]] = i;    }Â
    for (int i = 1; i <= n; i++) {Â
        // Compare temp[i] with distance        // of its last occurrence from the end        // of the array and store the maximum        if (temp[i] != -1)            temp[i] = max(temp[i], n - mp[i]);    }}Â
// Function to find the minimum common// element in subarrays of all possible lengthsvoid min_comm_ele(int a[], int ans[],                  int temp[], int n){    // Function call to find the maximum    // distance between every pair of repetition    max_distance(a, temp, n);Â
    // Initialize ans[] to -1    for (int i = 1; i <= n; i++) {        ans[i] = -1;    }Â
    for (int i = 1; i <= n; i++) {Â
        // Check if subarray of length        // temp[i] contains i as one        // of the common elements        if (ans[temp[i]] == -1)            ans[temp[i]] = i;    }Â
    for (int i = 1; i <= n; i++) {Â
        // Find the minimum of all        // common elements        if (i > 1 && ans[i - 1] != -1) {Â
            if (ans[i] == -1)                ans[i] = ans[i - 1];            else                ans[i] = min(ans[i],                             ans[i - 1]);        }Â
        cout << ans[i] << " ";    }}Â
// Driver Codeint main(){Â Â Â Â int N = 6;Â Â Â Â int a[] = { 1, 3, 4, 5, 6, 7 };Â Â Â Â int temp[100], ans[100];Â Â Â Â min_comm_ele(a, ans, temp, N);Â
    return 0;} |
Java
// Java program to implement the// above approachimport java.util.*;Â
class GFG{    // Function to find maximum distance// between every two elementstatic void max_distance(int a[], int temp[], int n){         // Stores index of last occurrence    // of each array element    Map<Integer,        Integer> mp = new HashMap<Integer,                                  Integer>(); Â
    // Initialize temp[] with -1    for(int i = 1; i <= n; i++)     {        temp[i] = -1;    }Â
    // Traverse the array    for(int i = 0; i < n; i++)     {                 // If array element has        // not occurred previously        if (mp.get(a[i]) == null)                     // Update index in temp            temp[a[i]] = i + 1;Â
        // Otherwise        elseÂ
            // Compare temp[a[i]] with distance            // from its previous occurrence and            // store the maximum            temp[a[i]] = Math.max(temp[a[i]],                    i - mp.getOrDefault(a[i], 0));Â
        mp.put(a[i], i);    }Â
    for(int i = 1; i <= n; i++)     {                 // Compare temp[i] with distance        // of its last occurrence from the end        // of the array and store the maximum        if (temp[i] != -1)            temp[i] = Math.max(temp[i],                               n - mp.getOrDefault(i, 0));    }}Â
// Function to find the minimum common// element in subarrays of all possible lengthsstatic void min_comm_ele(int a[], int ans[],                         int temp[], int n){         // Function call to find the maximum    // distance between every pair of repetition    max_distance(a, temp, n);Â
    // Initialize ans[] to -1    for(int i = 1; i <= n; i++)     {        ans[i] = -1;    }Â
    for(int i = 1; i <= n; i++)     {                 // Check if subarray of length        // temp[i] contains i as one        // of the common elements        if (temp[i] >= 0 && ans[temp[i]] == -1)            ans[temp[i]] = i;    }Â
    for(int i = 1; i <= n; i++)    {                 // Find the minimum of all        // common elements        if (i > 1 && ans[i - 1] != -1)        {            if (ans[i] == -1)                ans[i] = ans[i - 1];            else                ans[i] = Math.min(ans[i],                                  ans[i - 1]);        }        System.out.print(ans[i] + " ");    }}Â
// Driver Codepublic static void main(String args[]){Â Â Â Â int N = 6;Â Â Â Â int a[] = { 1, 3, 4, 5, 6, 7 };Â Â Â Â Â Â Â Â Â int []temp = new int[100];Â Â Â Â Arrays.fill(temp, 0);Â Â Â Â Â Â Â Â Â int []ans = new int[100];Â Â Â Â Arrays.fill(ans, 0);Â Â Â Â Â Â Â Â Â min_comm_ele(a, ans, temp, N);}}Â
// This code is contributed by SURENDRA_GANGWAR |
Python3
# Python3 Program to implement # the above approachÂ
def min_comm_ele(a):Â
    n = len(a)    seen = {}Â
    ans = [-1]*(n+1)    temp = {}Â
    for i in range(n):Â
        # If array element has        # not occurred previously        if (a[i] not in seen):Â
            # Update index in temp            temp[a[i]] = i + 1Â
        # Otherwise        else:Â
            # Compare temp[a[i]] with             # distance from its previous             # occurrence and store the maximum            temp[a[i]] = max(temp[a[i]], i - seen[a[i]])                 # Update the latest seen        seen[a[i]] = iÂ
    for i in range(n):Â
        # Compare temp[a[i]] with        # distance from last occurrence        # to the end of the array        # and store the maximum        if (temp[a[i]] != -1):            temp[a[i]] = max(temp[a[i]], n - seen[a[i]])Â
    # We now have a hashmap 'temp'    # which contains for all values in A    # the smallest size of subarray    # for which they will always be visibleÂ
    # ans[i] is the smallest value    # visible with subarray size i    # We can extract this value    # by iterating through temp:Â
    for i in temp:        if ans[temp[i]] == -1:            ans[temp[i]] = i        else:            ans[temp[i]] = min(ans[temp[i]], i)Â
    # If no specific value had     # size i as the minimum,    # we use the previous subarray's    # value (if it exists) for i    # If a value is visible in all    # subarrays of size n, it must    # be visible in subarrays of    # size n+1Â
    for i in range(1,n+1):        if ans[i] == -1 and ans[i-1] != -1:            ans[i] = ans[i-1]Â
    # Return the results for 1 to n    return ans[1:n+1]Â
# Driver Codeif __name__ == "__main__":Â Â Â Â a = [1,3,4,5,6,7]Â Â Â Â res = min_comm_ele(a)Â Â Â Â for m in res:Â Â Â Â Â Â Â Â print(m, end=" ")Â
# This code is contributed by jmcpeak |
C#
// C# program to implement the// above approachusing System;using System.Collections.Generic;class GFG {         // Function to find maximum distance    // between every two element    static void max_distance(int[] a, int[] temp, int n)    {                  // Stores index of last occurrence        // of each array element        Dictionary<int, int> mp = new Dictionary<int, int>();               // Initialize temp[] with -1        for(int i = 1; i <= n; i++)         {            temp[i] = -1;        }              // Traverse the array        for(int i = 0; i < n; i++)         {                          // If array element has            // not occurred previously            if (!mp.ContainsKey(a[i]))                              // Update index in temp                temp[a[i]] = i + 1;                  // Otherwise            else                      // Compare temp[a[i]] with distance                // from its previous occurrence and                // store the maximum                temp[a[i]] = Math.Max(temp[a[i]], i - mp[a[i]]);                         if(mp.ContainsKey(a[i]))            {                mp[a[i]] = i;            }            else{                mp.Add(a[i], i);            }        }              for(int i = 1; i <= n; i++)         {                          // Compare temp[i] with distance            // of its last occurrence from the end            // of the array and store the maximum            if (temp[i] != -1)            {                if(mp.ContainsKey(i))                {                    temp[i] = Math.Max(temp[i], n - mp[i]);                }                else{                    temp[i] = Math.Max(temp[i], n);                }            }        }    }          // Function to find the minimum common    // element in subarrays of all possible lengths    static void min_comm_ele(int[] a, int[] ans,                             int[] temp, int n)    {                  // Function call to find the maximum        // distance between every pair of repetition        max_distance(a, temp, n);              // Initialize ans[] to -1        for(int i = 1; i <= n; i++)         {            ans[i] = -1;        }              for(int i = 1; i <= n; i++)         {                          // Check if subarray of length            // temp[i] contains i as one            // of the common elements            if (temp[i] >= 0 && ans[temp[i]] == -1)                ans[temp[i]] = i;        }              for(int i = 1; i <= n; i++)        {                          // Find the minimum of all            // common elements            if (i > 1 && ans[i - 1] != -1)            {                if (ans[i] == -1)                    ans[i] = ans[i - 1];                else                    ans[i] = Math.Min(ans[i],                                      ans[i - 1]);            }            Console.Write(ans[i] + " ");        }    }Â
  // Driver code  static void Main()   {               int N = 6;        int[] a = { 1, 3, 4, 5, 6, 7 };                  int[] temp = new int[100];        Array.Fill(temp, 0);                  int[] ans = new int[100];        Array.Fill(ans, 0);                  min_comm_ele(a, ans, temp, N);  }}Â
// This code is contributed by divyeshrabadiya07 |
Javascript
<script>Â Â // JavaScript Program to implement the// above approachÂ
// Function to find maximum distance// between every two elementfunction max_distance(a, temp, n){    // Stores index of last occurrence    // of each array element    var mp = new Map();Â
    // Initialize temp[] with -1    for (var i = 1; i <= n; i++) {        temp[i] = -1;    }Â
    // Traverse the array    for (var i = 0; i < n; i++) {Â
        // If array element has        // not occurred previously        if (!mp.has(a[i]))Â
            // Update index in temp            temp[a[i]] = i + 1;Â
        // Otherwise        elseÂ
            // Compare temp[a[i]] with distance            // from its previous occurrence and            // store the maximum            temp[a[i]] = Math.max(temp[a[i]],                             i - mp[a[i]]);Â
        mp.set(a[i], i);    }Â
    for (var i = 1; i <= n; i++) {Â
        // Compare temp[i] with distance        // of its last occurrence from the end        // of the array and store the maximum        if (temp[i] != -1)            temp[i] = Math.max(temp[i], n - mp.get(i));    }}Â
// Function to find the minimum common// element in subarrays of all possible lengthsfunction min_comm_ele(a, ans, temp, n){    // Function call to find the maximum    // distance between every pair of repetition    max_distance(a, temp, n);Â
    // Initialize ans[] to -1    for (var i = 1; i <= n; i++) {        ans[i] = -1;    }Â
    for (var i = 1; i <= n; i++) {Â
        // Check if subarray of length        // temp[i] contains i as one        // of the common elements        if (ans[temp[i]] == -1)            ans[temp[i]] = i;    }Â
    for (var i = 1; i <= n; i++) {Â
        // Find the minimum of all        // common elements        if (i > 1 && ans[i - 1] != -1) {Â
            if (ans[i] == -1)                ans[i] = ans[i - 1];            else                ans[i] = Math.min(ans[i],                             ans[i - 1]);        }Â
        document.write( ans[i] + " ");    }}Â
// Driver Codevar N = 6;var a = [1, 3, 4, 5, 6, 7];var temp =Â new Array(100), ans = Array(100);min_comm_ele(a, ans, temp, N);Â
Â
</script> |
-1 -1 -1 4 3 1
Time Complexity: O(N)Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



