Browser History (Back and Forward)
Problem
A browser starts on the page home. Commands: visit url goes to a new page and forgets all forward pages; back goes to the previous page (nothing happens if there is none); forward goes to the page you came back from (nothing happens if there is none). After every command print the current page. Use two stacks: one for the pages behind you and one for the pages ahead.
Constraints
- 1 <= commands <= 10^5
Examples
Input
visit a visit b back forward
Output
a b a b
Solutions
Two stacks model any undo-redo style history: moving between them keeps the order right. A new visit clears the 'ahead' stack, because the old future no longer exists. Java's ArrayDeque is the recommended stack; the old Stack class is slow and out of date.
/*
* Problem : Process lines.
* Input : Several lines.
* Output : The current page after each command.
* Approach: Two stacks.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
// Step 1: "behind" holds the pages we can go back to. "ahead" holds the pages we can go forward to.
java.util.ArrayDeque<String> behind = new java.util.ArrayDeque<>();
java.util.ArrayDeque<String> ahead = new java.util.ArrayDeque<>();
String current = "home";
String[] output = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
String[] part = lines[i].split(" ");
if (part[0].equals("visit")) {
// Step 2: A new page clears the forward history, like in a real browser.
behind.push(current);
current = part[1];
ahead.clear();
} else if (part[0].equals("back") && !behind.isEmpty()) {
// Step 3: Going back moves the current page to the "ahead" stack.
ahead.push(current);
current = behind.pop();
} else if (part[0].equals("forward") && !ahead.isEmpty()) {
behind.push(current);
current = ahead.pop();
}
output[i] = current;
}
return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (1)
- Why must visit clear the forward stack?