# The Trip Grouper

> Where did everyone go, and for how long?

Canonical URL: <https://datadriven.io/problems/the_trip_grouper>

Domain: Python · Difficulty: easy · Seniority: L4

## 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.

## 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**

```python
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
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the number of trips.
> 
> **Space:** O(d) where d is the number of unique destinations.

> **Interviewers Watch For**
>
> Using `.get(dest, 0)` for safe initialization. Candidates who use `if dest not in totals` for every entry write more verbose but equivalent code.

> **Common Pitfall**
>
> Overwriting instead of accumulating: `totals[dest] = days` instead of `totals[dest] = totals.get(dest, 0) + days`. This keeps only the last trip's duration.

---

## Common follow-up questions

- What if you also needed the count of trips per destination? _(Tests maintaining a second accumulator or a compound value.)_
- How would you sort the result by total duration descending? _(Tests `sorted(totals.items(), key=lambda x: x[1], reverse=True)`.)_
- What if the trip dicts had inconsistent key names? _(Tests defensive access with `.get()` and handling missing keys.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_trip_grouper)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.