Skip to content

Commit

Permalink
Added solutions 49-73
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev authored Feb 18, 2024
1 parent 63239d3 commit fb1d25f
Show file tree
Hide file tree
Showing 10 changed files with 442 additions and 10 deletions.
50 changes: 49 additions & 1 deletion src/main/java/g0001_0100/s0049_group_anagrams/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,52 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ

* <code>1 <= strs.length <= 10<sup>4</sup></code>
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.
* `strs[i]` consists of lowercase English letters.

To solve the "Group Anagrams" problem in Java with the Solution class, follow these steps:

1. Define a method `groupAnagrams` in the `Solution` class that takes an array of strings `strs` as input and returns a list of lists of strings.
2. Initialize an empty HashMap to store the groups of anagrams. The key will be the sorted string, and the value will be a list of strings.
3. Iterate through each string `str` in the input array `strs`.
4. Sort the characters of the current string `str` to create a key for the HashMap.
5. Check if the sorted string exists as a key in the HashMap:
- If it does, add the original string `str` to the corresponding list of strings.
- If it doesn't, create a new entry in the HashMap with the sorted string as the key and a new list containing `str` as the value.
6. After iterating through all strings, return the values of the HashMap as the result.

Here's the implementation of the `groupAnagrams` method in Java:

```java
import java.util.*;

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Initialize a HashMap to store the groups of anagrams
Map<String, List<String>> anagramGroups = new HashMap<>();

// Iterate through each string in the input array
for (String str : strs) {
// Sort the characters of the current string
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedStr = new String(chars);

// Check if the sorted string exists as a key in the HashMap
if (anagramGroups.containsKey(sortedStr)) {
// If it does, add the original string to the corresponding list
anagramGroups.get(sortedStr).add(str);
} else {
// If it doesn't, create a new entry in the HashMap
List<String> group = new ArrayList<>();
group.add(str);
anagramGroups.put(sortedStr, group);
}
}

// Return the values of the HashMap as the result
return new ArrayList<>(anagramGroups.values());
}
}
```

This implementation ensures that all anagrams are grouped together efficiently using a HashMap.
81 changes: 80 additions & 1 deletion src/main/java/g0001_0100/s0051_n_queens/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,83 @@ Each solution contains a distinct board configuration of the n-queens' placement

**Constraints:**

* `1 <= n <= 9`
* `1 <= n <= 9`

To solve the "N-Queens" problem in Java with the Solution class, follow these steps:

1. Define a method `solveNQueens` in the `Solution` class that takes an integer `n` as input and returns a list of lists of strings.
2. Initialize a board represented as a 2D character array of size `n x n`. Initialize all cells to `'.'`, indicating an empty space.
3. Define a recursive backtracking function `backtrack` to explore all possible configurations of queens on the board.
4. In the `backtrack` function:
- Base case: If the current row index `row` is equal to `n`, it means we have successfully placed `n` queens on the board. Add the current board configuration to the result.
- Iterate through each column index `col` from `0` to `n - 1`:
- Check if it's safe to place a queen at position `(row, col)` by calling a helper function `isSafe`.
- If it's safe, place a queen at position `(row, col)` on the board, mark it as `'Q'`.
- Recur to the next row by calling `backtrack(row + 1)`.
- Backtrack: After exploring all possibilities, remove the queen from position `(row, col)` by marking it as `'.'`.
5. In the `solveNQueens` method, initialize an empty list `result` to store the solutions.
6. Call the `backtrack` function with initial parameters `0` for the row index.
7. Return the `result` list containing all distinct solutions.

Here's the implementation of the `solveNQueens` method in Java:

```java
import java.util.*;

class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(board[i], '.');
}
backtrack(board, 0, result);
return result;
}

private void backtrack(char[][] board, int row, List<List<String>> result) {
int n = board.length;
if (row == n) {
result.add(constructBoard(board));
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col)) {
board[row][col] = 'Q';
backtrack(board, row + 1, result);
board[row][col] = '.';
}
}
}

private boolean isSafe(char[][] board, int row, int col) {
int n = board.length;
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q') {
return false;
}
}
return true;
}

private List<String> constructBoard(char[][] board) {
List<String> solution = new ArrayList<>();
for (char[] row : board) {
solution.add(new String(row));
}
return solution;
}
}
```

This implementation efficiently finds all distinct solutions to the N-Queens problem using backtracking.
32 changes: 31 additions & 1 deletion src/main/java/g0001_0100/s0053_maximum_subarray/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,34 @@ A **subarray** is a **contiguous** part of an array.
* <code>1 <= nums.length <= 10<sup>5</sup></code>
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>

**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.

To solve the "Maximum Subarray" problem in Java with the Solution class, follow these steps:

1. Define a method `maxSubArray` in the `Solution` class that takes an integer array `nums` as input and returns an integer representing the largest sum of a contiguous subarray.
2. Initialize two variables `maxSum` and `currentSum` to store the maximum sum found so far and the sum of the current subarray being considered, respectively. Set both to the value of the first element in `nums`.
3. Iterate through the array `nums` from index `1` to `nums.length - 1`:
- Update `currentSum` as the maximum of the current element and the sum of the current element plus `currentSum`.
- Update `maxSum` as the maximum of `maxSum` and `currentSum`.
4. After iterating through all elements in `nums`, return `maxSum`.

Here's the implementation of the `maxSubArray` method in Java:

```java
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
```

This implementation efficiently finds the largest sum of a contiguous subarray in the given array `nums` using the Kadane's algorithm, which has a time complexity of O(n).
36 changes: 35 additions & 1 deletion src/main/java/g0001_0100/s0055_jump_game/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,38 @@ Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Constraints:**

* <code>1 <= nums.length <= 10<sup>4</sup></code>
* <code>0 <= nums[i] <= 10<sup>5</sup></code>
* <code>0 <= nums[i] <= 10<sup>5</sup></code>

To solve the "Jump Game" problem in Java with the Solution class, follow these steps:

1. Define a method `canJump` in the `Solution` class that takes an integer array `nums` as input and returns a boolean indicating whether it's possible to reach the last index.
2. Initialize a variable `maxReach` to keep track of the maximum index that can be reached.
3. Iterate through the array `nums` from index `0` to `nums.length - 1`:
- Check if the current index `i` is greater than `maxReach`. If it is, return `false` as it's not possible to reach the last index.
- Update `maxReach` as the maximum of `maxReach` and `i + nums[i]`, which represents the furthest index that can be reached from the current position.
4. After iterating through all elements in `nums`, return `true` as it's possible to reach the last index.

Here's the implementation of the `canJump` method in Java:

```java
class Solution {
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
int maxReach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= nums.length - 1) {
return true;
}
}
return false;
}
}
```

This implementation efficiently determines whether it's possible to reach the last index in the given array `nums` using a greedy approach, with a time complexity of O(n).
35 changes: 34 additions & 1 deletion src/main/java/g0001_0100/s0056_merge_intervals/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,37 @@ Given an array of `intervals` where <code>intervals[i] = [start<sub>i</sub>, end

* <code>1 <= intervals.length <= 10<sup>4</sup></code>
* `intervals[i].length == 2`
* <code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code>
* <code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code>

To solve the "Merge Intervals" problem in Java with the Solution class, follow these steps:

1. Define a method `merge` in the `Solution` class that takes an array of integer arrays `intervals` as input and returns an array of the non-overlapping intervals that cover all the intervals in the input.
2. Sort the intervals based on the start times.
3. Initialize an ArrayList to store the merged intervals.
4. Iterate through the sorted intervals:
- If the list of merged intervals is empty or the current interval's start time is greater than the end time of the last merged interval, add the current interval to the list of merged intervals.
- Otherwise, merge the current interval with the last merged interval by updating its end time if needed.
5. Convert the ArrayList of merged intervals into an array and return it as the result.

Here's the implementation of the `merge` method in Java:

```java
import java.util.*;

class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
if (merged.isEmpty() || interval[0] > merged.get(merged.size() - 1)[1]) {
merged.add(interval);
} else {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
}
}
return merged.toArray(new int[merged.size()][]);
}
}
```

This implementation efficiently merges overlapping intervals in the given array `intervals` using sorting and iteration, with a time complexity of O(n log n) due to sorting.
35 changes: 34 additions & 1 deletion src/main/java/g0001_0100/s0062_unique_paths/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,37 @@ How many possible unique paths are there?
**Constraints:**

* `1 <= m, n <= 100`
* It's guaranteed that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.
* It's guaranteed that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.

To solve the "Unique Paths" problem in Java with the Solution class, follow these steps:

1. Define a method `uniquePaths` in the `Solution` class that takes two integers `m` and `n` as input and returns the number of unique paths from the top-left corner to the bottom-right corner of an `m x n` grid.
2. Initialize a 2D array `dp` of size `m x n` to store the number of unique paths for each position in the grid.
3. Initialize the first row and first column of `dp` to 1 since there is only one way to reach any position in the first row or column (by moving only right or down).
4. Iterate over each position `(i, j)` in the grid, starting from the second row and second column:
- Update `dp[i][j]` by adding the number of unique paths from the cell above `(i-1, j)` and the cell to the left `(i, j-1)`.
5. Return the value of `dp[m-1][n-1]`, which represents the number of unique paths to reach the bottom-right corner of the grid.

Here's the implementation of the `uniquePaths` method in Java:

```java
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
dp[i][0] = 1; // Initialize first column to 1
}
for (int j = 0; j < n; j++) {
dp[0][j] = 1; // Initialize first row to 1
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1]; // Calculate number of paths for current cell
}
}
return dp[m-1][n-1]; // Return number of unique paths for bottom-right corner
}
}
```

This implementation efficiently calculates the number of unique paths using dynamic programming, with a time complexity of O(m * n) and a space complexity of O(m * n).
43 changes: 42 additions & 1 deletion src/main/java/g0001_0100/s0064_minimum_path_sum/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,45 @@ Given a `m x n` `grid` filled with non-negative numbers, find a path from top le
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
* `0 <= grid[i][j] <= 100`

To solve the "Minimum Path Sum" problem in Java with the Solution class, follow these steps:

1. Define a method `minPathSum` in the `Solution` class that takes a 2D grid of non-negative numbers as input and returns the minimum sum of all numbers along the path from the top-left corner to the bottom-right corner of the grid.
2. Initialize a 2D array `dp` of size `m x n`, where `dp[i][j]` represents the minimum sum of the path from the top-left corner to position `(i, j)` in the grid.
3. Initialize `dp[0][0]` to the value of the top-left cell in the grid.
4. Initialize the first row and first column of `dp` based on the grid values and the previous cells in the same row or column.
5. Iterate over each position `(i, j)` in the grid, starting from the second row and second column:
- Update `dp[i][j]` by adding the current grid value at `(i, j)` to the minimum of the values of the previous cells `(i-1, j)` and `(i, j-1)` in `dp`.
6. Return `dp[m-1][n-1]`, which represents the minimum path sum from the top-left corner to the bottom-right corner of the grid.

Here's the implementation of the `minPathSum` method in Java:

```java
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];

dp[0][0] = grid[0][0];
// Initialize first row
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j-1] + grid[0][j];
}
// Initialize first column
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i-1][0] + grid[i][0];
}
// Fill in the rest of the dp array
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = grid[i][j] + Math.min(dp[i-1][j], dp[i][j-1]);
}
}
return dp[m-1][n-1];
}
}
```

This implementation efficiently calculates the minimum path sum using dynamic programming, with a time complexity of O(m * n) and a space complexity of O(m * n).
34 changes: 33 additions & 1 deletion src/main/java/g0001_0100/s0070_climbing_stairs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,36 @@ Each time you can either climb `1` or `2` steps. In how many distinct ways can y

**Constraints:**

* `1 <= n <= 45`
* `1 <= n <= 45`

To solve the "Climbing Stairs" problem in Java with the Solution class, follow these steps:

1. Define a method `climbStairs` in the `Solution` class that takes an integer `n` as input and returns the number of distinct ways to climb to the top of the staircase with `n` steps.
2. Initialize an array `dp` of size `n+1` to store the number of distinct ways to reach each step.
3. Set `dp[0] = 1` and `dp[1] = 1` since there is only one way to reach the first and second steps.
4. Iterate over the steps from `2` to `n`:
- At each step `i`, the number of distinct ways to reach step `i` is the sum of the number of ways to reach steps `i-1` and `i-2`.
- Store this sum in `dp[i]`.
5. Return `dp[n]`, which represents the number of distinct ways to climb to the top of the staircase with `n` steps.

Here's the implementation of the `climbStairs` method in Java:

```java
class Solution {
public int climbStairs(int n) {
if (n == 1) return 1;

int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;

for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}

return dp[n];
}
}
```

This implementation efficiently calculates the number of distinct ways to climb the stairs using dynamic programming, with a time complexity of O(n) and a space complexity of O(n).
Loading

0 comments on commit fb1d25f

Please sign in to comment.