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

0% completed

Vote For New Content
How do we know that we will need to start looking from the last index instead of starting from the beginning?

Priyanka B

Feb 14, 2024

I tried to solve this problem by iterating from the beginning, but couldn't solve it. How do we know that we will need to start looking from the last index instead of starting from the beginning?

1

0

Comments
Comments
Pradyumna Kubear
Pradyumna Kubeara year ago

From beginning I belive that you need to make use of 2 pointers first and the next and keep on iterating backward and forward, so it will be way more complex to code,

so maybe starting from back is more suitable in this scenario I guess

C
c.avina05 a year ago

This problem specifically benefits by going backwards because the last item in the array will have no greatest element. It will always be -1 in the last spot of the result array.

Aditya Agnihotri
Aditya Agnihotri8 months ago

My first hunch was to solve from the beginning too.

class Solution:     def nextLargerElement(self, arr):         res = [-1]*len(arr)         # ToDo: Write Your Code Here.         stack = []         for idx, val in enumerate(arr):             while stac...

On this page

Problem Statement

Examples

Solution:

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity