Collapse Consecutive Duplicates
Python data engineering interview problem. Difficulty: beginner. Pattern: Arrays. About 10 minutes. Free to practice.
Collapse runs of equal adjacent values into one. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Sensor data and logs often repeat the same value many times in a row, for example a sensor that reports 'OK' every second. To make the data smaller you can keep only one value from each run of repeats. Write a function collapse_duplicates(nums) that takes a list and returns a new list in which each run of equal neighbours is replaced by a single value. Only values that are next to each other are collapsed. The same value can still appear again later, after a different one. For [1, 1, 2, 2, 2, 3] the answer is [1, 2, 3]. Keep the print lines in the editor.
Requirements
- Return a list where no two neighbouring values are equal.
- Keep the first value of every run of equal values.
- Do not remove duplicates that are separated by a different value.
- Keep the original order.
Constraints
- Only adjacent equal values are merged. For example [1, 2, 1] stays [1, 2, 1].
- An empty list must give back an empty list.
Examples
Input: collapse_duplicates([1, 1, 2, 2, 2, 3]) Output: [1, 2, 3] Adjacent equals collapse.
Topics: lakebench, python, dedupe, run-length.
More Python interview questions · All interview problems · Learn data engineering
Collapse Consecutive Duplicates
Interview-style drill: Collapse runs of equal adjacent values into one.
Implement `collapse_duplicates(nums: list) -> list` keeping the first of each consecutive equal run. Example: `[1, 1, 2, 2, 2, 3]` → `[1, 2, 3]`. Keep the harness.