Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Input: arr = [1,2]
Output: false
EDGE CASE
Input: arr = [1]
Output: true
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Array problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Create a Hash Table and count the occurance of each number. Once we move through the array, we know if there are unique number of occurrences of each number
1) Initialize Hash Table
2) Iterate through numbers
a) Count each number
3) Return if duplicate values exist in hash table
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
# Initialize Hash Table
hashTable = defaultdict(int)
# Iterate through numbers: Count each number
for num in arr:
hashTable[num] += 1
# Return if duplicate values exist in hash table
return len(list(hashTable.values())) == len(set(hashTable.values()))
class Solution {
public boolean uniqueOccurrences(int[] arr)
{
// Initialize Hash Table
HashMap<Integer,Integer> hmap=new HashMap<>();
// Iterate through numbers: Count each number
for(int i:arr)
hmap.put(i,hmap.getOrDefault(i,0)+1);
// Return if duplicate values exist in hash table
HashSet<Integer> hset=new HashSet<>(hmap.values());
return hset.size()==hmap.size();
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of items in the array.
O(N)
because we need to traverse all numbers in the array.O(N)
because we need to store all numbers in the hash table.