Subarrays
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A subarray is a connected chunk of a list: some items in a row with no gaps and no reordering. Many real questions, such as best period, longest streak or trimmed clip, are really questions about subarrays, so knowing how many there are guides the design.
Practical use cases
- Web app: Trimming a clip from a longer video. A video editor page lets users pick a start and end time for a clip. That selection is a subarray of the frames or seconds. Because the chunk is connected, the app can cut it out by simply noting two positions, without copying or rearranging the video, so saving the trim is just two numbers in the database.
- Web app: Best week in a sales table. A report asks for the strongest 7-day stretch within a year of daily sales. Every possible 7-day stretch is a subarray, and spotting that helps choose a sliding window instead of building thousands of separate lists.
- System: Substrings and counting problems. Text searching treats every connected piece of a string as a substring, which is the same idea. Counting problems, such as how many stretches add to a target, rely on knowing that even a modest list contains a very large number of chunks, so listing them all can be slow.
The story: The Sweet Shop's Barfi Slab
Grandpa Bhaskar brought a long rectangular slab of barfi, already marked into four pieces: 3, 1, 4, 2 (the numbers are how many nuts are on each piece). "Mira, you may cut it only straight through the grooves, and each cut must be one unbroken slice."
Mira could take just piece 0, or pieces 0 and 1 together, or pieces 1, 2, 3 together... But Kabir said, "Can I take piece 0 and piece 2?" Grandpa laughed. "That would leave a gap. A slice must be shoulder to shoulder. That is not allowed."
Mira wrote down every legal slice by fixing the left edge first, then sliding the right edge to the end, then moving the left edge one step and doing it again. She found 10 different slices from just 4 pieces, and kept a running nut-count as she stretched each slice so she never had to recount.
Every unbroken slice of an array is called a subarray. Many famous problems (best sum, longest stretch, count the slices that add to a target) are searches over all subarrays, and the clever tricks you are learning (prefix sums, sliding window, Kadane) avoid checking all of them one by one.
How to spot this problem, and where you need it
The task asks about contiguous pieces of a list, such as best period or longest run, and you are unsure how many pieces exist or how to cover them without wasting time.
Signs you need it
- The problem says contiguous, consecutive, continuous, in a row, or a window, and items between the ends cannot be skipped.
- You are slicing the array again and again with array_slice or slice inside loops.
- The question counts or compares stretches, like how many periods add up to a target.
Where to use it in a project
- Time-series features: selecting a date range, a video segment or an audio clip from a longer sequence.
- Reports looking for the best, worst or matching consecutive period in sales, visits, or sensor readings.
The solution
A subarray is described by just two numbers: its start and its end. List them with two loops, start from the first to the last position and end from start to the last position, if the list is small. For big lists, avoid copying slices; keep the two positions and update them cleverly using a running sum, a prefix sum list or a sliding window.
Payoff: Before: copying thousands of slices into new arrays. After: tracking only a start and an end position, with no copying.
Explain it like I am 8
Take a row of LEGO bricks stuck together. A subarray is any chunk you can snap off from the row without taking bricks out of the middle: left part, middle part or right part, but no gaps.
How it works, step by step
- Pick a start index
i(the left edge). - Pick an end index
jfromito the last index (the right edge). - The items from
itojare one subarray. Keep a running sum by addinga[j]asjgrows. - Move
ione step right and repeat. Nested loops list every subarray. - Counting: 4 items give 4 + 3 + 2 + 1 = 10 slices, so the number of subarrays grows roughly with the square of the length.
The code in four languages
PHP
<?php
// List every subarray with its sum, using a running sum
$a = [3, 1, 4, 2];
$count = 0;
for ($i = 0; $i < count($a); $i++) { // left edge
$sum = 0;
for ($j = $i; $j < count($a); $j++) { // right edge slides right
$sum += $a[$j]; // add only the new item
$slice = array_slice($a, $i, $j - $i + 1);
echo '[' . implode(', ', $slice) . '] sum = ' . $sum . PHP_EOL;
$count++;
}
}
echo "Total subarrays: $count" . PHP_EOL; // 10JavaScript
// List every subarray with its sum, using a running sum
const a = [3, 1, 4, 2];
let count = 0;
for (let i = 0; i < a.length; i++) { // left edge
let sum = 0;
for (let j = i; j < a.length; j++) { // right edge slides right
sum += a[j]; // add only the new item
console.log('[' + a.slice(i, j + 1).join(', ') + '] sum = ' + sum);
count++;
}
}
console.log('Total subarrays: ' + count); // 10Java
import java.util.*;
public class Main {
public static void main(String[] args) {
// List every subarray with its sum, using a running sum
int[] a = {3, 1, 4, 2};
int count = 0;
for (int i = 0; i < a.length; i++) { // left edge
int sum = 0;
for (int j = i; j < a.length; j++) { // right edge slides right
sum += a[j]; // add only the new item
int[] slice = Arrays.copyOfRange(a, i, j + 1);
System.out.println(Arrays.toString(slice) + " sum = " + sum);
count++;
}
}
System.out.println("Total subarrays: " + count); // 10
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// joinInts turns [3 1] into "3, 1".
func joinInts(nums []int, sep string) string {
parts := make([]string, len(nums))
for i, n := range nums {
parts[i] = strconv.Itoa(n)
}
return strings.Join(parts, sep)
}
func main() {
// List every subarray with its sum, using a running sum
a := []int{3, 1, 4, 2}
count := 0
for i := 0; i < len(a); i++ { // left edge
sum := 0
for j := i; j < len(a); j++ { // right edge slides right
sum += a[j] // add only the new item
fmt.Printf("[%s] sum = %d\n", joinInts(a[i:j+1], ", "), sum)
count++
}
}
fmt.Println("Total subarrays:", count) // 10
}Time: O(n²) subarrays to visit · Extra space: O(1). There are about n × n / 2 slices. Building each one to print it costs extra, but the running sum keeps the checking itself cheap.
Watch out for
- Mixing up subarray with subsequence. A subarray cannot skip items in the middle.
- Starting the inner loop at 0 instead of
i, which produces slices with the end before the start. - Re-adding the whole slice each time instead of keeping a running sum, which makes it O(n³).
Quick check
- Is [3, 4] a subarray of [3, 1, 4, 2]?
- Yes
- No, it skips the 1
- Only if sorted
- How many subarrays does a 4-item array have?
- 4
- 8
- 10
- What do the two loops represent?
- Left edge and right edge
- Sorting passes
- Two different arrays