Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - Check if an array is stack-sortable

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The logic is not correct, as already mentioned in the comments, you cannot just push and then pop.

The easiest way is to always push if the number is not matching and if it is a match then pop as many values as possible:

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++
           while (stack.length > 0 && stack[stack.length - 1] == array[idx]) {
               idx++
               stack.pop()
           }
        }
    }
    return idx == array.length
}

console.log(solution([1,3,2]))
console.log(solution([3,1,2]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...