BackmediumSliding WindowTCS

Longest Unique Segment Solution

Problem Statement

Given an array of integers packetTypes, find the length of the longest continuous segment with no repeating elements.

Example 1
Input
[1, 2, 3, 1, 2, 3, 4]
Output
4

Explanation: Step-by-step: with input [1, 2, 3, 1, 2, 3, 4], we find the longest continuous segment with no repeating elements. The longest segment is [1, 2, 3, 4] which has a length of 4.

Example 2
Input
[1, 1, 1, 1, 1]
Output
1

Explanation: Step-by-step: with input [1, 1, 1, 1, 1], we find the longest continuous segment with no repeating elements. The longest segment is [1] which has a length of 1.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Longest Unique Segment — Problem Statement & Solution Guide

Sliding WindowMediumSliding Window / Hash Set
TimeO(n)
|
SpaceO(n)

Problem Description

Given an array of integers packetTypes, find the length of the longest continuous segment with no repeating elements.

Examples

Example 1

Input

[1, 2, 3, 1, 2, 3, 4]

Output

4

Explanation: Step-by-step: with input [1, 2, 3, 1, 2, 3, 4], we find the longest continuous segment with no repeating elements. The longest segment is [1, 2, 3, 4] which has a length of 4.

Example 2

Input

[1, 1, 1, 1, 1]

Output

1

Explanation: Step-by-step: with input [1, 1, 1, 1, 1], we find the longest continuous segment with no repeating elements. The longest segment is [1] which has a length of 1.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces.

Optimal Approach & Strategy

Sliding window with left and right pointers. Add s[right] to set. If it exists in set, remove s[left] from set and increment left until the duplicate is gone. Update maxLength. Time O(N), Space O(min(N, charset)).

Brute Force Approach

Check all substrings for uniqueness. Time O(N^3).

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(packetTypes) { 
       let maxLength = 0; 
       let left = 0; 
       let uniqueElements = new Set(); 
       for (let right = 0; right < packetTypes.length; right++) { 
           while (uniqueElements.has(packetTypes[right])) { 
               uniqueElements.delete(packetTypes[left]); 
               left++; 
           } 
           uniqueElements.add(packetTypes[right]); 
           maxLength = Math.max(maxLength, right - left + 1); 
       } 
       return maxLength; 
   }

Asked in Top Tech Interviews

TCS

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.