Skip to content

3042. Count Prefix and Suffix Pairs I #1102

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to iterate through all index pairs (i, j) where i < j and check whether the string words[i] is both a prefix and a suffix of words[j]. For each pair, we can use PHP's built-in functions substr() to check for prefixes and suffixes.

Let's implement this solution in PHP: 3042. Count Prefix and Suffix Pairs I

<?php
/**
 * @param String[] $words
 * @return Integer
 */
function countPrefixAndSuffixPairs($words) {
    // Initialize a counter to keep track of valid index pairs
    $count = 0;
    
    // Loop through all index pairs (i, j) where i < j
    for ($i = 0; $i < count($words); $i++) {
        for ($j = $i + 1; $j < count($words); $j++) {
            // Check if words[i] is both…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Jan 8, 2025
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Jan 8, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Jan 8, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants