News:

How did you even find this place?

Main Menu

Mild Nerdsnipe

Started by Sidoh, July 06, 2008, 01:01:45 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Sidoh

A friend at work got me with this one, but luckily I forgot about it because I got distracted with work.  When he asked me about it the next morning, I thought about it for a few minutes and had an answer. :)

You're given a list of arbitrary length where each element in the list is repeated exactly once except for one value in an arbitrary location.  Your task is to find the value.  You're allowed to pass over the list exactly once and use O(1) (constant, i.e. the amount of space you're using doesn't depend on the size of the list) extra space.

Camel

#1
EZ-cakes.

int findDuplicate(int array[]) {
    int[] heap = new int[2^sizeof(int)]; // assume heap is all zeroes
    for(int value : array) {
        if(heap[value]++ > 0)
            return value;
    }
    throw exception;
}


edit: code tag

<Camel> i said what what
<Blaze> in the butt
<Camel> you want to do it in my butt?
<Blaze> in my butt
<Camel> let's do it in the butt
<Blaze> Okay!

Camel

It just occurred to me that I misread the question.

No matter; simply iterate over the heap and look for a value of 1.

<Camel> i said what what
<Blaze> in the butt
<Camel> you want to do it in my butt?
<Blaze> in my butt
<Camel> let's do it in the butt
<Blaze> Okay!

Sidoh

#3
Yuck. :P

No, the answer isn't gross.  There's a pseudo-clever solution.

Also notice that the data in the list aren't necessarily of type int.  You don't have the upper bound you've inferred.

Camel

That code works with any fixed-width type, and meets all of the criteria you gave.

However, it did just occur to me that there's a way to eliminate the heap due to the contraint that the non-singletons appear an even number of times. This forum should definitely have spoiler tags!

[spoiler]int findSingleton(int array[]) {
    int result = 0;
    for(int value : array)
        result ^= value;
    return result;
}
[/spoiler]

<Camel> i said what what
<Blaze> in the butt
<Camel> you want to do it in my butt?
<Blaze> in my butt
<Camel> let's do it in the butt
<Blaze> Okay!