CategoryC Program

C Program to find the longest consecutive sequence of equal numbers

Learn how to find the longest contiguous run of equal numbers in a C array and report its value, length, and indices.

The longest consecutive sequence of equal numbers is the largest contiguous run in which every neighboring element has the same value.

For example:

Array: 4 4 2 2 2 7 7 7 7 3
Longest run: 7 7 7 7
Length: 4

The four 7 values form the longest run because they occupy adjacent positions. Equal values separated by other numbers do not belong to the same run.

C Program to Find the Longest Run of Equal Numbers

#include <stdio.h>

#define MAX_SIZE 100

int main(void) {
    int array[MAX_SIZE];
    int size;

    printf("Enter the number of elements: ");
    if (scanf("%d", &size) != 1 || size < 1 || size > MAX_SIZE) {
        printf("Please enter a size between 1 and %d.\n", MAX_SIZE);
        return 1;
    }

    printf("Enter %d elements:\n", size);
    for (int index = 0; index < size; index++) {
        if (scanf("%d", &array[index]) != 1) {
            printf("Invalid array element.\n");
            return 1;
        }
    }

    int currentStart = 0;
    int currentLength = 1;
    int longestStart = 0;
    int longestLength = 1;

    for (int index = 1; index < size; index++) {
        if (array[index] == array[index - 1]) {
            currentLength++;
        } else {
            currentStart = index;
            currentLength = 1;
        }

        if (currentLength > longestLength) {
            longestStart = currentStart;
            longestLength = currentLength;
        }
    }

    printf("Value in the longest run: %d\n", array[longestStart]);
    printf("Length of the longest run: %d\n", longestLength);
    printf("Start index: %d\n", longestStart);
    printf("End index: %d\n", longestStart + longestLength - 1);

    printf("Longest run: ");
    for (int index = longestStart;
         index < longestStart + longestLength;
         index++) {
        printf("%d ", array[index]);
    }
    printf("\n");

    return 0;
}

Sample Output

Enter the number of elements: 10
Enter 10 elements:
4 4 2 2 2 7 7 7 7 3
Value in the longest run: 7
Length of the longest run: 4
Start index: 5
End index: 8
Longest run: 7 7 7 7

How the Program Works

The program tracks two runs:

  • The current run, which ends at the element currently being examined.
  • The longest run, which is the best run found anywhere so far.

The current element is compared with the previous element:

if (array[index] == array[index - 1]) {
    currentLength++;
} else {
    currentStart = index;
    currentLength = 1;
}

If they match, the current run grows. If they differ, a new run begins at the current index with length 1.

Whenever currentLength becomes greater than longestLength, the program saves the current run as the new longest run.

Dry Run

Consider the array 4 4 2 2 2 7 7 7 7 3:

IndexValueComparison with previousCurrent run lengthLongest run length
04Initial element11
14Equal22
22Different; reset12
32Equal22
42Equal33
57Different; reset13
67Equal23
77Equal33
87Equal44
93Different; reset14

The longest run begins at index 5 and has length 4, so its final index is:

5 + 4 - 1 = 8

What Does “Consecutive” Mean Here?

In this problem, consecutive means next to each other in the array. It does not mean numerically consecutive values.

1 2 3 4

These numbers are consecutive integers, but no two adjacent values are equal. The longest equal run therefore has length 1.

By contrast:

5 5 5

contains a consecutive sequence of three equal values.

Why Does the Scan Start at Index 1?

The algorithm compares array[index] with array[index - 1]. Index 1 is the first position that has a valid predecessor at index 0.

Before the loop begins, the element at index 0 initializes both the current run and the longest run. Starting at index 0 would attempt to read array[-1], which is outside the array.

Why Are the Initial Lengths 1?

Every non-empty array contains at least one run, and each individual element forms a run of length one. Initializing both lengths to 1 correctly handles:

  • An array with one element.
  • An array in which every value differs from its neighbors.
  • A longest run that begins at index 0.

No special result value is required for these cases.

How Are Ties Handled?

The program updates the saved result only when the current run is strictly longer:

if (currentLength > longestLength)

Therefore, if several runs share the maximum length, the first one is reported.

For example:

Array: 5 5 1 2 2

Both 5 5 and 2 2 have length 2, so the program reports the earlier run 5 5.

To keep the last longest run instead, change > to >=. To print every tied run, first determine the maximum length and then perform a second scan that prints all runs of that length.

Longest Run Versus Most Frequent Element

These are different problems. Frequency counts every occurrence, even when occurrences are separated. A run counts only adjacent equal values.

Array: 1 2 1 2 1

The number 1 occurs most often, with three appearances. However, every run has length 1 because no equal values are adjacent.

Sorting the array would group equal values and reveal frequencies, but it would destroy the original run structure. This program must examine the original order.

What If Every Element Is Different?

Every element forms a run of length 1. Because ties favor the first run, the program reports the first element:

Array: 8 3 6 1
Value in the longest run: 8
Length: 1
Start index: 0
End index: 0

What If Every Element Is Equal?

The current run grows during every loop iteration and eventually covers the complete array:

Array: 4 4 4 4
Value in the longest run: 4
Length: 4
Start index: 0
End index: 3

What Happens with One Element?

The loop does not execute, and the initialized result is returned:

Array: -7
Longest run: -7
Length: 1

A single value is a valid run of length one.

Negative Numbers and Zero

The algorithm uses direct equality, so it works without changes for negative values and zero:

Array: -2 -2 0 0 0 -2
Longest run: 0 0 0
Length: 3

The final -2 is separated from the earlier -2 values and therefore belongs to a different run.

Does the Program Modify the Array?

No. It performs a read-only scan and stores only the locations and lengths of runs. The original array remains unchanged.

Relationship to Run-Length Encoding

Run-length encoding represents consecutive equal values as a value and a count. For example:

4 4 2 2 2 7

can be represented as:

(4, 2), (2, 3), (7, 1)

The algorithm in this article performs the essential counting step of run-length encoding but retains only the longest run instead of storing every run.

Time and Space Complexity

For an array containing n elements:

  • Time complexity: O(n) because every element is examined once.
  • Extra space complexity: O(1) because only start indices and lengths are stored.

The final loop that prints the winning run visits at most n elements, so the total running time remains linear.

Common Mistakes

  • Counting every occurrence of a value instead of only adjacent equal occurrences.
  • Sorting the array and losing its original contiguous runs.
  • Starting at index 0 while comparing with array[index - 1].
  • Forgetting to reset both currentStart and currentLength when the value changes.
  • Initializing the run lengths to zero for a non-empty array.
  • Using >= accidentally when the first longest run should win a tie.
  • Reporting longestStart + longestLength as the end index instead of subtracting one.

By extending a run when neighboring values match and resetting it when they differ, the program finds the longest consecutive sequence of equal numbers in a single pass without changing the array.