Time Portal Usage - codepath/compsci_guides GitHub Wiki

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 create a display table showing the number of times each portal was used at each specific time.
    • What input is provided?
      • An array usage_records where each element is [traveler_name, portal_number, time_used].

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Collect unique times and portals, then construct a table showing the count of portal usages at each time.

1) Collect all unique `times` and `portals` from `usage_records`.
2) Sort the `times` and `portals`.
3) Create a dictionary `usage_dict` to track the frequency of each portal usage at each time.
4) Construct the display table:
   - Start with a header row containing "Portal" followed by sorted times.
   - For each portal, create a row showing the number of times the portal was used at each time.
5) Return the display table.

⚠️ Common Mistakes

  • Not correctly initializing the dictionary or misaligning the counts in the display table.

I-mplement

def display_time_portal_usage(usage_records):
    # Collect all unique times and portal numbers
    times = set()
    portals = set()
    for record in usage_records:
        traveler, portal, time = record
        times.add(time)
        portals.add(portal)

    # Sort the times and portals
    sorted_times = sorted(times)
    sorted_portals = sorted(portals, key=int)

    # Create the frequency dictionary
    usage_dict = {}
    for record in usage_records:
        traveler, portal, time = record
        if portal not in usage_dict:
            usage_dict[portal] = {}
        if time not in usage_dict[portal]:
            usage_dict[portal][time] = 0
        usage_dict[portal][time] += 1

    # Construct the display table
    display_table = []
    header = ["Portal"] + sorted_times
    display_table.append(header)

    for portal in sorted_portals:
        row = [portal]
        for time in sorted_times:
            row.append(str(usage_dict.get(portal, {}).get(time, 0)))
        display_table.append(row)

    return display_table