Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
ASHWIN SHIRVA
Time complexity in solution is wrong?

ASHWIN SHIRVA

Jul 11, 2024

I think the stack solution has a time complexity of O(n^2) in the worst case.

Consider this input: [4, 1, 2, 3, 5]

If we start from the end of the array, by the time we reach 0th index, the stack would have the following elements:

1

2

3

5

So as we compare the current element 4 with the top element in stack we would end up popping all 1, 2, 3. We have to pop till 5 to get next greater element to 4. So, our inner loop ends up running 4 times (for elements 1, 2, 3, 5 in stack) for our array arr of size 5 in this case. Therefore I believe the worst case time complexity must be O(n^2).

1

0

Comments
Comments
Shubham Vora
Shubham Voraa year ago

The time complexity of the stack solution is actually O(n), not O(n^2).

Here's why: Each element is pushed and popped from the stack at most once. Although it might seem like popping multiple elements could lead to O(n^2) complexity, each element only enters and...

On this page

Problem Statement

Examples

Solution:

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity