Number of Pairs of Strings With Concatenation Equal to Target Problem
#2023
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2023.
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 1:
Input: nums = ["777","7","77","77"], target = "7777"
Output: 4
Explanation: Valid pairs are:
- (0, 1): "777" + "7"
- (1, 0): "7" + "777"
- (2, 3): "77" + "77"
- (3, 2): "77" + "77"
Example 2:
Input: nums = ["123","4","12","34"], target = "1234"
Output: 2
Explanation: Valid pairs are:
- (0, 1): "123" + "4"
- (2, 3): "12" + "34"
Example 3:
Input: nums = ["1","1","1"], target = "11"
Output: 6
Explanation: Valid pairs are:
- (0, 1): "1" + "1"
- (1, 0): "1" + "1"
- (0, 2): "1" + "1"
- (2, 0): "1" + "1"
- (1, 2): "1" + "1"
- (2, 1): "1" + "1"
Constraints:
2 <= nums.length <= 1001 <= nums[i].length <= 1002 <= target.length <= 100nums[i]andtargetconsist of digits.nums[i]andtargetdo not have leading zeros.
Solution
Approach: Enumeration
There are at most 100 strings, so try every ordered pair (i, j) with i != j and count those where nums[i] + nums[j] equals target.
Complexity: O(n2 * m) time, where n is the number of strings and m is the length of target (each comparison costs up to m), and O(m) extra space for the concatenated string.
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)
)