Count Prefix And Suffix Pairs I
Algorithm/String
Intuition
The problem can be solved with a brute-force approach where we iterate over all possible pairs and check the condition for each.
Approach
Below is the step-by-step breakdown of the approach:
-
Helper Function:
- Define a helper function
isPrefixAndSuffix
, usingstartsWith
andendsWith
to check if one string is both a prefix and a suffix of another string. - Return false early if the first string is longer than the second string, since it can't be a valid prefix or suffix.
- Define a helper function
-
Iterate Over Pairs:
- Use two nested loops to iterate over all possible pairs of words in the array, ensuring i < j to avoid redundant checks.
- For each pair, use the helper function to determine if the condition is met, and increment the count accordingly.
-
Return the Count:
- After iterating through all pairs, return the total count of valid prefix-suffix pairs.
Complexity
- Time Complexity: ,
- The brute-force approach involves pair comparisons, where
n
is the number of words. - For each pair, the
isPrefixAndSuffix
function has a worst-case complexity of , whereL
is the average length of the words.
- The brute-force approach involves pair comparisons, where
- Space Complexity: , as the function uses constant extra space.