Skip to content

Commit e915751

Browse files
authored
Added tasks 48-72
1 parent 0209c09 commit e915751

File tree

20 files changed

+942
-0
lines changed

20 files changed

+942
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Math #Matrix
2+
# #Data_Structure_II_Day_3_Array #Programming_Skills_II_Day_7 #Udemy_2D_Arrays/Matrix
3+
# #Big_O_Time_O(n^2)_Space_O(1) #2024_06_08_Time_26_ms_(98.93%)_Space_16.5_MB_(91.88%)
4+
5+
class Solution:
6+
def rotate(self, matrix: List[List[int]]) -> None:
7+
"""
8+
Do not return anything, modify matrix in-place instead.
9+
"""
10+
n = len(matrix)
11+
for i in range(n // 2):
12+
for j in range(i, n - i - 1):
13+
positions = [
14+
[i, j],
15+
[j, n - 1 - i],
16+
[n - 1 - i, n - 1 - j],
17+
[n - 1 - j, i]
18+
]
19+
t = matrix[positions[0][0]][positions[0][1]]
20+
for k in range(1, len(positions)):
21+
temp = matrix[positions[k][0]][positions[k][1]]
22+
matrix[positions[k][0]][positions[k][1]] = t
23+
t = temp
24+
matrix[positions[0][0]][positions[0][1]] = t
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
48\. Rotate Image
2+
3+
Medium
4+
5+
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
6+
7+
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
8+
9+
**Example 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg)
12+
13+
**Input:** matrix = [[1,2,3],[4,5,6],[7,8,9]]
14+
15+
**Output:** [[7,4,1],[8,5,2],[9,6,3]]
16+
17+
**Example 2:**
18+
19+
![](https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg)
20+
21+
**Input:** matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
22+
23+
**Output:** [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
24+
25+
**Example 3:**
26+
27+
**Input:** matrix = [[1]]
28+
29+
**Output:** [[1]]
30+
31+
**Example 4:**
32+
33+
**Input:** matrix = [[1,2],[3,4]]
34+
35+
**Output:** [[3,1],[4,2]]
36+
37+
**Constraints:**
38+
39+
* `matrix.length == n`
40+
* `matrix[i].length == n`
41+
* `1 <= n <= 20`
42+
* `-1000 <= matrix[i][j] <= 1000`
43+
44+
To solve the "Rotate Image" problem in Java with a `Solution` class, we can follow these steps:
45+
46+
1. Define a `Solution` class.
47+
2. Define a method named `rotate` that takes a 2D array `matrix` representing an image as input and rotates the image by 90 degrees clockwise.
48+
3. Determine the number of layers in the matrix, which is equal to half of the matrix's size.
49+
4. Iterate through each layer from outer to inner layers.
50+
5. For each layer:
51+
- Iterate through each element in the current layer.
52+
- Swap the elements of the current layer in a clockwise manner.
53+
6. Return the rotated matrix.
54+
55+
Here's the implementation:
56+
57+
```java
58+
public class Solution {
59+
public void rotate(int[][] matrix) {
60+
int n = matrix.length;
61+
int layers = n / 2;
62+
63+
for (int layer = 0; layer < layers; layer++) {
64+
int first = layer;
65+
int last = n - 1 - layer;
66+
67+
for (int i = first; i < last; i++) {
68+
int offset = i - first;
69+
int top = matrix[first][i];
70+
71+
// Move left to top
72+
matrix[first][i] = matrix[last - offset][first];
73+
74+
// Move bottom to left
75+
matrix[last - offset][first] = matrix[last][last - offset];
76+
77+
// Move right to bottom
78+
matrix[last][last - offset] = matrix[i][last];
79+
80+
// Move top to right
81+
matrix[i][last] = top;
82+
}
83+
}
84+
}
85+
}
86+
```
87+
88+
This implementation provides a solution to the "Rotate Image" problem in Java. It rotates the given 2D matrix representing an image by 90 degrees clockwise in-place.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #String #Hash_Table #Sorting
2+
# #Data_Structure_II_Day_8_String #Programming_Skills_II_Day_11 #Udemy_Strings
3+
# #Big_O_Time_O(n*k_log_k)_Space_O(n) #2024_06_08_Time_79_ms_(93.60%)_Space_19.6_MB_(76.55%)
4+
5+
from collections import defaultdict
6+
7+
class Solution:
8+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
9+
anagram_groups = defaultdict(list)
10+
for s in strs:
11+
sorted_str = ''.join(sorted(s))
12+
anagram_groups[sorted_str].append(s)
13+
return list(anagram_groups.values())
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
49\. Group Anagrams
2+
3+
Medium
4+
5+
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
6+
7+
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
8+
9+
**Example 1:**
10+
11+
**Input:** strs = ["eat","tea","tan","ate","nat","bat"]
12+
13+
**Output:** [["bat"],["nat","tan"],["ate","eat","tea"]]
14+
15+
**Example 2:**
16+
17+
**Input:** strs = [""]
18+
19+
**Output:** [[""]]
20+
21+
**Example 3:**
22+
23+
**Input:** strs = ["a"]
24+
25+
**Output:** [["a"]]
26+
27+
**Constraints:**
28+
29+
* <code>1 <= strs.length <= 10<sup>4</sup></code>
30+
* `0 <= strs[i].length <= 100`
31+
* `strs[i]` consists of lowercase English letters.
32+
33+
To solve the "Group Anagrams" problem in Java with the Solution class, follow these steps:
34+
35+
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.
36+
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.
37+
3. Iterate through each string `str` in the input array `strs`.
38+
4. Sort the characters of the current string `str` to create a key for the HashMap.
39+
5. Check if the sorted string exists as a key in the HashMap:
40+
- If it does, add the original string `str` to the corresponding list of strings.
41+
- 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.
42+
6. After iterating through all strings, return the values of the HashMap as the result.
43+
44+
Here's the implementation of the `groupAnagrams` method in Java:
45+
46+
```java
47+
import java.util.*;
48+
49+
class Solution {
50+
public List<List<String>> groupAnagrams(String[] strs) {
51+
// Initialize a HashMap to store the groups of anagrams
52+
Map<String, List<String>> anagramGroups = new HashMap<>();
53+
54+
// Iterate through each string in the input array
55+
for (String str : strs) {
56+
// Sort the characters of the current string
57+
char[] chars = str.toCharArray();
58+
Arrays.sort(chars);
59+
String sortedStr = new String(chars);
60+
61+
// Check if the sorted string exists as a key in the HashMap
62+
if (anagramGroups.containsKey(sortedStr)) {
63+
// If it does, add the original string to the corresponding list
64+
anagramGroups.get(sortedStr).add(str);
65+
} else {
66+
// If it doesn't, create a new entry in the HashMap
67+
List<String> group = new ArrayList<>();
68+
group.add(str);
69+
anagramGroups.put(sortedStr, group);
70+
}
71+
}
72+
73+
// Return the values of the HashMap as the result
74+
return new ArrayList<>(anagramGroups.values());
75+
}
76+
}
77+
```
78+
79+
This implementation ensures that all anagrams are grouped together efficiently using a HashMap.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# #Hard #Top_100_Liked_Questions #Array #Backtracking #Big_O_Time_O(N!)_Space_O(N)
2+
# #2024_06_08_Time_31_ms_(99.90%)_Space_16.9_MB_(70.82%)
3+
4+
class Solution:
5+
def solveNQueens(self, n: int) -> List[List[str]]:
6+
pos = [False] * (n + 2 * n - 1 + 2 * n - 1)
7+
pos2 = [0] * n
8+
ans = []
9+
self.helper(n, 0, pos, pos2, ans)
10+
return ans
11+
12+
def helper(self, n: int, row: int, pos: List[bool], pos2: List[int], ans: List[List[str]]):
13+
if row == n:
14+
self.construct(n, pos2, ans)
15+
return
16+
for i in range(n):
17+
index = n + 2 * n - 1 + n - 1 + i - row
18+
if pos[i] or pos[n + i + row] or pos[index]:
19+
continue
20+
pos[i] = True
21+
pos[n + i + row] = True
22+
pos[index] = True
23+
pos2[row] = i
24+
self.helper(n, row + 1, pos, pos2, ans)
25+
pos[i] = False
26+
pos[n + i + row] = False
27+
pos[index] = False
28+
29+
def construct(self, n: int, pos: list[int], ans: list[list[str]]):
30+
sol = []
31+
for r in range(n):
32+
queenRow = ['.'] * n
33+
queenRow[pos[r]] = 'Q'
34+
sol.append(''.join(queenRow))
35+
ans.append(sol)
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
51\. N-Queens
2+
3+
Hard
4+
5+
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
6+
7+
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
8+
9+
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
10+
11+
**Example 1:**
12+
13+
![](https://assets.leetcode.com/uploads/2020/11/13/queens.jpg)
14+
15+
**Input:** n = 4
16+
17+
**Output:** [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
18+
19+
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
20+
21+
**Example 2:**
22+
23+
**Input:** n = 1
24+
25+
**Output:** [["Q"]]
26+
27+
**Constraints:**
28+
29+
* `1 <= n <= 9`
30+
31+
To solve the "N-Queens" problem in Java with the Solution class, follow these steps:
32+
33+
1. Define a method `solveNQueens` in the `Solution` class that takes an integer `n` as input and returns a list of lists of strings.
34+
2. Initialize a board represented as a 2D character array of size `n x n`. Initialize all cells to `'.'`, indicating an empty space.
35+
3. Define a recursive backtracking function `backtrack` to explore all possible configurations of queens on the board.
36+
4. In the `backtrack` function:
37+
- 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.
38+
- Iterate through each column index `col` from `0` to `n - 1`:
39+
- Check if it's safe to place a queen at position `(row, col)` by calling a helper function `isSafe`.
40+
- If it's safe, place a queen at position `(row, col)` on the board, mark it as `'Q'`.
41+
- Recur to the next row by calling `backtrack(row + 1)`.
42+
- Backtrack: After exploring all possibilities, remove the queen from position `(row, col)` by marking it as `'.'`.
43+
5. In the `solveNQueens` method, initialize an empty list `result` to store the solutions.
44+
6. Call the `backtrack` function with initial parameters `0` for the row index.
45+
7. Return the `result` list containing all distinct solutions.
46+
47+
Here's the implementation of the `solveNQueens` method in Java:
48+
49+
```java
50+
import java.util.*;
51+
52+
class Solution {
53+
public List<List<String>> solveNQueens(int n) {
54+
List<List<String>> result = new ArrayList<>();
55+
char[][] board = new char[n][n];
56+
for (int i = 0; i < n; i++) {
57+
Arrays.fill(board[i], '.');
58+
}
59+
backtrack(board, 0, result);
60+
return result;
61+
}
62+
63+
private void backtrack(char[][] board, int row, List<List<String>> result) {
64+
int n = board.length;
65+
if (row == n) {
66+
result.add(constructBoard(board));
67+
return;
68+
}
69+
for (int col = 0; col < n; col++) {
70+
if (isSafe(board, row, col)) {
71+
board[row][col] = 'Q';
72+
backtrack(board, row + 1, result);
73+
board[row][col] = '.';
74+
}
75+
}
76+
}
77+
78+
private boolean isSafe(char[][] board, int row, int col) {
79+
int n = board.length;
80+
for (int i = 0; i < row; i++) {
81+
if (board[i][col] == 'Q') {
82+
return false;
83+
}
84+
}
85+
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
86+
if (board[i][j] == 'Q') {
87+
return false;
88+
}
89+
}
90+
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
91+
if (board[i][j] == 'Q') {
92+
return false;
93+
}
94+
}
95+
return true;
96+
}
97+
98+
private List<String> constructBoard(char[][] board) {
99+
List<String> solution = new ArrayList<>();
100+
for (char[] row : board) {
101+
solution.add(new String(row));
102+
}
103+
return solution;
104+
}
105+
}
106+
```
107+
108+
This implementation efficiently finds all distinct solutions to the N-Queens problem using backtracking.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Dynamic_Programming
2+
# #Divide_and_Conquer #Data_Structure_I_Day_1_Array #Dynamic_Programming_I_Day_5
3+
# #Udemy_Famous_Algorithm #Big_O_Time_O(n)_Space_O(1)
4+
# #2024_06_08_Time_501_ms_(83.84%)_Space_30.7_MB_(91.05%)
5+
6+
class Solution:
7+
def maxSubArray(self, nums: List[int]) -> int:
8+
maxi = float('-inf')
9+
sum_val = 0
10+
for num in nums:
11+
# calculating sub-array sum
12+
sum_val += num
13+
maxi = max(sum_val, maxi)
14+
if sum_val < 0:
15+
# there is no point to carry a -ve subarray sum. hence setting to 0
16+
sum_val = 0
17+
return maxi

0 commit comments

Comments
 (0)