00:00

Problem Statement

Input/Output Examples

Visual Explanation

Storing the last index of every character lets the left edge jump directly past a repeat, instead of moving one step at a time. Each character is therefore visited by the right edge once.

Approaches

Both approaches keep a window of distinct characters. The first jumps the left edge; the second slides it one step at a time.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string and k the number of distinct characters. Both pointers only move forward, so the total work is linear.

Interview Tips and Recommended Approach

  • Guard against old indexes. Without last[c] ≥ left, the left edge could move backwards, as in "abba".
  • Explain why it is linear. The left pointer never moves back, so each character is added and removed at most once.
  • Return the substring if asked. Remember the window start whenever the best length improves.
  • Use an array for ASCII. It is faster than a HashMap, which is needed only for larger alphabets.

Recommended Approach: Sliding Window With Last Index

Why: it moves the left edge directly to the right place, giving a single linear pass with a fixed-size array.