Problem Description
Given an array of strings words, count the number of index pairs (i, j) where i < j and words[i] is both a prefix and a suffix of words[j].
Key Insights
- Iterate over all unique pairs (i, j) with i < j.
- Check if words[i] is a prefix of words[j] by comparing words[j][0:len(words[i])] with words[i].
- Check if words[i] is a suffix of words[j] by comparing words[j][-len(words[i]):] with words[i].
- The constraints (n ≤ 50 and word length ≤ 10) allow a simple O(n²) solution.
Space and Time Complexity
Time Complexity: O(n² * m), where n is the number of words and m is the maximum length of a word. Space Complexity: O(1) extra space apart from the input.
Solution
The solution uses a nested loop to iterate over every pair (i, j) with i < j. For each pair, we verify that words[i] is both the prefix and the suffix of words[j] by comparing the relevant substrings. If both conditions hold, we increment the count. This approach is efficient given the small input size and leverages simple string operations.