We are given a list of integers. We need to find the mode, which is the element that appears most frequently. There can be multiple modes if multiple elements have the same maximum frequency. The problem statement says "the mode" but typically in the case of multiple modes, we might return one of them or all? The problem says "the mode", which might imply we return a single mode. But to be safe, we should clarify what to return in case of multiple modes. The problem statement: "Write a function to find the mode of the list." Usually, if there are multiple modes, the set of modes is returned. But the phrasing "the mode" might suggest there is a unique one. However, we should handle the general case.
The instruction says: "Please the mode is the most frequently occurring element, write a function that solves this problem, explain your algorithm using a hash map, and what is the time and space complexity."
So we need to write a function and explain the algorithm using a hash map. We'll assume we return a list of modes if there are multiple, or maybe just one? Let's read carefully: "the mode is the most frequently occurring element" - it says element (singular). So maybe we assume there is a unique mode? But we cannot guarantee that. Typically, in programming problems, if there are multiple, we might return any one, or sometimes the smallest one. But the problem doesn't specify. We should clarify.
Since it says "the mode", it might be that the input is such that the mode is unique. But to be robust, we can return a list of all modes. Or we can return one of them. The problem says "find the mode", not "find the modes". So perhaps we return one mode, and if there are multiple, we can return the one that appears first? Or the smallest? But not specified.
Given that we are to explain using a hash map, we can compute frequencies, then find the maximum frequency, then collect all elements with that frequency. But then returning a single mode? If we return all, it's actually the set of modes. But the problem says "the mode", so maybe we return just one. However, many definitions: in statistics, the mode is the value that appears most frequently. A set of data may have one mode, more than one mode, or no mode at all. But here we have a list of integers, so it will have at least one mode? Actually, if all elements are distinct, then every element is a mode? But typically, if every value appears exactly once, then there is no mode, or all are modes? That's ambiguous. Usually, if no value repeats, then there is no mode. But the problem says "the most frequently occurring element", so if all have frequency 1, then any element is a mode? Because they all have the same frequency and that is the maximum. So there would be multiple modes.
Given the ambiguity, I'll assume that we need to return a list of all modes. Because the problem asks for "the mode" but in code we can return a list. Alternatively, we can return the first encountered mode? But that might not be consistent.
Let me check similar problems: on LeetCode, "Find the Mode in Binary Search Tree" returns a list of modes. So returning a list is common.
But the problem statement here says "the mode", not "the modes". However, in the explanation we can say we return all elements that have the maximum frequency.
Given that it's a simple list, we can do:
- Use a hash map (dictionary) to count frequencies of each integer.
- Find the maximum frequency value from the counts.
- Collect all keys that have that maximum frequency.
- Return the list of those keys.
But if we are to return a single mode, we might just pick one, e.g., the first one we encounter with max frequency. But that might be arbitrary.
Given that the problem says "explain your algorithm using a hash map", it's straightforward to compute all frequencies and then find the maximum and then get all keys with that max. That gives all modes.
But if we are required to return a single mode, we could just return the first one from the list of keys with max frequency? But then the function return type would be an integer, not a list. The problem doesn't specify the return type. It says "write a function", so we need to decide.
Perhaps the intended solution is to return the mode as an integer. But if there are multiple, we can return any one. However, that might not be deterministic. To be deterministic, we could return the smallest mode? Not specified.
Given the typical definition: the mode of a set of values is the value that appears most frequently. If multiple values have the same highest frequency, the data is multimodal. But often when asked "find the mode", if there are multiple, they might expect all. But the wording "the mode" suggests singular.
I think it's safer to return a list of all modes. In the explanation, we can mention that.
Alternatively, we can ask for clarification, but as an AI, we must provide an answer.
Let's look at the exact phrasing: "You are given a list of integers. Write a function to find the mode of the list. Please the mode is the most frequently occurring element, write a function that solves this problem, explain your algorithm using a hash map, and what is the time and space complexity."
It says "the mode is the most frequently occurring element". That implies we want the element that occurs most frequently. If there are multiple, then there are multiple such elements. So we might return one of them? But then it says "element" singular. So maybe we assume the mode is unique? But we cannot assume that about the input.
In many simple problems, they assume the mode is unique. But to be safe, I'll handle the general case and return a list of all modes. In the function signature, we can return a list. And we can say: if there is a unique mode, the list will have one element.
Thus:
Function: find_mode(nums: list) -> list
Algorithm:
- Create an empty dictionary to count frequencies.
- Iterate through each number in nums, increment its count in the dictionary.
- Then find the maximum frequency value from the dictionary values.
- Then iterate through the dictionary and collect all keys that have that maximum frequency.
- Return the list of those keys.
Time complexity: O(n) for counting, plus O(m) for finding max and collecting, where m is the number of distinct elements. Since m <= n, overall O(n).
Space complexity: O(m) for the dictionary, which in worst case is O(n) if all distinct.
But what if we want to return a single mode? We could do:
After finding max frequency, we can return the first key we encounter with that frequency. But that depends on the order of iteration in the dictionary, which is arbitrary (in Python 3.7+ it preserves insertion order). But if we want the smallest mode, we might sort the list of modes and return the smallest. That would add O(m log m). But not specified.
Given the instruction to use a hash map, we are using a hash map for counting. The rest is linear.
So I'll go with returning all modes.
Now, we need to write the function. Let's write in Python.
Example:
Input: [1,2,2,3,3,4]
Modes: [2,3] because both appear twice.
Input: [1,1,2,2,3] -> modes: [1,2]? Actually both appear twice, so [1,2]. But if we want a single mode, we might return 1 or 2? Not sure.
But I'll return all.
Implementation:
def find_mode(nums):
if not nums:
return [] # or maybe raise error? But empty list has no mode.
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
max_freq = max(freq.values())
modes = [num for num, count in freq.items() if count == max_freq]
return modes
That's it.
Now explain algorithm using hash map.
We use a hash map (dictionary) to store the frequency of each integer. We iterate through the list once to populate the hash map. Then we find the maximum frequency by examining all values in the hash map. Then we collect all keys that have that maximum frequency. This gives us the mode(s).
Complexity: O(n) time, O(m) space.
But note: finding max(freq.values()) is O(m), and collecting is O(m). So overall O(n + m) = O(n) since m <= n.
Space: O(m) for the hash map.
We can also do it in one pass? Possibly, but we need to know the max frequency and the modes. We could keep track of current max frequency and a list of modes as we go, but when we increase count of an element, it might become the new mode or tie the current mode. But if it ties, we need to add it. But if we later find a higher frequency, we reset the list. So we can do:
Initialize max_freq = 0, modes = []
For each number:
increment count in hash map
if count > max_freq:
max_freq = count
modes = [num]
elif count == max_freq:
modes.append(num)
But careful: if we have multiple numbers reaching the same max at different times, we need to ensure we don't miss any. But also, if we have a number that starts with count 1 and max_freq is 0 initially, we set max_freq=1 and modes=[num]. Then if another number gets count 1, we append? But that would make modes list contain all numbers with frequency 1, but that is not necessarily the mode if later some number gets frequency 2. So we need to reset when we find a higher frequency. But if we have a tie at the current max, we add. But if later we find a higher, we reset. That works.
But there is a subtlety: when we see a number for the first time, count becomes 1. If max_freq is 0, we set max_freq=1 and modes=[num]. Then if we see another new number, its count becomes 1, which equals max_freq, so we append. So modes will accumulate all numbers that have ever reached the current max frequency. But if later we find a number that reaches frequency 2, then max_freq becomes 2 and modes resets to that number only. But what about numbers that had frequency 2 earlier? They will be caught when their count becomes 2? Actually, when a number's count increases to 2, at that moment we check: if count > max_freq (which is 1), then we set max_freq=2 and modes=[num]. So we reset. But what if there is another number that also reaches 2 later? When its count becomes 2, count == max_freq, so we append. That works.
But what if we have a number that reaches 2, then later another number reaches 2, then another reaches 3? The first time a number reaches 3, we reset modes to that number only. But what about other numbers that might have already been at 3? Actually, we only update when we increment a count. So if a number is incremented to 3, at that moment we check and reset if necessary. But if there is another number that is already at 3 (from previous increments) but we haven't incremented it in this step, we won't add it until we increment it again? That's a problem. For example, suppose we have numbers: [1,1,2,2,3,3,1].
Processing:
1: count1=1 -> max=1, modes=[1]
1: count1=2 -> max=2, modes=[1]
2: count2=1 -> count1=2, so count2=1 < max, ignore.
2: count2=2 -> count2=2 == max, so append 2 -> modes=[1,2]
3: count3=1 -> ignore
3: count3=2 -> append 3 -> modes=[1,2,3]
1: count1=3 -> count1=3 > max(2), so set max=3, modes=[1]. Now modes only [1], but actually at this point, 1 has frequency 3, others have 2. So mode is [1]. That is correct.
But what if we had: [1,1,2,2,3,3,2]?
1: count1=1 -> modes=[1], max=1
1: count1=2 -> modes=[1], max=2
2: count2=1 -> ignore
2: count2=2 -> append 2 -> modes=[1,2]
3: count3=1 -> ignore
3: count3=2 -> append 3 -> modes=[1,2,3]
2: count2=3 -> count2=3 > max(2), so set max=3, modes=[2]. Now modes=[2]. But at this point, frequencies: 1:2, 2:3, 3:2. So mode is [2]. Correct.
But what about a scenario where two numbers both reach the same max frequency but not at the same time? For example, [1,2,1,2].
1: count1=1 -> modes=[1], max=1
2: count2=1 -> append 2 -> modes=[1,2]
1: count1=2 -> count1=2 > max(1), so set max=2, modes=[1]
2: count2=2 -> count2=2 == max, append 2 -> modes=[1,2]. Correct.
So this one-pass approach works? But wait, in the step when we see the second 2, count2 becomes 2, and max is already 2, so we append. That gives [1,2]. So it seems to work.
But consider: [1,2,2,1].
1: count1=1 -> modes=[1], max=1
2: count2=1 -> append 2 -> modes=[1,2]
2: count2=2 -> count2=2 > max(1), so set max=2, modes=[2]
1: count1=2 -> count1=2 == max, append 1 -> modes=[2,1]. Correct.
But what about if there are three numbers: [1,2,3,1,2,3].
1: count1=1 -> modes=[1], max=1
2: count2=1 -> append 2 -> modes=[1,2]
3: count3=1 -> append 3 -> modes=[1,2,3]
1: count1=2 -> count1=2 > max(1), set max=2, modes=[1]
2: count2=2 -> append 2 -> modes=[1,2]
3: count3=2 -> append 3 -> modes=[1,2,3]. Correct.
So it seems to work. But is it always correct? The key is: when we increase a count, if it becomes greater than current max, we reset the modes list to only that number. If it equals the current max, we add it. But what if there is a number that already has count equal to max but we haven't just incremented it? That number is already in the modes list? Actually, when we first reached that max frequency for that number, we added it (either by resetting when it became greater, or by appending when it became equal). But if max frequency increased later, that number might have been left behind. For example, suppose we have numbers that reach frequency 2 early, and then later one number reaches frequency 3. When that number reaches 3, we reset the modes list to only that number. But what about other numbers that also eventually reach frequency 3? They will be added when their count becomes 3, because at that time count == max (3), so we append. But what if a number already had frequency 3 before we incremented it to 3? That cannot happen because we increment one by one. So when a number's count becomes 3, that is the moment we should add it if max is already 3? But if max is already 3 from another number, then when this number's count becomes 3, we will append. But what if max was increased to 3 by this number itself? Then we reset. So all numbers that eventually reach the final max frequency will be added at the moment their count reaches that max (if max was already that value from another number, we append; if this number is the first to reach that new max, we reset and start a new list). But what about numbers that already had count equal to the new max before we encountered them? That cannot happen because we process sequentially. So if the final max frequency is M, then for a number to have frequency M, at some point its count must become M. At that point, if the current max is already M, we append; if not, we reset and set max to M and set list to that number. But if later another number also reaches M, we will append because max is already M. So all numbers with final frequency M will be in the list at the end.
But there is a catch: what if after we have set max to M and modes to some list, we later increment a number that already has count M? That would make it M+1, then we reset. That's fine because then the final max is higher. But what about numbers that have count M but we haven't incremented them after we set max to M? They are already in the list? They should be, because when they reached M, we either reset or appended. But if they reached M before we set max to M? That cannot happen because max increases monotonically. So when a number reaches M, if max is already M, then we append. If max is less than M, then we reset max to M and set list to that number. So after processing all numbers, the modes list will contain all numbers that have frequency equal to the final max frequency.
But is it possible that a number reaches frequency M, but at that time max is already M, so we append. But later, max increases to M+1, so that number is no longer a mode. But we don't remove it from the list? In the algorithm above, when we reset for a higher max, we set modes to a new list containing only the current number. So the old list is discarded. So that's fine.
But what about a number that reaches M after max has been increased to M+1? That cannot happen because if max is M+1, then for a number to reach M, it would have to increment from M-1 to M, but that is less than max, so we ignore. So it won't be added. So only numbers that reach the final max frequency will be in the list at the end.
But there is a subtle issue: when we reset, we set modes to [num]. But what if there is another number that already has count equal to the new max? That number might have been incremented earlier and already had count equal to the new max? But if max is increasing, then the new max is greater than the old max. So no number could have had count equal to the new max before because the new max is greater than the previous max. So when we reset, we are the first to reach that new max, so no other number has that count yet. But what if two numbers both reach the new max at the same time? That cannot happen because we process one number at a time. So when we increment a number and its count becomes new_max, we set max to new_max and modes=[num]. Then later, when another number's count becomes new_max, we will append because at that time max is already new_max. So that works.
So the one-pass algorithm is correct.
But is it more efficient? It still uses O(n) time and O(m) space, and we avoid the second pass over the dictionary to find max and collect. But we still need the hash map to store counts. So time complexity is still O(n) but with a smaller constant factor? Actually, we are still doing the same number of hash map operations. But we avoid the extra loop over all distinct elements. However, the number of distinct elements m can be much less than n, so the extra loop is not heavy. But in worst case m = n, so the extra loop is O(n) as well. So overall it's still O(n). But the one-pass might be slightly better if m is large.
But we need to be careful: in the one-pass, we are maintaining a list of modes. When we reset, we discard the old list. But what if we have many resets? That could cause overhead of creating new lists. But worst-case, the max frequency might increase many times, but at most n times? Actually, the max frequency can increase at most up to n, but typically much less. But in worst case, if the list is sorted and each number appears once until the last number repeats many times? For example, [1,2,3,...,n-1, n, n, n,... n]. Then the max frequency will increase when we process the first n, then second n, etc. But we reset only when we exceed the current max. So if we have one number that appears many times, we will reset about O(occurrences) times? Actually, if a number appears k times, when we process its first occurrence, max becomes 1, modes=[that number]. Second occurrence: count becomes 2, which is greater than 1, so reset: modes=[that number] again. So we reset for every occurrence beyond the first? That would be k-1 resets. But each reset creates a new list of size 1. That's not too bad. But if many numbers have high frequencies, we might reset many times. But overall, the total number of appends and resets is bounded by n. So still O(n).
But the one-pass algorithm might be more complex to explain? Actually, it's similar.
Given that the problem says "explain your algorithm using a hash map", we can use the two-pass approach: first build frequency map, then find max and collect. That is straightforward.
I'll go with the two-pass for clarity.
But we need to write the function. Let's write it.
Also, consider edge cases: empty list? We return empty list. Single element? Return that element in a list.
Now, complexity: time O(n), space O(m) where m is number of distinct elements.
Now, we need to output the explanation as well.
The user said: "Write a function to find the mode of the list. Please the mode is the most frequently occurring element, write a function that solves this problem, explain your algorithm using a hash map, and what is the time and space complexity."
So we need to provide the function and the explanation.
I'll write in Python.
Let me write the function with type hints.
def find_mode(nums: List[int]) -> List[int]:
if not nums:
return []
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
max_freq = max(freq.values())
return [num for num, count in freq.items() if count == max_freq]
But we can also do:
from collections import Counter
def find_mode(nums):
if not nums: return []
counts = Counter(nums)
max_count = max(counts.values())
return [num for num, cnt in counts.items() if cnt == max_count]
But using Counter is also using a hash map. But we are asked to explain using a hash map, so we can either use Counter or implement manually. I think implementing manually shows the hash map explicitly.
I'll implement manually.
Now, explanation:
We use a hash map (dictionary) to count the frequency of each integer in the list. We iterate through the list once, updating the count for each integer. After we have the frequency of each integer, we find the maximum frequency among all values. Then we iterate through the hash map and collect all integers that have this maximum frequency. These integers are the mode(s) of the list.
Time complexity: O(n) for the first pass to count frequencies, plus O(m) to find the max and collect modes, where m is the number of distinct integers. Since m <= n, the total time complexity is O(n).
Space complexity: O(m) for the hash map, which in the worst case is O(n) when all integers are distinct.
That should be it.
But wait, what about the case where there are multiple modes? We return all. That might be what is expected.
If the problem expects a single mode, we could return the first one or the smallest. But since not specified, returning all is safer.
I'll mention in the explanation that if there is a unique mode, the list will have one element; if multiple, it will have all.
Now, let's produce the final answer.
We can find the mode(s) of a list of integers using a hash map (dictionary) to count frequencies. The algorithm works in two passes:
- Count frequencies: Iterate through the list, updating the count for each integer in the hash map.
- Find modes: Determine the maximum frequency from the hash map values, then collect all integers whose frequency equals this maximum.
This approach handles both unique and multiple modes.
Python Function
from typing import List
def find_mode(nums: List[int]) -> List[int]:
if not nums:
return []
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
max_freq = max(freq.values())
modes = [num for num, count in freq.items() if count == max_freq]
return modes
Explanation
- Hash Map Usage: The dictionary
freq stores each integer as a key and its occurrence count as the value.
- First Pass: For each number in
nums, we increment its count in freq. This takes (O(n)) time.
- Second Pass: We find the maximum frequency (
max_freq) by examining all values in freq\) (\(O(m)\) time, where \(m\) is the number of distinct integers). Then we collect all keys with count equal to max_freq` ((O(m)) time).
- Result: The list
modes contains all integers with the highest frequency. If there is a unique mode, the list has one element; if multiple integers share the highest frequency, all are returned.
Complexity Analysis
- Time Complexity: (O(n)), where (n) is the length of the input list. The two passes are linear, and since (m \leq n), the total is (O(n)).
- Space Complexity: (O(m)), where (m) is the number of distinct integers. In the worst case ((m = n)), it is (O(n)).
Example
print(find_mode([1, 2, 2, 3, 3, 4])) # Output: [2, 3] (both appear twice)
print(find_mode([1, 1, 2, 3])) # Output: [1] (appears twice)
print(find_mode([1, 2, 3, 4])) # Output: [1, 2, 3, 4] (all appear once)