AlgoTales · Roadmap

Generate subsequences

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

Where you will meet this in real life

A subsequence is what you get by deleting some items from a list while keeping the rest in their original order. Generating them all means walking through the items and, for each one, choosing "keep it" or "skip it". It is the base pattern for every "pick some of these" problem.

Practical use cases

  • Web app: Filter combinations on a shop page. A product page lets shoppers tick optional add-ons: gift wrap, extended warranty, express delivery. The QA team wants to test every combination of ticks. With 5 add-ons, going through each one and choosing "on" or "off" produces all 32 combinations, so a script can click through them all and catch a price bug that only appears when two particular boxes are ticked together.
  • Web app: Fuzzy search that skips letters. A user types "mngo" into a search box and expects "mango". The app checks whether the typed letters appear inside the product name in the same order with other letters allowed in between. That is exactly asking whether one string is a subsequence of another, and it lets the search box forgive missing letters.
  • System: Diff tools and DNA matching. Tools that compare two files or two DNA strings look for letters or lines that appear in both, in the same order, with gaps allowed. Every candidate match is a subsequence of each text. Understanding how to list them is the first step to understanding how the smarter comparison works.

The story: Raju's Secret Menu Board

Raju's chai stall had a signboard that read CHAI in big painted letters. One day a rival stall owner sneered, "Your board is boring." Raju grinned and said, "Hide some letters with a cloth and see how many new words you can read."

Mira tried it. Hide the C and the board reads HAI. Hide H and I and it reads CA. Hide everything and it reads... nothing. "But I can't swap letters," she realised. "AC is not allowed, because A comes after C on the board."

That is a subsequence: letters taken from a word, in the same order, skipping any you like. To list them all without missing or repeating any, Mira used the same trick as the tiffin box: for each letter, keep or drop, walk to the end, write the word, then back up and flip the last decision.

The board of four letters gave 16 words. Raju printed them on a poster, and the rival stall owner stopped smiling.

How to spot this problem, and where you need it

You have a list of things and need to consider every way of keeping some and dropping others, but the order of what you keep must stay the same.

Signs you need it

  • The problem says "subsequence", "subset" or "every possible selection", and the answer for 3 items has 8 possibilities, for 4 items 16.
  • You are writing nested loops to try on/off options and realise you would need a different number of loops for each list length.
  • A feature has several independent optional toggles and you must test or price every combination of them.

Where to use it in a project

  • Generating all option combinations for a product configurator or a test matrix of feature flags.
  • Checking whether a typed pattern appears in order inside a longer text, as in simple fuzzy matching.

The solution

Walk through the items from left to right. At each item make two choices, one after the other: first keep it and carry on with the rest, then skip it and carry on with the rest. When you run out of items, whatever you kept is one finished subsequence, so save it. Going back to try the other choice is called backtracking. A single short function that calls itself twice does the job, instead of a loop for each item.

Payoff: Before: hand-written loops that only work for exactly 3 toggles. After: one small function that covers any number, producing all 32 combinations for 5 toggles.

Explain it like I am 8

Take the word CAT written on a strip of paper. Put your finger over any letters you like, and read what is left, still left to right. You can never shuffle the letters. Covering different letters gives different mini-words, and trying every way to cover is what we teach the computer to do.

How it works, step by step

  1. Walk through the word with an index i, keeping the current text built so far.
  2. Base case: when i reaches the end, record the current text (it may be empty).
  3. Choose: add letter i to the current text, then explore from i + 1.
  4. Un-choose: cut that letter back off the end of the current text.
  5. Explore from i + 1 again without the letter. Order is preserved automatically because we only move forward.

The code in four languages

PHP

<?php
// List every subsequence of a word (letters keep their original order).
function subsequences(string $word): array {
    $result = [];
    $current = '';
    $explore = function (int $i) use (&$explore, &$result, &$current, $word) {
        if ($i === strlen($word)) {
            $result[] = $current;                        // base case: record
            return;
        }
        $current .= $word[$i];                           // choose: keep the letter
        $explore($i + 1);
        $current = substr($current, 0, -1);              // un-choose: cut it off
        $explore($i + 1);                                // explore without it
    };
    $explore(0);
    return $result;
}

$all = subsequences('chai');
echo count($all) . " subsequences\n";
foreach ($all as $s) {
    echo '"' . $s . '" ';
}
echo "\n";

JavaScript

// List every subsequence of a word (letters keep their original order).
function subsequences(word) {
  const result = [];
  let current = '';
  function explore(i) {
    if (i === word.length) {
      result.push(current);                // base case: record
      return;
    }
    current += word[i];                    // choose: keep the letter
    explore(i + 1);
    current = current.slice(0, -1);        // un-choose: cut it off
    explore(i + 1);                        // explore without it
  }
  explore(0);
  return result;
}

const all = subsequences('chai');
console.log(all.length + ' subsequences');
console.log(all.map((s) => '"' + s + '"').join(' '));

Java

import java.util.*;

public class Main {
    // List every subsequence of a word (letters keep their original order).
    static List<String> subsequences(String word) {
        List<String> result = new ArrayList<>();
        explore(word, 0, new StringBuilder(), result);
        return result;
    }

    static void explore(String word, int i, StringBuilder current, List<String> result) {
        if (i == word.length()) {
            result.add(current.toString());                  // base case: record
            return;
        }
        current.append(word.charAt(i));                      // choose: keep the letter
        explore(word, i + 1, current, result);
        current.deleteCharAt(current.length() - 1);          // un-choose: cut it off
        explore(word, i + 1, current, result);               // explore without it
    }

    public static void main(String[] args) {
        List<String> all = subsequences("chai");
        System.out.println(all.size() + " subsequences");
        StringJoiner sj = new StringJoiner(" ");
        for (String s : all) sj.add("\"" + s + "\"");
        System.out.println(sj);
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// subsequences lists every subsequence of a word (letters keep their original order).
func subsequences(word string) []string {
	var result []string
	current := ""
	var explore func(i int)
	explore = func(i int) {
		if i == len(word) {
			result = append(result, current) // base case: record
			return
		}
		current += string(word[i]) // choose: keep the letter
		explore(i + 1)
		current = current[:len(current)-1] // un-choose: cut it off
		explore(i + 1)                     // explore without it
	}
	explore(0)
	return result
}

func main() {
	all := subsequences("chai")
	fmt.Println(len(all), "subsequences")
	quoted := make([]string, len(all))
	for i, s := range all {
		quoted[i] = `"` + s + `"`
	}
	fmt.Println(strings.Join(quoted, " "))
}

Time: O(n × 2^n) · Extra space: O(n). Two choices per letter doubles the list each time. Building each word costs up to n more.

Watch out for

  • Mixing up subsequence and substring. A substring must be a block of neighbours ("ha" in "chai"), a subsequence may skip letters ("ci").
  • Forgetting the empty subsequence, or forgetting that words with repeated letters (like "aab") will produce duplicate subsequences unless you remove them.
  • Reordering letters. If you ever write code that swaps letters, you are listing permutations, not subsequences.

Quick check

  1. Which of these is a subsequence of "chai" but NOT a substring?
    • ha
    • chai
    • ci
    • hai
  2. Is "ac" a subsequence of "chai"?
    • No, because a comes after c in the word
    • Yes
    • Only if we sort first
  3. How many subsequences does a 5-letter word with all different letters have?
    • 10
    • 25
    • 32
    • 120