Longest Subarray with Distinct Elements
HardPractice library · +30 XPhash mapsliding windowtwo pointers
Given an array of N integers, find the length of the longest contiguous subarray that contains only distinct elements.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers representing the array elements.
Output
Print a single integer, the length of the longest subarray with distinct elements.
Constraints
1 <= N <= 200000, 1 <= arr[i] <= 10^9
Time limit 2 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
5 1 2 3 2 1
Output
3
The longest subarray with distinct elements is [1, 2, 3], length 3.
Example 2
Input
7 1 1 1 1 1 1 1
Output
1
The longest subarray with distinct elements is [1], length 1.
Hints
Similar problems
- Count Subarrays with Distinct ElementsMedium
- Longest Subarray with At Most K Distinct ElementsMedium
- Minimum Window SubstringHard
- Longest Subarray with Equal Number of Zeroes and OnesHard
- Distinct Subarrays with Bounded SumHard
- Longest Subarray with At Most K Duplicate PairsMedium
More topics: Hash Map and Hashing problems, Two Pointers problems, Sliding Window problems
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 1 2 3 2 1
Example 2 input
7 1 1 1 1 1 1 1