# Distance from Next Greater element

Given an array arr[] of size N, the task is to print the distance of every array element from its next greater element. For array elements having no next greater element, print 0.

Examples:

Input: arr[] = {73, 74, 75, 71, 69, 72, 76, 73}
Output: {1, 1, 4, 2, 1, 1, 0, 0}
Explanation:
The next greater element for 73 is 74, which is at position 1. Distance = 1 – 0 = 1
The next greater element for 74 is 75, which is at position 2. Distance = 2 – 1 = 1
The next greater element for 75 is 76, which is at position 6. Distance = 6 – 2 = 4
The next greater element for 71 is 72, which is at position 5. Distance = 5 – 3 = 2
The next greater element for 69 is 72, which is at position 5. Distance = 5 – 4 = 1
The next greater element for 72 is 76, which is at position 6. Distance = 6 – 5 = 1
No, next greater element for 76. Distance = 0
No, next greater element for 73. Distance = 0

Input: arr[] = {5, 4, 3, 2, 1}
Output: {0, 0, 0, 0, 0}

Naive Approach: The simplest approach is to traverse the array and for every array element, traverse to its right to obtain its next greater element and calculate the difference between the indices.

Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use Stack to find the next greater element.
Below are the steps:

1. Maintain a Stack which will contain the elements in non-increasing order.
2. Check if the current element arr[i]is greater than the element at the top of the stack.
3. Keep popping all the elements from the stack one by one from the top, that are found to be smaller than arr[i] and calculate the distance for each of them as the difference of current index and the index of the popped element.
4. Push the current element into the stack and repeat the above steps.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the ` `// above approach ` `#include` `using` `namespace` `std;`   `vector<``int``> mindistance(vector<``int``> arr)` `{` `    ``int` `N = arr.size();` `    `  `    ``// Stores the required distances ` `    ``vector<``int``> ans(N);` `    ``int` `st = 0;` `    `  `    ``// Maintain a stack of elements ` `    ``// in non-increasing order ` `    ``for``(``int` `i = 0; i < N - 1; i++)` `    ``{` `        ``if` `(arr[i] < arr[i + 1])` `        ``{` `            ``ans[i] = 1;` `        ``}` `        ``else` `        ``{` `            ``st = i + 1;` `            ``while` `(st <= N - 1)` `            ``{` `                ``if` `(arr[i] < arr[st]) ` `                ``{` `                    ``ans[i] = st - i;` `                    ``break``;` `                ``}` `                ``else` `                ``{` `                    ``st++;` `                ``}` `            ``}` `        ``}` `    ``}` `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``vector<``int``> arr = { 73, 74, 75, 71, ` `                        ``69, 72, 76, 73 };` `    `  `    ``vector<``int``> x = mindistance(arr);` `    `  `    ``cout << ``"["``;` `    ``for``(``int` `i = 0; i < x.size(); i++)` `    ``{` `        ``if` `(i == x.size() - 1)` `            ``cout << x[i];` `        ``else` `          ``cout << x[i] << ``", "``;` `    ``}` `    ``cout << ``"]"``;` `}`   `// This code is contributed by SURENDRA_GANGWAR`

## Java

 `// Java implementation of the ` `// above approach ` `import` `java.io.*;`   `class` `GFG{` `    `  `public` `static` `int``[] mindistance(``int``[] arr)` `{` `    ``int` `N = arr.length;` `    `  `    ``// Stores the required distances ` `    ``int``[] ans = ``new` `int``[N];` `    ``int` `st = ``0``;` `    `  `    ``// Maintain a stack of elements ` `    ``// in non-increasing order ` `    ``for``(``int` `i = ``0``; i < N - ``1``; i++)` `    ``{` `        ``if` `(arr[i] < arr[i + ``1``])` `        ``{` `            ``ans[i] = ``1``;` `        ``}` `        ``else` `        ``{` `            ``st = i + ``1``;` `            ``while` `(st <= N - ``1``)` `            ``{` `                ``if` `(arr[i] < arr[st]) ` `                ``{` `                    ``ans[i] = st - i;` `                    ``break``;` `                ``}` `                ``else` `                ``{` `                    ``st++;` `                ``}` `            ``}` `        ``}` `    ``}` `    ``return` `ans;` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    ``int` `arr[] = ``new` `int``[]{ ``73``, ``74``, ``75``, ``71``, ` `                           ``69``, ``72``, ``76``, ``73` `};` `    `  `    ``int` `x[] = mindistance(arr);` `    `  `    ``System.out.print(``"["``);` `    ``for``(``int` `i = ``0``; i < x.length; i++)` `        ``System.out.print(x[i]+``", "``);` `        `  `    ``System.out.print(``"]"``);` `}` `}`   `// This code is contributed by sai-sampath mahajan` `// and ramprasad kondoju`

## Python3

 `# Python3 implementation of the` `# above approach`   `def` `mindistance(arr, N): ` `    `  `    ``if` `N <``=` `1``:` `        ``return` `[``0``]` `      `  `    ``# Stores the required distances` `    ``ans ``=` `[``0` `for` `i ``in` `range``(N)]` `    ``st ``=` `[``0``]` `    `  `    ``# Maintain a stack of elements` `    ``# in non-increasing order` `    ``for` `i ``in` `range``(``1``, N):  ` `        `  `        ``# If the current element exceeds ` `        ``# the element at the top of the stack` `        ``while``(st ``and` `arr[i] > arr[st[``-``1``]]):  ` `            ``pos ``=` `st.pop()` `            ``ans[pos] ``=` `i ``-` `pos` `            `  `        ``# Push the current index to the stack` `        ``st.append(i)`   `    ``return` `ans`   `# Given array` `arr ``=` `[``73``, ``74``, ``75``, ``71``, ``69``, ``72``, ``76``, ``73``]` `N ``=` `len``(arr)`   `# Function call` `print``(mindistance(arr, N))`

Output:

```[1, 1, 4, 2, 1, 1, 0, 0]

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.