DSA - 3

Modified on Tue, 28 Mar, 2023 at 4:52 PM

Why can’t we use shift() while implementing a Queue in JavaScript?

Do you understand the error?

We might fail perf-cases if we are using shift() to implement a queue in JavaScript, can we think why this causes a performance issue?

Where is the error occurring?

Can we check part of the code where we implemented the queue using shift()? How many times is this function being called?

Why do you think you are seeing this error? What might be causing it?

What does shift() do when you call it on an array? What will happen to the time complexity of code?

How to Debug this? To debug this issue, I would recommend the following steps:

When we use shift() to implement a queue the popping from the queue will take O(n) as the elements need to be shifted to left. You need to implement your own queue, with the functions to handle it. You can use a hashmap or array to implement the queue, so that these operations can be performed in O(1).

Resource: Queue Implementation in JS


Having a Stack underflow exception?

Do you understand the error?

The error says that we have an underflow exception, when do we have an underflow?

Where is the error occurring?

Can we check the error stack and go to the line where the error is occurring? What are we doing at that line? 

Why do you think you are seeing this error? What might be causing it?

Stack underflow occurs when we pop from an empty stack, how can we avoid this? 

How to Debug this? To debug this issue, I would recommend the following steps:

To solve this issue we can add a condition so we make sure that the stack is not empty before popping it. 


C++:

if(!st.empty()) {

    st.pop(); // st is name of the stack

  }


Java:

if(!st.empty()){

    st.pop(); // st is name of the stack

}


Python:

if len(st) > 0:

     st.pop() # st is name of the stack


JavaScript:

/* While JS does not give an error when popping, we will get an undefined value, so we need to check here as well */

if(st.length > 0){

    st.pop(); // st is name of the stack 

}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article