Skip to content

Commit 7b38abb

Browse files
authored
Added solutions 74-101
1 parent 5a5d2ed commit 7b38abb

File tree

10 files changed

+446
-10
lines changed

10 files changed

+446
-10
lines changed

Diff for: src/main/java/g0001_0100/s0074_search_a_2d_matrix/readme.md

+39-1
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,42 @@ Write an efficient algorithm that searches for a value in an `m x n` matrix. Thi
2828
* `m == matrix.length`
2929
* `n == matrix[i].length`
3030
* `1 <= m, n <= 100`
31-
* <code>-10<sup>4</sup> <= matrix[i][j], target <= 10<sup>4</sup></code>
31+
* <code>-10<sup>4</sup> <= matrix[i][j], target <= 10<sup>4</sup></code>
32+
33+
To solve the "Search a 2D Matrix" problem in Java with the Solution class, follow these steps:
34+
35+
1. Define a method `searchMatrix` in the `Solution` class that takes a 2D integer matrix `matrix` and an integer `target` as input and returns `true` if the target value is found in the matrix, otherwise returns `false`.
36+
2. Initialize two pointers `row` and `col` to start at the top-right corner of the matrix. `row` starts from 0 and `col` starts from the last column.
37+
3. Loop until `row` is less than the number of rows in the matrix and `col` is greater than or equal to 0:
38+
- If `matrix[row][col]` is equal to the target, return `true`.
39+
- If `matrix[row][col]` is greater than the target, decrement `col`.
40+
- If `matrix[row][col]` is less than the target, increment `row`.
41+
4. If the target is not found after the loop, return `false`.
42+
43+
Here's the implementation of the `searchMatrix` method in Java:
44+
45+
```java
46+
class Solution {
47+
public boolean searchMatrix(int[][] matrix, int target) {
48+
int m = matrix.length;
49+
int n = matrix[0].length;
50+
51+
int row = 0;
52+
int col = n - 1;
53+
54+
while (row < m && col >= 0) {
55+
if (matrix[row][col] == target) {
56+
return true;
57+
} else if (matrix[row][col] > target) {
58+
col--;
59+
} else {
60+
row++;
61+
}
62+
}
63+
64+
return false;
65+
}
66+
}
67+
```
68+
69+
This implementation searches for the target value efficiently in the given matrix by starting from the top-right corner and moving either left or down based on the comparison with the target value. The time complexity of this solution is O(m + n), where m is the number of rows and n is the number of columns in the matrix.

Diff for: src/main/java/g0001_0100/s0075_sort_colors/readme.md

+44-1
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,47 @@ You must solve this problem without using the library's sort function.
3838
* `1 <= n <= 300`
3939
* `nums[i]` is `0`, `1`, or `2`.
4040

41-
**Follow up:** Could you come up with a one-pass algorithm using only constant extra space?
41+
**Follow up:** Could you come up with a one-pass algorithm using only constant extra space?
42+
43+
To solve the "Sort Colors" problem in Java with the Solution class, follow these steps:
44+
45+
1. Define a method `sortColors` in the `Solution` class that takes an array of integers `nums` as input and sorts it in-place according to the colors red, white, and blue.
46+
2. Initialize three pointers: `low`, `mid`, and `high`. `low` points to the beginning of the array, `mid` points to the current element being processed, and `high` points to the end of the array.
47+
3. Loop while `mid` is less than or equal to `high`:
48+
- If `nums[mid]` is 0, swap `nums[low]` with `nums[mid]`, increment `low` and `mid`.
49+
- If `nums[mid]` is 1, increment `mid`.
50+
- If `nums[mid]` is 2, swap `nums[mid]` with `nums[high]`, decrement `high`.
51+
4. After the loop, the array will be sorted in-place according to the colors red, white, and blue.
52+
53+
Here's the implementation of the `sortColors` method in Java:
54+
55+
```java
56+
class Solution {
57+
public void sortColors(int[] nums) {
58+
int low = 0;
59+
int mid = 0;
60+
int high = nums.length - 1;
61+
62+
while (mid <= high) {
63+
if (nums[mid] == 0) {
64+
swap(nums, low, mid);
65+
low++;
66+
mid++;
67+
} else if (nums[mid] == 1) {
68+
mid++;
69+
} else {
70+
swap(nums, mid, high);
71+
high--;
72+
}
73+
}
74+
}
75+
76+
private void swap(int[] nums, int i, int j) {
77+
int temp = nums[i];
78+
nums[i] = nums[j];
79+
nums[j] = temp;
80+
}
81+
}
82+
```
83+
84+
This implementation sorts the array in-place using a one-pass algorithm with constant extra space. It iterates through the array and swaps elements as needed to group them according to their colors. The time complexity of this solution is O(n), where n is the length of the array.

Diff for: src/main/java/g0001_0100/s0076_minimum_window_substring/readme.md

+72-1
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,75 @@ A **substring** is a contiguous sequence of characters within the string.
3939
* <code>1 <= m, n <= 10<sup>5</sup></code>
4040
* `s` and `t` consist of uppercase and lowercase English letters.
4141

42-
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
42+
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
43+
44+
To solve the "Minimum Window Substring" problem in Java with the Solution class, follow these steps:
45+
46+
1. Define a method `minWindow` in the `Solution` class that takes two strings `s` and `t` as input and returns the minimum window substring of `s` containing all characters from `t`.
47+
2. Create two frequency maps: `tFreqMap` to store the frequency of characters in string `t`, and `sFreqMap` to store the frequency of characters in the current window of string `s`.
48+
3. Initialize two pointers `left` and `right` to track the window boundaries. Initialize a variable `minLength` to store the minimum window length found so far.
49+
4. Iterate over string `s` using the `right` pointer until the end of the string:
50+
- Update the frequency map `sFreqMap` for the character at index `right`.
51+
- Check if the current window contains all characters from `t`. If it does, move the `left` pointer to minimize the window while maintaining the condition.
52+
- Update the `minLength` if the current window length is smaller.
53+
- Move the `right` pointer to expand the window.
54+
5. Return the minimum window substring found, or an empty string if no such substring exists.
55+
56+
Here's the implementation of the `minWindow` method in Java:
57+
58+
```java
59+
import java.util.HashMap;
60+
import java.util.Map;
61+
62+
class Solution {
63+
public String minWindow(String s, String t) {
64+
Map<Character, Integer> tFreqMap = new HashMap<>();
65+
Map<Character, Integer> sFreqMap = new HashMap<>();
66+
67+
// Initialize tFreqMap with character frequencies from string t
68+
for (char ch : t.toCharArray()) {
69+
tFreqMap.put(ch, tFreqMap.getOrDefault(ch, 0) + 1);
70+
}
71+
72+
int left = 0;
73+
int right = 0;
74+
int minLength = Integer.MAX_VALUE;
75+
int minStart = 0;
76+
77+
while (right < s.length()) {
78+
char rightChar = s.charAt(right);
79+
sFreqMap.put(rightChar, sFreqMap.getOrDefault(rightChar, 0) + 1);
80+
right++;
81+
82+
// Check if the current window contains all characters from t
83+
while (containsAllChars(sFreqMap, tFreqMap)) {
84+
// Update the minimum window length
85+
if (right - left < minLength) {
86+
minLength = right - left;
87+
minStart = left;
88+
}
89+
90+
char leftChar = s.charAt(left);
91+
sFreqMap.put(leftChar, sFreqMap.get(leftChar) - 1);
92+
left++;
93+
}
94+
}
95+
96+
return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength);
97+
}
98+
99+
// Helper method to check if sFreqMap contains all characters from tFreqMap
100+
private boolean containsAllChars(Map<Character, Integer> sFreqMap, Map<Character, Integer> tFreqMap) {
101+
for (Map.Entry<Character, Integer> entry : tFreqMap.entrySet()) {
102+
char ch = entry.getKey();
103+
int count = entry.getValue();
104+
if (sFreqMap.getOrDefault(ch, 0) < count) {
105+
return false;
106+
}
107+
}
108+
return true;
109+
}
110+
}
111+
```
112+
113+
This implementation finds the minimum window substring in `O(m + n)` time complexity, where `m` is the length of string `s` and `n` is the length of string `t`. It uses two frequency maps to keep track of character frequencies and adjusts the window boundaries to find the minimum window containing all characters from `t`.

Diff for: src/main/java/g0001_0100/s0078_subsets/readme.md

+46-1
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,49 @@ The solution set **must not** contain duplicate subsets. Return the solution in
2222

2323
* `1 <= nums.length <= 10`
2424
* `-10 <= nums[i] <= 10`
25-
* All the numbers of `nums` are **unique**.
25+
* All the numbers of `nums` are **unique**.
26+
27+
To solve the "Subsets" problem in Java with the Solution class, follow these steps:
28+
29+
1. Define a method `subsets` in the `Solution` class that takes an integer array `nums` as input and returns all possible subsets of `nums`.
30+
2. Initialize an empty list to store the result subsets.
31+
3. Implement a backtracking algorithm to generate all possible subsets:
32+
- Define a recursive helper function `generateSubsets` that takes the current subset, the current index in the array, and the array `nums` as parameters.
33+
- Base case: If the current index is equal to the length of `nums`, add the current subset to the result list.
34+
- Recursive case:
35+
- Include the current element in the subset and recursively call `generateSubsets` with the next index.
36+
- Exclude the current element from the subset and recursively call `generateSubsets` with the next index.
37+
4. Call the `generateSubsets` function with an empty subset and the starting index 0.
38+
5. Return the list containing all subsets.
39+
40+
Here's the implementation of the `subsets` method in Java:
41+
42+
```java
43+
import java.util.ArrayList;
44+
import java.util.List;
45+
46+
class Solution {
47+
public List<List<Integer>> subsets(int[] nums) {
48+
List<List<Integer>> result = new ArrayList<>();
49+
generateSubsets(new ArrayList<>(), 0, nums, result);
50+
return result;
51+
}
52+
53+
private void generateSubsets(List<Integer> subset, int index, int[] nums, List<List<Integer>> result) {
54+
// Base case: add the current subset to the result list
55+
result.add(new ArrayList<>(subset));
56+
57+
// Recursive case
58+
for (int i = index; i < nums.length; i++) {
59+
// Include the current element in the subset
60+
subset.add(nums[i]);
61+
// Recursively generate subsets starting from the next index
62+
generateSubsets(subset, i + 1, nums, result);
63+
// Exclude the current element from the subset
64+
subset.remove(subset.size() - 1);
65+
}
66+
}
67+
}
68+
```
69+
70+
This implementation uses backtracking to generate all possible subsets of the input array `nums`. It has a time complexity of O(2^N), where N is the number of elements in the input array.

Diff for: src/main/java/g0001_0100/s0079_word_search/readme.md

+52-1
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,55 @@ The word can be constructed from letters of sequentially adjacent cells, where a
3838
* `1 <= word.length <= 15`
3939
* `board` and `word` consists of only lowercase and uppercase English letters.
4040

41-
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
41+
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
42+
43+
To solve the "Word Search" problem in Java with the Solution class, follow these steps:
44+
45+
1. Define a method `exist` in the `Solution` class that takes a 2D character array `board` and a string `word` as input and returns `true` if the `word` exists in the `board`.
46+
2. Implement a backtracking algorithm to search for the `word` in the `board`.
47+
3. Iterate through each cell in the `board`:
48+
- For each cell, call a recursive helper function `search` to check if the `word` can be found starting from that cell.
49+
- If `search` returns `true`, return `true` immediately.
50+
4. Define the `search` method to perform the recursive backtracking:
51+
- Check if the current cell is out of bounds or if the current character in the `board` does not match the corresponding character in the `word`.
52+
- If any of the conditions are met, return `false`.
53+
- Mark the current cell as visited by changing its value to a special character (e.g., `#`) to avoid revisiting it.
54+
- Recursively call `search` on neighboring cells (up, down, left, right) with the next character in the `word`.
55+
- After exploring all possible paths from the current cell, backtrack by restoring the original value of the current cell.
56+
5. If the `search` method reaches the end of the `word`, return `true`.
57+
6. If no match is found after exploring all cells, return `false`.
58+
59+
Here's the implementation of the `exist` method in Java:
60+
61+
```java
62+
class Solution {
63+
public boolean exist(char[][] board, String word) {
64+
int m = board.length;
65+
int n = board[0].length;
66+
for (int i = 0; i < m; i++) {
67+
for (int j = 0; j < n; j++) {
68+
if (search(board, word, i, j, 0))
69+
return true;
70+
}
71+
}
72+
return false;
73+
}
74+
75+
private boolean search(char[][] board, String word, int i, int j, int index) {
76+
if (index == word.length())
77+
return true;
78+
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index))
79+
return false;
80+
char temp = board[i][j];
81+
board[i][j] = '#'; // Mark as visited
82+
boolean found = search(board, word, i + 1, j, index + 1) ||
83+
search(board, word, i - 1, j, index + 1) ||
84+
search(board, word, i, j + 1, index + 1) ||
85+
search(board, word, i, j - 1, index + 1);
86+
board[i][j] = temp; // Restore original value
87+
return found;
88+
}
89+
}
90+
```
91+
92+
This implementation uses backtracking to search for the word in the board, with a time complexity of O(M * N * 4^L), where M and N are the dimensions of the board and L is the length of the word.

Diff for: src/main/java/g0001_0100/s0084_largest_rectangle_in_histogram/readme.md

+45-1
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,48 @@ Given an array of integers `heights` representing the histogram's bar height whe
2525
**Constraints:**
2626

2727
* <code>1 <= heights.length <= 10<sup>5</sup></code>
28-
* <code>0 <= heights[i] <= 10<sup>4</sup></code>
28+
* <code>0 <= heights[i] <= 10<sup>4</sup></code>
29+
30+
To solve the "Largest Rectangle in Histogram" problem in Java with the Solution class, follow these steps:
31+
32+
1. Define a method `largestRectangleArea` in the `Solution` class that takes an array of integers `heights` as input and returns the area of the largest rectangle in the histogram.
33+
2. Implement a stack-based algorithm to find the largest rectangle:
34+
- Initialize a stack to store indices of bars in the histogram.
35+
- Iterate through each bar in the histogram:
36+
- If the stack is empty or the current bar's height is greater than or equal to the height of the bar at the top of the stack, push the current bar's index onto the stack.
37+
- If the current bar's height is less than the height of the bar at the top of the stack, keep popping bars from the stack until either the stack is empty or the height of the bar at the top of the stack is less than the height of the current bar.
38+
- Calculate the area of the rectangle formed by the popped bar using its height and width (the difference between the current index and the index of the previous bar in the stack or -1 if the stack is empty).
39+
- Update the maximum area if the calculated area is greater.
40+
- After iterating through all bars, pop the remaining bars from the stack and calculate the area of rectangles formed by them using the same method as above.
41+
3. Return the maximum area calculated.
42+
43+
Here's the implementation of the `largestRectangleArea` method in Java:
44+
45+
```java
46+
import java.util.Stack;
47+
48+
class Solution {
49+
public int largestRectangleArea(int[] heights) {
50+
Stack<Integer> stack = new Stack<>();
51+
int maxArea = 0;
52+
int i = 0;
53+
while (i < heights.length) {
54+
if (stack.isEmpty() || heights[i] >= heights[stack.peek()]) {
55+
stack.push(i++);
56+
} else {
57+
int top = stack.pop();
58+
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
59+
maxArea = Math.max(maxArea, heights[top] * width);
60+
}
61+
}
62+
while (!stack.isEmpty()) {
63+
int top = stack.pop();
64+
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
65+
maxArea = Math.max(maxArea, heights[top] * width);
66+
}
67+
return maxArea;
68+
}
69+
}
70+
```
71+
72+
This implementation uses a stack-based approach to find the largest rectangle in the histogram, with a time complexity of O(N), where N is the number of bars in the histogram.

Diff for: src/main/java/g0001_0100/s0094_binary_tree_inorder_traversal/readme.md

+43-1
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,46 @@ Given the `root` of a binary tree, return _the inorder traversal of its nodes' v
4545
* The number of nodes in the tree is in the range `[0, 100]`.
4646
* `-100 <= Node.val <= 100`
4747

48-
**Follow up:** Recursive solution is trivial, could you do it iteratively?
48+
**Follow up:** Recursive solution is trivial, could you do it iteratively?
49+
50+
To solve the "Binary Tree Inorder Traversal" problem in Java with the Solution class, follow these steps:
51+
52+
1. Define a method `inorderTraversal` in the `Solution` class that takes the root of a binary tree as input and returns the inorder traversal of its nodes' values.
53+
2. Implement an iterative algorithm to perform inorder traversal:
54+
- Initialize an empty list to store the inorder traversal result.
55+
- Initialize a stack to track the nodes during traversal.
56+
- Start with the root node and push it onto the stack.
57+
- While the stack is not empty:
58+
- Traverse down the left subtree by pushing all left child nodes onto the stack.
59+
- Pop the top node from the stack and add its value to the traversal result list.
60+
- Move to the right subtree of the popped node and repeat the process.
61+
- Return the traversal result list.
62+
3. Return the inorder traversal result list.
63+
64+
Here's the implementation of the `inorderTraversal` method in Java:
65+
66+
```java
67+
import java.util.ArrayList;
68+
import java.util.List;
69+
import java.util.Stack;
70+
71+
class Solution {
72+
public List<Integer> inorderTraversal(TreeNode root) {
73+
List<Integer> inorder = new ArrayList<>();
74+
Stack<TreeNode> stack = new Stack<>();
75+
TreeNode curr = root;
76+
while (curr != null || !stack.isEmpty()) {
77+
while (curr != null) {
78+
stack.push(curr);
79+
curr = curr.left;
80+
}
81+
curr = stack.pop();
82+
inorder.add(curr.val);
83+
curr = curr.right;
84+
}
85+
return inorder;
86+
}
87+
}
88+
```
89+
90+
This implementation performs an iterative inorder traversal of the binary tree using a stack, with a time complexity of O(N), where N is the number of nodes in the tree.

0 commit comments

Comments
 (0)