LeetCode – Longest Substring Without Repeating Characters

This is a typical problem that can be solved using Sliding Window Algorithm. To keep track of unique characters in the current window, there are two options I can think of.

Use a hash set which contains the characters in the current window
Use a boolean array as map for the whole character set.
Note: This option works better if the character set is small.
For the algorithm,

  • Keep two indexes (left and right) as the left and right positions of the window
  • Iterate the characters in the string starting from the beginning.
  • If the character pointed by the right index is already in the map, increment the left index by 1 and remove the left character from the set.

Increment left index

Otherwise, it means that the character pointed by the right index is not in the map, move the window by incrementing the right index and add the right character to the set.

Increment right index

[pastacode lang=”java” message=”” highlight=”” provider=”manual”]

public static int lengthOfLongestSubstring(String str) {
      boolean[] checked = new boolean[256];
      int left = 0;
      int right = 0;
      int max = 0;

      while (right < str.length()) {
          char rightCh = str.charAt(right);
          char leftCh = str.charAt(left);
          if (checked[rightCh]) {
              checked[leftCh] = false;
              left++;
          } else {
              checked[rightCh] = true;
              right++;
          }
          max = Math.max(right - left, max);
      }

      return max;
  }

[/pastacode]

The time complexity is O(n).
The space complexity is O(C) where C is the number of characters in the character set.