// Java program to implement the
// above approach
import java.util.*;
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
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 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]);
}
System.out.print(ans[i] + " ");
}
}
// Driver Code
public 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