Advertisement

Count Prefix and Suffix Pairs I - LeetCode 3042 Solution

Count Prefix and Suffix Pairs I - Complete Solution Guide

Count Prefix and Suffix Pairs I is LeetCode problem 3042, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given a 0-indexed string array words . Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2 : isPrefixAndSuffix(str1, str2) returns true if str1 is both a prefix and a suffix of str2 , and false otherwise. For example, isPrefixAndSuffix("aba", "ababa") is true because "aba" is a prefix of "ababa" and also a suffix, but isPrefixAndSuffix("abc", "abcd") is false . Return an integer denoting the number of index pairs (i, j) such that i < j , and isPrefixAn

Detailed Explanation

The problem asks you to count the number of pairs of strings (words[i], words[j]) where i < j, and words[i] is both a prefix and a suffix of words[j]. The input is a list of strings, and the output is a single integer representing the count of such pairs. The problem emphasizes that words[i] must be a prefix AND a suffix of words[j], not just one or the other. Constraints limit the length of the input list and the length of individual strings.

Solution Approach

The provided solutions use a brute-force approach. They iterate through all possible pairs of strings using nested loops. For each pair (words[i], words[j]), a helper function `isPrefixAndSuffix` checks if words[i] is both a prefix and a suffix of words[j]. If it is, the counter is incremented. Finally, the total count is returned.

Step-by-Step Algorithm

  1. Step 1: Initialize a counter `count` to 0.
  2. Step 2: Iterate through the `words` array using a nested loop. The outer loop iterates from i = 0 to n-1, and the inner loop iterates from j = i+1 to n-1 (to ensure i < j).
  3. Step 3: For each pair (words[i], words[j]), call the `isPrefixAndSuffix` function to check the prefix and suffix condition.
  4. Step 4: If `isPrefixAndSuffix` returns true, increment the `count`.
  5. Step 5: After iterating through all pairs, return the final value of `count`.

Key Insights

  • Insight 1: The problem requires checking both prefix and suffix conditions simultaneously for each pair of strings.
  • Insight 2: A nested loop is a straightforward way to iterate through all possible pairs of strings (i, j) where i < j.
  • Insight 3: Efficient string manipulation functions (like startsWith and endsWith in Python/Java) can significantly reduce the time taken to check the prefix and suffix conditions.

Complexity Analysis

Time Complexity: O(n^2 * m)

Space Complexity: O(1)

Topics

This problem involves: Array, String, Trie, Rolling Hash, String Matching, Hash Function.

Companies

Asked at: Autodesk, Capital One.