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 :
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
Cycle Detection
A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer
View Solution →Find Merge Point of Two Lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share
View Solution →Inserting a Node Into a Sorted Doubly Linked List
Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function
View Solution →Reverse a doubly linked list
This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.
View Solution →Tree: Preorder Traversal
Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's
View Solution →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 →