Leetcode 2023: Number of Pairs of Strings With Concatenation Equal to Target

grid47
grid47
Exploring patterns and algorithms
Apr 18, 2024 5 min read

You are given an array of digit strings nums and a target digit string target. Count the number of valid pairs of indices (i, j) where i != j such that the concatenation of nums[i] and nums[j] equals target.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `nums` of digit strings and a target digit string `target`.
Example: nums = ["123", "4", "12", "34"], target = "1234"
Constraints:
• 2 <= nums.length <= 100
• 1 <= nums[i].length <= 100
• 2 <= target.length <= 100
• nums[i] and target consist of digits.
Output: Return the number of valid pairs of indices `(i, j)` where `i != j` such that `nums[i] + nums[j] == target`.
Example: Output: 2
Constraints:
• The valid pairs must not have the same index for both `i` and `j`.
Goal: The goal is to find all pairs of strings `nums[i]` and `nums[j]` such that their concatenation equals the target.
Steps:
• 1. Create a frequency map to count occurrences of strings in `nums` that are smaller than `target` in length.
• 2. Loop through the frequency map and check if the prefix of `target` matches each string in `nums`.
• 3. If a valid prefix is found, find the corresponding suffix in the `nums` array and update the count of valid pairs.
Goal: The constraints on the input values.
Steps:
• 2 <= nums.length <= 100
• 1 <= nums[i].length <= 100
• 2 <= target.length <= 100
• nums[i] and target consist of digits.
• nums[i] and target do not have leading zeros.
Assumptions:
• All strings in `nums` and the `target` contain only digits and are non-empty.
• The solution should efficiently handle arrays with up to 100 elements.
Input: nums = ["123", "4", "12", "34"], target = "1234"
Explanation: The valid pairs are (0, 1) for "123" + "4" and (2, 3) for "12" + "34".

Input: nums = ["1", "1", "1"], target = "11"
Explanation: There are 6 valid pairs: (0, 1), (1, 0), (0, 2), (2, 0), (1, 2), (2, 1).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus