-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmock_interview1.js
117 lines (84 loc) · 2.47 KB
/
mock_interview1.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
[1, -5, 6, 10, 4, 8]
[6, 6, 10, -1, 8, -1]
// i = 0
// j = (i+ 1)%arr.length || (j < i )
// if(arr[i] < arr[j]) {max[i] = arr[j];break;};
arr = [10, 7, 4, 3, 2, 5, 8]
answer = [ 10 , 8 , 5, 5, 5 , 8 , 8]
stack =
7
8
function maxEleIndex(arr) {
let max = arr[0], index = 0;
for (let itr = 1; itr < arr.length; itr++) {
if(max < arr[itr]) {
max = arr[itr];
index = itr;
}
}
return index;
}
var nextGreaterElements = function(arr) {
if(arr.length == 1) [-1];
let nextGEArr = [];
let reverseStartingIndex = maxEleIndex(arr);
nextGEArr[reverseStartingIndex] = -1;
let stack = [arr[reverseStartingIndex]];
let itr = reverseStartingIndex -1 ;
while(itr != reverseStartingIndex ) {
let currentEle = arr[itr];
while(stack.length >= 1 && currentEle > stack[stack.length-1]){
stack.pop();
}
if(stack.length == 0) {
nextGEArr[itr] = -1;
stack.push(currentEle);
} else {
let stackEle = stack[stack.length-1]
nextGEArr[itr] = stackEle;
stack.push(currentEle);
}
if(itr == 0) itr = arr.length;
itr--
}
return nextGEArr;
};
function maxEleIndex(arr) {
let max = arr[0], index = 0;
for (let itr = 1; itr < arr.length; itr++) {
if(max < arr[itr]) {
max = arr[itr];
index = itr;
}
}
return index;
}
var nextGreaterElements = function(arr) {
if(arr.length == 1) [-1];
let nextGEArr = new Array(arr.length);
let reverseStartingIndex = maxEleIndex(arr);
nextGEArr[reverseStartingIndex] = -1;
let stack = [arr[reverseStartingIndex]];
let itr = reverseStartingIndex -1 ;
// console.log(arr)
// console.log(reverseStartingIndex)
while(itr != reverseStartingIndex ) {
let currentEle = arr[itr];
while(stack.length >= 1 && currentEle >= stack[stack.length-1]){
stack.pop();
}
if(stack.length == 0) {
nextGEArr[itr] = -1;
stack.push(currentEle);
} else {
let stackEle = stack[stack.length-1]
nextGEArr[itr] = stackEle;
stack.push(currentEle);
}
if(itr == 0) itr = arr.length;
itr--
// console.log(stack)
}
return nextGEArr;
};
//https://leetcode.com/problems/next-greater-element-ii/