Problem 1657

Abstract / Summary

Check if two strings can be made equal by replacing characters with one other character at a time.

Note

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

Python 1657.py

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        if len(word1) != len(word2):
            return False

        def getHistogram(w):
            freq = defaultdict(int)
            for c in w:
                freq[c] += 1
            return freq

        f1 = getHistogram(word1)
        f2 = getHistogram(word2)

        return f1.keys() == f2.keys() and sorted(f1.values()) == sorted(f2.values())
15 lines | 449 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (1+ million submissions).

Typical patterns to solve this problem:
  • Counting
  • Hash Table
  • Sorting
  • 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 class Solution with a method closeStrings that determines whether two input strings can be transformed into each other using a specific set of operations. The method first checks a basic length condition, then builds frequency histograms for each string, and finally compares the character sets and the multiset of frequencies. The logic is concise and leverages Python’s built-in data structures to achieve the required checks efficiently.

Key Steps

Length Check

The very first operation verifies that the two strings have identical lengths. If the lengths differ, the method returns False immediately, avoiding any further processing.

if len(word1) != len(word2):
    return False

This early exit prevents unnecessary work when the strings cannot possibly be transformed into each other because the total number of characters is different.

Histogram Construction

A nested helper function getHistogram creates a frequency map for a given string. It uses defaultdict(int) to simplify the counting logic, incrementing the count for each character encountered.

def getHistogram(w):
    freq = defaultdict(int)
    for c in w:
        freq[c] += 1
    return freq

The function is called separately for word1 and word2, producing two dictionaries f1 and f2 that map characters to their occurrence counts.

f1 = getHistogram(word1)
f2 = getHistogram(word2)

Set and Frequency Comparison

The final return statement performs two logical checks:

  1. It compares the sets of keys (the distinct characters) from both histograms. Equality of these sets ensures that both strings contain exactly the same characters, regardless of order or frequency.

  2. It compares the sorted lists of frequency values from both histograms. Sorting the frequency values and then checking equality verifies that the multiset of counts matches, which is necessary for the transformation rules to be satisfied.

return f1.keys() == f2.keys() and sorted(f1.values()) == sorted(f2.values())

Both conditions must hold for the method to return True.

Edge Cases Handled

The code gracefully handles several edge conditions without additional branching:

  • Empty strings: When both inputs are empty, the length check passes, the histograms are empty, and the key sets as well as the sorted frequency lists are equal, resulting in True. If only one string is empty, the length mismatch triggers an early False.

  • Strings with identical characters but different frequencies: The key set comparison succeeds, but the sorted frequency lists differ, leading to a False result. This correctly reflects the inability to transform when the distribution of character counts cannot be matched.

  • Strings with the same frequency distribution but different characters: The frequency lists may match after sorting, but the key set comparison fails, causing the method to return False. This captures the requirement that the exact character set must be shared.

  • Strings containing repeated characters: The histogram correctly aggregates counts, and the sorted frequency comparison accounts for any number of repetitions, ensuring accurate evaluation.

Performance Optimizations

The implementation incorporates several choices that contribute to efficient execution:

  • Early termination on length mismatch eliminates the need for histogram construction when the strings cannot possibly be transformed, saving both time and memory.

  • Use of defaultdict(int) avoids explicit existence checks for each character during counting, reducing overhead in the inner loop.

  • Direct comparison of dictionary key views (f1.keys() == f2.keys()) leverages the fact that dictionary key views support set-like equality checks, providing a fast way to verify that the character sets match.

  • Sorting of frequency values is performed only once per string, and the resulting lists are compared directly. Since the number of distinct characters is bounded by the alphabet size (at most 26 for lowercase English letters), the sorting step operates on a small collection, keeping the overall cost low.

  • Avoidance of intermediate data structures beyond the necessary histograms and sorted lists keeps memory usage modest, especially for long input strings where the number of distinct characters remains limited.

written by openai gpt

ELI5 - Simplified Explanation

Imagine two boxes filled with colorful building blocks. The goal of this code is to check if these two boxes are essentially the same. First, the code counts how many blocks are in each box. If the boxes have a different number of blocks, they cannot be the same, so the answer is no. If they have the same number, the code starts looking closer. It makes a little list for each box to keep track of how many blocks of each color are inside. Once all the blocks are counted, the code compares the two lists. It checks that both boxes have the exact same set of colors. Then, it sorts the numbers of blocks from smallest to largest to see if the pattern of how many blocks there are of each color matches up perfectly. If the colors and the tallies line up, these two boxes are considered a match.

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 = 8 | μ = 7.37 | σ = 1.59

Complexity Analysis

not analyzed yet

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 Rust TS
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
MacJim C++
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
35 links | 23 authors | 9 languages

Videos

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

Similar Problems

3 similar problems

Solved On The Same Day

26 solutions   September 12, 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