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
Array-DS
An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3
View Solution →2D Array-DS
Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t
View Solution →Dynamic Array
Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.
View Solution →Left Rotation
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d
View Solution →Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →