Number of Pairs of Strings With Concatenation Equal to Target — LeetCode 2023 Python Solution

MediumArrayHash TableStringCounting
Problem
#2023
Pattern
Hash Map
Reading time
2 min

The problem

Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.

Example

Input
nums = ["777","7","77","77"], target = "7777"
Output
4
Explanation
Valid pairs are:

Python solution

Python
class Solution:
    def numOfPairs(self, nums: List[str], target: str) -> int:
        n = len(nums)
        return sum(
            i != j and nums[i] + nums[j] == target for i in range(n) for j in range(n)
        )

Complexity

MeasureComplexity
TimeO(n^2 \times m), where n and m are the lengths of the array `nums` and the string `target`, respectively
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target?
LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target is rated Medium on LeetCode.
What is the time complexity of LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target?
The Python solution on this page runs in O(n^2 \times m), where n and m are the lengths of the array `nums` and the string `target`, respectively.
What is the space complexity of LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target cover?
LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target is tagged Array, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview