Number of Pairs of Strings With Concatenation Equal to Target - Problem

You're given an array of digit strings nums and a target digit string. Your mission is to find how many pairs of strings from the array can be concatenated together to form the target string.

More specifically, you need to count the number of pairs of indices (i, j) where i != j such that concatenating nums[i] + nums[j] equals the target.

Example: If nums = ["777", "7", "77", "77"] and target = "7777", then nums[1] + nums[0] = "7" + "777" = "7777" forms one valid pair.

Note: The order matters! nums[i] + nums[j] is different from nums[j] + nums[i] unless both strings are identical.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = ["777","7","77","77"], target = "7777"
โ€บ Output: 4
๐Ÿ’ก Note: Valid pairs: (1,0): "7"+"777", (0,1): "777"+"7", (2,1): "77"+"7"+"7" (invalid), actually (2,0) and (3,0) don't work. Let me recalculate: "7"+"777"="7777" โœ“, "777"+"7"="7777" โœ“. That's 2 pairs total.
example_2.py โ€” No Valid Pairs
$ Input: nums = ["123","4","12","34"], target = "1234"
โ€บ Output: 2
๐Ÿ’ก Note: Valid pairs: (2,3): "12"+"34"="1234" โœ“, (0,1): "123"+"4"="1234" โœ“. Total of 2 pairs.
example_3.py โ€” Duplicate Strings
$ Input: nums = ["1","1","1"], target = "11"
โ€บ Output: 6
๐Ÿ’ก Note: Each "1" can pair with every other "1". With 3 strings, we have 3ร—2=6 ordered pairs: (0,1), (0,2), (1,0), (1,2), (2,0), (2,1).

Constraints

  • 2 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค nums[i].length, target.length โ‰ค 100
  • nums[i] and target consist of digits only
  • All strings contain only digits 0-9

Visualization

Tap to expand
String Concatenation Puzzle"777""7""77""77"TARGET"7777"โœ“ "7" + "777" = "7777"โœ“ "777" + "7" = "7777"Count: 2 valid pairs found
Understanding the Visualization
1
Identify Pieces
Each string in the array is a puzzle piece
2
Find Complements
For each piece, find what other piece would complete the target
3
Count Matches
Count all valid piece combinations that form the complete target
Key Takeaway
๐ŸŽฏ Key Insight: Every valid concatenation corresponds to a unique way to split the target string into a prefix and suffix, both of which must exist in our input array.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen