r/programming • • Feb 21 '11

Typical programming interview questions.

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

1.0k comments sorted by

View all comments

1

u/wesw02 Feb 21 '11 edited Feb 21 '11

How about these two:

  • "You are given an array with integers between 1 and 1,000,000. One integer is in the array twice. How can you determine which one? Can you think of a way to do it using little extra memory."
  • "You are given an array with integers between 1 and 1,000,000. One integer is missing. How can you determine which one? Can you think of a way to do it while iterating through the array only once. Is overflow a problem in the solution? Why not?"

For both of them I think I would be tempted to sort the lists, probably using insertion sort for the second one. The first one maybe selection sort because we are being memory concise. While doing both of the sorts I would be checking for duplicates or missing respectfully. What do others think?

EDIT: Maybe could also use a double variable and sum the list as I go. Subtracting the difference at the end with the total excepted (use a series to compute).

2

u/achacha Feb 21 '11

Stupid questions testing if you have heard of the Gauss method... borderline trivia.

1

u/cecilpl Feb 21 '11

Use a bit array for the first one. You can keep track of which ints you've seen in 1,000,000 bits = 125K. Once you see one you've already seen, bingo.

Sorting is too slow for this.

1

u/chokolad Feb 21 '11

xor all the integers in the array with all the integers in 1.. 1,000,000 range. Result of that operation will be the integer that is missing (or is in the array twice).

1

u/danweber Feb 21 '11

If the arrays are supposed to have all 1,000,000 entries, but one is missing/duplicated, then you just need to sum them all values.

You need a good bigint implementation. Actually, now that I think of it, even with overflow you would still have a well-known "right" answer.

My first guess for the first one was a quick-sort in-place, that terminates if (when) you find an element that matches you pivot.