Skip to content

Commit f2f0063

Browse files
authored
Added tasks 73-98
1 parent dcd8373 commit f2f0063

File tree

21 files changed

+1145
-0
lines changed

21 files changed

+1145
-0
lines changed

README.md

Lines changed: 28 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table #Matrix
2+
# #Udemy_2D_Arrays/Matrix #Big_O_Time_O(m*n)_Space_O(1)
3+
# #2024_06_09_Time_93_ms_(94.48%)_Space_17.4_MB_(67.69%)
4+
5+
class Solution:
6+
def setZeroes(self, matrix: List[List[int]]) -> None:
7+
"""
8+
Do not return anything, modify matrix in-place instead.
9+
"""
10+
m = len(matrix)
11+
n = len(matrix[0])
12+
row0 = False
13+
col0 = False
14+
15+
# Check if 0th column needs to be marked all 0s in future
16+
for i in range(m):
17+
if matrix[i][0] == 0:
18+
col0 = True
19+
break
20+
21+
# Check if 0th row needs to be marked all 0s in future
22+
for j in range(n):
23+
if matrix[0][j] == 0:
24+
row0 = True
25+
break
26+
27+
# Store the signals in 0th row and column
28+
for i in range(1, m):
29+
for j in range(1, n):
30+
if matrix[i][j] == 0:
31+
matrix[i][0] = 0
32+
matrix[0][j] = 0
33+
34+
# Mark 0 for all cells based on signal from 0th row and 0th column
35+
for i in range(1, m):
36+
for j in range(1, n):
37+
if matrix[i][0] == 0 or matrix[0][j] == 0:
38+
matrix[i][j] = 0
39+
40+
# Set 0th column
41+
if col0:
42+
for i in range(m):
43+
matrix[i][0] = 0
44+
45+
# Set 0th row
46+
if row0:
47+
for j in range(n):
48+
matrix[0][j] = 0
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
73\. Set Matrix Zeroes
2+
3+
Medium
4+
5+
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s, and return _the matrix_.
6+
7+
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
8+
9+
**Example 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg)
12+
13+
**Input:** matrix = [[1,1,1],[1,0,1],[1,1,1]]
14+
15+
**Output:** [[1,0,1],[0,0,0],[1,0,1]]
16+
17+
**Example 2:**
18+
19+
![](https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg)
20+
21+
**Input:** matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
22+
23+
**Output:** [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
24+
25+
**Constraints:**
26+
27+
* `m == matrix.length`
28+
* `n == matrix[0].length`
29+
* `1 <= m, n <= 200`
30+
* <code>-2<sup>31</sup> <= matrix[i][j] <= 2<sup>31</sup> - 1</code>
31+
32+
**Follow up:**
33+
34+
* A straightforward solution using `O(mn)` space is probably a bad idea.
35+
* A simple improvement uses `O(m + n)` space, but still not the best solution.
36+
* Could you devise a constant space solution?
37+
38+
To solve the "Set Matrix Zeroes" problem in Python with the Solution class, follow these steps:
39+
40+
1. Define a method `setZeroes` in the `Solution` class that takes a 2D integer matrix `matrix` as input and modifies it in place to set the entire row and column to zeros if an element is zero.
41+
2. Initialize two boolean arrays `rowZero` and `colZero` of size `m` and `n` respectively, where `m` is the number of rows in the matrix and `n` is the number of columns. These arrays will track whether a row or column needs to be set to zero.
42+
3. Iterate over the matrix to mark the rows and columns that contain zeros:
43+
- If `matrix[i][j]` is zero, set `rowZero[i] = true` and `colZero[j] = true`.
44+
4. Iterate over the matrix again and set the entire row to zeros if `rowZero[i] = true` or the entire column to zeros if `colZero[j] = true`.
45+
5. Return the modified matrix.
46+
47+
Here's the implementation of the `setZeroes` method in Python:
48+
49+
```python
50+
class Solution:
51+
def setZeroes(self, matrix):
52+
"""
53+
Do not return anything, modify matrix in-place instead.
54+
"""
55+
m = len(matrix)
56+
n = len(matrix[0])
57+
row0 = False
58+
col0 = False
59+
60+
# Check if 0th column needs to be marked all 0s in future
61+
for i in range(m):
62+
if matrix[i][0] == 0:
63+
col0 = True
64+
break
65+
66+
# Check if 0th row needs to be marked all 0s in future
67+
for j in range(n):
68+
if matrix[0][j] == 0:
69+
row0 = True
70+
break
71+
72+
# Store the signals in 0th row and column
73+
for i in range(1, m):
74+
for j in range(1, n):
75+
if matrix[i][j] == 0:
76+
matrix[i][0] = 0
77+
matrix[0][j] = 0
78+
79+
# Mark 0 for all cells based on signal from 0th row and 0th column
80+
for i in range(1, m):
81+
for j in range(1, n):
82+
if matrix[i][0] == 0 or matrix[0][j] == 0:
83+
matrix[i][j] = 0
84+
85+
# Set 0th column
86+
if col0:
87+
for i in range(m):
88+
matrix[i][0] = 0
89+
90+
# Set 0th row
91+
if row0:
92+
for j in range(n):
93+
matrix[0][j] = 0
94+
95+
# Example usage:
96+
# sol = Solution()
97+
# matrix = [
98+
# [1, 1, 1],
99+
# [1, 0, 1],
100+
# [1, 1, 1]
101+
# ]
102+
# sol.setZeroes(matrix)
103+
# print(matrix) # Output should be [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
104+
105+
```
106+
107+
This implementation modifies the matrix in place to set entire rows and columns to zeros, with a time complexity of O(m * n) and a space complexity of O(m + n), where `m` is the number of rows and `n` is the number of columns in the matrix.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# #Medium #Top_100_Liked_Questions #Array #Binary_Search #Matrix #Data_Structure_I_Day_5_Array
2+
# #Algorithm_II_Day_1_Binary_Search #Binary_Search_I_Day_8 #Level_2_Day_8_Binary_Search
3+
# #Udemy_2D_Arrays/Matrix #Big_O_Time_O(endRow+endCol)_Space_O(1)
4+
# #2024_06_09_Time_35_ms_(97.66%)_Space_17_MB_(69.27%)
5+
6+
class Solution:
7+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
8+
endRow = len(matrix)
9+
endCol = len(matrix[0])
10+
targetRow = 0
11+
result = False
12+
13+
for i in range(endRow):
14+
if matrix[i][endCol - 1] >= target:
15+
targetRow = i
16+
break
17+
18+
for i in range(endCol):
19+
if matrix[targetRow][i] == target:
20+
result = True
21+
break
22+
23+
return result
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
74\. Search a 2D Matrix
2+
3+
Medium
4+
5+
Write an efficient algorithm that searches for a value in an `m x n` matrix. This matrix has the following properties:
6+
7+
* Integers in each row are sorted from left to right.
8+
* The first integer of each row is greater than the last integer of the previous row.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2020/10/05/mat.jpg)
13+
14+
**Input:** matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
15+
16+
**Output:** true
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg)
21+
22+
**Input:** matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
23+
24+
**Output:** false
25+
26+
**Constraints:**
27+
28+
* `m == matrix.length`
29+
* `n == matrix[i].length`
30+
* `1 <= m, n <= 100`
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 Python 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 Python:
44+
45+
```python
46+
class Solution:
47+
def searchMatrix(self, matrix, target):
48+
endRow = len(matrix)
49+
endCol = len(matrix[0])
50+
targetRow = 0
51+
result = False
52+
53+
for i in range(endRow):
54+
if matrix[i][endCol - 1] >= target:
55+
targetRow = i
56+
break
57+
58+
for i in range(endCol):
59+
if matrix[targetRow][i] == target:
60+
result = True
61+
break
62+
63+
return result
64+
65+
# Example usage:
66+
# sol = Solution()
67+
# matrix = [
68+
# [1, 3, 5, 7],
69+
# [10, 11, 16, 20],
70+
# [23, 30, 34, 60]
71+
# ]
72+
# target = 3
73+
# print(sol.searchMatrix(matrix, target)) # Output should be True
74+
```
75+
76+
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.
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 #Sorting #Two_Pointers
2+
# #Data_Structure_II_Day_2_Array #Udemy_Arrays #Big_O_Time_O(n)_Space_O(1)
3+
# #2024_06_09_Time_31_ms_(90.70%)_Space_16.4_MB_(80.54%)
4+
5+
class Solution:
6+
def sortColors(self, nums: List[int]) -> None:
7+
"""
8+
Do not return anything, modify nums in-place instead.
9+
"""
10+
zeroes = 0
11+
ones = 0
12+
13+
for i in range(len(nums)):
14+
if nums[i] == 0:
15+
nums[zeroes] = 0
16+
zeroes += 1
17+
elif nums[i] == 1:
18+
ones += 1
19+
20+
for j in range(zeroes, zeroes + ones):
21+
nums[j] = 1
22+
23+
for k in range(zeroes + ones, len(nums)):
24+
nums[k] = 2
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
75\. Sort Colors
2+
3+
Medium
4+
5+
Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
6+
7+
We will use the integers `0`, `1`, and `2` to represent the color red, white, and blue, respectively.
8+
9+
You must solve this problem without using the library's sort function.
10+
11+
**Example 1:**
12+
13+
**Input:** nums = [2,0,2,1,1,0]
14+
15+
**Output:** [0,0,1,1,2,2]
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [2,0,1]
20+
21+
**Output:** [0,1,2]
22+
23+
**Example 3:**
24+
25+
**Input:** nums = [0]
26+
27+
**Output:** [0]
28+
29+
**Example 4:**
30+
31+
**Input:** nums = [1]
32+
33+
**Output:** [1]
34+
35+
**Constraints:**
36+
37+
* `n == nums.length`
38+
* `1 <= n <= 300`
39+
* `nums[i]` is `0`, `1`, or `2`.
40+
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 Python 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 Python:
54+
55+
```python
56+
class Solution:
57+
def sortColors(self, nums: List[int]) -> None:
58+
"""
59+
Do not return anything, modify nums in-place instead.
60+
"""
61+
zeroes = 0
62+
ones = 0
63+
64+
for i in range(len(nums)):
65+
if nums[i] == 0:
66+
nums[zeroes] = 0
67+
zeroes += 1
68+
elif nums[i] == 1:
69+
ones += 1
70+
71+
for j in range(zeroes, zeroes + ones):
72+
nums[j] = 1
73+
74+
for k in range(zeroes + ones, len(nums)):
75+
nums[k] = 2
76+
77+
# Example usage:
78+
# sol = Solution()
79+
# nums = [2, 0, 2, 1, 1, 0]
80+
# sol.sortColors(nums)
81+
# print(nums) # Output should be [0, 0, 1, 1, 2, 2]
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.

0 commit comments

Comments
 (0)