#2023

Number of Pairs of Strings With Concatenation Equal to Target

Medium
ArrayHash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking all pairs, we can use a hash map to store the frequency of each string. For each string, we can check if the required complement exists in the map to form the target.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a hash map to store the frequency of each string in nums.
  2. 2Step 2: Initialize a counter to zero for valid pairs.
  3. 3Step 3: Iterate through each string in nums, for each string, calculate its complement needed to form the target.
  4. 4Step 4: Check if the complement exists in the map. If it does, add its frequency to the counter.
  5. 5Step 5: Adjust the count to avoid counting pairs where i == j.
solution.py11 lines
1def countPairs(nums, target):
2    from collections import Counter
3    count = 0
4    freq = Counter(nums)
5    for num in nums:
6        complement = target[len(num):]
7        if complement in freq:
8            count += freq[complement]
9            if complement == num:
10                count -= 1
11    return count

Complexity note: This complexity is achieved because we only iterate through the list a couple of times, and the hash map operations (insert and lookup) are average O(1).

  • 1Using a hash map reduces the need for nested loops.
  • 2Understanding string concatenation helps in identifying complements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.