Skip to content
Algorithms for Beginners

Problems / Two pointers

Squash repeats

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

nums is sorted from smallest to largest, and may contain repeats, like [1, 1, 2, 3, 3, 3].

Move one copy of each different value to the front of the list, in order, by overwriting items in nums itself. Then return the front part that holds them: for the example, [1, 2, 3].

Use only a few extra variables, not a second list or a Set. (Slicing the front off at the very end is fine.)

Examples

  1. Example 1

    Input
    nums = [1, 1, 2, 3, 3, 3]
    Output
    [1, 2, 3]
  2. Example 2

    Input
    nums = [-2, 0, 0, 0, 5]
    Output
    [-2, 0, 5]
  3. Example 3

    Input
    nums = [4, 4, 4]
    Output
    [4]

    Every item is the same, so only one is kept.

Rules

  • nums is sorted from smallest to largest and has between 0 and 100,000 numbers.
Words on this page, in plain English (3)Open if any word is new to you
Variable
A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Sorted
In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function squashRepeats(nums) {
  // Return the front of nums, holding one of each value.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in two pointers

  • Learn the two pointers pattern

    Walk through a list from both ends (or at two speeds) at once.

  • Biggest tank

    Medium. Choose two walls that, with the ground between them, hold the most water.

  • Three to zero

    Medium. Find every different set of three numbers in a list that adds up to zero.

  • Mirror phrase

    Easy. Check whether a phrase reads the same backwards, ignoring spaces, punctuation and capitals.

  • Flip in place

    Easy. Reverse a list by swapping items inside it, without building a new list.

  • Pair in a sorted list

    Easy. Find two prices that add up to a budget, when the prices are already sorted.