Skip to main content

LeetCode 3: Longest Substring Without Repeating Characters

· One min read
Apache Wangye
Software developer and technical writer

Use a sliding window whose left boundary always remains after the previous occurrence of the current character.

import java.util.HashMap;
import java.util.Map;

class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastIndex = new HashMap<>();
int left = 0;
int best = 0;

for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
Integer previous = lastIndex.get(ch);
if (previous != null && previous >= left) {
left = previous + 1;
}
lastIndex.put(ch, right);
best = Math.max(best, right - left + 1);
}

return best;
}
}

For abcabcbb, the longest valid window has length three. Updating left with max-equivalent logic prevents the window from moving backward.

Time complexity is O(n) and extra space is O(k), where k is the number of distinct characters tracked. For full Unicode code points rather than UTF-16 code units, iterate with codePoints() or explicit code-point indexes.

Page views: --

Total views -- · Visitors --