Skip to content

Commit 51b8730

Browse files
feat: add NeetCode 150 - Sliding Window category with complete solutions
- Added 6 problems from Sliding Window category: - Best Time to Buy and Sell Stock - Longest Substring Without Repeating Characters - Longest Repeating Character Replacement - Permutation in String - Minimum Window Substring - Sliding Window Maximum - Each problem includes: - Comprehensive explanation with approach, algorithm, and insights - Solutions in Java, JavaScript, and Python - Multiple approaches and optimizations - Edge cases and applications - Time and space complexity analysis - Sliding Window technique patterns: - Fixed window size (Permutation in String, Sliding Window Maximum) - Variable window size (Longest Substring, Minimum Window Substring) - Optimization problems (Best Time to Buy and Sell Stock) - Character frequency tracking (Longest Repeating Character Replacement)
1 parent ae1ea74 commit 51b8730

File tree

24 files changed

+2214
-0
lines changed

24 files changed

+2214
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Best Time to Buy and Sell Stock
2+
3+
## Problem Statement
4+
5+
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
6+
7+
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
8+
9+
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return `0`.
10+
11+
## Examples
12+
13+
**Example 1:**
14+
```
15+
Input: prices = [7,1,5,3,6,4]
16+
Output: 5
17+
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
18+
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
19+
```
20+
21+
**Example 2:**
22+
```
23+
Input: prices = [7,6,4,3,1]
24+
Output: 0
25+
Explanation: In this case, no transactions are done and the max profit = 0.
26+
```
27+
28+
## Approach
29+
30+
### Method 1: One Pass (Recommended)
31+
1. Keep track of minimum price seen so far
32+
2. For each day, calculate profit if we sell today
33+
3. Update maximum profit if current profit is better
34+
35+
**Time Complexity:** O(n) - Single pass through the array
36+
**Space Complexity:** O(1) - Only using two variables
37+
38+
### Method 2: Brute Force
39+
1. Check all possible buy-sell pairs
40+
2. Return maximum profit
41+
42+
**Time Complexity:** O(n²) - Nested loops
43+
**Space Complexity:** O(1) - No extra space
44+
45+
## Algorithm
46+
47+
```
48+
1. Initialize minPrice = prices[0], maxProfit = 0
49+
2. For each price in prices:
50+
a. Update minPrice = min(minPrice, price)
51+
b. Calculate profit = price - minPrice
52+
c. Update maxProfit = max(maxProfit, profit)
53+
3. Return maxProfit
54+
```
55+
56+
## Key Insights
57+
58+
- **One Pass**: Can solve in single iteration
59+
- **Minimum Tracking**: Keep track of lowest price seen
60+
- **Greedy Strategy**: Always consider selling at current price
61+
- **No Future Knowledge**: Can only use past and current information
62+
63+
## Alternative Approaches
64+
65+
1. **Brute Force**: Check all pairs - O(n²) time
66+
2. **Dynamic Programming**: More complex state tracking
67+
3. **Divide and Conquer**: Recursive approach
68+
69+
## Edge Cases
70+
71+
- Empty array: Return 0
72+
- Single element: Return 0
73+
- Decreasing prices: Return 0
74+
- All same prices: Return 0
75+
- Single transaction: Only one buy-sell pair
76+
77+
## Applications
78+
79+
- Financial analysis
80+
- Algorithm design patterns
81+
- Interview preparation
82+
- Trading algorithms
83+
- Optimization problems
84+
85+
## Optimization Opportunities
86+
87+
- **Single Pass**: Most efficient approach
88+
- **Early Exit**: Stop if no profit possible
89+
- **Memory Efficient**: O(1) space solution
90+
- **Greedy Choice**: Always consider current day for selling
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Time Complexity: O(n) - Single pass through the array
3+
* Space Complexity: O(1) - Only using two variables
4+
*/
5+
class Solution {
6+
public int maxProfit(int[] prices) {
7+
if (prices.length == 0) return 0;
8+
9+
int minPrice = prices[0];
10+
int maxProfit = 0;
11+
12+
for (int i = 1; i < prices.length; i++) {
13+
// Update minimum price seen so far
14+
minPrice = Math.min(minPrice, prices[i]);
15+
16+
// Calculate profit if we sell today
17+
int profit = prices[i] - minPrice;
18+
19+
// Update maximum profit
20+
maxProfit = Math.max(maxProfit, profit);
21+
}
22+
23+
return maxProfit;
24+
}
25+
}
26+
27+
// Alternative approach using brute force
28+
class SolutionBruteForce {
29+
public int maxProfit(int[] prices) {
30+
int maxProfit = 0;
31+
32+
for (int i = 0; i < prices.length; i++) {
33+
for (int j = i + 1; j < prices.length; j++) {
34+
int profit = prices[j] - prices[i];
35+
maxProfit = Math.max(maxProfit, profit);
36+
}
37+
}
38+
39+
return maxProfit;
40+
}
41+
}
42+
43+
// More concise version
44+
class SolutionConcise {
45+
public int maxProfit(int[] prices) {
46+
int minPrice = Integer.MAX_VALUE;
47+
int maxProfit = 0;
48+
49+
for (int price : prices) {
50+
minPrice = Math.min(minPrice, price);
51+
maxProfit = Math.max(maxProfit, price - minPrice);
52+
}
53+
54+
return maxProfit;
55+
}
56+
}
57+
58+
// Using streams for functional approach
59+
class SolutionStreams {
60+
public int maxProfit(int[] prices) {
61+
if (prices.length == 0) return 0;
62+
63+
int minPrice = prices[0];
64+
return Arrays.stream(prices)
65+
.skip(1)
66+
.map(price -> {
67+
minPrice = Math.min(minPrice, price);
68+
return price - minPrice;
69+
})
70+
.max()
71+
.orElse(0);
72+
}
73+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Time Complexity: O(n) - Single pass through the array
3+
* Space Complexity: O(1) - Only using two variables
4+
*/
5+
var maxProfit = function(prices) {
6+
if (prices.length === 0) return 0;
7+
8+
let minPrice = prices[0];
9+
let maxProfit = 0;
10+
11+
for (let i = 1; i < prices.length; i++) {
12+
// Update minimum price seen so far
13+
minPrice = Math.min(minPrice, prices[i]);
14+
15+
// Calculate profit if we sell today
16+
const profit = prices[i] - minPrice;
17+
18+
// Update maximum profit
19+
maxProfit = Math.max(maxProfit, profit);
20+
}
21+
22+
return maxProfit;
23+
};
24+
25+
// Alternative approach using brute force
26+
var maxProfitBruteForce = function(prices) {
27+
let maxProfit = 0;
28+
29+
for (let i = 0; i < prices.length; i++) {
30+
for (let j = i + 1; j < prices.length; j++) {
31+
const profit = prices[j] - prices[i];
32+
maxProfit = Math.max(maxProfit, profit);
33+
}
34+
}
35+
36+
return maxProfit;
37+
};
38+
39+
// More concise version
40+
var maxProfitConcise = function(prices) {
41+
let minPrice = Infinity;
42+
let maxProfit = 0;
43+
44+
for (const price of prices) {
45+
minPrice = Math.min(minPrice, price);
46+
maxProfit = Math.max(maxProfit, price - minPrice);
47+
}
48+
49+
return maxProfit;
50+
};
51+
52+
// Using reduce for functional approach
53+
var maxProfitFunctional = function(prices) {
54+
if (prices.length === 0) return 0;
55+
56+
let minPrice = prices[0];
57+
return prices.slice(1).reduce((maxProfit, price) => {
58+
minPrice = Math.min(minPrice, price);
59+
return Math.max(maxProfit, price - minPrice);
60+
}, 0);
61+
};
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""
2+
Time Complexity: O(n) - Single pass through the array
3+
Space Complexity: O(1) - Only using two variables
4+
"""
5+
class Solution:
6+
def maxProfit(self, prices: List[int]) -> int:
7+
if not prices:
8+
return 0
9+
10+
min_price = prices[0]
11+
max_profit = 0
12+
13+
for i in range(1, len(prices)):
14+
# Update minimum price seen so far
15+
min_price = min(min_price, prices[i])
16+
17+
# Calculate profit if we sell today
18+
profit = prices[i] - min_price
19+
20+
# Update maximum profit
21+
max_profit = max(max_profit, profit)
22+
23+
return max_profit
24+
25+
# Alternative approach using brute force
26+
class SolutionBruteForce:
27+
def maxProfit(self, prices: List[int]) -> int:
28+
max_profit = 0
29+
30+
for i in range(len(prices)):
31+
for j in range(i + 1, len(prices)):
32+
profit = prices[j] - prices[i]
33+
max_profit = max(max_profit, profit)
34+
35+
return max_profit
36+
37+
# More concise version
38+
class SolutionConcise:
39+
def maxProfit(self, prices: List[int]) -> int:
40+
min_price = float('inf')
41+
max_profit = 0
42+
43+
for price in prices:
44+
min_price = min(min_price, price)
45+
max_profit = max(max_profit, price - min_price)
46+
47+
return max_profit
48+
49+
# Using enumerate for more Pythonic approach
50+
class SolutionPythonic:
51+
def maxProfit(self, prices: List[int]) -> int:
52+
if not prices:
53+
return 0
54+
55+
min_price = prices[0]
56+
max_profit = 0
57+
58+
for price in prices[1:]:
59+
min_price = min(min_price, price)
60+
max_profit = max(max_profit, price - min_price)
61+
62+
return max_profit
63+
64+
# One-liner using reduce
65+
from functools import reduce
66+
67+
class SolutionOneLiner:
68+
def maxProfit(self, prices: List[int]) -> int:
69+
return reduce(lambda acc, price: (min(acc[0], price), max(acc[1], price - acc[0])),
70+
prices, (float('inf'), 0))[1] if prices else 0
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Longest Repeating Character Replacement
2+
3+
## Problem Statement
4+
5+
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English letter. You can perform this operation at most `k` times.
6+
7+
Return the length of the longest substring containing the same letter you can get after performing the above operations.
8+
9+
## Examples
10+
11+
**Example 1:**
12+
```
13+
Input: s = "ABAB", k = 2
14+
Output: 4
15+
Explanation: Replace the two 'A's with two 'B's or vice versa.
16+
```
17+
18+
**Example 2:**
19+
```
20+
Input: s = "AABABBA", k = 1
21+
Output: 4
22+
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
23+
The substring "BBBB" has the longest repeating letters, which is 4.
24+
```
25+
26+
## Approach
27+
28+
### Method 1: Sliding Window (Recommended)
29+
1. Use two pointers to define window
30+
2. Track frequency of each character in window
31+
3. Keep track of most frequent character
32+
4. If window size - most frequent count > k, contract window
33+
34+
**Time Complexity:** O(n) - Single pass through the string
35+
**Space Complexity:** O(1) - At most 26 characters
36+
37+
## Algorithm
38+
39+
```
40+
1. Initialize left = 0, maxLength = 0, maxCount = 0
41+
2. Use HashMap to track character frequencies
42+
3. For each right pointer:
43+
a. Update character frequency
44+
b. Update maxCount = max(maxCount, frequency)
45+
c. If window size - maxCount > k:
46+
- Contract window from left
47+
d. Update maxLength
48+
4. Return maxLength
49+
```
50+
51+
## Key Insights
52+
53+
- **Sliding Window**: Expand right, contract left when needed
54+
- **Character Frequency**: Track most frequent character
55+
- **Replacement Logic**: Window size - max frequency <= k
56+
- **Greedy Strategy**: Always try to maximize window size
57+
58+
## Alternative Approaches
59+
60+
1. **Brute Force**: Check all substrings - O(n²) time
61+
2. **Fixed Window**: Try all possible window sizes
62+
3. **Character-wise**: Process each character separately
63+
64+
## Edge Cases
65+
66+
- Empty string: Return 0
67+
- k = 0: Return length of longest same-character substring
68+
- All same characters: Return string length
69+
- k >= string length: Return string length
70+
71+
## Applications
72+
73+
- String processing
74+
- Data analysis
75+
- Algorithm design patterns
76+
- Interview preparation
77+
- Text optimization
78+
79+
## Optimization Opportunities
80+
81+
- **Sliding Window**: Most efficient approach
82+
- **Frequency Tracking**: O(1) updates
83+
- **Single Pass**: Linear time complexity
84+
- **Memory Efficient**: Constant space

0 commit comments

Comments
 (0)