Skip to content

Commit fce9ed6

Browse files
authored
Added tasks 11-25
1 parent 85dbc79 commit fce9ed6

File tree

20 files changed

+1365
-0
lines changed

20 files changed

+1365
-0
lines changed
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 #Greedy #Two_Pointers
2+
# #Algorithm_II_Day_4_Two_Pointers #Big_O_Time_O(n)_Space_O(1)
3+
# #2024_06_04_Time_488_ms_(91.81%)_Space_29.5_MB_(60.76%)
4+
5+
class Solution:
6+
def maxArea(self, height):
7+
max_area = -1
8+
left = 0
9+
right = len(height) - 1
10+
while left < right:
11+
if height[left] < height[right]:
12+
max_area = max(max_area, height[left] * (right - left))
13+
left += 1
14+
else:
15+
max_area = max(max_area, height[right] * (right - left))
16+
right -= 1
17+
return max_area
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
11\. Container With Most Water
2+
3+
Medium
4+
5+
Given `n` non-negative integers <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> , where each represents a point at coordinate <code>(i, a<sub>i</sub>)</code>. `n` vertical lines are drawn such that the two endpoints of the line `i` is at <code>(i, a<sub>i</sub>)</code> and `(i, 0)`. Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
6+
7+
**Notice** that you may not slant the container.
8+
9+
**Example 1:**
10+
11+
![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg)
12+
13+
**Input:** height = [1,8,6,2,5,4,8,3,7]
14+
15+
**Output:** 49
16+
17+
**Explanation:** The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
18+
19+
**Example 2:**
20+
21+
**Input:** height = [1,1]
22+
23+
**Output:** 1
24+
25+
**Example 3:**
26+
27+
**Input:** height = [4,3,2,1,4]
28+
29+
**Output:** 16
30+
31+
**Example 4:**
32+
33+
**Input:** height = [1,2,1]
34+
35+
**Output:** 2
36+
37+
**Constraints:**
38+
39+
* `n == height.length`
40+
* <code>2 <= n <= 10<sup>5</sup></code>
41+
* <code>0 <= height[i] <= 10<sup>4</sup></code>
42+
43+
To solve the Container With Most Water problem in Java using a `Solution` class, we'll follow these steps:
44+
45+
1. Define a `Solution` class with a method named `maxArea` that takes an array of integers `height` as input and returns the maximum area of water that can be contained.
46+
2. Initialize two pointers, `left` pointing to the start of the array and `right` pointing to the end of the array.
47+
3. Initialize a variable `maxArea` to store the maximum area encountered so far, initially set to 0.
48+
4. Iterate while `left` is less than `right`.
49+
5. Calculate the current area using the formula: `(right - left) * min(height[left], height[right])`.
50+
6. Update `maxArea` if the current area is greater than `maxArea`.
51+
7. Move the pointer pointing to the smaller height towards the other pointer. If `height[left] < height[right]`, increment `left`, otherwise decrement `right`.
52+
8. Continue the iteration until `left` becomes greater than or equal to `right`.
53+
9. Return `maxArea`.
54+
55+
Here's the implementation:
56+
57+
```java
58+
public class Solution {
59+
public int maxArea(int[] height) {
60+
int left = 0;
61+
int right = height.length - 1;
62+
int maxArea = 0;
63+
64+
while (left < right) {
65+
int currentArea = (right - left) * Math.min(height[left], height[right]);
66+
maxArea = Math.max(maxArea, currentArea);
67+
68+
if (height[left] < height[right]) {
69+
left++;
70+
} else {
71+
right--;
72+
}
73+
}
74+
75+
return maxArea;
76+
}
77+
78+
public static void main(String[] args) {
79+
Solution solution = new Solution();
80+
81+
// Test cases
82+
int[] height1 = {1, 8, 6, 2, 5, 4, 8, 3, 7};
83+
System.out.println("Example 1 Output: " + solution.maxArea(height1));
84+
85+
int[] height2 = {1, 1};
86+
System.out.println("Example 2 Output: " + solution.maxArea(height2));
87+
88+
int[] height3 = {4, 3, 2, 1, 4};
89+
System.out.println("Example 3 Output: " + solution.maxArea(height3));
90+
91+
int[] height4 = {1, 2, 1};
92+
System.out.println("Example 4 Output: " + solution.maxArea(height4));
93+
}
94+
}
95+
```
96+
97+
This implementation provides a solution to the Container With Most Water problem in Java.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Sorting #Two_Pointers
2+
# #Data_Structure_II_Day_1_Array #Algorithm_II_Day_3_Two_Pointers #Udemy_Two_Pointers
3+
# #Big_O_Time_O(n*log(n))_Space_O(n^2) #2024_06_04_Time_683_ms_(63.27%)_Space_20.8_MB_(49.61%)
4+
5+
class Solution:
6+
def threeSum(self, nums):
7+
nums.sort()
8+
result = []
9+
length = len(nums)
10+
11+
for i in range(length - 2):
12+
if i > 0 and nums[i] == nums[i - 1]:
13+
continue
14+
15+
left = i + 1
16+
right = length - 1
17+
18+
while left < right:
19+
total = nums[i] + nums[left] + nums[right]
20+
21+
if total < 0:
22+
left += 1
23+
elif total > 0:
24+
right -= 1
25+
else:
26+
result.append([nums[i], nums[left], nums[right]])
27+
28+
while left < right and nums[left] == nums[left + 1]:
29+
left += 1
30+
while left < right and nums[right] == nums[right - 1]:
31+
right -= 1
32+
33+
left += 1
34+
right -= 1
35+
36+
return result
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
15\. 3Sum
2+
3+
Medium
4+
5+
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`.
6+
7+
Notice that the solution set must not contain duplicate triplets.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [-1,0,1,2,-1,-4]
12+
13+
**Output:** [[-1,-1,2],[-1,0,1]]
14+
15+
**Example 2:**
16+
17+
**Input:** nums = []
18+
19+
**Output:** []
20+
21+
**Example 3:**
22+
23+
**Input:** nums = [0]
24+
25+
**Output:** []
26+
27+
**Constraints:**
28+
29+
* `0 <= nums.length <= 3000`
30+
* <code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code>
31+
32+
To solve the 3Sum problem in Java using a `Solution` class, we'll follow these steps:
33+
34+
1. Define a `Solution` class with a method named `threeSum` that takes an array of integers `nums` as input and returns a list of lists representing the triplets that sum up to zero.
35+
2. Sort the input array `nums` to ensure that duplicate triplets are avoided.
36+
3. Initialize an empty list `result` to store the triplets.
37+
4. Iterate over the elements of the sorted array `nums` up to the second to last element.
38+
5. Within the outer loop, initialize two pointers, `left` and `right`, where `left` starts at the next element after the current element and `right` starts at the last element of the array.
39+
6. While `left` is less than `right`, check if the sum of the current element (`nums[i]`), `nums[left]`, and `nums[right]` equals zero.
40+
7. If the sum is zero, add `[nums[i], nums[left], nums[right]]` to the `result` list.
41+
8. Move the `left` pointer to the right (increment `left`) and the `right` pointer to the left (decrement `right`).
42+
9. If the sum is less than zero, increment `left`.
43+
10. If the sum is greater than zero, decrement `right`.
44+
11. After the inner loop finishes, increment the outer loop index while skipping duplicates.
45+
12. Return the `result` list containing all the valid triplets.
46+
47+
Here's the implementation:
48+
49+
```java
50+
import java.util.ArrayList;
51+
import java.util.Arrays;
52+
import java.util.List;
53+
54+
public class Solution {
55+
public List<List<Integer>> threeSum(int[] nums) {
56+
Arrays.sort(nums);
57+
List<List<Integer>> result = new ArrayList<>();
58+
59+
for (int i = 0; i < nums.length - 2; i++) {
60+
if (i > 0 && nums[i] == nums[i - 1]) {
61+
continue; // Skip duplicates
62+
}
63+
64+
int left = i + 1;
65+
int right = nums.length - 1;
66+
67+
while (left < right) {
68+
int sum = nums[i] + nums[left] + nums[right];
69+
if (sum == 0) {
70+
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
71+
72+
// Skip duplicates
73+
while (left < right && nums[left] == nums[left + 1]) {
74+
left++;
75+
}
76+
while (left < right && nums[right] == nums[right - 1]) {
77+
right--;
78+
}
79+
80+
left++;
81+
right--;
82+
} else if (sum < 0) {
83+
left++;
84+
} else {
85+
right--;
86+
}
87+
}
88+
}
89+
90+
return result;
91+
}
92+
93+
public static void main(String[] args) {
94+
Solution solution = new Solution();
95+
96+
// Test cases
97+
int[] nums1 = {-1, 0, 1, 2, -1, -4};
98+
System.out.println("Example 1 Output: " + solution.threeSum(nums1));
99+
100+
int[] nums2 = {};
101+
System.out.println("Example 2 Output: " + solution.threeSum(nums2));
102+
103+
int[] nums3 = {0};
104+
System.out.println("Example 3 Output: " + solution.threeSum(nums3));
105+
}
106+
}
107+
```
108+
109+
This implementation provides a solution to the 3Sum problem in Java.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Backtracking
2+
# #Algorithm_II_Day_11_Recursion_Backtracking #Udemy_Backtracking/Recursion
3+
# #Big_O_Time_O(4^n)_Space_O(n) #2024_06_04_Time_28_ms_(91.85%)_Space_16.5_MB_(84.41%)
4+
5+
class Solution:
6+
def letterCombinations(self, digits):
7+
if not digits:
8+
return []
9+
10+
letters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
11+
ans = []
12+
self.findCombinations(0, digits, letters, [], ans)
13+
return ans
14+
15+
def findCombinations(self, start, digits, letters, curr, ans):
16+
if len(curr) == len(digits):
17+
ans.append("".join(curr))
18+
return
19+
20+
for i in range(start, len(digits)):
21+
n = int(digits[i])
22+
for ch in letters[n]:
23+
curr.append(ch)
24+
self.findCombinations(i + 1, digits, letters, curr, ans)
25+
curr.pop()
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
17\. Letter Combinations of a Phone Number
2+
3+
Medium
4+
5+
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
6+
7+
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
8+
9+
![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png)
10+
11+
**Example 1:**
12+
13+
**Input:** digits = "23"
14+
15+
**Output:** ["ad","ae","af","bd","be","bf","cd","ce","cf"]
16+
17+
**Example 2:**
18+
19+
**Input:** digits = ""
20+
21+
**Output:** []
22+
23+
**Example 3:**
24+
25+
**Input:** digits = "2"
26+
27+
**Output:** ["a","b","c"]
28+
29+
**Constraints:**
30+
31+
* `0 <= digits.length <= 4`
32+
* `digits[i]` is a digit in the range `['2', '9']`.
33+
34+
To solve the Letter Combinations of a Phone Number problem in Java using a `Solution` class, we'll follow these steps:
35+
36+
1. Define a `Solution` class with a method named `letterCombinations` that takes a string `digits` as input and returns a list of all possible letter combinations.
37+
2. Create a mapping of digits to letters using a hashmap or an array.
38+
3. Initialize an empty list `result` to store the combinations.
39+
4. If the input string `digits` is empty, return an empty list `result`.
40+
5. Call a recursive function `generateCombinations` to generate combinations for each digit.
41+
6. Within the recursive function:
42+
- Base case: If the current combination length equals the length of the input `digits`, add the combination to the `result` list.
43+
- Recursive step: For the current digit, iterate over its corresponding letters and append each letter to the current combination, then recursively call the function with the next digit.
44+
7. Return the `result` list containing all possible combinations.
45+
46+
Here's the implementation:
47+
48+
```java
49+
import java.util.ArrayList;
50+
import java.util.HashMap;
51+
import java.util.List;
52+
import java.util.Map;
53+
54+
public class Solution {
55+
private static final Map<Character, String> digitToLetters = new HashMap<>();
56+
static {
57+
digitToLetters.put('2', "abc");
58+
digitToLetters.put('3', "def");
59+
digitToLetters.put('4', "ghi");
60+
digitToLetters.put('5', "jkl");
61+
digitToLetters.put('6', "mno");
62+
digitToLetters.put('7', "pqrs");
63+
digitToLetters.put('8', "tuv");
64+
digitToLetters.put('9', "wxyz");
65+
}
66+
67+
public List<String> letterCombinations(String digits) {
68+
List<String> result = new ArrayList<>();
69+
if (digits.length() == 0) {
70+
return result;
71+
}
72+
generateCombinations(result, digits, "", 0);
73+
return result;
74+
}
75+
76+
private void generateCombinations(List<String> result, String digits, String combination, int index) {
77+
if (index == digits.length()) {
78+
result.add(combination);
79+
return;
80+
}
81+
82+
char digit = digits.charAt(index);
83+
String letters = digitToLetters.get(digit);
84+
for (char letter : letters.toCharArray()) {
85+
generateCombinations(result, digits, combination + letter, index + 1);
86+
}
87+
}
88+
89+
public static void main(String[] args) {
90+
Solution solution = new Solution();
91+
92+
// Test cases
93+
String digits1 = "23";
94+
System.out.println("Example 1 Output: " + solution.letterCombinations(digits1));
95+
96+
String digits2 = "";
97+
System.out.println("Example 2 Output: " + solution.letterCombinations(digits2));
98+
99+
String digits3 = "2";
100+
System.out.println("Example 3 Output: " + solution.letterCombinations(digits3));
101+
}
102+
}
103+
```
104+
105+
This implementation provides a solution to the Letter Combinations of a Phone Number problem in Java.

0 commit comments

Comments
 (0)