Problem 242014 · medium · Level 02 Linear Data Structures

Squash Adjacent Repeats In Place

arrays · in-place · two pointers

Given a list nums, modify it in place so that every run of consecutive equal values is collapsed to a single value, and shorten the list accordingly. Return the new length. Equal values that are not adjacent are kept separate.

Tests call it as (squash_adjacent(a := [1, 1, 2, 2, 2, 1]), a) and check both the returned length and the list afterwards.

Examples

Input:  nums = [1, 1, 2, 2, 2, 1]
Output: 3, and nums becomes [1, 2, 1]

Input:  nums = [9, 9, 9, 9]
Output: 1, and nums becomes [9]

Constraints

  • 0 <= len(nums) <= 10**5
  • Must modify nums in place (its length must change) and return the new length.
  • Target: O(n) time and O(1) extra space; do not build a second list.

Goals

  • Compact a list in place with a read and a write pointer
  • Truncate the list to its new length
  • Return the new length as well as mutating the list
Starting Python…