Skip to content

Group By Frequency

Sar Champagne Bielert edited this page Apr 10, 2024 · 5 revisions

Unit 2 Session 2 (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

    • A

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: TODO

1) TODO

⚠️ Common Mistakes

I-mplement

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
Clone this wiki locally