Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Main {
- // Function to find maximum distance between every two elements
- private static List<Integer> result;
- static void findMaxDistance(List<Integer> data, List<Integer> temp) {
- // Stores index of last occurrence of each array element
- Map<Integer, Integer> mp = new HashMap<>();
- // Initialize temp[] with -1
- for (int i = 1; i <= data.size(); i++) {
- temp.add(-1);
- }
- // Traverse the list
- for (int i = 0; i < data.size(); i++) {
- // If list element has not occurred previously
- if (!mp.containsKey(data.get(i))) {
- // Update index in temp
- temp.set(data.get(i) - 1, i + 1);
- } else {
- // Compare temp[a[i]] with distance from its previous occurrence
- // and store the maximum
- temp.set(data.get(i) - 1, Math.max(temp.get(data.get(i) - 1), i - mp.getOrDefault(data.get(i), 0)));
- }
- mp.put(data.get(i), i);
- }
- for (int i = 1; i <= data.size(); i++) {
- // Compare temp[i] with distance of its last occurrence from the end of the list
- // and store the maximum
- if (temp.get(i - 1) != -1) {
- temp.set(i - 1, Math.max(temp.get(i - 1), data.size() - mp.getOrDefault(i, 0)));
- }
- }
- }
- // Function to find the minimum common element in subarrays of all possible lengths
- static void minCommonElement(List<Integer> data, List<Integer> ans, List<Integer> temp) {
- // Function call to find the maximum distance between every pair of repetition
- findMaxDistance(data, temp);
- // Initialize ans[] to -1
- for (int i = 1; i <= data.size(); i++) {
- ans.add(-1);
- }
- for (int i = 1; i <= data.size(); i++) {
- // Check if subarray of length temp[i] contains i as one of the common elements
- if (temp.get(i - 1) >= 0 && ans.get(temp.get(i - 1) - 1) == -1) {
- ans.set(temp.get(i - 1) - 1, i);
- }
- }
- for (int i = 1; i <= data.size(); i++) {
- // Find the minimum of all common elements
- if (i > 1 && ans.get(i - 2) != -1) {
- if (ans.get(i - 1) == -1) {
- ans.set(i - 1, ans.get(i - 2));
- } else {
- ans.set(i - 1, Math.min(ans.get(i - 1), ans.get(i - 2)));
- }
- }
- result.add(ans.get(i - 1));
- }
- }
- private List<Integer> minCommon(List<Integer> data) {
- result = new ArrayList<>();
- List<Integer> temp = new ArrayList<>(Collections.nCopies((int) ((2 * 1e5) + 1), -1));
- List<Integer> ans = new ArrayList<>(Collections.nCopies((int) ((2 * 1e5) + 1), -1));
- minCommonElement(data, ans, temp);
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement