Best Time to Buy and Sell Stock β Complete LeetCode Solution with Sliding Window Pattern
Let BliniBot prep you for interviews
Try BliniBot FreeThe Best Time to Buy and Sell Stock problem is one of the most frequently tested coding interview questions and a perfect example of the Sliding Window pattern. Understanding this problem deeply will help you recognize and solve dozens of related problems that share the same underlying algorithmic structure. In this guide, we provide a complete walkthrough of the solution in both Python and TypeScript, explain the time and space complexity, discuss common variations, and show you how to recognize when to apply the Sliding Window pattern in new problems. Whether you are preparing for interviews at Google, Amazon, Meta, or any top tech company, mastering this fundamental pattern is essential. We start with the brute force approach to build intuition, then optimize step by step to arrive at the optimal solution. Each step is explained with the reasoning behind it so you can reproduce this thinking process in an actual interview rather than relying on memorization. The Sliding Window pattern appears in approximately 15 to 20 percent of all coding interview questions, making it one of the highest-leverage patterns to study thoroughly.
Problem Statement and Examples
Track the minimum price seen so far and the maximum profit at each step. The profit at any point is the current price minus the minimum price before it. This single-pass approach avoids checking all pairs. This problem is classified as Easy difficulty, though the Sliding Window technique it requires appears in problems across all difficulty levels. Understanding the core mechanic here unlocks solutions to many harder problems. Let us first examine what makes this problem well-suited for the Sliding Window approach: we need to process elements in a way that avoids redundant computation, and the Sliding Window pattern gives us exactly that efficiency. The brute force approach would check all possible combinations, resulting in O(n squared) or worse time complexity. The Sliding Window optimization reduces this dramatically by maintaining state intelligently as we traverse the input. Before coding, always verify your understanding by working through small examples by hand β this catches misunderstandings early and demonstrates thoroughness to your interviewer.
Python Solution
Here is the optimal Python solution using the Sliding Window pattern. Python's clean syntax makes the algorithm's logic easy to follow. Pay attention to how we initialize our data structures and handle edge cases before entering the main loop. The variable naming reflects the algorithmic concept to make the code self-documenting. In an interview, writing clean and readable code like this signals professionalism and attention to detail. Let us walk through the code line by line and understand why each decision was made.
def max_profit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profitTypeScript Solution
The TypeScript implementation uses the same algorithmic approach with proper type annotations. TypeScript's type system helps catch errors at compile time and makes the code more maintainable. Notice how the generic types and interfaces document the expected input and output formats. If your target company uses TypeScript (which is increasingly common in 2026), demonstrating fluency in typed solutions gives you an edge. The logic mirrors the Python solution exactly, so understanding one helps you write the other quickly.
function maxProfit(prices: number[]): number {
let minPrice = Infinity, maxProfit = 0;
for (const price of prices) {
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
}Have a question about Best Time to Buy and Sell Stock β Complete LeetCode Solution with Sliding Window Pattern?
Ask BliniBot βComplexity Analysis
Time complexity: O(n). Space complexity: O(1). Understanding complexity analysis is critical because interviewers almost always ask about it, and incorrect analysis can cost you the problem even if your code is correct. For time complexity, count how many times each element is processed β in the Sliding Window pattern, each element is typically visited a constant number of times, giving us linear time. For space complexity, consider the auxiliary data structures used beyond the input and output. In this solution, the space usage is O(1) because we only use a constant number of variables regardless of input size. When comparing approaches, an algorithm that is O(n) time and O(n) space is generally preferred over O(n log n) the and O(1) the for most interview contexts, since the complexity is usually the primary optimization target.
Ready to automate? BliniBot connects to 200+ tools.
Start Free TrialWhen to Use the Sliding Window Pattern
The Sliding Window pattern is applicable when you see these characteristics in a problem: the input involves a linear data structure (array, string, or linked list), you need to find or optimize something among contiguous or related elements, and a brute force approach would involve nested loops. Common signal words include "subarray," "substring," "consecutive," "contiguous," "minimum/maximum window," and "pair." Practice recognizing these signals across different problem phrasings. The Sliding Window pattern also combines well with other techniques: you might use Sliding Window as the outer strategy and binary search or hash maps as inner tools. Building this pattern recognition through deliberate practice is more effective than solving hundreds of random problems. Focus on understanding why the pattern works, not just how to apply it mechanically.
- Look for problems involving contiguous elements or subsequences in arrays and strings
- Check if brute force would require nested iteration that the Sliding Window can eliminate
- Consider whether maintaining running state eliminates recomputation
- Practice converting brute force to Sliding Window solutions to build intuition for the optimization step
Common Variations and Follow-ups
Interviewers frequently modify this problem to test deeper understanding. Common variations include: changing the constraint (find all pairs vs first pair, minimum vs maximum), modifying the input format (sorted vs unsorted, with duplicates vs without), adding constraints (in-place modification, space limit), or extending to higher dimensions (2D matrix version). For each variation, the core Sliding Window technique remains but the implementation details change. Practice at least 3 to 4 variations of every core problem to build the flexibility needed for interview success. When you encounter a variation in an interview, explicitly state how it differs from the base problem and how that difference affects your approach β this demonstrates depth of understanding that impresses interviewers. The Best Time to Buy and Sell Stock problem also frequently appears as a subproblem within harder questions, so understanding it thoroughly provides building blocks for tackling complex problems.
Key Takeaways
- 1.The Best Time to Buy and Sell Stock problem is best solved using the Sliding Window pattern with O(n) time complexity
- 2.Always start with brute force to build intuition before optimizing to the Sliding Window approach
- 3.Practice recognizing signal words that indicate when the Sliding Window pattern applies
- 4.Master both Python and TypeScript implementations since companies test in different languages
- 5.Understand complexity analysis deeply β interviewers expect you to justify your Big-O claims
Frequently Asked Questions
What is the optimal time complexity for Best Time to Buy and Sell Stock?
The optimal solution runs in O(n) time and O(1) space. The Sliding Window technique achieves this by processing each element a constant number of times, avoiding the nested iteration that a brute force approach would require. Any solution faster than this would need to skip elements, which risks missing the correct answer for this problem. In an interview, state the complexity clearly and be prepared to prove it by tracing through the algorithm with a sample input.
How do I recognize Sliding Window problems in interviews?
Look for these patterns: the problem involves a linear data structure, you need to find an optimal substructure or pair, and brute force would require quadratic time. Signal words include contiguous, subarray, substring, pair, window, and consecutive. The Sliding Window pattern is one of the most versatile techniques, appearing in approximately 15 to 20 percent of coding interviews. Practice identifying these signals in problem statements before reading the solution to build your pattern recognition ability.
Should I memorize the solution to Best Time to Buy and Sell Stock?
No. Memorization fails in interviews because interviewers modify problems to test understanding, not recall. Instead, understand why the Sliding Window approach works for this problem structure. Learn the pattern, practice applying it to multiple problems, and build the ability to derive solutions from first principles. If you understand the underlying mechanics, you can handle any variation the interviewer throws at you, which is exactly what they are testing.
What if I get stuck on Best Time to Buy and Sell Stock during an interview?
Start with the brute force approach and explain it clearly. Then analyze what makes it slow (usually redundant computation in nested loops). Ask yourself: what information from the previous iteration can I reuse? This naturally leads to the Sliding Window optimization. Communicate your thought process throughout β interviewers give credit for systematic problem-solving even if you do not reach the optimal solution immediately. Asking good clarifying questions and testing with examples also buys thinking time.
Related Articles
Research companies and their tech stacks before your next interview. Analyze top companies β
NexusBro helps developers catch bugs and SEO issues before they reach production. Try it free β
Automate your workflow with AI
14-day free trial. No charge today. Cancel anytime.
Start Free TrialReady to automate?
Join thousands of teams using BliniBot to automate repetitive tasks. Start free, upgrade anytime.