LeetCode 1472: Design Browser History Solution
Master LeetCode problem 1472 (Design Browser History), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1472. Design Browser History
Problem Explanation
Explanation
To solve this problem, we can use a list to keep track of the visited URLs. We also need to maintain an index to represent the current position in the history. When a new URL is visited, we add it to the list and update the index. When moving back or forward in history, we adjust the index accordingly.
Algorithm:
- Initialize a list to store visited URLs and an integer index to keep track of the current position in the history.
- Initialize the BrowserHistory class with the homepage by adding it to the list and setting the index to 0.
- When visiting a new URL, clear all entries after the current index, add the new URL to the list, and update the index.
- When moving back in history, decrement the index by the specified number of steps but ensure it stays within bounds.
- When moving forward in history, increment the index by the specified number of steps but ensure it stays within bounds.
Time Complexity:
- Visiting a URL, moving back, or moving forward: O(1)
- Overall space complexity: O(n), where n is the total number of visited URLs
Solution Code
class BrowserHistory {
List<String> history;
int index;
public BrowserHistory(String homepage) {
history = new ArrayList<>();
history.add(homepage);
index = 0;
}
public void visit(String url) {
while (history.size() > index + 1) {
history.remove(history.size() - 1);
}
history.add(url);
index++;
}
public String back(int steps) {
index = Math.max(0, index - steps);
return history.get(index);
}
public String forward(int steps) {
index = Math.min(history.size() - 1, index + steps);
return history.get(index);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1472 (Design Browser History)?
This page provides optimized solutions for LeetCode problem 1472 (Design Browser History) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1472 (Design Browser History)?
The time complexity for LeetCode 1472 (Design Browser History) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1472 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1472 in Java, C++, or Python.