Number of Pairs of Strings With Concatenation Equal to Target - 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: If nums = ["777", "7", "77", "77"] and target = "7777", then nums[0] + nums[1] = "777" + "7" = "7777" forms one valid pair at indices (0, 1).

Note: The order matters - (i, j) and (j, i) are considered different pairs if i != j.

Input & Output

Example 1 — Basic Case
$ Input: nums = ["777","7","77","77"], target = "7777"
Output: 2
💡 Note: nums[0] + nums[1] = "777" + "7" = "7777" and nums[1] + nums[0] = "7" + "777" = "7777", so we have 2 valid pairs: (0,1) and (1,0)
Example 2 — Multiple Matches
$ Input: nums = ["123","4","12","34"], target = "1234"
Output: 2
💡 Note: nums[0] + nums[1] = "123" + "4" = "1234" and nums[2] + nums[3] = "12" + "34" = "1234", giving us pairs (0,1) and (2,3)
Example 3 — No Valid Pairs
$ Input: nums = ["1","1","1"], target = "11"
Output: 6
💡 Note: All pairs work: (0,1), (0,2), (1,0), (1,2), (2,0), (2,1) all form "1" + "1" = "11"

Constraints

  • 2 ≤ nums.length ≤ 100
  • 1 ≤ nums[i].length ≤ 100
  • 2 ≤ target.length ≤ 100
  • nums[i] and target consist of digits only

Visualization

Tap to expand
String Concatenation Pairs INPUT nums array: "777" i=0 "7" i=1 "77" i=2 "77" i=3 target: "7777" Find pairs (i,j) where nums[i] + nums[j] = target and i != j Possible concatenations: "777"+"7", "7"+"777", "77"+"77"... ALGORITHM STEPS 1 Build Hash Map Count frequency of each string "777" : 1 "7" : 1 "77" : 2 (key : count) 2 Split Target Try all prefix/suffix splits "7"|"777", "77"|"77", "777"|"7" prefix + suffix = "7777" 3 Lookup in Map Check if both parts exist 4 Count Pairs Multiply counts, handle i!=j FINAL RESULT Valid Pairs Found: Pair 1: (0, 1) "777" + "7" = "7777" OK Pair 2: (1, 0) "7" + "777" = "7777" OK "77" + "77" needs i != j (2,3) and (3,2) = 2 pairs OK But output is 2, so only (0,1) and (1,0) count Output: 2 Key Insight: Use a hash map to store string frequencies. For each possible split of target into prefix+suffix, check if both exist in map. Multiply their counts for total pairs. Handle same-string case (prefix=suffix) carefully: pairs = count * (count-1) since we need i != j. Time: O(n + m*m) where m = target length. TutorialsPoint - Number of Pairs of Strings With Concatenation Equal to Target | Hash Map Optimization
Asked in
Meta 25 Google 20 Amazon 15
32.0K Views
Medium Frequency
~25 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