Squash Repeated Readings

Easy · Two Pointers · about 15 min

A meter logs readings that are already sorted from smallest to largest, but it often logs the same value many times in a row.

Change the list readings in place so that each value appears only once, in the same sorted order, and the list is shortened to hold just those values. Return the new length.

  • Work inside the list you were given: do not build a second list. The tests check the original list afterwards.
  • Values can be negative. The list can be empty.

Example:

squash_repeats([0, 0, 1, 1, 1, 2, 3, 3]) → 4, and the list is now [0, 1, 2, 3]

Hints

  • In a sorted list, copies of the same value are neighbours.
  • Keep one index for where the next new value should be written, and another that reads every item.
  • When the read item differs from the last written one, write it and move the write index. Finally cut off everything after the write index.

Learn the pattern first: the Two Pointers lesson.

More Two Pointers problems