Python 0503.py
lass Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
size = len(nums)
result = []
for i in range(size):
found = False
for j in range(1, size):
pos = (i + j) % size
if nums[pos] > nums[i]:
result.append(nums[pos])
found = True
break
if not found:
result.append(-1)
return result
Difficulty
and has an acceptance rate of about 68% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Monotonic Stack
- Stack
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 method nextGreaterElements that receives a list of integers and returns a new list where each position contains the first greater element encountered when traversing the array circularly. If no greater element exists for a given position, the method records -1. The algorithm iterates over each element, then scans forward through the circular array until it either finds a larger value or exhausts all possibilities.
Key Steps
The method begins by determining the length of the input list, storing it in size. This value is used throughout the loops to control iteration bounds and to compute circular indices.
size = len(nums)
An empty list result is created to accumulate the answers for each index.
result = []
The outer loop walks through every index i of the input list. For each i, a flag found is initialized to False. This flag tracks whether a greater element has been located during the inner scan.
for i in range(size):
found = False
Inside the outer loop, the inner loop iterates over offsets j ranging from 1 up to size - 1. The offset j represents how far ahead of the current index we look, wrapping around the array using the modulo operator. The computed position pos is the candidate index to compare against the current element nums[i].
for j in range(1, size):
pos = (i + j) % size
A comparison checks whether the element at pos exceeds the element at i. When a larger value is found, it is appended to result, the found flag is set to True, and the inner loop terminates early via break. This early exit prevents unnecessary checks once the next greater element is identified.
if nums[pos] > nums[i]:
result.append(nums[pos])
found = True
break
If the inner loop completes without setting found to True, the algorithm appends -1 to indicate the absence of a greater element for the current index.
if not found:
result.append(-1)
Finally, after processing all indices, the method returns the populated result list.
return result
Edge Cases
The code gracefully handles the scenario where the input list contains a single element. In that case, size equals 1, the inner loop range becomes empty, and the found flag remains False. Consequently, the method appends -1, correctly indicating that no greater element exists in a circular context.
When the input list includes duplicate values, the comparison nums[pos] > nums[i] ensures that only strictly larger elements are considered as candidates. Therefore, equal values are ignored, and the algorithm continues searching until a strictly greater element is encountered or the full circle is traversed.
If the input list is empty, size evaluates to 0. The outer loop does not execute, leaving result empty, and the method returns an empty list, which aligns with the expectation for an empty input.
Performance Optimizations
The implementation incorporates an early-exit mechanism inside the inner loop. As soon as a greater element is found for a particular index, the break statement stops further scanning, reducing the number of comparisons for that index. This optimization is particularly effective when larger elements appear soon after the current position, avoiding a full circular scan.
The use of the modulo operator (i + j) % size enables a seamless circular traversal without the need for additional data structures or explicit array duplication. By computing the wrapped index on the fly, the algorithm maintains a compact memory footprint while still achieving the required circular behavior.
ELI5 - Simplified Explanation
Imagine you have a long line of numbered cards laid out in a circle on the floor. The goal is to look at each card one by one and find the very next card in the circle that has a bigger number written on it.
The code starts by checking how many cards are in the circle. It walks through every card in order, starting from the first one. For each card, it begins looking at the next card in the circle, then the next one after that, and so on, moving all the way around toward the start if necessary.
As it looks at these other cards, it keeps a close watch to see if any of them are larger than the card currently being held. The moment it finds a bigger number, that number is written down as the answer for the current card. If it goes all the way around the entire circle and still cannot find any number bigger than the one held, it writes down a minus one to show that no larger card exists. This happens for every single card until the entire circle has been checked.
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 | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 496: Next Greater Element I
- problem 556: Next Greater Element III
Solved On The Same Day
- problem 455: Assign Cookies
- problem 500: Keyboard Row
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1071: Greatest Common Divisor of Strings
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1748: Sum of Unique Elements
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 216: Combination Sum III
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 470: Implement Rand10() Using Rand7()
- problem 556: Next Greater Element III
- problem 622: Design Circular Queue
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
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