Nutanix Interview Question
SDE-2sCountry: United States
There are some typos in the code. The last part where the stack is drawn down should be
while (!stack.isEmpty()) {
let j = stack.pop();
result[j][1] = nS.length - 1;
}
Here's what I'd do
for position
1 loop min from pos to 0(array index -1) and stop when array[min] becomes greater than array[pos](our given num) this will be the index at which our condition breaks so min+1 is in range where array[pos] is the largest num in range
2 similarly loop max from pos to array length, so when our condition breaks max-1 will contain the pos of the last number thats smaller than our given num
3 convert into our range that will be in [1 to array size] from machine index which will be in [0 to array size -1] by adding 1 to min+1 and max-1... which is min+2 and max
heres how the program goes
static int[] arr = {1, 5, 4, 3, 6};
public static void main(String[] args) {
for (int i = 0; i < arr.length; i++) {
printREIsMax(i);
}
}
private static void printREIsMax(int pos) {
int min = pos, max = pos;
while (min >= 0 && arr[min] <= arr[pos]) min--;
while (max < arr.length && arr[max] <= arr[pos]) max++;
System.out.println(arr[pos] + "[" + (min + 2) + "," + (max) + "]");
}
Just use a stack.
- xiongmao December 12, 2018