Skip to content

Commit 5053e5c

Browse files
authored
Improved tasks 73-98
1 parent f2f0063 commit 5053e5c

File tree

10 files changed

+351
-388
lines changed

10 files changed

+351
-388
lines changed

src/main/python/g0001_0100/s0073_set_matrix_zeroes/readme.md

Lines changed: 29 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -35,73 +35,48 @@ You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
3535
* A simple improvement uses `O(m + n)` space, but still not the best solution.
3636
* Could you devise a constant space solution?
3737

38-
To solve the "Set Matrix Zeroes" problem in Python with the Solution class, follow these steps:
38+
To solve this task using Python with a `Solution` class, you can follow these steps:
3939

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.
40+
1. Define a class named `Solution`.
41+
2. Inside the class, define a method named `setZeroes` that takes `matrix` as an input parameter.
42+
3. Implement the logic to set entire rows and columns to zeros if any element in the row or column is zero.
43+
4. Use two boolean arrays `rows` and `cols` to keep track of which rows and columns need to be zeroed out.
44+
5. Iterate through the matrix and update the corresponding elements in the `rows` and `cols` arrays if any zero is encountered.
45+
6. Iterate through the matrix again and set the entire row to zeros if the corresponding `rows[i]` is True, and set the entire column to zeros if the corresponding `cols[j]` is True.
4646

47-
Here's the implementation of the `setZeroes` method in Python:
47+
Here's the implementation:
4848

4949
```python
5050
class Solution:
5151
def setZeroes(self, matrix):
5252
"""
5353
Do not return anything, modify matrix in-place instead.
5454
"""
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
55+
m, n = len(matrix), len(matrix[0])
56+
rows, cols = [False] * m, [False] * n
57+
58+
# Mark which rows and columns contain zeros
6159
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):
60+
for j in range(n):
7561
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:
62+
rows[i] = True
63+
cols[j] = True
64+
65+
# Set entire rows and columns to zeros
66+
for i in range(m):
9267
for j in range(n):
93-
matrix[0][j] = 0
68+
if rows[i] or cols[j]:
69+
matrix[i][j] = 0
9470

9571
# 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-
72+
solution = Solution()
73+
matrix1 = [[1,1,1],[1,0,1],[1,1,1]]
74+
solution.setZeroes(matrix1)
75+
print(matrix1) # Output: [[1,0,1],[0,0,0],[1,0,1]]
76+
77+
matrix2 = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
78+
solution.setZeroes(matrix2)
79+
print(matrix2) # Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
10580
```
10681

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.
82+
This solution has a time complexity of O(m * n), where m is the number of rows and n is the number of columns in the matrix. It modifies the matrix in-place, fulfilling the requirement of the task.

src/main/python/g0001_0100/s0074_search_a_2d_matrix/readme.md

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -30,47 +30,45 @@ Write an efficient algorithm that searches for a value in an `m x n` matrix. Thi
3030
* `1 <= m, n <= 100`
3131
* <code>-10<sup>4</sup> <= matrix[i][j], target <= 10<sup>4</sup></code>
3232

33-
To solve the "Search a 2D Matrix" problem in Python with the Solution class, follow these steps:
33+
To solve this task using Python with a `Solution` class, you can follow these steps:
3434

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`.
35+
1. Define a class named `Solution`.
36+
2. Inside the class, define a method named `searchMatrix` that takes `matrix` and `target` as input parameters.
37+
3. Implement the efficient algorithm to search for the target value in the matrix.
38+
4. Use a binary search approach to efficiently find the target value.
39+
5. Start the binary search from the top-right corner of the matrix.
40+
6. If the current element is equal to the target, return True.
41+
7. If the current element is greater than the target, move left in the same row.
42+
8. If the current element is less than the target, move down to the next row.
43+
9. Repeat steps 6-8 until the entire matrix is traversed.
44+
10. If the target is not found, return False.
4245

43-
Here's the implementation of the `searchMatrix` method in Python:
46+
Here's the implementation:
4447

4548
```python
4649
class Solution:
4750
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
51+
if not matrix or not matrix[0]:
52+
return False
53+
54+
rows, cols = len(matrix), len(matrix[0])
55+
row, col = 0, cols - 1
56+
57+
while row < rows and col >= 0:
58+
if matrix[row][col] == target:
59+
return True
60+
elif matrix[row][col] < target:
61+
row += 1
62+
else:
63+
col -= 1
64+
65+
return False
6466

6567
# 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
68+
solution = Solution()
69+
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
70+
print(solution.searchMatrix(matrix, 3)) # Output: True
71+
print(solution.searchMatrix(matrix, 13)) # Output: False
7472
```
7573

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.
74+
This solution has a time complexity of O(m + n), where m is the number of rows and n is the number of columns in the matrix. It efficiently searches for the target value by starting the search from the top-right corner and making decisions to move left or down based on the comparison with the current element.

src/main/python/g0001_0100/s0075_sort_colors/readme.md

Lines changed: 43 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -40,45 +40,54 @@ You must solve this problem without using the library's sort function.
4040

4141
**Follow up:** Could you come up with a one-pass algorithm using only constant extra space?
4242

43-
To solve the "Sort Colors" problem in Python with the Solution class, follow these steps:
43+
To solve this task using Python with a `Solution` class, you can follow these steps:
4444

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.
45+
1. Define a class named `Solution`.
46+
2. Inside the class, define a method named `sortColors` that takes `nums` as an input parameter.
47+
3. Implement the one-pass algorithm to sort the colors in-place.
48+
4. Use three pointers: `left`, `right`, and `curr`.
49+
5. Initialize `left` to 0, `right` to `len(nums) - 1`, and `curr` to 0.
50+
6. Iterate through the array while `curr` is less than or equal to `right`.
51+
7. If `nums[curr]` is 0, swap `nums[curr]` with `nums[left]`, increment both `left` and `curr`.
52+
8. If `nums[curr]` is 2, swap `nums[curr]` with `nums[right]`, decrement `right`.
53+
9. If `nums[curr]` is 1, simply increment `curr`.
54+
10. Repeat steps 6-9 until `curr` is greater than `right`.
5255

53-
Here's the implementation of the `sortColors` method in Python:
56+
Here's the implementation:
5457

5558
```python
5659
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-
60+
def sortColors(self, nums):
61+
left, right, curr = 0, len(nums) - 1, 0
62+
63+
while curr <= right:
64+
if nums[curr] == 0:
65+
nums[curr], nums[left] = nums[left], nums[curr]
66+
left += 1
67+
curr += 1
68+
elif nums[curr] == 2:
69+
nums[curr], nums[right] = nums[right], nums[curr]
70+
right -= 1
71+
else:
72+
curr += 1
73+
7774
# 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]
75+
solution = Solution()
76+
nums1 = [2,0,2,1,1,0]
77+
solution.sortColors(nums1)
78+
print(nums1) # Output: [0,0,1,1,2,2]
79+
80+
nums2 = [2,0,1]
81+
solution.sortColors(nums2)
82+
print(nums2) # Output: [0,1,2]
83+
84+
nums3 = [0]
85+
solution.sortColors(nums3)
86+
print(nums3) # Output: [0]
87+
88+
nums4 = [1]
89+
solution.sortColors(nums4)
90+
print(nums4) # Output: [1]
8291
```
8392

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.
93+
This solution sorts the colors in-place using a one-pass algorithm with constant extra space. It traverses the array only once, so the time complexity is O(n), where n is the length of the array `nums`.

src/main/python/g0001_0100/s0076_minimum_window_substring/readme.md

Lines changed: 44 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -41,56 +41,55 @@ A **substring** is a contiguous sequence of characters within the string.
4141

4242
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
4343

44-
To solve the "Minimum Window Substring" problem in Python 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 Python:
44+
To solve this task using Python with a `Solution` class, you can follow these steps:
45+
46+
1. Define a class named `Solution`.
47+
2. Inside the class, define a method named `minWindow` that takes `s` and `t` as input parameters.
48+
3. Implement an algorithm to find the minimum window substring of `s` that contains all characters of `t`.
49+
4. Use a sliding window approach to efficiently search for the minimum window substring.
50+
5. Create a dictionary `t_count` to store the frequency of characters in string `t`.
51+
6. Initialize variables `left` and `right` to keep track of the window boundaries.
52+
7. Initialize variables `min_window_start` and `min_window_length` to store the starting index and length of the minimum window substring found so far.
53+
8. Iterate through string `s` using the right pointer (`right`), and update the character frequencies in a temporary dictionary `window_count`.
54+
9. When all characters of `t` are found in the current window, update `min_window_start` and `min_window_length` if the current window is smaller than the minimum window found so far.
55+
10. Move the left pointer (`left`) to shrink the window until the window no longer contains all characters of `t`.
56+
11. Repeat steps 8-10 until the right pointer reaches the end of `s`.
57+
12. Return the minimum window substring found, or an empty string if no such substring exists.
58+
59+
Here's the implementation:
5760

5861
```python
5962
class Solution:
6063
def minWindow(self, s: str, t: str) -> str:
61-
from collections import Counter
62-
63-
map = [0] * 128
64+
t_count = {}
6465
for char in t:
65-
map[ord(char) - ord('A')] += 1
66-
67-
count = len(t)
68-
begin = 0
69-
end = 0
70-
d = float('inf')
71-
head = 0
72-
73-
while end < len(s):
74-
if map[ord(s[end]) - ord('A')] > 0:
75-
count -= 1
76-
map[ord(s[end]) - ord('A')] -= 1
77-
end += 1
78-
79-
while count == 0:
80-
if end - begin < d:
81-
d = end - begin
82-
head = begin
83-
map[ord(s[begin]) - ord('A')] += 1
84-
if map[ord(s[begin]) - ord('A')] > 0:
85-
count += 1
86-
begin += 1
87-
88-
return "" if d == float('inf') else s[head:head + d]
66+
t_count[char] = t_count.get(char, 0) + 1
67+
68+
left, right = 0, 0
69+
min_window_start = 0
70+
min_window_length = float('inf')
71+
required_chars = len(t)
72+
73+
while right < len(s):
74+
if s[right] in t_count:
75+
if t_count[s[right]] > 0:
76+
required_chars -= 1
77+
t_count[s[right]] -= 1
78+
79+
while required_chars == 0:
80+
if right - left + 1 < min_window_length:
81+
min_window_length = right - left + 1
82+
min_window_start = left
83+
84+
if s[left] in t_count:
85+
t_count[s[left]] += 1
86+
if t_count[s[left]] > 0:
87+
required_chars += 1
88+
left += 1
89+
90+
right += 1
8991

90-
# Example usage:
91-
# sol = Solution()
92-
# result = sol.minWindow("ADOBECODEBANC", "ABC")
93-
# print(result) # Output should be "BANC"
92+
return s[min_window_start:min_window_start + min_window_length] if min_window_length != float('inf') else ""
9493
```
9594

96-
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`.
95+
This solution uses a sliding window approach to efficiently search for the minimum window substring. It iterates through the string `s` only once, so the time complexity is O(m + n), where m is the length of `s` and n is the length of `t`.

0 commit comments

Comments
 (0)