C++ 0744.cpp
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
auto i = upper_bound(letters.begin(), letters.end(), target);
if (i == letters.end())
return letters[0];
return *i;
}
};
Difficulty
and has an acceptance rate of about 59% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
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 solves the problem of finding the smallest character in a sorted array that is strictly greater than a given target character. It leverages the C++ Standard Library algorithm upper_bound to perform a binary search on the input vector, guaranteeing logarithmic search time. The function also correctly wraps around to the first element when the target is greater than or equal to all elements in the array.
Key Steps
The core logic consists of three distinct operations: invoking the binary search, handling the wrap-around case, and returning the result.
Binary Search with upper_bound
auto i = upper_bound(letters.begin(), letters.end(), target);
upper_bound receives the beginning and end iterators of the sorted vector letters along with the target character. It returns an iterator pointing to the first element that is greater than target. Because the vector is sorted, this operation runs in O(log n) time, where n is the number of characters.
Wrap-Around Detection
if (i == letters.end())
return letters[0];
If upper_bound reaches the end of the container, it means every element in letters is less than or equal to target. In this situation the specification requires returning the smallest element, which is the first element of the sorted vector. The code checks for this condition and returns letters[0] accordingly.
Returning the Found Character
return *i;
When the iterator i is not at the end, it points to the smallest character that exceeds target. Dereferencing the iterator yields the desired result, which is then returned to the caller.
Edge Cases Handled
The algorithm gracefully manages several boundary conditions:
- Target Smaller Than All Elements:
upper_boundwill return an iterator to the first element, and the function returns that element directly. - Target Equal to an Element: Because
upper_boundfinds the first element greater than the target, it skips any duplicates of the target and returns the next distinct character. - Target Larger Than All Elements: The iterator reaches
letters.end(), triggering the wrap-around branch that returnsletters[0]. - Single-Element Vector: Whether the target is less than, equal to, or greater than the sole character, the logic still returns the correct character, either the element itself or the same element after wrap-around.
Performance Optimizations
The implementation relies on the highly optimized upper_bound algorithm provided by the C++ Standard Library. This algorithm is typically implemented with a tight loop and branch prediction friendly comparisons, minimizing overhead compared to a manual binary search. By using iterators directly, the code avoids unnecessary copying of elements. The early exit when the iterator equals letters.end() prevents an extra dereference, ensuring the function returns as soon as the wrap-around condition is detected. Overall, the solution achieves optimal search performance for a sorted container without additional memory allocation.
ELI5 - Simplified Explanation
Imagine a row of alphabet cards laid out on the floor in order. Some letters are the same, and some are different, but they are all lined up just like a parade. You have a special letter in your hand, and the goal is to find the very next letter in the line that is bigger than the one you are holding.
Think of the code as a helper searching through the cards. It starts at the beginning and marches forward until it finds a letter that is strictly larger than your target. When it spots that bigger letter, it stops and points right at it.
Sometimes, the target letter is larger than everything in the parade. If the helper searches all the way to the end and cannot find a bigger letter, it simply trots back to the very first card at the start of the line and picks that one instead. It is like a circle where the end loops back around to the beginning.
Code Quality
Complexity Analysis
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
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++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | PHP | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- 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 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