Number of Pairs of Strings With Concatenation Equal to Target
MediumArrayHash TableStringCounting
Solution
Solution1: Brute Force
export function numOfPairs(nums: string[], target: string): number {
const n = nums.length;
let answer = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (nums[i] + nums[j] === target) {
answer += 1;
}
if (nums[j] + nums[i] === target) {
answer += 1;
}
}
}
return answer;
}
Complexity
- Time:
O(N^2)
- Space:
O(1)
Solution2: Using Map
export function numOfPairs(nums: string[], target: string): number {
const counter = new Map<string, number>();
for (const num of nums) {
counter.set(num, (counter.get(num) ?? 0) + 1);
}
let answer = 0;
for (const [num, count] of counter) {
if (!target.startsWith(num)) continue;
const suffix = target.slice(num.length);
if (num === suffix) {
answer += count * (count - 1);
} else {
const suffixCount = counter.get(suffix) ?? 0;
answer += count * suffixCount;
}
}
return answer;
}
Complexity
- Time:
O(N)
- Space:
O(N)