Today I´m going to share my first problem, its very cool problem and here it comes:
Nearest Smaller Element
From: InterviewBit
Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
More formally,
Elements for which no smaller element exist, consider next smaller element as -1.
Example:
Input :
Return :
Input :
Return :
Ideas:
-If we look at the value A[i-1] all the elements with i smaller and greater tan A[i-1] are not gonna work for G[i] so they are usless.
-Use the stack to put the lower values that can work with the G[i] , G[i+1]...
Solution:
Here I have the code for this problem in gitHub: https://github.com/AlexFaru/GoodCoding-/blob/master/Stacks%20&Queues/Nearest%20Smaller%20Element.txt
More formally,
G[i] for an element A[i] = an element A[j] such that
j is maximum possible AND
j < i AND
A[j] < A[i]
Example:
Input :
A : [4, 5, 2, 10, 8]Return :
[-1, 4, -1, 2, 2]
Example 2:Input :
A : [3, 2, 1]Return :
[-1, -1, -1]Ideas:
-If we look at the value A[i-1] all the elements with i smaller and greater tan A[i-1] are not gonna work for G[i] so they are usless.
-Use the stack to put the lower values that can work with the G[i] , G[i+1]...
Solution:
Here I have the code for this problem in gitHub: https://github.com/AlexFaru/GoodCoding-/blob/master/Stacks%20&Queues/Nearest%20Smaller%20Element.txt
