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

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →