Problem 242

Abstract / Summary

Given two strings, determine if they contain exactly the same characters with the same frequency.

Note

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

C++ 0242.cpp

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};
8 lines | 174 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (9+ million submissions).

Typical patterns to solve this problem:
  • 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 Solution class with a single public member function isAnagram. The function receives two std::string objects, s and t, and determines whether they are anagrams of each other. The core strategy is to reorder the characters of each string into a canonical form by sorting, then compare the resulting sequences for equality. If the sorted strings match, the original inputs contain the same multiset of characters and are therefore anagrams.

Key Steps

The algorithm proceeds through three distinct operations, each expressed concisely in the source code.

Sorting the first string

sort(s.begin(), s.end());

The call to std::sort rearranges the characters of s in non-decreasing order. Because std::sort works in-place, no additional containers are allocated, and the original string is transformed directly.

Sorting the second string

sort(t.begin(), t.end());

A second invocation of std::sort applies the same ordering to t. After this step, both s and t share an identical ordering scheme, making a direct comparison meaningful.

Comparing the sorted strings

return s == t;

The equality operator for std::string performs a character-by-character check. If every position matches, the function returns true; otherwise it returns false. This single return statement encapsulates the final decision.

Edge Cases Handled

The implementation naturally accommodates several boundary conditions without additional code.

When both input strings are empty, the sorting operations are no-ops, and the equality comparison yields true, correctly indicating that two empty strings are anagrams.

If the strings differ in length, the sorting step still executes, but the subsequent equality check fails because the underlying buffers have different sizes. This handles mismatched lengths efficiently.

Repeated characters are preserved by the sorting process; identical multiplicities appear in the same positions after sorting, ensuring that strings like "aabb" and "bbaa" are recognized as anagrams.

The use of std::string means that any characters representable in the string’s encoding (typically UTF-8 bytes) are processed uniformly. The algorithm does not rely on locale-specific rules, so it treats all byte values consistently.

Performance Optimizations Observed

The code leverages the standard library’s std::sort, which implements introsort-a hybrid algorithm that combines quicksort, heapsort, and insertion sort. This choice provides robust performance across varied input distributions while maintaining in-place operation, minimizing memory overhead.

Sorting is performed directly on the original string buffers, avoiding the creation of temporary copies or auxiliary arrays. This in-place transformation reduces cache pressure and improves data locality, especially for short to medium-length strings that fit comfortably within CPU caches.

The final comparison uses the built-in operator== for std::string, which is highly optimized. It first checks the lengths of the two strings; a length mismatch leads to an immediate false result without scanning the character data. When lengths match, the operator proceeds with a memcmp-style byte comparison, taking advantage of word-size operations where possible.

By structuring the logic as a straight-line sequence of three statements, the function benefits from straightforward control flow, enabling the compiler to apply aggressive inlining and register allocation, further reducing call overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having two word boxes in front of you. Each box is filled with letter tiles that spell out a word. To see if the two words are secret twins, you first take all the tiles out of the first box and line them up in alphabetical order, just like a row of blocks. Then you do the exact same thing with the second box. Once everything is neat and lined up, you look at both rows side by side. If every single letter matches perfectly in the same spot, you know the words are made of the exact same puzzle pieces.

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 = 7 | μ = 7.15 | σ = 1.30

Complexity Analysis

Time: loglinear
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 C# C Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong TS
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong TypeScript
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
60 links | 42 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 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