C++ 0028.cpp
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
Difficulty
and has an acceptance rate of about 47% (9+ million submissions).
Typical patterns to solve this problem:
- String
- String Matching
- Two Pointers
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single public member function strStr. The purpose of this function is to locate the first occurrence of the substring needle within the string haystack. It leverages the standard library’s std::string::find method to perform the search and directly returns the result as an integer.
Core Logic
The heart of the algorithm is a one-line call to find. The function receives two std::string parameters, haystack and needle, and forwards them to the library routine.
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
std::string::find scans haystack for the pattern needle and yields the index of the first match. If the pattern is not present, the function returns std::string::npos, which is a constant representing an invalid position. Because the return type of strStr is int, the npos value is implicitly converted to -1 when it does not fit within the range of a signed integer, thereby signaling “not found” in a conventional manner.
Edge Cases Handled
When needle is an empty string, the C++ standard specifies that find returns 0. This behavior aligns with the typical definition of substring search where an empty pattern is considered to be found at the start of any string. The implementation therefore correctly returns 0 for this scenario without any additional checks.
If needle is longer than haystack, find immediately determines that a match is impossible and returns npos. The conversion to int yields -1, indicating the absence of the substring.
When needle does not occur anywhere inside haystack, find again returns npos. The conversion to int produces -1, providing a clear sentinel value for “not found”.
The function also gracefully handles strings that contain embedded null characters because std::string stores size information separately from the character data. The find method operates on the stored length, so embedded nulls do not prematurely terminate the search.
Performance Optimizations
By delegating the search to std::string::find, the implementation benefits from the highly tuned algorithms present in the standard library. Modern C++ libraries often employ advanced techniques such as two-way string matching, Boyer-Moore-Horspool, or SIMD-accelerated scans, depending on the length of the pattern and the characteristics of the input. These internal optimizations are applied automatically without any extra code.
The direct return of the result avoids additional copying or temporary variables, keeping the call overhead minimal. The function signature passes the strings by value, which may trigger move semantics when the arguments are rvalues, reducing unnecessary allocations.
Overall, the code achieves an efficient search by relying on the standard library’s internal mechanisms, which are continuously refined by compiler and library maintainers.
ELI5 - Simplified Explanation
Imagine a giant box filled with blocks, where each block has a letter written on it in a long, straight row. This row of blocks is called a haystack. There is also a smaller group of blocks called a needle. The goal is to find where that small group of blocks first appears inside the long row. The code uses a special, fast tool built into the computer to look through the haystack. It slides along the row of blocks, checking if the group matches the needle. As soon as it spots the needle, it points to the very first block where the match begins. If the needle is not inside the haystack at all, it simply says that it could not be found.
Code Quality
Complexity Analysis
Other Solutions
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# | Rust | JS | Go | PHP | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||||
| Progiez | C++ | Python | Java | ||||||||||||
| github | aylei | Rust | |||||||||||||
| begeekmyfriend | C | ||||||||||||||
| BigEggStudy | C# | ||||||||||||||
| chandansgowda | Python | ||||||||||||||
| charles-wangkai | Java | ||||||||||||||
| Dijkstra-Edu | Java | ||||||||||||||
| DimitrisJim | C | ||||||||||||||
| everthis | JS | ||||||||||||||
| fartem | Ruby | ||||||||||||||
| fengvyi | C++ | ||||||||||||||
| gaosq0604 | Python | ||||||||||||||
| halfrost | Go | ||||||||||||||
| JoshCrozier | JS | ||||||||||||||
| lennylxx | C | ||||||||||||||
| linouk23 | C++ | ||||||||||||||
| lkwq007 | Python | ||||||||||||||
| MacJim | C++ | ||||||||||||||
| martianoff | Scala | ||||||||||||||
| muhammadfarhankt | Go | ||||||||||||||
| pruthvikp | Python | ||||||||||||||
| qiyuangong | Python | ||||||||||||||
| ruoru | Rust | ||||||||||||||
| Shamik07 | Dart | ||||||||||||||
| shreymehul | C# | ||||||||||||||
| sonugiri1043 | C++ | ||||||||||||||
| suxrobGM | C# | ||||||||||||||
| varunu28 | Java | ||||||||||||||
| vli02 | C | ||||||||||||||
| vthwang | Java | ||||||||||||||
| wisdompeak | C++ | ||||||||||||||
| XiaotaoGuo | C++ | ||||||||||||||
| yuanliu666 | Kotlin | ||||||||||||||
| zfang399 | C++ | ||||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | ||||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||||
| Progiez | C++, Java, Python | ||||||||||||||
| aylei | Rust | ||||||||||||||
| begeekmyfriend | C | ||||||||||||||
| BigEggStudy | C# | ||||||||||||||
| chandansgowda | Python | ||||||||||||||
| charles-wangkai | Java | ||||||||||||||
| Dijkstra-Edu | Java | ||||||||||||||
| DimitrisJim | C | ||||||||||||||
| everthis | JavaScript | ||||||||||||||
| fartem | Ruby | ||||||||||||||
| fengvyi | C++ | ||||||||||||||
| gaosq0604 | Python | ||||||||||||||
| halfrost | Go | ||||||||||||||
| JoshCrozier | JavaScript | ||||||||||||||
| lennylxx | C | ||||||||||||||
| linouk23 | C++ | ||||||||||||||
| lkwq007 | Python | ||||||||||||||
| MacJim | C++ | ||||||||||||||
| martianoff | Scala | ||||||||||||||
| muhammadfarhankt | Go | ||||||||||||||
| pruthvikp | Python | ||||||||||||||
| qiyuangong | Python | ||||||||||||||
| ruoru | Rust | ||||||||||||||
| Shamik07 | Dart | ||||||||||||||
| shreymehul | C# | ||||||||||||||
| sonugiri1043 | C++ | ||||||||||||||
| suxrobGM | C# | ||||||||||||||
| varunu28 | Java | ||||||||||||||
| vli02 | C | ||||||||||||||
| vthwang | Java | ||||||||||||||
| wisdompeak | C++ | ||||||||||||||
| XiaotaoGuo | C++ | ||||||||||||||
| yuanliu666 | Kotlin | ||||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 214: Shortest Palindrome
- problem 459: Repeated Substring Pattern
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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