-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathNearestSmallestElement.java
More file actions
74 lines (60 loc) · 1.89 KB
/
NearestSmallestElement.java
File metadata and controls
74 lines (60 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
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,
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]
Elements for which no smaller element exist, consider next smaller element as -1.
Input Format
The only argument given is integer array A.
Output Format
Return the integar array G such that G[i] contains nearest smaller number than A[i].If no such element occurs G[i] should be -1.
For Example
Input 1:
A = [4, 5, 2, 10, 8]
Output 1:
G = [-1, 4, -1, 2, 2]
Explaination 1:
index 1: No element less than 4 in left of 4, G[1] = -1
index 2: A[1] is only element less than A[2], G[2] = A[1]
index 3: No element less than 2 in left of 2, G[3] = -1
index 4: A[3] is nearest element which is less than A[4], G[4] = A[3]
index 4: A[3] is nearest element which is less than A[5], G[5] = A[3]
Input 2:
A = [3, 2, 1]
Output 2:
[-1, -1, -1]
Explaination 2:
index 1: No element less than 3 in left of 3, G[1] = -1
index 2: No element less than 2 in left of 2, G[2] = -1
index 3: No element less than 1 in left of 1, G[3] = -1
**/
public class Solution
{
public int[] prevSmaller(int[] A)
{
int[] solution = new int[A.length];
Stack<Integer> stack = new Stack<Integer>();
stack.push(A[0]);
solution[0] = -1;
//Arrays.fill(solution, -1);
for(int i=1; i<A.length; i++)
{
while(!stack.isEmpty() && (stack.peek() >= A[i]))
{
stack.pop();
}
if(stack.isEmpty())
{
solution[i] = -1;
}
else
{
solution[i] = stack.peek();
}
stack.push(A[i]);
}
return solution;
}
}