Search⌘ K
AI Features

Substring, Subsequence, Prefix, and Suffix

Explore the definitions and differences between substring, subsequence, prefix, and suffix in strings. Understand their properties and learn how to identify and extract them using Python, which is essential for solving common string problems accurately.

As we begin solving more string problems, we quickly encounter terms such as substring, subsequence, prefix, and suffix. These words appear often in problem statements, and it is important to understand them precisely.

These concepts are related, but they are not the same. A substring must occupy a continuous part of a string. A subsequence only needs to preserve order and does not need to be continuous. A prefix is a substring that starts at the beginning. A suffix is a substring that ends at the end.

These definitions may sound simple at first, but confusing them leads to wrong solutions. So, let's understand these ideas carefully.

Substring

A substring is a contiguous sequence of characters taken from within a string. Contiguous means the characters must appear consecutively, with no gaps, in the same order they appear in the original.

For the string "hello", some valid substrings are:

Substring

Indices

"h"

0 to 0

"hel"

0 to 2

"ell"

1 to 3

"llo"

2 to 4

"hello"

0 to 4

""

any position

Two things are worth noting.

  1. A string is a substring of itself.

  2. The empty string is a substring of every string.

The key property of a substring is contiguity. The characters must come from consecutive ...