Leetcode 3042: Count Prefix and Suffix Pairs I

grid47
grid47
Exploring patterns and algorithms
Jan 7, 2024 7 min read

You are given a 0-indexed string array words. You need to determine the number of index pairs (i, j) such that i < j and the string at index i is both a prefix and a suffix of the string at index j. The function isPrefixAndSuffix(str1, str2) returns true if str1 is both a prefix and a suffix of str2, and false otherwise.
Problem
Approach
Steps
Complexity
Input: You are given an array `words` of strings.
Example: words = ["ab", "abab", "abc", "ababc"]
Constraints:
• 1 <= words.length <= 50
• 1 <= words[i].length <= 10
• words[i] consists only of lowercase English letters.
Output: Return an integer representing the number of valid index pairs `(i, j)` where `i < j` and `isPrefixAndSuffix(words[i], words[j])` is true.
Example: For the input words = ["ab", "abab", "abc", "ababc"], the output is 1.
Constraints:
• Return 0 if no such pairs exist.
Goal: The function should iterate through all pairs `(i, j)` with `i < j` and check whether the word at index `i` is both a prefix and a suffix of the word at index `j`. If this condition is met, the pair is valid, and the counter should be incremented.
Steps:
• Iterate through all pairs of indices (i, j) with i < j.
• For each pair, check if the word at index i is a prefix and suffix of the word at index j.
• If both conditions are true, increment the counter.
• Finally, return the count.
Goal: The array contains lowercase English words, and each word has a length of at most 10 characters. The total number of words does not exceed 50.
Steps:
• 1 <= words.length <= 50
• 1 <= words[i].length <= 10
Assumptions:
• The input contains only lowercase English letters.
• Each word can be a valid prefix and suffix for another word in the array.
Input: words = ["ab", "abab", "abc", "ababc"]
Explanation: In this case, the only valid pair is i = 0 and j = 1, because 'ab' is a prefix and suffix of 'abab'. The result is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus