Reading history

Generate All Subarrays of an Array in C

6 min read 2 views

Print every contiguous subarray of an array in C using nested loops or recursion. Count of subarrays, output for a sample array and complexity.

A subarray is a slice of an array taken without gaps, such as [7, 2] from [4, 7, 2]. Generating every subarray is the starting point for many array problems: maximum subarray sum, subarrays with a given sum, longest subarray with some property. You pick a start, pick an end, and take everything in between.

In this lesson you will learn

  • How a subarray differs from a subsequence and a subset
  • Why an array of n elements has exactly n(n + 1)/2 subarrays
  • How to print every subarray with loops and with recursion
  • How to turn an O(n³) solution into O(n²) with a running sum

Subarrays vs Subsequences

These three words are easy to mix up. For the array [1, 2, 3]:

TermRuleExample from [1, 2, 3]How many for n items
SubarrayContiguous: no gaps, original order[2, 3] yes, [1, 3] non(n + 1)/2
SubsequenceGaps allowed, original order kept[1, 3] yes, [3, 1] no2n − 1 (non-empty)
SubsetAny selection; order does not matter{1, 3} and {3, 1} are the same2n (including empty)

Every subarray is also a subsequence, but not the other way round. Interview questions that say “contiguous” mean subarrays.

Choosing Every Start and End Point

A subarray is fully described by two numbers: where it starts and where it ends, with start ≤ end.

  • With start at index 0, the end can be any of n positions.
  • With start at index 1, the end can be any of n − 1 positions.
  • … and with start at the last index, there is just 1 choice.

Adding these up: n + (n − 1) + … + 1 = n(n + 1)/2. For 3 elements that is 6 subarrays; for 1,000 elements it is 500,500.

Programs to Print All Subarrays

Method 1: Three Nested Loops

The outer loop picks the start, the middle loop picks the end, and the inner loop prints the elements between them.

#include <stdio.h>

/* Print every subarray: choose a start, then an end, then print between them. */
int main(void) {
    int a[] = {4, 7, 2};
    int n = 3, count = 0;
    for (int start = 0; start < n; start++) {
        for (int end = start; end < n; end++) {
            printf("[");
            for (int k = start; k <= end; k++) printf(k > start ? " %d" : "%d", a[k]);
            printf("]\n");
            count++;
        }
    }
    printf("%d subarrays (n*(n+1)/2 = %d)\n", count, n * (n + 1) / 2);
    return 0;
}

Output

[4]
[4 7]
[4 7 2]
[7]
[7 2]
[2]
6 subarrays (n*(n+1)/2 = 6)

Printing every element of every subarray takes O(n³) time, because there are about n²/2 subarrays and each can be up to n long. There is no way around that if you really need to print them all: the output itself is that big.

Method 2: Recursion

The same order can be produced recursively. Move the end forward one step at a time; when it runs off the array, move the start forward and begin again.

#include <stdio.h>

/* Recursive version: move the end forward; when it passes the array, move the start. */
static void subarrays(const int a[], int n, int start, int end) {
    if (start == n) return;
    if (end == n) { subarrays(a, n, start + 1, start + 1); return; }
    printf("[");
    for (int k = start; k <= end; k++) printf(k > start ? " %d" : "%d", a[k]);
    printf("]\n");
    subarrays(a, n, start, end + 1);
}

int main(void) {
    int a[] = {1, 2, 3};
    subarrays(a, 3, 0, 0);
    return 0;
}

Output

[1]
[1 2]
[1 2 3]
[2]
[2 3]
[3]

Recursion here is mainly a thinking exercise. It uses up to about n²/2 nested calls, so for large arrays the loop version is safer.

Method 3: Work With Subarrays Without Re-scanning

Most problems do not need to print subarrays; they need a value from each one, such as its sum. Then you can avoid the innermost loop. When the end moves one step right, the new subarray’s sum is just the old sum plus one element.

#include <stdio.h>

/* Sum of every subarray, two ways. */
int main(void) {
    int a[] = {4, 7, 2, 5};
    int n = 4;
    long slow = 0, fast = 0, slow_steps = 0, fast_steps = 0;

    for (int s = 0; s < n; s++)                 /* O(n^3): re-add from scratch */
        for (int e = s; e < n; e++)
            for (int k = s; k <= e; k++) { slow += a[k]; slow_steps++; }

    for (int s = 0; s < n; s++) {               /* O(n^2): extend a running sum */
        long running = 0;
        for (int e = s; e < n; e++) { running += a[e]; fast += running; fast_steps++; }
    }
    printf("O(n^3) total = %ld in %ld steps\n", slow, slow_steps);
    printf("O(n^2) total = %ld in %ld steps\n", fast, fast_steps);
    return 0;
}

Output

O(n^3) total = 90 in 20 steps
O(n^2) total = 90 in 10 steps

Both methods add up the sums of all 10 subarrays of [4, 7, 2, 5] and get 90, but the running-sum version does half the work here, and the gap widens fast: for 1,000 elements it is about 500,000 steps against about 167 million. Ideas like this lead to faster techniques such as prefix sums, sliding windows and Kadane’s algorithm. There is even an O(n) formula for this particular total, explained in sum of all subarrays.

Off-by-One and Performance Traps

  1. Starting the end loop at 0. for (end = 0; ...) creates pairs where end is before start. Start it at start.
  2. Using < where you need <=. The inner print loop must include end: k <= end. Using < misses the last element and prints empty subarrays.
  3. Counting subsequences by mistake. If your answer for n = 3 is 7, you generated subsequences (with gaps), not subarrays.
  4. Brute force on big inputs. For n = 100,000 there are about 5 billion subarrays. Generating them all is far too slow; look for a prefix-sum, sliding-window or two-pointer approach instead.
  5. Integer overflow in sums. Totals over many subarrays grow quickly. Use long long.

Practice Exercises

Exercise 1. How many subarrays does an array of 8 elements have?

Show answer

8 × 9 / 2 = 36.

Exercise 2. Change Method 3 to print the largest subarray sum of {-2, 3, -1, 4, -5}.

Show answer

Keep a variable best, start it at a[0], and after each running += a[e] do if (running > best) best = running;. The answer is 6, from [3, -1, 4].

Exercise 3. How many subarrays of [1, 2, 3, 4] have length exactly 2?

Show answer

3: [1, 2], [2, 3] and [3, 4]. In general, an array of n elements has n − k + 1 subarrays of length k.

Frequently Asked Questions

Is an empty array a subarray?

Usually not. Most problems count only non-empty subarrays, which gives n(n + 1)/2. Check the problem statement.

Is the whole array a subarray of itself?

Yes. Start at 0 and end at n − 1.

What is the fastest way to generate all subarrays?

Printing them all is O(n³) because of the output size. Visiting each one to compute a running value, such as a sum, takes O(n²).

Subarray Generation Summary

  • A subarray is a contiguous slice; there are n(n + 1)/2 non-empty ones.
  • Pick a start, then an end from the start onwards, then use the elements between them.
  • Printing every subarray costs O(n³); computing running values costs O(n²).
  • For large inputs, use prefix sums, sliding windows or Kadane’s algorithm instead of brute force.
Lessons are also marked complete when you click Next.