The problem:
You are given all numbers between 1,2,…,n except one. Your task is to find the missing number. The first input line contains an integer n. The second line contains n−1 numbers. Each number is distinct and between 1 and n (inclusive). Print the missing number. Constraints 2≤n≤2⋅105 Example Input: 5 2 3 1 5 Output: 4
This is the code that I've tried:
n=int(input())
arr = list(map(int,input().strip().split()))[:n-1]
arr.sort(reverse=True)
for i in range(n-1):
if(arr[i]-arr[i+1]>1):
print(arr[i]-1)
break
I've also tried this:
n=int(input())
arr = list(map(int,input().strip().split()))[:n-1]
arr.sort(reverse=True)
for i in range(n-1):
if n-1==1 and arr[0]==1:
print(2)
break
elif n-1==1 and arr[0]==2:
print(1)
break
elif i==n-1:
print(arr[i]-1)
break
elif arr[i]-arr[i+1]>1:
print(arr[i]-1)
break
I'm getting a Runtime error in a few test cases:
Error:
Traceback (most recent call last):
File "input/code.py", line 14, in <module>
elif arr[i]-arr[i+1]>1:
IndexError: list index out of range
How can I fix this?