Skip to content

Commit c4a6886

Browse files
committed
Binary Tree Maximum Path Sum
1 parent c475ce8 commit c4a6886

28 files changed

+578
-383
lines changed

README.md

Lines changed: 64 additions & 63 deletions
Large diffs are not rendered by default.

docs/0001-Two-Sum.md

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11
# [Two Sum](https://leetcode.com/problems/two-sum/)
22

3-
The "Two Sum" problem on LeetCode is a fundamental challenge in array manipulation and hash table usage. Let's explore
3+
The "Two Sum" problem on LeetCode is a fundamental challenge in array manipulation and hash table usage. Let's explore
44
the optimal solution:
55

66
## Intuition
77

8-
The primary intuition behind solving the Two Sum problem efficiently is recognizing that each number needs a specific
9-
**"partner"** number to reach the target sum. This understanding shifts the focus from searching for a number to
10-
identifying its necessary partner. The key insight is to store and quickly look up these partner numbers as we
8+
The primary intuition behind solving the Two Sum problem efficiently is recognizing that each number needs a specific
9+
**"partner"** number to reach the target sum. This understanding shifts the focus from searching for a number to
10+
identifying its necessary partner. The key insight is to store and quickly look up these partner numbers as we
1111
iterate through the array.
1212

1313
## Approach
1414

15-
1. **Hash Table Usage:** The optimal approach involves using a hash table to store numbers from the array along with
16-
their indices. The hash table allows for constant-time lookups, which is crucial for efficiency.
15+
1. **Hash Table Usage:** The optimal approach involves using a hash table to store numbers from the array along with
16+
their indices. The hash table allows for constant-time lookups, which is crucial for efficiency.
1717

18-
2. **Single Pass Iteration:** As we iterate through the array, we compute the complement (or partner) for each number
19-
(i.e., target - currentNumber). We then check if this complement is already in the hash table.
18+
2. **Single Pass Iteration:** As we iterate through the array, we compute the complement (or partner) for each number
19+
(i.e., target - currentNumber). We then check if this complement is already in the hash table.
2020

21-
3. **Early Return:** If the complement is found, it means a pair that sums up to the target has been identified, and we
22-
can immediately return their indices. If not, we store the current number and its index in the hash table for future
23-
reference.
21+
3. **Early Return:** If the complement is found, it means a pair that sums up to the target has been identified, and we
22+
can immediately return their indices. If not, we store the current number and its index in the hash table for future
23+
reference.
2424

2525
## Complexity
2626

27-
- **Time Complexity: O(N)**, where N is the number of elements in the array. This is because each element is processed
28-
exactly once, and hash table operations like insertion and lookup are O(1).
29-
- **Space Complexity: O(N)** in the worst-case scenario, which occurs when no matching pair is found until the end of
30-
the array, necessitating storing all elements in the hash table.
27+
- **Time Complexity: O(N)**, where N is the number of elements in the array. This is because each element is processed
28+
exactly once, and hash table operations like insertion and lookup are O(1).
29+
- **Space Complexity: O(N)** in the worst-case scenario, which occurs when no matching pair is found until the end of
30+
the array, necessitating storing all elements in the hash table.
3131

3232
## Code
3333

docs/0011-Container-With-Most-Water.md

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,27 @@
22

33
## Intuition
44

5-
The “Container With Most Water” problem involves finding two lines (out of a given array of heights) that together with
6-
the x-axis form a container, such that the container holds the maximum amount of water. The key observation is that the
7-
amount of water held by the container is determined by the shorter of the two lines and the distance between them.
5+
The “Container With Most Water” problem involves finding two lines (out of a given array of heights) that together with
6+
the x-axis form a container, such that the container holds the maximum amount of water. The key observation is that the
7+
amount of water held by the container is determined by the shorter of the two lines and the distance between them.
88
Therefore, to maximize the water held, we should consider both the height of the lines and the distance between them.
99

1010
## Approach
1111

12-
1. **Initialize Two Pointers:** Start with two pointers, one at the beginning `leftIndex` and one at the end
13-
`rightIndex` of the array.
14-
2. **Calculate the Area:** In each iteration, calculate the area formed by the lines at the left and right pointers and
15-
the distance between them.
16-
3. **Update Maximum Area:** Keep track of the maximum area encountered so far.
17-
4. **Move the Pointers:** Move the pointer that points to the shorter line inward. This is because moving the taller
18-
line inward will not increase the height of the water (since it is constrained by the shorter line), and moving the
19-
shorter line inward might find a taller line that increases the water capacity.
20-
5. **Repeat:** Continue this process until the two pointers meet.
12+
1. **Initialize Two Pointers:** Start with two pointers, one at the beginning `leftIndex` and one at the end
13+
`rightIndex` of the array.
14+
2. **Calculate the Area:** In each iteration, calculate the area formed by the lines at the left and right pointers and
15+
the distance between them.
16+
3. **Update Maximum Area:** Keep track of the maximum area encountered so far.
17+
4. **Move the Pointers:** Move the pointer that points to the shorter line inward. This is because moving the taller
18+
line inward will not increase the height of the water (since it is constrained by the shorter line), and moving the
19+
shorter line inward might find a taller line that increases the water capacity.
20+
5. **Repeat:** Continue this process until the two pointers meet.
2121

2222
## Complexity
2323

24-
- **Time Complexity: O(N)**, where `N` is the number of elements in the input array. This is because each element is
25-
considered at most once by the two pointers, which move towards each other.
24+
- **Time Complexity: O(N)**, where `N` is the number of elements in the input array. This is because each element is
25+
considered at most once by the two pointers, which move towards each other.
2626
- **Space Complexity: O(1)**, as the algorithm uses a constant amount of extra space regardless of the input size.
2727

2828
## Code

docs/0015-Three-Sum.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
## Intuition
44

5-
The problem requires us to find all unique triplets in an array that sum up to zero. Given the constraints and the need to avoid duplicates, a sorted array and a two-pointer approach are suitable. Sorting helps in easily skipping duplicates and efficiently using two pointers to find pairs that sum up to a target.
5+
The problem requires us to find all unique triplets in an array that sum up to zero. Given the constraints and the need
6+
to avoid duplicates, a sorted array and a two-pointer approach are suitable. Sorting helps in easily skipping duplicates
7+
and efficiently using two pointers to find pairs that sum up to a target.
68

79
## Approach
810

@@ -11,16 +13,18 @@ The problem requires us to find all unique triplets in an array that sum up to z
1113
- Use a loop to fix one element of the triplet. This element will be the current element in the loop.
1214
- Skip duplicate elements to ensure the uniqueness of the triplets.
1315
3. **Two-Pointer Technique:**
14-
- For each fixed element, use two pointers (`left` and `right`) to find pairs that sum up to the negative of the fixed element.
16+
- For each fixed element, use two pointers (`left` and `right`) to find pairs that sum up to the negative of the
17+
fixed element.
1518
- Adjust the pointers based on the sum of the triplet:
16-
- If the sum is less than zero, move the left pointer to the right to increase the sum.
17-
- If the sum is greater than zero, move the right pointer to the left to decrease the sum.
18-
- If the sum is zero, add the triplet to the result list and move both pointers, skipping duplicates.
19+
- If the sum is less than zero, move the left pointer to the right to increase the sum.
20+
- If the sum is greater than zero, move the right pointer to the left to decrease the sum.
21+
- If the sum is zero, add the triplet to the result list and move both pointers, skipping duplicates.
1922
4. **Return the Result:** After processing all elements, return the list of unique triplets.
2023

2124
## Complexity
2225

23-
- **Time Complexity: `O(N^2)`**, where `N` is the number of elements in the array. Sorting the array takes `O(NlogN)`, and the two-pointer technique takes `O(N^2)` in the worst case.
26+
- **Time Complexity: `O(N^2)`**, where `N` is the number of elements in the array. Sorting the array takes `O(NlogN)`,
27+
and the two-pointer technique takes `O(N^2)` in the worst case.
2428
- **Space Complexity: `O(1)` or `O(N)`** depending on the implementation of sorting the input.
2529

2630
## Code

docs/0022-Generate-Parentheses.md

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
## Intuition
44

5-
Generating all combinations of well-formed parentheses involves understanding the balance between open and close
6-
parentheses. A well-formed parentheses sequence must ensure that at no point do the close parentheses exceed the open
7-
ones, and by the end, the counts of open and close parentheses must be equal. This ensures that every opening
5+
Generating all combinations of well-formed parentheses involves understanding the balance between open and close
6+
parentheses. A well-formed parentheses sequence must ensure that at no point do the close parentheses exceed the open
7+
ones, and by the end, the counts of open and close parentheses must be equal. This ensures that every opening
88
parenthesis has a corresponding closing one, forming valid sequences.
99

1010
## Approach
@@ -14,20 +14,21 @@ of parentheses and ensures we only consider valid sequences. Here’s a step-by-
1414

1515
1. **Initialization:** We start with an empty string and zero counts for both open and close parentheses.
1616
2. **Backtracking Function:** The backtrack function recursively builds the parentheses sequences.
17-
- *Base Case:* When the counts of both open and close parentheses reach `N`, a valid sequence is formed, and we add
18-
it to the result list.
19-
- *Add Open Parenthesis:* If the count of open parentheses is less than `N`, we can add an open parenthesis and
20-
recursively call the function.
21-
- *Add Close Parenthesis:* If the count of close parentheses is less than the count of open parentheses, we can add
22-
a close parenthesis and recursively call the function.
17+
- *Base Case:* When the counts of both open and close parentheses reach `N`, a valid sequence is formed, and we add
18+
it to the result list.
19+
- *Add Open Parenthesis:* If the count of open parentheses is less than `N`, we can add an open parenthesis and
20+
recursively call the function.
21+
- *Add Close Parenthesis:* If the count of close parentheses is less than the count of open parentheses, we can add
22+
a close parenthesis and recursively call the function.
2323
3. **Recursion:** This process continues until all valid sequences are generated and stored in the result list.
2424

2525
## Complexity
2626

27-
- **Time Complexity:** The time complexity is `O(4^N / \sqrt{N})`. This is derived from the fact that the number of
28-
valid sequences is given by the [nth Catalan number](https://en.wikipedia.org/wiki/Catalan_number), which grows exponentially.
29-
- **Space Complexity:** The space complexity is `O(4^N / \sqrt{N})` for the result list storing all sequences.
30-
Additionally, the recursion stack depth is `O(N)`, making the auxiliary space complexity also `O(N)`.
27+
- **Time Complexity:** The time complexity is `O(4^N / \sqrt{N})`. This is derived from the fact that the number of
28+
valid sequences is given by the [nth Catalan number](https://en.wikipedia.org/wiki/Catalan_number), which grows
29+
exponentially.
30+
- **Space Complexity:** The space complexity is `O(4^N / \sqrt{N})` for the result list storing all sequences.
31+
Additionally, the recursion stack depth is `O(N)`, making the auxiliary space complexity also `O(N)`.
3132

3233
## Code
3334

docs/0033-Search-In-Rotated-Sorted-Array.md

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,27 @@
22

33
## Intuition
44

5-
The problem requires finding a target value in a rotated sorted array. The key challenge is to achieve this in
6-
`O(log N)` time complexity, which suggests using a binary search approach. The main insight is that even though the
7-
array is rotated, at least one half of the array (either left or right of the middle) will always be sorted. This
5+
The problem requires finding a target value in a rotated sorted array. The key challenge is to achieve this in
6+
`O(log N)` time complexity, which suggests using a binary search approach. The main insight is that even though the
7+
array is rotated, at least one half of the array (either left or right of the middle) will always be sorted. This
88
property can be exploited to decide which half to discard in each step of the binary search.
99

1010
## Approach
1111

12-
1. **Initialize Pointers:** Start with two pointers, `leftIndex` at the beginning of the array and `rightIndex` at the
13-
end.
12+
1. **Initialize Pointers:** Start with two pointers, `leftIndex` at the beginning of the array and `rightIndex` at the
13+
end.
1414
2. **Binary Search Loop:** Use a while loop that continues as long as `leftIndex` is less than or equal to `rightIndex`.
1515
3. **Find Middle:** Calculate the middle index, `middleIndex`, as the average of `leftIndex` and `rightIndex`.
1616
4. **Check Middle:** If the element at `middleIndex` is the target, return `middleIndex`.
1717
5. **Determine Sorted Half:**
1818
- **Left Half Sorted:** If `nums[leftIndex] <= nums[middleIndex]`, then the left half is sorted. Check if the target
19-
lies within this sorted half (`nums[leftIndex] <= target < nums[middleIndex]`).
20-
- If yes, move `rightIndex` to `middleIndex - 1`.
21-
- Otherwise, move `leftIndex` to `middleIndex + 1`.
22-
- **Right Half Sorted:** Otherwise, the right half must be sorted. Check if the target lies within this sorted half
23-
(`nums[middleIndex] < target <= nums[rightIndex]`).
24-
- If yes, move `leftIndex` to `middleIndex + 1`.
25-
- Otherwise, move `rightIndex` to `middleIndex - 1`.
19+
lies within this sorted half (`nums[leftIndex] <= target < nums[middleIndex]`).
20+
- If yes, move `rightIndex` to `middleIndex - 1`.
21+
- Otherwise, move `leftIndex` to `middleIndex + 1`.
22+
- **Right Half Sorted:** Otherwise, the right half must be sorted. Check if the target lies within this sorted half
23+
(`nums[middleIndex] < target <= nums[rightIndex]`).
24+
- If yes, move `leftIndex` to `middleIndex + 1`.
25+
- Otherwise, move `rightIndex` to `middleIndex - 1`.
2626
6. **Return -1:** If the loop ends without finding the target, return -1.
2727

2828
## Complexity
@@ -36,6 +36,6 @@ end.
3636

3737
## Summary
3838

39-
This solution effectively uses a modified binary search to find the target in a rotated sorted array. By identifying
40-
which half of the array is sorted at each step, We decide whether to search the left or right half, ensuring that the
39+
This solution effectively uses a modified binary search to find the target in a rotated sorted array. By identifying
40+
which half of the array is sorted at each step, We decide whether to search the left or right half, ensuring that the
4141
algorithm runs in logarithmic time. This approach is efficient and well-suited for the constraints given in the problem.

docs/0036-Valid-Sudoku.md

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,40 +2,42 @@
22

33
## Intuition
44

5-
The core idea is to ensure that each number from `1` to `9` appears only once in each row, each column, and each of the
6-
nine 3x3 sub-boxes of the Sudoku board. By keeping track of the numbers we have seen so far in each row, column, and
5+
The core idea is to ensure that each number from `1` to `9` appears only once in each row, each column, and each of the
6+
nine 3x3 sub-boxes of the Sudoku board. By keeping track of the numbers we have seen so far in each row, column, and
77
box, we can efficiently determine if the Sudoku board is valid or not.
88

99
## Approach
1010

1111
**Initialization:** We use three hash maps to keep track of the characters we encounter:
12-
- `rows` to track characters for each row.
13-
- `cols` to track characters for each column.
14-
- `boxes` to track characters for each 3x3 sub-box.
15-
- Each of these maps contains sets, which will store the characters seen so far.
12+
13+
- `rows` to track characters for each row.
14+
- `cols` to track characters for each column.
15+
- `boxes` to track characters for each 3x3 sub-box.
16+
- Each of these maps contains sets, which will store the characters seen so far.
1617

1718
**Filling the Maps:**
18-
- We iterate over each cell in the board using nested loops.
19-
- For each cell, if the character is not `.`, we do the following:
19+
20+
- We iterate over each cell in the board using nested loops.
21+
- For each cell, if the character is not `.`, we do the following:
2022
- Calculate the corresponding 3x3 box index using integer division (`rb = i / 3` and `cb = j / 3`).
2123
- Check if the character already exists in the respective row, column, or box set.
2224
- If it does, return `false` as it violates the Sudoku rule.
2325
- If it does not, add the character to the respective sets.
2426

25-
**Final Check:** If we complete the iteration without finding any duplicates, we return `true`, indicating the board is
27+
**Final Check:** If we complete the iteration without finding any duplicates, we return `true`, indicating the board is
2628
valid.
2729

2830
## Complexity
2931

3032
- **Time Complexity: O(1)**
31-
- We always iterate over a fixed 9x9 board, making the iteration part of the solution constant in terms of time
32-
complexity. Each cell is visited once.
33-
- The operations of checking and adding elements to the sets are average `O(1)` operations.
33+
- We always iterate over a fixed 9x9 board, making the iteration part of the solution constant in terms of time
34+
complexity. Each cell is visited once.
35+
- The operations of checking and adding elements to the sets are average `O(1)` operations.
3436
- **Space Complexity: O(1)**
35-
- Although we use additional data structures (maps and sets), their sizes are fixed and proportional to the size of
36-
the board, which is constant (81 cells).
37-
- Each map (rows, cols, boxes) holds at most 9 sets, and each set can hold up to 9 elements, making the extra space
38-
used constant.
37+
- Although we use additional data structures (maps and sets), their sizes are fixed and proportional to the size of
38+
the board, which is constant (81 cells).
39+
- Each map (rows, cols, boxes) holds at most 9 sets, and each set can hold up to 9 elements, making the extra space
40+
used constant.
3941

4042
## Code
4143

0 commit comments

Comments
 (0)