#2023
Number of Pairs of Strings With Concatenation Equal to Target
MediumArrayHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Create a hash map to store the frequency of each string in nums.
- 2Step 2: Initialize a counter to zero for valid pairs.
- 3Step 3: Iterate through each string in nums, for each string, calculate its complement needed to form the target.
- 4Step 4: Check if the complement exists in the map. If it does, add its frequency to the counter.
- 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.