DSA Factory
Free lessonsArrays · Stage 2 · Traversal with state · Step 4

Compare with the previous box

Find the longest run of equal values. About 9 minutes.

Compare with the box before

A fitness app shows your longest streak of days in a row with a workout. To know whether today continues the streak, it looks at yesterday.

Questions about neighbours work the same way: at each box, compare it with the box just before it. Start the loop at the second box, because the first box has nothing before it to compare with.

Look one box back: start from the second box.
Runs of equal values
5
0
5
1
1
2
1
3
1
4
7
5
i

run = 1, best = 1.

Move 1 of 6

The streak grows or starts over

Keep the length of the current streak. If this box equals the one before, the streak grows by 1. If it's different, a new streak starts, of length 1.

The current streak can drop back to 1 at any moment, so keep a second variable for the longest streak you've ever seen. For 5, 5, 1, 1, 1, 7 that's 3, the three 1s.

Same as before: the streak grows by 1.
Different: a new streak of 1 starts.
In code
if not nums:
    return 0
run = best = 1
for i in range(1, len(nums)):
    if nums[i] == nums[i - 1]:
        run += 1
    else:
        run = 1
    best = max(best, run)
return best
Quick check

What's the longest run of equal values next to each other?

nums = [2, 2, 3, 2, 2, 2]
  1. A5
  2. B3
  3. C2
Show the answer

3. The last three 2s sit next to each other. That's the longest run.

Your problem

Longest run

Return the length of the longest stretch of equal values next to each other. An empty list has no runs, so return 0.

Example
nums = [5, 5, 1, 1, 1, 7] → 3

0 ≤ n ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding