Print the longest prefix of the given string which is also the suffix of the same string in C Program.

Given a string, we need to find the length of the longest prefix which is also a suffix of the same string. For example, in the string "abcab", "ab" is both a prefix and suffix with length 2.

Syntax

int longest_prefix_suffix(char str[], int n);

Algorithm

The approach uses the KMP (Knuth-Morris-Pratt) failure function concept −

  • Start comparing from the middle of the string to avoid overlap
  • Use two pointers: one for prefix (length) and one for suffix (i)
  • When characters match, increment both pointers
  • When they don't match, reset according to the failure function logic

Example

Let's implement the algorithm to find the longest prefix-suffix match −

#include <stdio.h>
#include <string.h>

int longest_prefix_suffix(char str[], int n) {
    int length = 0, i = n / 2;
    
    if (n < 2)
        return 0;
    
    while (str[i] != '\0') {
        /* When we find matching character in prefix and suffix */
        if (str[i] == str[length]) {
            length++;
            i++;
        } else {
            /* When prefix and suffix don't match */
            if (length == 0) {
                i++;
            } else {
                length--;
            }
        }
    }
    return length;
}

int main() {
    char str1[] = "abccmmabcc";
    char str2[] = "aabbccdaabbcc";
    char str3[] = "abdab";
    
    printf("String: %s<br>", str1);
    printf("Longest prefix-suffix length: %d<br><br>", longest_prefix_suffix(str1, strlen(str1)));
    
    printf("String: %s<br>", str2);
    printf("Longest prefix-suffix length: %d<br><br>", longest_prefix_suffix(str2, strlen(str2)));
    
    printf("String: %s<br>", str3);
    printf("Longest prefix-suffix length: %d<br>", longest_prefix_suffix(str3, strlen(str3)));
    
    return 0;
}
String: abccmmabcc
Longest prefix-suffix length: 4

String: aabbccdaabbcc
Longest prefix-suffix length: 6

String: abdab
Longest prefix-suffix length: 2

How It Works

For the string "abccmmabcc":

  • We start comparing from the middle position
  • The prefix "abcc" matches with the suffix "abcc"
  • Length 4 is returned as the longest match

Conclusion

This algorithm efficiently finds the longest prefix-suffix match using the KMP failure function concept. It has O(n) time complexity and is useful in pattern matching algorithms.

Updated on: 2026-03-15T11:55:45+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements