Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 19

Remove Consecutive Duplicates

Medium

13 minute session

Summary

Return a new list with consecutive duplicate values collapsed to a single occurrence.

Problem statement

Given a list, produce a new list where runs of the same value that appear consecutively are collapsed into a single occurrence. Non-consecutive duplicates (the same value separated by different values) should be preserved. Implement remove_consecutive_duplicates(lst) that returns the cleaned list. The original list should not be modified.

Task

Learn to iterate through a sequence and build a result while comparing current and previous elements.

Examples

Simple example

Input

remove_consecutive_duplicates([1, 1, 2, 2, 1])

Output

[1, 2, 1]

Explanation

Consecutive runs of 1 and 2 are collapsed, but the later 1 is kept because it's not consecutive with the earlier 1.

Input format

A single argument: lst (a list of values).

Output format

A list with consecutive duplicates removed.

Constraints

You may assume the input is a list. Elements can be of any type that supports equality comparison. Aim for linear time O(n) and O(n) additional space for the output.

Samples

Sample input 0

remove_consecutive_duplicates(['a', 'a', 'b', 'a'])

Sample output 0

['a', 'b', 'a']

Explanation 0

Only consecutive 'a' at the start are collapsed; the later 'a' remains.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:46 AM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.