alternating numbers
array analysis
algorithm
counting technique
data structures

Counting alternating numbers in an array

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

"Alternating" in an array usually means the comparison direction flips at each step, such as up, down, up, down or down, up, down, up. The important part is to define exactly what you want to count, because counting alternating pairs, alternating subarrays, and the longest alternating run are related but different problems.

Define Alternation Clearly

For a sequence a[i], an alternating contiguous segment is typically one where consecutive comparisons change sign:

  • 'a[i] < a[i+1] > a[i+2] < a[i+3]'
  • or a[i] > a[i+1] < a[i+2] > a[i+3]

Equal adjacent values usually break alternation because the direction is neither positive nor negative.

For example, in:

text
[1, 3, 2, 5, 4]

the comparisons are:

text
up, down, up, down

so the whole array is alternating.

Counting Alternating Subarrays in Linear Time

A useful interpretation is: count how many contiguous subarrays of length at least two are alternating.

The key observation is that if the current element extends an alternating run, then every alternating subarray ending at that position can be counted from the previous run length.

python
1def count_alternating_subarrays(values):
2    if len(values) < 2:
3        return 0
4
5    total = 0
6    current_len = 1
7
8    for i in range(1, len(values)):
9        if i == 1:
10            if values[i] != values[i - 1]:
11                current_len = 2
12                total += 1
13            continue
14
15        left_diff = values[i - 1] - values[i - 2]
16        right_diff = values[i] - values[i - 1]
17
18        if right_diff == 0:
19            current_len = 1
20        elif left_diff == 0 or left_diff * right_diff < 0:
21            current_len += 1
22        else:
23            current_len = 2
24
25        if current_len >= 2:
26            total += current_len - 1
27
28    return total
29
30
31print(count_alternating_subarrays([1, 3, 2, 5, 4]))

This runs in O(n) time and O(1) extra space.

Why the Formula Works

Suppose an alternating run currently has length L. Then the number of alternating subarrays ending at the current position is L - 1, because you can take:

  • the last 2 elements
  • the last 3 elements
  • and so on up to the full run

So each step only needs to know whether the run continues or resets.

Counting Only Maximal Alternating Runs

Sometimes the task is not "count all alternating subarrays" but "count how many alternating segments exist." That is a different result.

python
1def count_alternating_runs(values):
2    if len(values) < 2:
3        return 0
4
5    runs = 0
6    in_run = False
7
8    for i in range(1, len(values)):
9        if i == 1:
10            in_run = values[i] != values[i - 1]
11            runs = 1 if in_run else 0
12            continue
13
14        left_diff = values[i - 1] - values[i - 2]
15        right_diff = values[i] - values[i - 1]
16
17        if right_diff == 0:
18            in_run = False
19        elif left_diff == 0 or left_diff * right_diff < 0:
20            if not in_run:
21                runs += 1
22            in_run = True
23        else:
24            runs += 1
25            in_run = True
26
27    return runs

That example shows why you must define the counting target before writing the algorithm.

Equal Values Need a Rule

If the array contains equal adjacent values, most definitions treat them as breaking alternation:

text
[1, 3, 3, 2]

The step from 3 to 3 is flat, so the alternating pattern stops there. If your domain wants to ignore equal values instead, the algorithm must be adjusted deliberately.

Common Pitfalls

The biggest pitfall is failing to specify what should be counted. "Alternating numbers" can mean alternating subarrays, maximal runs, or just whether the whole array alternates.

Another common mistake is forgetting that equal adjacent elements usually break the sign pattern. If you do not handle that case, the count is often wrong.

Developers also overcomplicate the problem with nested loops. For contiguous alternation, a single pass is enough because each new element either extends or resets the current run.

Summary

  • Alternation usually means consecutive comparisons flip direction.
  • Counting alternating subarrays can be done in one pass with constant extra space.
  • The same array can produce different answers depending on whether you count all subarrays or only maximal alternating runs.
  • Equal adjacent values typically break alternation.
  • Define the exact counting rule before choosing the algorithm.

Course illustration
Course illustration

All Rights Reserved.