Skip to content

Commit cb56b4c

Browse files
authored
Added tasks 31-46
1 parent 88c5c6d commit cb56b4c

File tree

20 files changed

+1086
-0
lines changed

20 files changed

+1086
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# #Medium #Top_100_Liked_Questions #Array #Two_Pointers #Big_O_Time_O(n)_Space_O(1)
2+
# #2024_06_08_Time_35_ms_(93.06%)_Space_16.5_MB_(44.75%)
3+
4+
class Solution:
5+
def nextPermutation(self, nums: List[int]) -> None:
6+
"""
7+
Do not return anything, modify nums in-place instead.
8+
"""
9+
if not nums or len(nums) <= 1:
10+
return
11+
12+
i = len(nums) - 2
13+
while i >= 0 and nums[i] >= nums[i + 1]:
14+
i -= 1
15+
16+
if i >= 0:
17+
j = len(nums) - 1
18+
while nums[j] <= nums[i]:
19+
j -= 1
20+
self.swap(nums, i, j)
21+
22+
self.reverse(nums, i + 1, len(nums) - 1)
23+
24+
def swap(self, nums, i, j):
25+
nums[i], nums[j] = nums[j], nums[i]
26+
27+
def reverse(self, nums, i, j):
28+
while i < j:
29+
self.swap(nums, i, j)
30+
i += 1
31+
j -= 1
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
31\. Next Permutation
2+
3+
Medium
4+
5+
Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers.
6+
7+
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
8+
9+
The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory.
10+
11+
**Example 1:**
12+
13+
**Input:** nums = [1,2,3]
14+
15+
**Output:** [1,3,2]
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [3,2,1]
20+
21+
**Output:** [1,2,3]
22+
23+
**Example 3:**
24+
25+
**Input:** nums = [1,1,5]
26+
27+
**Output:** [1,5,1]
28+
29+
**Example 4:**
30+
31+
**Input:** nums = [1]
32+
33+
**Output:** [1]
34+
35+
**Constraints:**
36+
37+
* `1 <= nums.length <= 100`
38+
* `0 <= nums[i] <= 100`
39+
40+
To solve the "Next Permutation" problem in Java with a `Solution` class, we can follow these steps:
41+
42+
1. Define a `Solution` class.
43+
2. Define a method named `nextPermutation` that takes an integer array `nums` as input and modifies it to find the next permutation in lexicographic order.
44+
3. Find the first index `i` from the right such that `nums[i] > nums[i - 1]`. If no such index exists, reverse the entire array, as it's already the last permutation.
45+
4. Find the smallest index `j` from the right such that `nums[j] > nums[i - 1]`.
46+
5. Swap `nums[i - 1]` with `nums[j]`.
47+
6. Reverse the suffix of the array starting from index `i`.
48+
49+
Here's the implementation:
50+
51+
```java
52+
public class Solution {
53+
public void nextPermutation(int[] nums) {
54+
int n = nums.length;
55+
56+
// Step 1: Find the first index i from the right such that nums[i] > nums[i - 1]
57+
int i = n - 1;
58+
while (i > 0 && nums[i] <= nums[i - 1]) {
59+
i--;
60+
}
61+
62+
// Step 2: If no such index exists, reverse the entire array
63+
if (i == 0) {
64+
reverse(nums, 0, n - 1);
65+
return;
66+
}
67+
68+
// Step 3: Find the smallest index j from the right such that nums[j] > nums[i - 1]
69+
int j = n - 1;
70+
while (nums[j] <= nums[i - 1]) {
71+
j--;
72+
}
73+
74+
// Step 4: Swap nums[i - 1] with nums[j]
75+
swap(nums, i - 1, j);
76+
77+
// Step 5: Reverse the suffix of the array starting from index i
78+
reverse(nums, i, n - 1);
79+
}
80+
81+
// Helper method to reverse a portion of the array
82+
private void reverse(int[] nums, int start, int end) {
83+
while (start < end) {
84+
swap(nums, start, end);
85+
start++;
86+
end--;
87+
}
88+
}
89+
90+
// Helper method to swap two elements in the array
91+
private void swap(int[] nums, int i, int j) {
92+
int temp = nums[i];
93+
nums[i] = nums[j];
94+
nums[j] = temp;
95+
}
96+
}
97+
```
98+
99+
This implementation provides a solution to the "Next Permutation" problem in Java. It finds the next lexicographically greater permutation of the given array `nums` and modifies it in place.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# #Hard #Top_100_Liked_Questions #String #Dynamic_Programming #Stack #Big_O_Time_O(n)_Space_O(1)
2+
# #2024_06_08_Time_36_ms_(89.25%)_Space_16.7_MB_(89.20%)
3+
4+
class Solution:
5+
def longestValidParentheses(self, s: str) -> int:
6+
max_length = 0
7+
left = 0
8+
right = 0
9+
n = len(s)
10+
11+
# First pass: left to right
12+
for i in range(n):
13+
if s[i] == '(':
14+
left += 1
15+
else:
16+
right += 1
17+
if right > left:
18+
left = 0
19+
right = 0
20+
if left == right:
21+
max_length = max(max_length, 2 * right)
22+
23+
left = 0
24+
right = 0
25+
26+
# Second pass: right to left
27+
for i in range(n - 1, -1, -1):
28+
if s[i] == '(':
29+
left += 1
30+
else:
31+
right += 1
32+
if left > right:
33+
left = 0
34+
right = 0
35+
if left == right:
36+
max_length = max(max_length, 2 * left)
37+
38+
return max_length
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
32\. Longest Valid Parentheses
2+
3+
Hard
4+
5+
Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring.
6+
7+
**Example 1:**
8+
9+
**Input:** s = "(()"
10+
11+
**Output:** 2
12+
13+
**Explanation:** The longest valid parentheses substring is "()".
14+
15+
**Example 2:**
16+
17+
**Input:** s = ")()())"
18+
19+
**Output:** 4
20+
21+
**Explanation:** The longest valid parentheses substring is "()()".
22+
23+
**Example 3:**
24+
25+
**Input:** s = ""
26+
27+
**Output:** 0
28+
29+
**Constraints:**
30+
31+
* <code>0 <= s.length <= 3 * 10<sup>4</sup></code>
32+
* `s[i]` is `'('`, or `')'`.
33+
34+
To solve the "Longest Valid Parentheses" problem in Java with a `Solution` class, we can follow these steps:
35+
36+
1. Define a `Solution` class.
37+
2. Define a method named `longestValidParentheses` that takes a string `s` as input and returns an integer representing the length of the longest valid parentheses substring.
38+
3. Initialize a stack to store the indices of characters.
39+
4. Initialize a variable `maxLen` to store the maximum length of valid parentheses found so far.
40+
5. Push `-1` onto the stack to mark the starting point of a potential valid substring.
41+
6. Iterate through each character of the string:
42+
- If the character is `'('`, push its index onto the stack.
43+
- If the character is `')'`:
44+
- Pop the top index from the stack.
45+
- If the stack is empty after popping, push the current index onto the stack to mark the starting point of the next potential valid substring.
46+
- Otherwise, update `maxLen` with the maximum of the current `maxLen` and `i - stack.peek()`, where `i` is the current index and `stack.peek()` is the index at the top of the stack.
47+
7. Return `maxLen`.
48+
49+
Here's the implementation:
50+
51+
```java
52+
import java.util.Stack;
53+
54+
public class Solution {
55+
public int longestValidParentheses(String s) {
56+
int maxLen = 0;
57+
Stack<Integer> stack = new Stack<>();
58+
stack.push(-1); // Mark the starting point of a potential valid substring
59+
60+
for (int i = 0; i < s.length(); i++) {
61+
char c = s.charAt(i);
62+
if (c == '(') {
63+
stack.push(i);
64+
} else { // c == ')'
65+
stack.pop();
66+
if (stack.isEmpty()) {
67+
stack.push(i); // Mark the starting point of the next potential valid substring
68+
} else {
69+
maxLen = Math.max(maxLen, i - stack.peek());
70+
}
71+
}
72+
}
73+
74+
return maxLen;
75+
}
76+
}
77+
```
78+
79+
This implementation provides a solution to the "Longest Valid Parentheses" problem in Java. It finds the length of the longest valid parentheses substring in the given string `s`.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Binary_Search
2+
# #Algorithm_II_Day_1_Binary_Search #Binary_Search_I_Day_11 #Level_2_Day_8_Binary_Search
3+
# #Udemy_Binary_Search #Big_O_Time_O(log_n)_Space_O(1)
4+
# #2024_06_08_Time_36_ms_(91.71%)_Space_16.8_MB_(98.65%)
5+
6+
class Solution:
7+
def search(self, nums: List[int], target: int) -> int:
8+
lo, hi = 0, len(nums) - 1
9+
10+
while lo <= hi:
11+
mid = (hi - lo) // 2 + lo
12+
if nums[mid] == target:
13+
return mid
14+
# If the left half is sorted
15+
if nums[lo] <= nums[mid]:
16+
if nums[lo] <= target <= nums[mid]:
17+
hi = mid - 1
18+
else:
19+
lo = mid + 1
20+
# If the right half is sorted
21+
else:
22+
if nums[mid] <= target <= nums[hi]:
23+
lo = mid + 1
24+
else:
25+
hi = mid - 1
26+
27+
return -1
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
33\. Search in Rotated Sorted Array
2+
3+
Medium
4+
5+
There is an integer array `nums` sorted in ascending order (with **distinct** values).
6+
7+
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
8+
9+
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
10+
11+
You must write an algorithm with `O(log n)` runtime complexity.
12+
13+
**Example 1:**
14+
15+
**Input:** nums = [4,5,6,7,0,1,2], target = 0
16+
17+
**Output:** 4
18+
19+
**Example 2:**
20+
21+
**Input:** nums = [4,5,6,7,0,1,2], target = 3
22+
23+
**Output:** -1
24+
25+
**Example 3:**
26+
27+
**Input:** nums = [1], target = 0
28+
29+
**Output:** -1
30+
31+
**Constraints:**
32+
33+
* `1 <= nums.length <= 5000`
34+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
35+
* All values of `nums` are **unique**.
36+
* `nums` is an ascending array that is possibly rotated.
37+
* <code>-10<sup>4</sup> <= target <= 10<sup>4</sup></code>
38+
39+
To solve the "Search in Rotated Sorted Array" problem in Java with a `Solution` class, we can follow these steps:
40+
41+
1. Define a `Solution` class.
42+
2. Define a method named `search` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index of `target` in `nums`. If `target` is not found, return `-1`.
43+
3. Implement the binary search algorithm to find the index of `target` in the rotated sorted array.
44+
4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1.
45+
5. While `left` is less than or equal to `right`:
46+
- Calculate the middle index `mid` as `(left + right) / 2`.
47+
- If `nums[mid]` is equal to `target`, return `mid`.
48+
- Check if the left half of the array (`nums[left]` to `nums[mid]`) is sorted:
49+
- If `nums[left] <= nums[mid]` and `nums[left] <= target < nums[mid]`, update `right = mid - 1`.
50+
- Otherwise, update `left = mid + 1`.
51+
- Otherwise, check if the right half of the array (`nums[mid]` to `nums[right]`) is sorted:
52+
- If `nums[mid] <= nums[right]` and `nums[mid] < target <= nums[right]`, update `left = mid + 1`.
53+
- Otherwise, update `right = mid - 1`.
54+
6. If `target` is not found, return `-1`.
55+
56+
Here's the implementation:
57+
58+
```java
59+
public class Solution {
60+
public int search(int[] nums, int target) {
61+
int left = 0;
62+
int right = nums.length - 1;
63+
64+
while (left <= right) {
65+
int mid = left + (right - left) / 2;
66+
67+
if (nums[mid] == target) {
68+
return mid;
69+
}
70+
71+
if (nums[left] <= nums[mid]) {
72+
if (nums[left] <= target && target < nums[mid]) {
73+
right = mid - 1;
74+
} else {
75+
left = mid + 1;
76+
}
77+
} else {
78+
if (nums[mid] < target && target <= nums[right]) {
79+
left = mid + 1;
80+
} else {
81+
right = mid - 1;
82+
}
83+
}
84+
}
85+
86+
return -1;
87+
}
88+
}
89+
```
90+
91+
This implementation provides a solution to the "Search in Rotated Sorted Array" problem in Java. It searches for the index of `target` in the rotated sorted array `nums`. The algorithm has a time complexity of O(log n).
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Binary_Search
2+
# #Algorithm_II_Day_1_Binary_Search #Binary_Search_I_Day_5 #Big_O_Time_O(log_n)_Space_O(1)
3+
# #2024_06_08_Time_64_ms_(97.49%)_Space_17.8_MB_(39.66%)
4+
5+
class Solution:
6+
def searchRange(self, nums: List[int], target: int) -> List[int]:
7+
ans = [-1, -1]
8+
ans[0] = self.helper(nums, target, False)
9+
ans[1] = self.helper(nums, target, True)
10+
return ans
11+
12+
def helper(self, nums: List[int], target: int, equals: bool) -> int:
13+
l, r = 0, len(nums) - 1
14+
result = -1
15+
while l <= r:
16+
mid = l + (r - l) // 2
17+
if nums[mid] == target:
18+
result = mid
19+
if nums[mid] < target or (nums[mid] == target and equals):
20+
l = mid + 1
21+
else:
22+
r = mid - 1
23+
return result

0 commit comments

Comments
 (0)