Problem 1638

Abstract / Summary

Count the number of pairs of substrings of the same length that differ by exactly one character.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1638.py

class Solution:
    def countSubstrings(self, s: str, t: str) -> int:
        # create all substrings
        dots = defaultdict(list)
        for i in range(len(t)):
            for j in range(i + 1, len(t) + 1):
                phrase = t[i : j]
                # replace each single letter by a dot and remember the original phrase/substring
                for k in range(len(phrase)):
                    regex = phrase[:k] + "." + phrase[k + 1:]
                    dots[regex].append(phrase)

        result = 0
        # and repeat the same for s
        for i in range(len(s)):
            for j in range(i + 1, len(s) + 1):
                phrase = s[i : j]
                for k in range(len(phrase)):
                    regex = phrase[:k] + "." + phrase[k + 1:]
                    # look up
                    if regex in dots:
                        for d in dots[regex]:
                            # avoid self-matching (the dot must represent a different character)
                            if d != phrase:
                                result += 1

        return result
27 lines | 1124 bytes | submitted December 8, 2023 | GitHub   25% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (50k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Enumeration
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that counts pairs of substrings, one taken from each of two input strings, that differ by exactly one character. The algorithm proceeds in two main phases: it first enumerates every possible substring of the second string, creates a “dot-pattern” for each possible single-character replacement, and stores these patterns in a hash map. In the second phase it repeats the enumeration for the first string, generates the same dot-patterns, and looks them up in the previously built map to count matching pairs while explicitly discarding cases where the two substrings are identical.

Key Steps

Building the dot-pattern dictionary for the second string

The method starts by creating a defaultdict(list) called dots. It then iterates over all start indices i and end indices j of the string t, extracts each substring phrase, and for every character position k inside that substring builds a new string where the character at k is replaced by a literal dot .. This dot-pattern serves as a key that represents all substrings that would match if a single character were allowed to differ. The original substring is appended to the list associated with that key.

dots = defaultdict(list)
for i in range(len(t)):
    for j in range(i + 1, len(t) + 1):
        phrase = t[i : j]
        for k in range(len(phrase)):
            regex = phrase[:k] + "." + phrase[k + 1:]
            dots[regex].append(phrase)

Enumerating substrings of the first string and counting matches

After the dictionary is populated, the method repeats a similar nested loop structure for the first string s. For each generated substring it creates the same set of dot-patterns. When a pattern exists in dots, the method iterates over the stored substrings from t. It increments the result counter for every stored substring d that is not exactly equal to the current substring phrase. The inequality check guarantees that the dot truly represents a differing character, thereby enforcing the “exactly one character difference” rule.

result = 0
for i in range(len(s)):
    for j in range(i + 1, len(s) + 1):
        phrase = s[i : j]
        for k in range(len(phrase)):
            regex = phrase[:k] + "." + phrase[k + 1:]
            if regex in dots:
                for d in dots[regex]:
                    if d != phrase:
                        result += 1
return result

Edge Cases Handled

The algorithm naturally accommodates empty input strings. When either s or t is empty, the outer loops have no iterations, leaving result at its initial value of zero, which correctly reflects that no substring pairs exist. Substrings of length one are also processed: the inner loop over k runs once, producing a dot-pattern consisting solely of ".". The subsequent self-comparison (d != phrase) ensures that a single-character substring is only counted when the characters differ, satisfying the “exactly one mismatch” condition.

Duplicate substrings within the same source string are treated as distinct occurrences because each generation of a substring leads to an insertion into the dictionary or a lookup, regardless of whether the same text has appeared before. Consequently, the count reflects the total number of ordered pairs of positions, not merely distinct textual values.

Performance Optimizations Observed

The most notable optimization is the separation of work into a preprocessing stage for t and a lookup stage for s. By constructing the dots dictionary once, the algorithm avoids recomputing dot-patterns for the second string during the counting phase, reducing redundant work. The use of a hash map (defaultdict) provides constant-time average lookup for each generated pattern, allowing the inner matching loop to focus only on candidates that share the same dot-pattern.

Storing the original substrings in lists attached to each pattern enables direct iteration over only the relevant candidates, rather than scanning the entire set of substrings of t. This selective access curtails the number of comparisons performed during the counting phase.

The explicit check if d != phrase prevents unnecessary increments when the dot does not correspond to a true character difference, thereby eliminating false positives without needing additional data structures or passes.

Overall, the design leverages dictionary-based indexing and early filtering to keep the amount of work proportional to the number of substrings that actually share a one-character-difference relationship.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two boxes filled with puzzle pieces made of words. The goal is to find pairs of words from these boxes that are almost exactly the same, but with just one tiny letter different.

First, the computer looks at every possible word inside the second box. For each word, it pretends to take away one letter and puts a magic dot in its place. These spotted words are stored in a special notebook so they can be found again later. Think of the dot as a place that can hold any letter at all.

Next, the computer does the exact same thing with the words in the first box. It turns every possible word into a spotted version by swapping one letter for a dot. Then, it checks the notebook to see if any words from the second box match that new spotted pattern. If it finds a match, it checks to make sure the words are not actually identical to each other. When it finds a good match, it adds one to the final score to keep track of how many pairs exist.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.07 | σ = 1.54

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
22 links | 12 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality