VOOZH about

URL: https://www.geeksforgeeks.org/dsa/prefix-and-suffix-pairs-count/

⇱ Prefix and Suffix Pair Count - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Prefix and Suffix Pair Count

Last Updated : 19 Mar, 2026

Given an array of strings arr[], count the number of pairs(i, j) such that i < j and the string arr[i] is both a prefix and a suffix of the string arr[j].

Examples:

Input: arr[] = ["gfg", "geeks", "gfg", "geeksforgeeks"]
Output: 2
Explanation: Valid pairs: [["gfg", "gfg"], ["geeks", "geeksforgeeks"]]

Input: arr[] = ["ab", "abcab", "a", "aaab"]
Output: 1
Explanation: Valid pairs: ["ab", "abcab"]

[Approach]: Brute Force Prefix-Suffix Check

The idea is to iterate over all pairs of strings (i, j) such that i < j and check whether arr[i] matches both the starting and ending part of arr[j]. For each pair, we compare characters to verify prefix and suffix conditions, and if both match, we increment the count of valid pairs.


Output
2

Time Complexity: O(n^2 * m) There are a total of (n(n − 1) / 2) pairs and for each pair we compare up to 'm' characters (length of the smaller string) to check both prefix and suffix.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: