Skip to content

Instantly share code, notes, and snippets.

@riddhi89
Last active October 8, 2020 05:47
Show Gist options
  • Save riddhi89/a16d66a4c4f747097a9299b612fc8d0c to your computer and use it in GitHub Desktop.
Save riddhi89/a16d66a4c4f747097a9299b612fc8d0c to your computer and use it in GitHub Desktop.
def missing_numbers(numbers: list) -> str:
"""
Returns a comma-separated number/range of numbers which are missing in the specified list
# O(n) solution; n - size of the input list of numbers
"""
i = 0
lnumbers = len(numbers)
result = ''
while(i < lnumbers - 1):
if numbers[i] + 1 != numbers[i+1]:
start = str(numbers[i] + 1)
end = str(numbers[i+1] - 1)
if start == end:
# single missing number
end = ''
result += start
if end:
# end of a range of missing numbers
result += '-' + end
result += ','
i += 1
return result.rstrip(',')
assert missing_numbers([1, 2, 4, 5, 49]) == '3,6-48'
assert missing_numbers([1, 2, 3, 4]) == ''
assert missing_numbers([10, 20, 30, 40]) == '11-19,21-29,31-39'
assert missing_numbers([5, 10, 11]) == '6-9'
assert missing_numbers([5]) == ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment