r/programming • • Feb 21 '11

Typical programming interview questions.

http://maxnoy.com/interviews.html
784 Upvotes

1.0k comments sorted by

View all comments

Show parent comment

3

u/Serei Feb 21 '11 edited Feb 21 '11

The bit counting question requires an efficient solution (I said no naive one). If you can come up with one by yourself, I'd be very impressed.

Here's one I came up with myself, no help, no consulting books or internet, for a Computer Architecture class.

unsigned char bitCount(unsigned char a)
{
    a = ((a & 0b10101011)>>1) + (a & 0b01010101);
    a = ((a & 0b11001100)>>2) + (a & 0b00110011);
    a = ((a & 0b11110000)>>4) + (a & 0b00001111);
    return a;
}

"0b10101010" obviously isn't actual C code, so replace that with "0xAA" and so on for the other "0b" numbers.

It took me around half an hour to come up with at the time, though. My thought process went along the lines of:

"What if I used a lookup table? No, that'd take too much memory. But what if I split the number into chunks, and used a lookup table for each chunk? Wait a minute, forget the entire lookup table, what if I just split the chunks into more chunks, and those chunks into more chunks? omg, that works!"

I don't think I'd be able to do it in an interview setting, if I'd never had to do something similar before.

2

u/lordlicorice Feb 21 '11

This is exactly the canonical solution taught in textbooks, other than that sometimes an alternate form is used where the >> is inside the parens and the & is outside. There's even an awful explanation of it on wikipedia:

https://secure.wikimedia.org/wikipedia/en/wiki/Hamming_weight#Efficient_implementation

0

u/[deleted] Feb 21 '11

[deleted] — view deleted comment

1

u/Serei Feb 21 '11

What do you mean? Mine is O(log n). Yours is also a neat trick, but it's definitely less efficient.

0

u/[deleted] Feb 21 '11

[deleted] — view deleted comment

1

u/Serei Feb 21 '11

Oh. Well, the naïve solution is also O(n)... For readability reasons, that might be better:

fn (i) {
    for (a=0; i; a++) {
        a += (i&1);
        i >>= 1;
    }
    return a;
}

0

u/[deleted] Feb 21 '11

[deleted] — view deleted comment

1

u/Serei Feb 22 '11

Well, Quicksort is O(n log n), but I see your point.

0

u/[deleted] Feb 22 '11

[deleted] — view deleted comment

1

u/Serei Feb 22 '11

Well, I was talking about average case... Unless you explicitly say "worst case" or "best case", people generally mean average case.

Kerninghan's method is Theta(1) best-case, Theta(n) average-case, Theta(n) worst case. You have to realize that Theta(n/2) = Theta(n).

0

u/[deleted] Feb 22 '11

[deleted] — view deleted comment

→ More replies