Skip to main content

Prefix / Suffix

Learn Prefix / Suffix (Strings, Data Structures & Algorithms) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

Prefixes and Suffixes of a String A prefix is a substring starting at index 0; a suffix is a substring ending at the last index. A length-n string has exactly n non-empty prefixes and n non-empty suffixes. s.startsWith(p) checks if p is a prefix. s.endsWith(suf) checks if suf is a suffix. These are the building blocks of pattern-matching algorithms like KMP, which precomputes "the longest prefix that is also a suffix" for every position of the pattern.

More lessons in Strings