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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Subsequence Check Walks Two Slices?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.