Funcia
Lv.2arrayhashsorting

Longest Consecutive Run

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

Return the length of the longest run of consecutive integers (x, x+1, …) whose values all appear in nums (order and duplicates do not matter).

Examples

numsresult
[100, 4, 200, 1, 3, 2]4
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1]9
[5, 5, 5]1

Efficiency

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

Function signature

solution(nums: int[]) → int

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000, −109≤-10^9 \le nums[i] ≤109\le 10^9

Expected complexity

Time
O(N)
Space
O(N)

Examples

numsExpected
[100,4,200,1,3,2]4
[0,3,7,2,5,8,4,6,0,1]9
[5,5,5]1

Hint

Hint

Sort and scan, or put everything in a hash set and only start counting at values x where x - 1 is absent. Checking membership by scanning the array is O(N2)O(N^2).

Time limits per language

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

Test groups

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

No result yet. Run or submit your code.