Consecutive numbers
Write a function that determines whether a sequence of integers can be rearranged into a sequence of consecutive numbers without duplicates. The function should return the sequence of consecutive numbers or nil
if it is not possible.
Examples
(consec []) ;=> () ;; trivially true
(consec [1]) ;=> (1) ;; ditto
(consec [3 1 2]) ;=> (1 2 3)
(consec [5 3 2 1]) ;=> nil ;; non-consecutive (4 is missing)
(consec [7 8 9 7]) ;=> nil ;; 7 repeats
Thanks to this site for the problem idea, where it is rated Hard in Java. The problem has been modified.
Please submit your solutions as comments on this gist.
To subscribe: https://purelyfunctional.tv/newsletter/
I tried to implement a solution that (i) doesn't need sorting and (ii) doesn't need an intermediate data structure for bookkeeping. I came up with this solution that checks the sum of squares to see if the numbers are consecutive. It works for inputs such as
[1 3 3 3 5]
but I don't know how to mathematically prove that it works for all inputs: