How to use the Stack Data Structure In Javascript
In this approach, we are using the Stack DS where we are iterating through the elements of the array and also we are maintaining the stack of the elements along with the index values, when the smaller element from the array is computed, it updates the next smaller element for the elements in the stack and then pushes the current element onto the stack. All the remaining elements in the array are then assigned a -1 value.
Example: This example implements the above mentioned approach
Javascript
function nextSmall(inputArray) { let inputArrayLength = inputArray.length; let outputElements = new Array(inputArrayLength); let stackVar = []; for (let i = 0; i < inputArrayLength; i++) { while ( stackVar.length > 0 && stackVar[stackVar.length - 1].value > inputArray[i] ) { let topOfStack = stackVar.pop(); outputElements[topOfStack.index] = inputArray[i]; } stackVar.push({ index: i, value: inputArray[i] }); } while (stackVar.length > 0) { let topOfStack = stackVar.pop(); outputElements[topOfStack.index] = -1; } return outputElements; } let inputArr1 = [11, 13, 21, 3]; let inputArr2 = [1, 2, 3, 4]; console.log(nextSmall(inputArr1).join( " " )); console.log(nextSmall(inputArr2).join( " " )); |
3 3 3 -1 -1 -1 -1 -1
JavaScript Program to Find Next Smaller Element
In this JavaScript article, we will see how we can find the next smaller elements from the first input Array. We have given the array in which we need to print the next smaller element. The next smaller element is an element that is present after the target element in the input array. For elements for which no next smaller elements are present then the -1 will be printed.
Examples:
Input: inputArray=[ 11, 13, 21, 3 ]
Output: 3 3 3 -1
Explanation:
For the rightmost element (3), the next smaller is always -1 since there are no elements to its right.
Element: 3 => -1
Now, let's find the ISE for each element:
Element: 11: The next smaller element to its right is 3.
Element: 13: The next smaller element to its right is 3.
Element: 21: The next smaller element to its right is 3.
Element: 3: The rightmost element, so ISE is -1.
For printing the next Smaller Element we have four different approaches in JavaScript language. We have mentioned these approaches below:
- Using Dynamic Programming Approach
- Using the Stack Data Structure approach
- Using the Reverse Iteration of the Elements approach
- Using the Array Map and Find approach
Contact Us