Skip to content
Algorithms for Beginners

Problems / Sliding window

Two kinds

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.

A row of trees grows fruit, and fruit[i] is the kind of fruit on tree i. You have two baskets, and each basket can only hold one kind of fruit.

Starting at any tree, you walk to the right, picking one fruit from every tree, until you reach a tree whose kind fits in neither basket. Return the most fruit you can pick.

In other words: return the length of the longest stretch of fruit with at most two different values.

Examples

  1. Example 1

    Input
    fruit = [4, 9, 4]
    Output
    3

    All three trees have only two kinds between them.

  2. Example 2

    Input
    fruit = [5, 6, 7, 7]
    Output
    3

    Start at tree 1: kinds 6, 7, 7.

  3. Example 3

    Input
    fruit = [8, 6, 8, 9, 9, 9]
    Output
    4

    Start at tree 2: 8, 9, 9, 9.

Rules

  • fruit has between 0 and 100,000 whole numbers.
Words on this page, in plain English (1)Open if any word is new to you
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 twoKinds(fruit) {
  // Return the longest stretch with at most two kinds.
}

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