Repository navigation
Group By Frequency
codepath-wiki-review[bot] edited this page Nov 20, 2026
·
8 revisions
TIP101 Unit 2 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What is the input?
- A list
lstof elements, which may contain repeats.
- A list
- What should the function return?
- A dictionary that maps each frequency to a list of the elements that appear exactly that many times.
- In what order do the elements appear in each list?
- In the order of their first appearance in
lst, because the frequency map and the inverted map are both filled in that order.
- In the order of their first appearance in
- What if the list is empty?
- Return an empty dictionary.
HAPPY CASE
Input: lst = [1, 2, 2, 3, 3, 3, 4]
Output: {1: [1, 4], 2: [2], 3: [3]}
Explanation: 1 and 4 each appear once, 2 appears twice and 3 appears three times.
EDGE CASE
Input: lst = []
Output: {}
Explanation: There are no elements to count, so the result is an empty dictionary.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Create a frequency map, then create an inverted version -- so the frequencies are KEYS and the values are a list of nums with that frequency.
1) First, create a frequency map for the list¹
2) Next, create an empty dict to hold our inverted map
3) Loop through each num, frequency in frequency map:
a) If the frequency is not in inverted map
i) Map it to an empty list
b) Add the num to the inverted dict's list for that frequency
4) Return the inverted map¹ see Frequency Count for pseudocode
def group_by_frequency(lst):
# Step 1: Count the frequency of each element
frequency_map = {}
for element in lst:
if element in frequency_map:
frequency_map[element] += 1
else:
frequency_map[element] = 1
# Step 2: Invert the mapping from element:frequency to frequency:[elements]
inverted_map = {}
for element, freq in frequency_map.items():
if freq not in inverted_map:
inverted_map[freq] = []
inverted_map[freq].append(element)
# Step 3: Ensure the elements in the inverted map are sorted by their first appearance
# This is inherently maintained as we append elements in the order we traverse them
return inverted_map