Skip to main content

Finding Duplicate Elements in an Array :: Phil! Gregory

Popularity Report

Total Popularity Score: 0

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Rank

URL Tag Cloud

Bookmark History

Saved by 1 people (0 private), first by anonymouse user on 2007-09-03


Public Comment

on 2007-09-03 by taylortree

Interesting way to find duplicates in an array.  Enjoyed the links on the pigeonhold principle and Floyd's cycle-finding algorithm.

Public Sticky notes

Now, suppose that the array is of length n and only contains positive integers less than n. We can be sure (by the pigeonhole principle) that there is at least one duplicate.

Highlighted by taylortree

So, how do we find the beginning of the cycle? The easiest approach is to use Floyd's cycle-finding algorithm. It works roughly like this: Start at the beginning of the sequence. Keep track of two values (call them ai and aj). At each step of the algorithm, move ai one step along the sequence, but move aj two steps. Stop when ai = aj.

Highlighted by taylortree

Readers (1)