Problem 744

Abstract / Summary

Given a sorted list of letters and a target, find the smallest letter in the list that is larger than the target, wrapping around to the first letter if needed.

Note

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

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;
    }
};
10 lines | 263 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 59% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
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 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_bound will return an iterator to the first element, and the function returns that element directly.
  • Target Equal to an Element: Because upper_bound finds 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 returns letters[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.

written by openai gpt

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.

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 = 9 | μ = 8.85 | σ = 0.89

Complexity Analysis

Time: logarithmic
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++ 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++
42 links | 27 authors | 11 languages

Videos

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

Similar Problems

1 similar problem

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