![]() |
VOOZH | about |
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"]
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.
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)