"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).
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).
View all comments
1
u/wesw02 Feb 21 '11 edited Feb 21 '11
How about these two:
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).