Funcia
Lv.1arraybit-manipulationmath

Missing Number

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Tickets numbered 0 to n (that is, n + 1 tickets) were handed out, and exactly one is missing. Given the n remaining distinct ticket numbers tickets in any order (n is the length of tickets), return the missing number.

Examples

ticketsresult
[3, 0, 1]2
[0, 1]2
[9, 6, 4, 2, 3, 5, 7, 0, 1]8

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(tickets: int[]) → int

Constraints

  • 1≤n=1 \le n = tickets.length ≤200,000\le 200{,}000
  • 0≤0 \le tickets[i] ≤n\le n, all values are distinct

Expected complexity

Time
O(N)
Space
O(1)

Examples

ticketsExpected
[3,0,1]2
[0,1]2
[9,6,4,2,3,5,7,0,1]8

Hint

Hint

The sum 0 + 1 + … + n is n(n+1)/2n(n+1)/2; subtract the sum of the tickets (use 64-bit integers). Alternatively XOR 0..n with all tickets: paired values cancel and the missing one remains. Searching the array for every number is O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251026 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.