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 code for its dish: s for salmon, t for tuna, e for eel and so on. The whole line for the evening is written as a string, like "stseat".

A food blogger wants to grab one unbroken run of plates as they pass, without ever taking the same dish twice. She wants to taste as many plates as possible this way. How long is the longest run of plates 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

For every starting plate, extend the run to the right, keeping a set of dishes, until a repeat appears. Record the longest run found.

Here there are only 62 possible codes, so no run is longer than 62 and each start scans at most 63 plates: about 630,000 steps for 10,000 plates. That is fast enough, but only because the alphabet is small. The cost is O(n × k) for k possible codes, so with any Unicode character allowed it grows toward O(n²). And most of the work is repeated: when the run from start i hits a repeat, the run from i + 1 rescans almost the same plates.

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