Here is the question:
We want to rearrange a sorted array [1, ..., N] using a stack.
Ex:
* push 1 then pop 1.
* push 2 then push 3 then pop twice and get 3 then 2.
Then we can get [1,3,2] from [1,2,3]
Check if we can get the given array by rearranging the sorted array (ascending order) using a stack.
Limitation:
* 0 < The size of the given array (N) <= 100,000
* 1 <= The items of the given array <= N
* No duplicates inside the given array
Test cases:
* [1, 3, 2]: true
* [3,1,2]: false
I wanted to know what I am missing from the code below. The following code fails on some test cases:
function solution(array) {
const stack = [];
let idx = 0;
for (let i = 1; i <= array.length; i++) {
if (i !== array[idx]) {
stack.push(i);
} else {
idx++;
}
}
for (idx; idx < array.length; idx++) {
let item = stack.pop();
if (item !== array[idx]) {
return false;
}
}
return true;
}
Many thanks!
question from:
https://stackoverflow.com/questions/65879572/check-if-an-array-is-stack-sortable 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…