Codility - PermMissingElem

https://codility.com/programmers/task/perm_missing_elem

My solution

def solution(a)
  return 1 if a.empty?

  # edge case, N + 1 is missing
  # but unlike the case below, we can immediately compute and return this
  if a.length == 1
    return 2 if a[0] == 1
    return 1 if a[0] == 2
  end

  sorted = a.sort
  sorted.each_index do |index|
    return index + 1 if(sorted[index] != index + 1)
  end

  # edge case, N + 1 is missing
  return a.length + 1
end

Learning points

Comments

comments powered by Disqus