Finding Next Greater Element in Python29 Aug 2024 | 9 min read In this problem, we will be given an array of integers, and we have to find the Next Greater Element for every element of each element of the array. The Next Greater Element is the first element on the right-hand side of the current element that is greater than the current element. For the elements of the array for which no greater element exists, we will return -1 for those elements. Let us see some examples to understand the problem. Input: array = [ 7, 3, 9, 12, 8 ] Output: 7 -> 9 3 -> 9 9 -> 12 12 -> -1 8 -> -1 The first element that is greater than 7 and is present on the right side of it is 9. Likewise, for every element except for 8 and 12, there exists a greater element on the right side of the element Input: arr = [ 19, 10, 7, 5, 13 ] Output: 19 -> -1 10 -> 13 7 -> 13 5 -> 13 13 -> -1 Except for 19, other elements have 13 as their greater counterparts. Approach - 1In this approach, we will use two for loops to iterate over the array. The outer loop will iterate over every element of the array. The inner loop will be responsible for finding the greater element for the current element. This loop will run over the rest of the loop on the right-hand side of the current element. If there is no greater element, we will print -1 for that element. We will follow the following steps to solve this problem:
Below is the Python code for the approach mentioned above. Code Output: 7 - 9 3 - 9 9 - 12 12 - -1 8 - -1 Time Complexity: Since we are using two loops in this approach, the time complexity of this approach is O(N2) Space Complexity: Since we are not creating any extra data structure, the space complexity of this approach is O(1). Approach - 2In this approach, we will use the stack data structure. In this approach, we will use the stack to store the elements for which we have to find the next greater element. When traversing the array, we will pair a greater element with the elements of the stack. We will continue the process until the stack's top element has a lesser value than the current element. We will follow the following steps to solve the problem using the approach mentioned above:
Below is the Python code for the approach mentioned above. Code Output: 3 - 9 7 - 9 9 - 12 8 - -1 12 - -1 Time Complexity: Since we are running a linear loop, the time complexity of this approach is O(N). Space Complexity: We have used an extra space to store the elements, i.e., the stack; hence the space complexity is O(N). Approach - 3In this new approach, we will use a map to find the NGE of the elements of the array. The approach is similar to the one we saw earlier. The difference in this method is that we will push and pop the elements from the stack only once. Also, the array will be changed in place. We will push the elements of the array in the stack until we find an element greater than the top element of the stack. Hence, we will pop the top element from the stack when we find an element smaller than the current array element. When all the array elements are visited, and the stack is still not empty, the rest of the stack elements do not have any NGE in the array. Hence, we will pop those elements from the stack and change the value at their index to -1 in the original array. Code Output: [9, 9, 12, -1, -1] Time Complexity: We are using a linear loop. Hence the time complexity is O(N). Space Complexity: The space complexity of this approach is O(N). We have used this space to store the stack and map. Approach - 4There is a better and more optimized approach to solving this problem. Let us now see that approach. Below are the steps to solve the problem using the optimized approach.
Code Output: [9, 9, 12, -1, -1] Time complexity: Since we traverse the element only once, the time complexity is O(N). This is the average time complexity; however, the worst time complexity can be O(N2) because we have a nested loop for some specific conditions. Space Complexity: Since we are not using any extra space to store the elements, the space complexity is constant, hence, O(1). |
In the following tutorial, we will learn about the finite automata algorithm used for searching patterns and discuss the method of implementing the algorithm in the Python programming language. But before we get started, let us understand what finite automata means. A Brief Introduction to Finite Automata Finite...
13 min read
When we get a huge number of datasets, then it will be quite beneficial to speed through the datasheet into an equal chance and then process each data frame on an individual basis. This will be only possible when the operation on the data frame is...
5 min read
Because Python accelerates the trading process, this method is known as automated or quantitative trading. Python's popularity is due to its powerful libraries, like Pyplot, TA-Lib, Scipy, NumPy, Zipline, Matplotlib, Pandas, etc. What is Automated Trading? Automated trading engages capital markets by executing pre-set procedures for accepting and...
13 min read
Introduction IDLE stands for Integrated Development and Learning Environment. The lightweight and user-friendly Python IDLE (Integrated Development and Learning Environment) is a tool for Python programming. Since version 1.5.2b1, the standard Python implementation has included IDLE, an integrated development environment. Many Linux distributions include it in the Python...
6 min read
"isna()" Function in Python The isna() method in Python is a robust data manipulation and analysis toolbox that is widely utilized while working with pandas. The isna() function finds missing or null values in a pandas DataFrame or Series. The usage of the isna() function in various scenarios...
3 min read
In this article, we will discuss how we can input a list in Python. But before discussion their methods, we must know about the list in Python. What is a List? A list is a built-in data structure provided by Python, which enables the organization and storage of...
6 min read
How to Design a Hashset in Python? As we know that HashSet is a famous class in Java. HashSet is used to store the values using a hash table. In this tutorial, we will cover HashSet in Python. We will also learn about how we can design...
8 min read
Introduction: In this tutorial, we are learning about the forward driver method in Selenium Python. The Selenium module is used for automatic testing using Python. Selenium Python bindings provide a simple API. Using Selenium WebDriver, this API is used to write functional or acceptance tests. A web...
3 min read
In this article, we discuss . A counter is a field that tracks how often equal values are added. The Python Counter elegance is part of the Collections module and a subclass of Dictionary. A listing or string handed as input returns the output as a dictionary,...
3 min read
Most of us have thought about why Python is growing so much rapidly when we compare it with other programming languages? Yes, Python indeed got famous in a very short span of time, and now we can see applications of Python in every field. And, yes,...
9 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India