Funcia
Lv.2arrayhashsliding-windowtwo-pointers

Longest Subarray Without Repeats

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

Given an integer array nums, return the length of the longest contiguous subarray in which no value appears twice.

Examples

numsresult
[1, 2, 1, 3, 4, 3]4
[5, 5, 5]1
[7, 3, 9, 1]4

Example 1 — [2, 1, 3, 4]; extending it in either direction repeats 1 or 3.

Example 2 — Every value is the same, so only single elements qualify.

Example 3 — All values are distinct.

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≤N=1 \le N = 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
[1,2,1,3,4,3]4
[5,5,5]1
[7,3,9,1]4

Hint

Hint

Slide a window: move the right end r forward and never move the left end l backwards. Remember the last index of each value in a hash map; when nums[r] was last seen at last ≥ l, jump l to last + 1. That is O(N)O(N). Restarting a set from every start is O(N2)O(N^2) when most values are distinct.

Time limits per language

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

Test groups

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

No result yet. Run or submit your code.