Finding the smallest integer that is not the sum of a sorted array

I just got back from an exam that had a question that I just don't know how to approach it:

Given a sorted array (each element in the array is greater than or equal to the previous one) arr of a positive integer, find the smallest positive integer that is not the sum of the elements of array arr , where each element of the array can appear only once in total.

So, for example, given the array {1, 2, 4, 6},

  • 1 is not the answer as it is the sum of 1.
  • 2 does not work for the same reason.
  • 3 is not present, since 3 = 1 + 2

  • ...

  • 13 is not present, since 13 = 1 + 2 + 4 + 6
  • 14 is the answer as it is not the sum of the elements in the array (where each element appears once).

Therefore, the result will be 14.

The algorithm should be as efficient as possible. I wrote two very inefficient algorithms, one of which iterates over each number from 1 to and checks with recursion if it is a sum; and another algorithm that documents all the possible sums of an array in a very large array and each time checking if there are two consecutive sums whose difference is greater than one (therefore it returns the smallest integer that lies between these sums).

ps - we have to write in Java, but if you have a solution in another language like C or Python, use whatever language you feel comfortable with.

+3


source to share





All Articles