The Trip Grouper

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4
Asked in
Booking.com

Problem

Given a list of trip dicts (each with 'destination' and 'duration_days'), return a dict mapping each destination to the total duration_days across all matching trips.

Where did everyone go, and for how long?

Example

Input:

trips = [{"traveler":"Alice","destination":"Paris","duration_days":7},{"traveler":"Bob","destination":"Tokyo","duration_days":5},{"traveler":"Carol","destination":"Paris","duration_days":3}]

Output:

{"Paris":10,"Tokyo":5}

Worked solution and explanation

Why this problem exists in real interviews

This tests dict-based aggregation by a string key, the Python equivalent of GROUP BY destination, SUM(duration_days) in SQL. It probes basic loop accumulation with dict operations.


Break down the requirements

Step 1: Iterate through trip records

Each trip dict has destination and duration_days keys.

Step 2: Accumulate duration by destination

Use a result dict, adding each trip's duration to its destination's running total.


The solution

Single-pass dict accumulation
def group_by_destination(trips: list) -> dict:
    totals = {}
    for trip in trips:
        dest = trip["destination"]
        days = trip["duration_days"]
        totals[dest] = totals.get(dest, 0) + days
    return totals

Common follow-up questions