Lv.2arrayhashsliding-windowtwo-pointers
Longest Subarray Without Repeats
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums, return the length of the longest contiguous subarray in which no value appears twice.
Examples
| nums | result |
|---|---|
[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
-
nums.length -
nums[i]
Expected complexity
- Time
- O(N)
- Space
- O(N)
Examples
| nums | Expected |
|---|---|
[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 . Restarting a set from every
start is when most values are distinct.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1234 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 4 | verdict only |