Arrays and strings · Exercise 7 of 100

Removing Duplicates

To keep only the first copy of each value, scan from left to right and track the values you have seen. Add a value to the output only on its first visit so the surviving values keep their original order.

Try it yourself

Parcel labels arrive in the order [oak, ash, oak, elm, ash, fir]. If you keep only the first copy of each label, which label comes third?

One-step hint

Start a new row for labels you keep. Read the arrivals left to right and add a label only if that row lacks it.

Worked solution
  1. Keep oak and ash, then skip the next oak because you already kept it.
  2. The next label, elm, is new, so it takes the third spot. Later labels cannot change that spot.
DSA compiler