Longest stretch with no repeat
A token generator checks its output for the longest run of characters in which nothing appears twice.
- The run has to be a single unbroken stretch, not a selection.
- Every character counts, including spaces and punctuation.
- Empty text has a longest run of zero.
longestUniqueRun(text: string) → int
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int longestUniqueRun(String text) {
}
Worked examples
| Call | Result |
|---|---|
longestUniqueRun("abcabcbb") | 3 |
longestUniqueRun("bbbbb") | 1 |
longestUniqueRun("pwwkew") | 3 |
longestUniqueRun("abcdef") | 6 |
Hint
Slide a window. When a repeat comes in, pull the left edge past where that character was last seen — never backwards.
Reference solution in Java
int longestUniqueRun(String text) {
Map<Character, Integer> lastAt = new HashMap<>();
int best = 0, start = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
Integer seen = lastAt.get(c);
if (seen != null && seen >= start) start = seen + 1;
lastAt.put(c, i);
best = Math.max(best, i - start + 1);
}
return best;
}