Sushi Belt Without Repeats

Mediumsliding windowAlso known as Longest Substring Without Repeating Characters

At a conveyor-belt sushi bar, plates roll past in a fixed line. Each plate has a one-character dish code (s for salmon, t for tuna, and so on), so the evening's line is a string like "stseat".

A food blogger wants to grab one unbroken run of plates without taking the same dish twice. How long is the longest run with no repeated code?

Your task

Write longestFreshRun(plates). Return the length of the longest stretch of consecutive characters in plates in which no character appears more than once.

Codes are case-sensitive: A and a are different dishes. An empty belt gives 0.

longestFreshRun(plates: string) → int

Examples

Example 1
Input
plates = "stseat"
Output
4
Why

The run seat (positions 2 to 5) has four different dishes. Any run of five plates contains a repeat: tseat has two t's, stsea has two s's.

Example 2
Input
plates = "tutor"
Output
4
Why

The best run is utor, length 4. If you restarted from scratch at every repeat you would miss it: on the second t you would start over at that t and lose the u before it.

Constraints

  • 0 ≤ plates.length ≤ 10,000
  • plates contains letters (a-z, A-Z) and digits only.
Start with brute force

From every starting plate, extend the run right with a set of dishes until a repeat appears. Keep the longest.

With only 62 possible codes, each start scans at most 63 plates: about 630,000 steps for 10,000 plates. That is fast only because the alphabet is small; the cost is O(n × k) for k possible codes, heading toward O(n²) with any Unicode character. And the run from i + 1 rescans almost the same plates as the run from i.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code