## Minimum Impossible Sum

### April 24, 2015

We have today another from our inexhaustible list of interview questions:

Given a list of positive integers, find the smallest number that cannot be calculated as the sum of the integers in the list. For instance, given the integers 4, 13, 2, 3 and 1, the smallest number that cannot be calculated as the sum of the integers in the list is 11.

Your task is to write a program that solves the interview question. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

Wow, I was *sure* this would require an O(2^n) solution, but the O(n) solution (assuming sorted input) is so elegant.

In Python.

Finding minimum is easy with sort and a loop of max n iterations.

Added couple of methods to find them all (within a given range)

For [4, 13, 2, 3, 1] it finds

1 True True

2 True True

3 True True

4 True True

5 True True

6 True True

7 True True

8 True True

9 True True

10 True True

11 False False

12 False False

13 True True

14 True True

15 True True

16 True True

17 True True

18 True True

19 True True

20 True True

21 True True

22 True True

23 True True

@mvaneerde: As an exercise, why don’t you write the O(2**n) solution and show it to us. Or if not that, an O(n**2) solution. Or some other time complexity. It is often instructive to be able to compare such solutions.

I’m not sure if this is O(2^n) or if it’s worse than that. Very roughly, it computes the powerbag of 2^n elements up to 2^n times; the append and map in P may or may not affect the complexity class. What next? Ordering the powerbag by the sum in order to walk it only once?

(define (conser a) (lambda (d) (cons a d)))

(define (P B)

(if (null? B) '(())

(let ((S (P (cdr B))))

(append S (map (conser (car B)) S)))))

(define (min-non-sum B)

(let s ((PB (P B)) (m 0))

(if (null? PB) m

(if (= (apply + (car PB)) m)

(s (P B) (+ m 1))

(s (cdr PB) m)))))

`; (length (P '(3 1 4 1))) => 16`

; (min-non-sum '(3 1 4 1)) => 10

; (min-non-sum '(4 13 2 3 1)) => 11

; (min-non-sum '()) => 1

; (min-non-sum '(1)) => 2

;-)

A Haskell solution. The more efficient version is basically the same as Paul’s Python function.

A sample run, printing the output of both functions.