Problem 503

Abstract / Summary

Given a circular array, find for each element the next greater element moving forward in the array.

Note

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

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
18 lines | 502 bytes | submitted August 14, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Monotonic Stack
  • Stack
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.31 | σ = 1.73

Complexity Analysis

Time: polynomial
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 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++
41 links | 27 authors | 9 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

20 solutions   August 14, 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