Implementing Backward and Forward buttons of Browser
Design the forward and backward buttons of a Browser using Stack Data Structure. If at any instance, the URL does not exist after pressing any of the two buttons, then print “Not Available”. Otherwise, print the current URL.
Approach: The idea is to use two stacks backward and forward to keep track of visited URLs and a variable “currentStateURL” to store the currently visited URL. Follow the steps below to solve the problem:
- Initialize currentStateURL that will store the current URL of the Browser.
- Initialize two stacks forwardStack and backwardStack that will store the sequence of URLs accessed when the forward and the backward buttons are pressed respectively.
- While visiting any new URL, push it into backwardStack.
- While pressing the forward button push currentStateURL into backwardStack and pop the last URL from forwardStack and set it as currentStateURL.
- While pressing the backward button, push currentStateURL into forwardStack and pop the last URL from backwardStack, and set it as currentStateURL.
Below is the implementation of the above approach:
Current URL is: ajay.com Current URL is: abc.com Current URL after pressing Backward button is: ajay.com Current URL after pressing Forward button is: abc.com Current URL is: nikhil.com Not Available Current URL after pressing Forward button is: nikhil.com Current URL after pressing Backward button is: abc.com
Time Complexity: O(N).
Auxiliary Space: O(N).
My Personal Notes arrow_drop_up
Please Login to comment...