Count Pairs of Equal Substrings With Minimum Difference - Problem

You are given two strings firstString and secondString that are 0-indexed and consist only of lowercase English letters.

Count the number of index quadruples (i,j,a,b) that satisfy the following conditions:

  • 0 <= i <= j < firstString.length
  • 0 <= a <= b < secondString.length
  • The substring of firstString that starts at the ith character and ends at the jth character (inclusive) is equal to the substring of secondString that starts at the ath character and ends at the bth character (inclusive)
  • j - a is the minimum possible value among all quadruples that satisfy the previous conditions

Return the number of such quadruples.

Input & Output

Example 1 — Basic Case
$ Input: firstString = "abc", secondString = "bc"
Output: 2
💡 Note: Matching substrings: "b" at (1,1) and (0,0) with j-a=1, "c" at (2,2) and (1,1) with j-a=1. Both achieve minimum j-a=1, so count is 2.
Example 2 — Single Character
$ Input: firstString = "a", secondString = "a"
Output: 1
💡 Note: Only one match: "a" at (0,0) and (0,0) with j-a=0. This is the minimum, so count is 1.
Example 3 — No Matches
$ Input: firstString = "abc", secondString = "def"
Output: 0
💡 Note: No common substrings between the two strings, so no valid quadruples exist.

Constraints

  • 1 ≤ firstString.length, secondString.length ≤ 100
  • firstString and secondString consist only of lowercase English letters

Visualization

Tap to expand
Count Pairs of Equal Substrings INPUT firstString = "abc" a i=0 b i=1 c i=2 secondString = "bc" b a=0 c a=1 Find quadruples (i,j,a,b) where substrings match and j-a is minimized first = "abc" second = "bc" ALGORITHM STEPS 1 Build Hash Maps Store first/last occurrence of each char in both strings 2 For Each Character Get earliest j in first Get latest a in second 3 Calculate j - a Track minimum diff value Count pairs at minimum 4 Count Valid Pairs Return count of quadruples with minimum j-a Hash Map char: first_j b: j=1 c: j=2 a: j=0 Hash Map char: last_a b: a=0 c: a=1 FINAL RESULT Valid Quadruples Found: Pair 1: char 'b' (i=1, j=1, a=0, b=0) j - a = 1 - 0 = 1 Pair 2: char 'c' (i=2, j=2, a=1, b=1) j - a = 2 - 1 = 1 Minimum difference = 1 Both pairs achieve this min OUTPUT 2 OK - 2 valid quadruples Key Insight: For single characters, we only need to match the same character between strings. To minimize j-a, use the EARLIEST occurrence of each char in firstString (smallest j) and LATEST occurrence in secondString (largest a). This greedy approach with hash maps achieves O(n) time complexity. TutorialsPoint - Count Pairs of Equal Substrings With Minimum Difference | Hash Map Optimization
Asked in
Google 12 Amazon 8 Microsoft 6
8.5K Views
Medium Frequency
~25 min Avg. Time
234 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