data-structures · intermediate · ~15 min

Longest common substring

Find the longest contiguous common substring.

Challenge

Implement:

int longest_common_substring(const char *a, const char *b);

Return the length of the longest contiguous substring common to a and b.

Input format

Two strings.

Output format

Longest common substring length.

Constraints

2-D table; reset to 0 on mismatch.

Starter code

#include <stddef.h>
/* Length of the Longest Common (contiguous) Substring of a and b. */
int longest_common_substring(const char *a,const char *b){ (void)a;(void)b; return -1; }

Common mistakes

Carrying the diagonal value through a mismatch (that computes subsequence, not substring).

Edge cases to handle

No common characters -> 0.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.