Most Popular Even Destination - 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 find the most popular even destination based on its popularity score.
    • What input is provided?
      • A list of integers destinations.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Filter the even destinations, count their occurrences, and return the most popular one. If there's a tie, return the smallest one.

1) Create a dictionary `even_count` to store the frequency of each even destination.
2) Iterate through `destinations`:
   - If the destination is even, update its count in `even_count`.
3) Find the most popular even destination:
   - If multiple destinations have the same count, return the smallest one.
4) If no even destinations are found, return `-1`.

⚠️ Common Mistakes

  • Not correctly handling ties or cases with no even destinations.

I-mplement

def most_popular_even_destination(destinations):
    even_count = {}
    
    # Step 1: Filter and count even destinations
    for destination in destinations:
        if destination % 2 == 0:
            if destination in even_count:
                even_count[destination] += 1
            else:
                even_count[destination] = 1
    
    # Step 2: Find the most popular even destination
    most_popular = -1
    max_count = 0
    
    for destination, count in even_count.items():
        if count > max_count or (count == max_count and destination < most_popular):
            most_popular = destination
            max_count = count
    
    return most_popular