Subsequence Check Walks Two Slices

Walk two slices with one index per side to test whether a short sequence appears in order inside a longer event stream.

GoData Integrity

Code

gosnippet
23 lines
package main

import "fmt"

// isSubsequence reports whether sub appears in s with order preserved.
func isSubsequence[T comparable](s, sub []T) bool {
	j := 0
	for i := 0; i < len(s) && j < len(sub); i++ {
		if s[i] == sub[j] {
			j++
		}
	}
	return j == len(sub)
}

func main() {
	stream := []string{"boot", "config", "ready", "request", "request", "shutdown"}

	fmt.Println(isSubsequence(stream, []string{"config", "request"}))
	fmt.Println(isSubsequence(stream, []string{"request", "config"}))
	fmt.Println(isSubsequence(stream, []string{"shutdown"}))
	fmt.Println(isSubsequence([]int{1, 2, 3, 4}, []int{2, 4}))
}

What to notice first — Subsequence Check Walks Two Slices

Subsequence Check Walks Two Slices keeps everything in the function main.

The cycling part of this snippet is for i := 0; i < len(s) && j < len(sub); i++.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func main()

Core lines

func isSubsequence[T comparable](s, sub []T) bool {
	j := 0
	for i := 0; i < len(s) && j < len(sub); i++ {
		if s[i] == sub[j] {
			j++
		}
	}
	return j == len(sub)
}

Interactive Tools for This Topic

FAQ

How do you run Subsequence Check Walks Two Slices?
It runs as-is — treat the file as the whole program and execute it.