Runtime error in CSES problem set Missing Number

Viewed 273

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?

1 Answers

You might want to try:

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-2:
    print(arr[0]+1)
    break
  elif arr[i]-arr[i+1]>1:
    print(arr[i]-1)
    break

This will remove your error list index out of range. Also, a faster way to approach this problem can be:

n = int(input())
print(n * (n + 1) // 2 - sum(map(int, input().split())))
Related