Next Smaller Element
You are given an array 'ARR' of integers of length N. Your task is to find the next smaller element for each of the array elements.
Next Smaller Element for an array element is the first element to the right of that element which has a value strictly smaller than that element.
If for any array element the next smaller element does not exist, you should print -1 for that array element.
For Example:
If the given array is [ 2, 3, 1], we need to return [1, 1, -1]. Because for 2, 1 is the Next Smaller element. For 3, 1 is the Next Smaller element and for 1, there is no next smaller element hence the answer for this element is -1.
Input Format:
The first line of input contains an integer ‘T’ which contains the number of test cases.
The first line of each test case contains an integer 'N' denoting the number of elements in the array 'ARR'.
The second line of each test case contains 'N' space-separated integers denoting the array 'ARR'.
Output Format:
For each test case, print a single line containing 'N' space-separated integers denoting the value of Next Smaller Element for each of the 'N' array elements.
The output for each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10 ^ 5
0 <= ARR [i] <= 10 ^ 9
Time Limit: 1sec.
CodingNinjas
author
2y
I used stack to solve this problem. Here we maintain items in increasing order in the stack (instead of decreasing in next greater element problem).
Push the first element to stack.
Pick rest of the ele...read more
CodingNinjas
author
2y
Brute Force Approach
The idea is to find the Next Smaller Element for each array element one by one. To find the Next Smaller for an array element we will start moving to the right of that element and ...read more
CodingNinjas
author
2y
Optimized Approach using Stack
The idea is to find the Next Smaller Element for each of the N array elements in one iteration of the array by using a stack. Our approach is to traverse the array from r...read more
Add answer anonymously...
Top Walmart Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app