Prefix with Equivalent Frequencies - Amazon Top Interview Questions


Problem Statement :


You are given a list of integers nums. Return the length of the longest prefix of nums such that after we remove one element in the prefix, each number occurs the same number of times.

Constraints

n ≤ 100,000 where n is the length of nums

Example 1

Input

nums = [5, 5, 3, 7, 3, 9]

Output

5

Explanation

If we pick the prefix [5, 5, 3, 7, 3] and remove 7 then every number would occur twice.



Solution :



title-img




                        Solution in C++ :

int solve(vector<int>& nums) {
    // we use two hashmaps one to keep the track of the frequecny of elements and one to keep the
    // track of the of the frequecny of frequencies.
    map<int, int> f, fc;
    int ans = 0;

    for (int i = 0; i < nums.size(); i++) {
        // if we have already inserted the element inside our prefix window
        // we first remove old frequency contribution
        // if there is only one  element with this frequency than after the frequency change there
        // will be no element remaining with this frequency so we remove it's existance
        if (f.find(nums[i]) != f.end() and fc[f[nums[i]]]-- == 1) {
            fc.erase(f[nums[i]]);
        }

        // now we increase the frequency of the element and also the frequency count of f[nums[i]]
        // afterwards.
        fc[++f[nums[i]]]++;

        // now checking if the window so far is valid.
        if (fc.size() == 2) {
            if (fc.find(1) != fc.end()) {
                if (fc[1] == 1) ans = max(ans, i + 1);
            }
            if (fc.begin()->first == fc.rbegin()->first - 1) {
                if (fc.rbegin()->second == 1) ans = max(ans, i + 1);
            }
        } else if (fc.size() == 1 and (fc.begin()->first == 1 or f.size() == 1)) {
            ans = max(ans, i + 1);
        }
    }
    return ans;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int[] nums) {
        // 1234567 remove one of them
        // 1111111 remove one of them
        // 111 222 333 4 remove 4
        // 111 222 333 4444 remove one of 4
        Map<Integer, List<Integer>> window = new HashMap<>();
        Map<Integer, Integer> freq = new HashMap<>();

        int len = nums.length;
        if (len == 2) {
            return 2;
        }
        int res = 0;

        for (int i = 0; i < len; i++) {
            int n = nums[i];
            freq.put(n, freq.getOrDefault(n, 0) + 1);
            int f = freq.get(n);

            if (window.containsKey(f - 1)) {
                window.get(f - 1).remove(new Integer(n));
                if (window.get(f - 1).size() == 0) {
                    window.remove(f - 1);
                }
            }
            window.putIfAbsent(f, new ArrayList<Integer>());
            window.get(f).add(n);

            // if frequency of all the elements is 1
            if (window.size() == 1 && window.containsKey(1)) {
                res = i + 1;
                // if all the elements are same inside the prefix window
            } else if (window.size() == 1) {
                for (int key : window.keySet()) {
                    if (window.get(key).size() == 1) {
                        res = i + 1;
                    }
                }
            } else if (window.size() == 2) {
                int first = -1;
                int second = -1;
                for (int key : window.keySet()) {
                    if (first == -1) {
                        first = key;
                    } else {
                        second = key;
                    }
                }
                if (first + 1 == second && window.get(second).size() == 1) {
                    res = i + 1;
                } else if (second + 1 == first && window.get(first).size() == 1) {
                    res = i + 1;
                } else if (window.containsKey(1) && window.get(1).size() == 1) {
                    res = i + 1;
                }
            } else {
                continue;
            }
        }
        return res;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, nums):
        freq = dict()  # stores the amount of different counts
        counts = dict()  # stores the count of each number

        for i, num in enumerate(nums):
            old_c, new_c = counts.get(num, 0), counts.get(num, 0) + 1

            if old_c in freq:  # remove previous frequency
                freq[old_c] -= 1
                if freq[old_c] == 0:
                    del freq[old_c]

            counts[num] = new_c  # add the new frequency
            freq[new_c] = freq.get(new_c, 0) + 1

            if len(freq) == 1:
                for k, v in freq.items():
                    if v == 1 or k == 1:
                        res = i + 1

            if len(freq) == 2:
                tmp = [(k, v) for k, v in freq.items()]
                (f1, c1), (f2, c2) = tmp[0], tmp[1]
                if (f1 == 1 and c1 == 1) or (f2 == 1 and c2 == 1):
                    res = i + 1
                if c1 == 1 and f1 - 1 == f2 or c2 == 1 and f2 - 1 == f1:
                    res = i + 1
        return res
                    


View More Similar Problems

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →