CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2003
    Location
    NY
    Posts
    12

    Finding duplicates in an array

    Hi I am trying to solve this puzzle:
    Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?


    Its easy to solve it using secondary array of 100 integers however I am looking for a way to do it without using aux array.

    Any ideas?
    Thanks.
    RS

  2. #2
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    I'm not saying that it's not possible, but I cannot think of any way
    to access the elements only once and not use auxiliary storage
    while still retaining the amount of times each number has been
    accessed. Of course, I'm not trying to imply that it is possible
    either I just can't see any way that it can be done and I hope
    to also be enlightened.

    --Paul

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    just add up the numbers ...

    and subtract 500500 (which is 1000*1001/2)

    The difference is the duplicate element.


    The sum of 1 + 2 + ... + n = n*(n+1)/2

  4. #4
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    Dang! Each number appears only once in the array! How could
    I miss that?

  5. #5
    Join Date
    Mar 2003
    Location
    NY
    Posts
    12

    Thanks

    Hi Philip,
    Thanks again for the solution.
    RS

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured