Skip to content

Commit 6a8e3d7

Browse files
committed
add java solutions upto QuickSort
1 parent 12ac724 commit 6a8e3d7

File tree

76 files changed

+5626
-75
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+5626
-75
lines changed

java/3Sum.md

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,79 @@
1-
# 3Sum.md
1+
# [15. 3Sum](https://leetcode.com/problems/3sum/)
22

3+
## Approach 1: Brute Force (Basic)
4+
5+
### Solution
6+
```java
7+
// Time Complexity: O(n^3)
8+
// Space Complexity: O(1) (excluding output list)
9+
import java.util.*;
10+
11+
public class Solution {
12+
public List<List<Integer>> threeSum(int[] nums) {
13+
Set<List<Integer>> result = new HashSet<>();
14+
int n = nums.length;
15+
16+
// Iterate through all possible triplets
17+
for (int i = 0; i < n - 2; i++) {
18+
for (int j = i + 1; j < n - 1; j++) {
19+
for (int k = j + 1; k < n; k++) {
20+
if (nums[i] + nums[j] + nums[k] == 0) {
21+
List<Integer> triplet = Arrays.asList(nums[i], nums[j], nums[k]);
22+
Collections.sort(triplet); // Ensure the triplet is in sorted order
23+
result.add(triplet); // Add triplet to the set to avoid duplicates
24+
}
25+
}
26+
}
27+
}
28+
29+
return new ArrayList<>(result); // Convert set to list for the output
30+
}
31+
}
32+
```
33+
34+
## Approach 2: Two Pointers (Optimal)
35+
36+
### Solution
37+
```java
38+
// Time Complexity: O(n^2)
39+
// Space Complexity: O(n) (for sorting or output list)
40+
import java.util.*;
41+
42+
public class Solution {
43+
public List<List<Integer>> threeSum(int[] nums) {
44+
List<List<Integer>> result = new ArrayList<>();
45+
Arrays.sort(nums); // Sort the array to use two-pointer technique
46+
47+
for (int i = 0; i < nums.length - 2; i++) {
48+
// Skip duplicates for the first element
49+
if (i > 0 && nums[i] == nums[i - 1]) {
50+
continue;
51+
}
52+
53+
int left = i + 1;
54+
int right = nums.length - 1;
55+
56+
// Two-pointer approach
57+
while (left < right) {
58+
int sum = nums[i] + nums[left] + nums[right];
59+
if (sum == 0) {
60+
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
61+
62+
// Skip duplicates for the second and third elements
63+
while (left < right && nums[left] == nums[left + 1]) left++;
64+
while (left < right && nums[right] == nums[right - 1]) right--;
65+
66+
left++;
67+
right--;
68+
} else if (sum < 0) {
69+
left++; // Increase the sum
70+
} else {
71+
right--; // Decrease the sum
72+
}
73+
}
74+
}
75+
76+
return result;
77+
}
78+
}
79+
```

java/add_two_numbers.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,38 @@
1-
# add_two_numbers.md
1+
# [2. Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)
22

3+
## Approach: Iterative Solution with Carry
4+
5+
### Solution
6+
```java
7+
// Time Complexity: O(max(m, n)), where m and n are the lengths of the two lists
8+
// Space Complexity: O(max(m, n)), for the new linked list
9+
public class Solution {
10+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11+
ListNode dummy = new ListNode(0); // Dummy node to simplify the process
12+
ListNode current = dummy; // Pointer to the current node in the result list
13+
int carry = 0; // Store carry from the addition
14+
15+
// Traverse both lists
16+
while (l1 != null || l2 != null || carry != 0) {
17+
int sum = carry; // Start with the carry
18+
19+
// Add values from l1 and l2 if they exist
20+
if (l1 != null) {
21+
sum += l1.val;
22+
l1 = l1.next;
23+
}
24+
if (l2 != null) {
25+
sum += l2.val;
26+
l2 = l2.next;
27+
}
28+
29+
// Calculate new carry and the digit to store
30+
carry = sum / 10;
31+
current.next = new ListNode(sum % 10); // Store the last digit of the sum
32+
current = current.next; // Move to the next node
33+
}
34+
35+
return dummy.next; // Skip the dummy node
36+
}
37+
}
38+
```

java/basic_calculator_2.md

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,51 @@
1-
# basic_calculator_2.md
1+
# [227. Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)
22

3+
## Approach: Using a Stack for Intermediate Results
4+
5+
### Solution
6+
```java
7+
// Time Complexity: O(n)
8+
// Space Complexity: O(n)
9+
import java.util.Stack;
10+
11+
public class Solution {
12+
public int calculate(String s) {
13+
Stack<Integer> stack = new Stack<>();
14+
int currentNumber = 0;
15+
char operation = '+'; // Default operation is addition
16+
17+
for (int i = 0; i < s.length(); i++) {
18+
char c = s.charAt(i);
19+
20+
// Build the current number
21+
if (Character.isDigit(c)) {
22+
currentNumber = currentNumber * 10 + (c - '0');
23+
}
24+
25+
// Process operators and the last number
26+
if (!Character.isDigit(c) && c != ' ' || i == s.length() - 1) {
27+
if (operation == '+') {
28+
stack.push(currentNumber);
29+
} else if (operation == '-') {
30+
stack.push(-currentNumber);
31+
} else if (operation == '*') {
32+
stack.push(stack.pop() * currentNumber);
33+
} else if (operation == '/') {
34+
stack.push(stack.pop() / currentNumber);
35+
}
36+
37+
operation = c; // Update the operation
38+
currentNumber = 0; // Reset the current number
39+
}
40+
}
41+
42+
// Sum up all the values in the stack
43+
int result = 0;
44+
while (!stack.isEmpty()) {
45+
result += stack.pop();
46+
}
47+
48+
return result;
49+
}
50+
}
51+
```

java/construct_quad_tree.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,39 @@
1-
# construct_quad_tree.md
1+
# [427. Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/)
22

3+
## Approach 1: Recursive Division of Grid
4+
5+
### Solution
6+
```java
7+
// Time Complexity: O(n^2 * log n), where n is the side length of the grid
8+
// Space Complexity: O(log n) (due to recursion stack)
9+
public class Solution {
10+
public Node construct(int[][] grid) {
11+
return buildTree(grid, 0, 0, grid.length);
12+
}
13+
14+
private Node buildTree(int[][] grid, int x, int y, int size) {
15+
if (size == 1) {
16+
// Base case: single cell
17+
return new Node(grid[x][y] == 1, true, null, null, null, null);
18+
}
19+
20+
int halfSize = size / 2;
21+
22+
// Recursively divide the grid into four quadrants
23+
Node topLeft = buildTree(grid, x, y, halfSize);
24+
Node topRight = buildTree(grid, x, y + halfSize, halfSize);
25+
Node bottomLeft = buildTree(grid, x + halfSize, y, halfSize);
26+
Node bottomRight = buildTree(grid, x + halfSize, y + halfSize, halfSize);
27+
28+
// Check if all four quadrants are leaves with the same value
29+
if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf
30+
&& topLeft.val == topRight.val && topRight.val == bottomLeft.val
31+
&& bottomLeft.val == bottomRight.val) {
32+
return new Node(topLeft.val, true, null, null, null, null); // Merge into one leaf
33+
}
34+
35+
// Otherwise, create an internal node
36+
return new Node(true, false, topLeft, topRight, bottomLeft, bottomRight);
37+
}
38+
}
39+
```

java/container_with_most_water.md

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,56 @@
1-
# container_with_most_water.md
1+
# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
22

3+
## Approach 1: Brute Force
4+
5+
### Solution
6+
```java
7+
// Time Complexity: O(n^2)
8+
// Space Complexity: O(1)
9+
public class Solution {
10+
public int maxArea(int[] height) {
11+
int maxArea = 0;
12+
13+
// Check all pairs of lines
14+
for (int i = 0; i < height.length; i++) {
15+
for (int j = i + 1; j < height.length; j++) {
16+
// Calculate the area for the current pair of lines
17+
int area = Math.min(height[i], height[j]) * (j - i);
18+
maxArea = Math.max(maxArea, area); // Update max area if needed
19+
}
20+
}
21+
22+
return maxArea;
23+
}
24+
}
25+
```
26+
27+
## Approach 2: Two Pointers (Optimal)
28+
29+
### Solution
30+
```java
31+
// Time Complexity: O(n)
32+
// Space Complexity: O(1)
33+
public class Solution {
34+
public int maxArea(int[] height) {
35+
int left = 0; // Start pointer
36+
int right = height.length - 1; // End pointer
37+
int maxArea = 0; // Initialize max area
38+
39+
// Iterate until the two pointers meet
40+
while (left < right) {
41+
// Calculate the current area
42+
int area = Math.min(height[left], height[right]) * (right - left);
43+
maxArea = Math.max(maxArea, area); // Update max area if needed
44+
45+
// Move the pointer pointing to the shorter line
46+
if (height[left] < height[right]) {
47+
left++;
48+
} else {
49+
right--;
50+
}
51+
}
52+
53+
return maxArea;
54+
}
55+
}
56+
```

java/contiguous_array.md

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,64 @@
1-
# contiguous_array.md
1+
# [525. Contiguous Array](https://leetcode.com/problems/contiguous-array/)
22

3+
## Approach 1: Brute Force (Basic)
4+
5+
### Solution
6+
```java
7+
// Time Complexity: O(n^2)
8+
// Space Complexity: O(1)
9+
public class Solution {
10+
public int findMaxLength(int[] nums) {
11+
int maxLength = 0;
12+
13+
// Check all possible subarrays
14+
for (int i = 0; i < nums.length; i++) {
15+
int count = 0;
16+
17+
for (int j = i; j < nums.length; j++) {
18+
// Increment or decrement count based on value
19+
count += nums[j] == 1 ? 1 : -1;
20+
21+
// If count is zero, it means equal number of 0s and 1s
22+
if (count == 0) {
23+
maxLength = Math.max(maxLength, j - i + 1);
24+
}
25+
}
26+
}
27+
28+
return maxLength;
29+
}
30+
}
31+
```
32+
33+
## Approach 2: HashMap (Optimal)
34+
35+
### Solution
36+
```java
37+
// Time Complexity: O(n)
38+
// Space Complexity: O(n)
39+
import java.util.HashMap;
40+
41+
public class Solution {
42+
public int findMaxLength(int[] nums) {
43+
HashMap<Integer, Integer> map = new HashMap<>();
44+
map.put(0, -1); // Initialize with a count of 0 at index -1
45+
int maxLength = 0;
46+
int count = 0;
47+
48+
for (int i = 0; i < nums.length; i++) {
49+
// Increment or decrement count based on value
50+
count += nums[i] == 1 ? 1 : -1;
51+
52+
if (map.containsKey(count)) {
53+
// Calculate the length of the subarray
54+
maxLength = Math.max(maxLength, i - map.get(count));
55+
} else {
56+
// Store the first occurrence of this count
57+
map.put(count, i);
58+
}
59+
}
60+
61+
return maxLength;
62+
}
63+
}
64+
```

0 commit comments

Comments
 (0)