ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Sliding Window: Find Longest Substring Without Repeating Characters

JavaScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function lengthOfLongestSubstring(s) {
2if (!s) return 0;
3
4let maxLength = 0;
5let start = 0;
6const charSet = new Set();
7
8for (let end = 0; end < s.length; end++) {
9while (charSet.has(s[end])) {
10charSet.delete(s[start]);
11start++;
12}
13charSet.add(s[end]);
14maxLength = Math.max(maxLength, end - start + 1);
15}
16
17return maxLength;
18}
Algorithm description viewbox

Sliding Window: Find Longest Substring Without Repeating Characters

Algorithm description:

This function finds the length of the longest substring within a given string that does not contain any repeating characters. It employs the sliding window technique, which is efficient for problems involving contiguous subarrays or substrings. This is a common problem in coding interviews and is applicable in text analysis and data processing scenarios.

Algorithm explanation:

The `lengthOfLongestSubstring` function uses a sliding window approach with two pointers, `start` and `end`, and a `Set` to store characters within the current window. It iterates through the string with the `end` pointer. If the character at `end` is already in the `charSet`, it means a repeating character is found. The `while` loop then shrinks the window from the `start` by removing characters from the `charSet` and incrementing `start` until the repeating character is no longer in the window. The current character `s[end]` is then added to the `charSet`, and `maxLength` is updated with the current window size (`end - start + 1`). The time complexity is O(n) because each character is added and removed from the set at most once. The space complexity is O(k), where k is the number of unique characters in the string (at most 26 for lowercase English letters, or 128 for ASCII).

Pseudocode:

function lengthOfLongestSubstring(string s):
  if s is empty:
    return 0

  maxLength = 0
  start = 0
  create a set called charSet

  for end from 0 to length of s - 1:
    while s[end] is in charSet:
      remove s[start] from charSet
      increment start
    add s[end] to charSet
    maxLength = max(maxLength, end - start + 1)

  return maxLength