Collapse Consecutive Duplicates

Medium ⏱ 12 min 61% acceptance ★★★★★ 4.6
Write collapse_consecutive(items) that returns a new list where every run of consecutive equal values is collapsed to a single value (unlike full dedup, non-adjacent repeats are kept separately).

Examples

Example 1
Input
items = [1, 1, 2, 2, 2, 1, 3, 3]
Output
[1, 2, 1, 3]
Explanation

Each run of identical neighbors collapses to one; the 1 reappears after the 2s since it is a new run.

Constraints

  • 0 <= len(items) <= 10^5

Topics

ListsDeduplication

Companies

AmazonFlipkart

Hints

Hint 1

Walk through the list and only append a value if it differs from the last value appended.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.