Skip to content

Gallery Wall

LeWiz24 edited this page Aug 13, 2024 · 2 revisions

U-nderstand

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

  • Q
    • What is the desired outcome?
      • To organize a collection of art prints into a 2D array where each row contains distinct strings and the number of rows is minimal.
    • What input is provided?
      • A list of strings collection.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Count the occurrences of each print, then distribute them into the minimal number of rows such that each row contains distinct prints.

1) Count the occurrences of each print using `Counter`.
2) Organize prints into rows by their frequency.
3) Initialize the 2D array `rows`.
4) Distribute prints into rows while ensuring each row contains distinct prints.
5) Remove any empty rows and return the result.

⚠️ Common Mistakes

  • Not correctly distributing prints into rows, leading to duplicate prints in a row.

I-mplement

from collections import Counter, defaultdict

def organize_exhibition(collection):
    # Step 1: Count occurrences of each print
    print_count = Counter(collection)
    
    # Step 2: Create a list of unique prints and their counts
    unique_prints = defaultdict(list)
    for print_name, count in print_count.items():
        unique_prints[count].append(print_name)
    
    # Step 3: Determine the number of rows needed
    max_count = max(print_count.values())
    
    # Step 4: Initialize the 2D array
    rows = [[] for _ in range(max_count)]
    
    # Step 5: Distribute prints into rows
    for count, prints in unique_prints.items():
        for i in range(count):
            for print_name in prints:
                rows[i].append(print_name)
    
    # Step 6: Remove any empty rows
    result = [row for row in rows if row]
    
    return result
Clone this wiki locally