AlgoTales · Roadmap

Subsequence vs subarray

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A subarray must be one connected chunk, but a subsequence can skip items as long as the original order is kept. Mixing them up is a common source of wrong answers, and the difference decides which technique fits: sliding windows for chunks, dynamic programming for skipping.

Practical use cases

  • Web app: Why a diff tool matches lines that are not adjacent. A code review page shows two versions of a file side by side. It matches lines that stayed the same even when new lines were added between them. That is subsequence thinking: matches keep their order but need not be neighbours, unlike a simple search for one connected block.
  • Web app: Search-as-you-type fuzzy match. A command palette matches the typed letters pj to the file project.js, because p and j appear in order but not together. The letters form a subsequence of the file name. A search that required them to be adjacent would never find it, and users would have to type the full name.
  • System: DNA comparison and trends. Biologists compare gene strings by finding the longest shared subsequence, allowing gaps for mutations. Stock tools find the longest rising trend even when there are dips between rises. In both cases skipping is allowed, but the order of items is never broken.

The story: The Garland and the Flower Basket

For Diwali, Mira's aunt made a long marigold garland: flower 1, flower 2, flower 3, flower 4, flower 5, all stitched in a line. Kabir asked, "Can I have a piece?" "Sure, take a piece." He snipped two places with scissors and held up flowers 2, 3, 4, still joined together.

Next, aunt gave Mira the loose flowers in a basket, still in the same order: 1, 2, 3, 4, 5. "Pick whichever flowers you like for your hair, but string them in the same order." Mira took 1, 3 and 5, skipping the ones in between. It looked pretty!

Then Kabir got cheeky: "I want 5 first, then 1." Aunt shook her head. "Order must stay. You cannot walk backward through the row."

Kabir's snipped piece is a subarray: continuous, no gaps. Mira's picked flowers are a subsequence: order kept, gaps allowed. Knowing which one a problem asks for changes the whole solution, so always ask: "may I skip items?"

How to spot this problem, and where you need it

You are unsure whether the problem allows skipping items, and picking the wrong meaning gives answers that look correct on small tests but fail when gaps matter.

Signs you need it

  • The problem says not necessarily contiguous, in order, delete some elements, or may skip, which signals a subsequence.
  • The words substring, window, slice or consecutive signal a subarray, where no skipping is allowed.
  • A comparison feature must match similar content even with extra items inserted in between.

Where to use it in a project

  • Diff, compare and merge features for documents, configuration files and code.
  • Fuzzy search, autocomplete and recommendation features where typed letters or events must appear in order but not together.

The solution

First, underline the key words in the problem. If items must be side by side, treat it as a subarray and use two positions, a sliding window or running totals. If items may be skipped but must stay in order, treat it as a subsequence and use a table that remembers the best answer for each pair of positions, building up from smaller prefixes.

Payoff: Before: a diff that fails to match lines separated by one new line. After: a correct, readable diff that pairs up shared lines in order.

Explain it like I am 8

A subarray is a chunk of a chocolate bar snapped off in one go. A subsequence is when you pick some squares from the bar, in order, from different places. You may skip squares, but you may not go backward.

How it works, step by step

  1. A subarray must be contiguous: neighbours in the original, no gaps.
  2. A subsequence keeps the original order but may skip items.
  3. Checking a subarray: slide the wanted list along the big array and compare every position.
  4. Checking a subsequence: walk the big array once; whenever the current item equals the next wanted item, advance the wanted pointer.
  5. Every subarray is a subsequence, but not the other way round.

The code in four languages

PHP

<?php
// Subarray: the wanted list must appear as one unbroken run
function isSubarray(array $big, array $want): bool {
    $n = count($big); $m = count($want);
    for ($start = 0; $start + $m <= $n; $start++) {
        $ok = true;
        for ($k = 0; $k < $m; $k++) {
            if ($big[$start + $k] !== $want[$k]) { $ok = false; break; }
        }
        if ($ok) return true;
    }
    return false;
}

// Subsequence: same order, gaps allowed
function isSubsequence(array $big, array $want): bool {
    $w = 0;                                   // next wanted item
    foreach ($big as $x) {
        if ($w < count($want) && $x === $want[$w]) $w++;
    }
    return $w === count($want);
}

$row = [1, 2, 3, 4, 5];
foreach ([[2, 3, 4], [1, 3, 5], [5, 1]] as $want) {
    echo '[' . implode(',', $want) . '] subarray: ' . (isSubarray($row, $want) ? 'yes' : 'no')
       . ', subsequence: ' . (isSubsequence($row, $want) ? 'yes' : 'no') . PHP_EOL;
}

JavaScript

// Subarray: the wanted list must appear as one unbroken run
function isSubarray(big, want) {
  for (let start = 0; start + want.length <= big.length; start++) {
    let ok = true;
    for (let k = 0; k < want.length; k++) {
      if (big[start + k] !== want[k]) { ok = false; break; }
    }
    if (ok) return true;
  }
  return false;
}

// Subsequence: same order, gaps allowed
function isSubsequence(big, want) {
  let w = 0;                                  // next wanted item
  for (const x of big) {
    if (w < want.length && x === want[w]) w++;
  }
  return w === want.length;
}

const row = [1, 2, 3, 4, 5];
for (const want of [[2, 3, 4], [1, 3, 5], [5, 1]]) {
  console.log('[' + want.join(',') + '] subarray: ' + (isSubarray(row, want) ? 'yes' : 'no')
    + ', subsequence: ' + (isSubsequence(row, want) ? 'yes' : 'no'));
}

Java

public class Main {
    // Subarray: the wanted list must appear as one unbroken run
    static boolean isSubarray(int[] big, int[] want) {
        for (int start = 0; start + want.length <= big.length; start++) {
            boolean ok = true;
            for (int k = 0; k < want.length; k++) {
                if (big[start + k] != want[k]) { ok = false; break; }
            }
            if (ok) return true;
        }
        return false;
    }

    // Subsequence: same order, gaps allowed
    static boolean isSubsequence(int[] big, int[] want) {
        int w = 0;                                  // next wanted item
        for (int x : big) {
            if (w < want.length && x == want[w]) w++;
        }
        return w == want.length;
    }

    public static void main(String[] args) {
        int[] row = {1, 2, 3, 4, 5};
        int[][] wants = {{2, 3, 4}, {1, 3, 5}, {5, 1}};
        for (int[] want : wants) {
            String text = java.util.Arrays.toString(want).replace(" ", "");
            System.out.println(text + " subarray: " + (isSubarray(row, want) ? "yes" : "no")
                    + ", subsequence: " + (isSubsequence(row, want) ? "yes" : "no"));
        }
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// isSubarray: the wanted list must appear as one unbroken run.
func isSubarray(big, want []int) bool {
	for start := 0; start+len(want) <= len(big); start++ {
		ok := true
		for k := 0; k < len(want); k++ {
			if big[start+k] != want[k] {
				ok = false
				break
			}
		}
		if ok {
			return true
		}
	}
	return false
}

// isSubsequence: same order, gaps allowed.
func isSubsequence(big, want []int) bool {
	w := 0 // next wanted item
	for _, x := range big {
		if w < len(want) && x == want[w] {
			w++
		}
	}
	return w == len(want)
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	row := []int{1, 2, 3, 4, 5}
	for _, want := range [][]int{{2, 3, 4}, {1, 3, 5}, {5, 1}} {
		parts := make([]string, len(want))
		for i, n := range want {
			parts[i] = strconv.Itoa(n)
		}
		fmt.Printf("[%s] subarray: %s, subsequence: %s\n",
			strings.Join(parts, ","), yesNo(isSubarray(row, want)), yesNo(isSubsequence(row, want)))
	}
}

Time: Subsequence check O(n); subarray check O(n × m) · Extra space: O(1). The subsequence walk reads the big array once. The subarray check may compare a short list at every start position.

Watch out for

  • Treating "subsequence" and "subarray" as synonyms. In an interview, "contiguous" is the keyword that means subarray.
  • Allowing the order to change. A subsequence may skip items but never rearrange them.
  • Forgetting that the empty list and the whole array are valid in both worlds.

Quick check

  1. Which is a subsequence but NOT a subarray of [1, 2, 3, 4, 5]?
    • [2, 3, 4]
    • [1, 3, 5]
    • [5, 4]
  2. Is every subarray also a subsequence?
    • Yes
    • No
    • Only if the numbers are sorted
  3. What keyword in a problem points to subarray?
    • Sorted
    • Distinct
    • Contiguous