The Streak Breaker

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
L3
Asked in
Take-Two Interactive

Problem

You're compacting a run of sensor readings where each value repeats on the wire until it changes. Collapse every stretch of identical consecutive readings down to just the first reading of the stretch, and hand back the compacted result as a new list.

It has a problem with repetition.

Example 1

Input:

items = [1,1,2,3,3,3,2]

Output:

[1,2,3,2]

Example 2

Input:

items = ["a","a","b","a"]

Output:

["a","b","a"]

Worked solution and explanation

What this really is

Strip the sensor-stream costume and this is run-length dedup, and the whole problem lives in one distinction the interviewer is quietly checking: do you collapse consecutive repeats, or do you collapse ALL repeats? Anyone can dedup a list. The tell is whether you reach for a global seen set (wrong) or compare each element only to the last one you kept (right). Get it wrong and the trailing 2 in [1, 1, 2, 3, 3, 3, 2] vanishes, because your set already saw a 2, and you've silently changed what the stream said.


Break down the requirements

Step 1: Track the last kept element

Compare each element to the last one you actually kept, not to some set of everything seen so far. Append only when it differs from that neighbor. This is the single decision that separates run-length dedup from global dedup.

Step 2: Seed with the first element

The first element is always included since there is no previous kept element to compare against. That means you must special-case an empty input up front, or the first-element peek throws.


The solution

Single-pass consecutive comparison
def remove_consecutive_dupes(items: list) -> list:
    if not items:
        return []
    result = [items[0]]
    for i in range(1, len(items)):
        if items[i] != result[-1]:
            result.append(items[i])
    return result
Global set (wrong)
Keep a seen set; skip anything already in it. On [1, 1, 2, 3, 3, 3, 2] this returns [1, 2, 3] and eats the final 2.
Neighbor compare (right)
Compare to the last kept value only. On the same input it returns [1, 2, 3, 2], preserving the 2 that reappears after the 3s.

Common follow-up questions