Skip to content
Algorithms for Beginners

Problems / Sliding window

Longest unique stretch

medium

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

Given text, find the longest stretch of characters next to each other in which no character appears twice. Return its length.

For example, in banana the longest such stretch is ban, so the answer is 3.

Examples

  1. Example 1

    Input
    text = "banana"
    Output
    3

    "ban" has no repeats. Any longer stretch, like "bana", repeats a letter.

  2. Example 2

    Input
    text = "zzzz"
    Output
    1

    Every stretch longer than one repeats z.

  3. Example 3

    Input
    text = "abcdeafg"
    Output
    7

    "bcdeafg" has no repeats. The whole word doesn't count: it has two a's.

Rules

  • text has between 0 and 100,000 characters: letters, digits, spaces and symbols.
  • Capital and small letters are different characters.
Words on this page, in plain English (2)Open if any word is new to you
String
A piece of text, written between quotes. Each letter in it is a character.
Length
How many items a list (or letters a string) has. The last position is always length - 1.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function longestUniqueStretch(text) {
  // Return the length of the longest stretch with no repeats.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in sliding window

  • Learn the sliding window pattern

    Keep a stretch of the list and slide it along instead of starting over.

  • Shortest to target

    Medium. Find the fewest days in a row whose rainfall adds up to at least a target.

  • Repaint the fence

    Medium. Repaint at most k fence boards to make the longest possible stretch of one colour.

  • Hidden shuffle

    Medium. Check whether some rearrangement of a short word appears inside a longer text.

  • Two kinds

    Medium. Find the longest stretch of a list that contains at most two different values.

  • Best streak

    Easy. Find the highest total of any k days in a row.