Skip to content
Algorithms for Beginners

Problems / Sliding window

Shortest to target

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.

rain lists how many millimetres of rain fell on each day. All the numbers are positive.

Find the shortest stretch of days in a row whose rain adds up to at least target. Return how many days it has, or 0 if no stretch is enough.

Examples

  1. Example 1

    Input
    rain = [1, 4, 2, 2, 5, 3], target = 8
    Output
    2

    5 + 3 = 8 takes 2 days. No single day has 8 mm.

  2. Example 2

    Input
    rain = [2, 6, 6], target = 6
    Output
    1

    A single day of 6 mm is enough.

  3. Example 3

    Input
    rain = [2, 2, 2], target = 7
    Output
    0

    All three days together only make 6 mm.

Rules

  • rain has between 0 and 100,000 numbers, each from 1 to 10,000.
  • target is between 1 and 1,000,000,000.
Words on this page, in plain English (1)Open if any word is new to you
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function shortestToTarget(rain, target) {
  // Return the fewest days, or 0.
}

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.

  • 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.

  • Longest unique stretch

    Medium. Find the longest stretch of text in which no character repeats.