Skip to content

Commit 8e2ceb0

Browse files
authored
Improved tasks 1-101
1 parent 7ecadab commit 8e2ceb0

File tree

52 files changed

+2214
-2220
lines changed

Some content is hidden

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

52 files changed

+2214
-2220
lines changed

README.md

Lines changed: 155 additions & 155 deletions
Large diffs are not rendered by default.

src/main/java/g0001_0100/s0001_two_sum/readme.md

Lines changed: 50 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -40,44 +40,64 @@ You can return the answer in any order.
4040

4141
**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code> time complexity?
4242

43-
## Solution
43+
To solve the Two Sum problem in Java using a `Solution` class, we'll follow these steps:
44+
45+
1. Define a `Solution` class with a method named `twoSum`.
46+
2. Inside the `twoSum` method, create a hashmap to store elements and their indices.
47+
3. Iterate through the array:
48+
- For each element, calculate the complement required to reach the target sum.
49+
- Check if the complement exists in the hashmap.
50+
- If found, return the indices of the current element and the complement.
51+
- If not found, add the current element and its index to the hashmap.
52+
4. Handle edge cases:
53+
- If no solution is found, return an empty array or null (depending on the problem requirements).
54+
55+
Here's the implementation:
4456

4557
```java
4658
import java.util.HashMap;
47-
import java.util.Map;
4859

4960
public class Solution {
50-
public int[] twoSum(int[] numbers, int target) {
51-
Map<Integer, Integer> indexMap = new HashMap<>();
52-
for (int i = 0; i < numbers.length; i++) {
53-
Integer requiredNum = target - numbers[i];
54-
if (indexMap.containsKey(requiredNum)) {
55-
return new int[] {indexMap.get(requiredNum), i};
61+
62+
public int[] twoSum(int[] nums, int target) {
63+
// Create a hashmap to store elements and their indices
64+
HashMap<Integer, Integer> map = new HashMap<>();
65+
66+
// Iterate through the array
67+
for (int i = 0; i < nums.length; i++) {
68+
int complement = target - nums[i];
69+
// Check if the complement exists in the hashmap
70+
if (map.containsKey(complement)) {
71+
// Return the indices of the current element and the complement
72+
return new int[]{map.get(complement), i};
5673
}
57-
indexMap.put(numbers[i], i);
74+
// Add the current element and its index to the hashmap
75+
map.put(nums[i], i);
5876
}
59-
return new int[] {-1, -1};
77+
// If no solution is found, return an empty array or null
78+
return new int[]{};
79+
}
80+
81+
public static void main(String[] args) {
82+
Solution solution = new Solution();
83+
84+
// Test cases
85+
int[] nums1 = {2, 7, 11, 15};
86+
int target1 = 9;
87+
int[] result1 = solution.twoSum(nums1, target1);
88+
System.out.println("Example 1 Output: [" + result1[0] + ", " + result1[1] + "]");
89+
90+
int[] nums2 = {3, 2, 4};
91+
int target2 = 6;
92+
int[] result2 = solution.twoSum(nums2, target2);
93+
System.out.println("Example 2 Output: [" + result2[0] + ", " + result2[1] + "]");
94+
95+
int[] nums3 = {3, 3};
96+
int target3 = 6;
97+
int[] result3 = solution.twoSum(nums3, target3);
98+
System.out.println("Example 3 Output: [" + result3[0] + ", " + result3[1] + "]");
6099
}
61100
}
62101
```
63102

64-
**Time Complexity (Big O Time):**
65-
66-
The time complexity of this program is O(n), where "n" represents the number of elements in the `numbers` array. Here's the breakdown:
67-
68-
1. The program iterates through the `numbers` array once using a `for` loop, which runs for "n" iterations (n is the length of the array).
69-
2. Inside the loop, it performs constant-time operations:
70-
- It calculates the `requiredNum` (constant time).
71-
- It checks if `requiredNum` is present in the `indexMap` (constant time).
72-
- It puts `numbers[i]` and `i` into the `indexMap` (constant time).
73-
74-
Since all the operations inside the loop are constant time, and the loop itself runs for "n" iterations, the overall time complexity is O(n).
75-
76-
**Space Complexity (Big O Space):**
77-
78-
The space complexity of this program is also O(n), where "n" represents the number of elements in the `numbers` array. Here's why:
79-
80-
1. The program uses a `Map<Integer, Integer>` called `indexMap` to store the numbers and their corresponding indices. In the worst case, it could store all "n" elements from the `numbers` array.
81-
2. The program returns an integer array of size 2 (constant space), regardless of the input size.
82-
83-
The dominant factor in terms of space complexity is the `indexMap`, which can potentially store "n" key-value pairs. Therefore, the space complexity is O(n).
103+
This implementation provides a solution to the Two Sum problem with a time complexity of O(n), where n is the number of elements in the input array.

src/main/java/g0001_0100/s0002_add_two_numbers/readme.md

Lines changed: 80 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -37,65 +37,100 @@ You may assume the two numbers do not contain any leading zero, except the numbe
3737
* `0 <= Node.val <= 9`
3838
* It is guaranteed that the list represents a number that does not have leading zeros.
3939

40-
## Solution
40+
To solve the Add Two Numbers problem in Java using a `Solution` class, we'll follow these steps:
41+
42+
1. Define a `ListNode` class to represent nodes in a linked list.
43+
2. Define a `Solution` class with a method named `addTwoNumbers`.
44+
3. Inside the `addTwoNumbers` method, traverse both input linked lists simultaneously:
45+
- Keep track of a carry variable to handle cases where the sum of two digits exceeds 9.
46+
- Calculate the sum of the current nodes' values along with the carry.
47+
- Update the carry for the next iteration.
48+
- Create a new node with the sum % 10 and attach it to the result linked list.
49+
- Move to the next nodes in both input lists.
50+
4. After finishing the traversal, check if there is any remaining carry. If so, add a new node with the carry to the result.
51+
5. Return the head of the result linked list.
52+
53+
Here's the implementation:
4154

4255
```java
43-
import com_github_leetcode.ListNode;
44-
45-
/*
46-
* Definition for singly-linked list.
47-
* public class ListNode {
48-
* int val;
49-
* ListNode next;
50-
* ListNode(int x) { val = x; }
51-
* }
52-
*/
56+
class ListNode {
57+
int val;
58+
ListNode next;
59+
60+
ListNode() {}
61+
62+
ListNode(int val) {
63+
this.val = val;
64+
}
65+
66+
ListNode(int val, ListNode next) {
67+
this.val = val;
68+
this.next = next;
69+
}
70+
}
71+
5372
public class Solution {
73+
5474
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
55-
ListNode dummyHead = new ListNode(0);
56-
ListNode p = l1;
57-
ListNode q = l2;
75+
ListNode dummyHead = new ListNode();
5876
ListNode curr = dummyHead;
5977
int carry = 0;
60-
while (p != null || q != null) {
61-
int x = (p != null) ? p.val : 0;
62-
int y = (q != null) ? q.val : 0;
63-
int sum = carry + x + y;
64-
carry = sum / 10;
65-
curr.next = new ListNode(sum % 10);
66-
curr = curr.next;
67-
if (p != null) {
68-
p = p.next;
78+
79+
while (l1 != null || l2 != null) {
80+
int sum = carry;
81+
if (l1 != null) {
82+
sum += l1.val;
83+
l1 = l1.next;
6984
}
70-
if (q != null) {
71-
q = q.next;
85+
if (l2 != null) {
86+
sum += l2.val;
87+
l2 = l2.next;
7288
}
89+
curr.next = new ListNode(sum % 10);
90+
curr = curr.next;
91+
carry = sum / 10;
7392
}
93+
7494
if (carry > 0) {
7595
curr.next = new ListNode(carry);
7696
}
97+
7798
return dummyHead.next;
7899
}
79-
}
80-
```
81-
82-
**Time Complexity (Big O Time):**
83-
84-
The time complexity of this program is O(max(N, M)), where "N" and "M" represent the lengths of the input linked lists `l1` and `l2`, respectively. Here's the breakdown:
85-
86-
1. The program iterates through both linked lists `l1` and `l2` simultaneously using a `while` loop. The loop runs as long as either of the two lists has elements to process.
87-
2. Inside the loop, it performs constant-time operations for each node:
88-
- It calculates the sum of three integer values (constant time).
89-
- It creates a new node (constant time).
90-
- It updates pointers and variables (constant time).
91-
92-
Since the loop runs until the end of the longer of the two input linked lists, the overall time complexity is O(max(N, M)), where "N" and "M" are the lengths of `l1` and `l2`, respectively.
93-
94-
**Space Complexity (Big O Space):**
95100

96-
The space complexity of this program is O(max(N, M)), which is primarily determined by the space used for the output linked list. Here's why:
101+
// Helper method to print a linked list
102+
public void printList(ListNode head) {
103+
ListNode curr = head;
104+
while (curr != null) {
105+
System.out.print(curr.val + " ");
106+
curr = curr.next;
107+
}
108+
System.out.println();
109+
}
97110

98-
1. The program creates a new linked list to store the result, and the length of this linked list can be at most max(N, M) + 1 (where +1 is for the potential carry at the end).
99-
2. Other than the output linked list, the program uses a constant amount of space for variables like `dummyHead`, `p`, `q`, `curr`, and `carry`.
111+
public static void main(String[] args) {
112+
Solution solution = new Solution();
113+
114+
// Test cases
115+
ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
116+
ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
117+
ListNode result1 = solution.addTwoNumbers(l1, l2);
118+
System.out.print("Example 1 Output: ");
119+
solution.printList(result1);
120+
121+
ListNode l3 = new ListNode(0);
122+
ListNode l4 = new ListNode(0);
123+
ListNode result2 = solution.addTwoNumbers(l3, l4);
124+
System.out.print("Example 2 Output: ");
125+
solution.printList(result2);
126+
127+
ListNode l5 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
128+
ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))));
129+
ListNode result3 = solution.addTwoNumbers(l5, l6);
130+
System.out.print("Example 3 Output: ");
131+
solution.printList(result3);
132+
}
133+
}
134+
```
100135

101-
Therefore, the space complexity is O(max(N, M)).
136+
This implementation provides a solution to the Add Two Numbers problem using linked lists in Java.

src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md

Lines changed: 47 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -42,54 +42,65 @@ Given a string `s`, find the length of the **longest substring** without repeati
4242
* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
4343
* `s` consists of English letters, digits, symbols and spaces.
4444

45-
## Solution
45+
To solve the Longest Substring Without Repeating Characters problem in Java using a `Solution` class, we'll follow these steps:
46+
47+
1. Define a `Solution` class with a method named `lengthOfLongestSubstring`.
48+
2. Initialize variables to keep track of the starting index of the substring (`start`), the maximum length (`maxLen`), and a hashmap to store characters and their indices.
49+
3. Iterate through the string `s`, and for each character:
50+
- Check if the character exists in the hashmap and its index is greater than or equal to the `start` index.
51+
- If found, update the `start` index to the index after the last occurrence of the character.
52+
- Update the maximum length if necessary.
53+
- Update the index of the current character in the hashmap.
54+
4. Return the maximum length found.
55+
5. Handle the edge case where the input string is empty.
56+
57+
Here's the implementation:
4658

4759
```java
60+
import java.util.HashMap;
61+
4862
public class Solution {
63+
4964
public int lengthOfLongestSubstring(String s) {
50-
int[] lastIndices = new int[256];
51-
for (int i = 0; i < 256; i++) {
52-
lastIndices[i] = -1;
53-
}
54-
int maxLen = 0;
55-
int curLen = 0;
65+
// Initialize variables
5666
int start = 0;
57-
for (int i = 0; i < s.length(); i++) {
58-
char cur = s.charAt(i);
59-
if (lastIndices[cur] < start) {
60-
lastIndices[cur] = i;
61-
curLen++;
62-
} else {
63-
int lastIndex = lastIndices[cur];
64-
start = lastIndex + 1;
65-
curLen = i - start + 1;
66-
lastIndices[cur] = i;
67-
}
68-
if (curLen > maxLen) {
69-
maxLen = curLen;
67+
int maxLen = 0;
68+
HashMap<Character, Integer> map = new HashMap<>();
69+
70+
// Iterate through the string
71+
for (int end = 0; end < s.length(); end++) {
72+
char ch = s.charAt(end);
73+
// If the character exists in the hashmap and its index is greater than or equal to the start index
74+
if (map.containsKey(ch) && map.get(ch) >= start) {
75+
// Update the start index to the index after the last occurrence of the character
76+
start = map.get(ch) + 1;
7077
}
78+
// Update the maximum length if necessary
79+
maxLen = Math.max(maxLen, end - start + 1);
80+
// Update the index of the current character in the hashmap
81+
map.put(ch, end);
7182
}
83+
7284
return maxLen;
7385
}
74-
}
75-
```
76-
77-
**Time Complexity (Big O Time):**
78-
79-
The time complexity of this program is O(n), where "n" represents the length of the input string `s`. Here's the breakdown:
8086

81-
1. The program iterates through the characters of the input string `s` using a `for` loop, and this loop runs for "n" iterations, where "n" is the length of `s`.
82-
2. Inside the loop, it performs constant-time operations:
83-
- Initializing the `lastIndices` array (constant time).
84-
- Updating values in the `lastIndices` array (constant time).
85-
- Updating variables like `maxLen`, `curLen`, `start`, and `lastIndices[cur]` (constant time).
87+
public static void main(String[] args) {
88+
Solution solution = new Solution();
8689

87-
Since the loop runs for "n" iterations, and all operations inside the loop are constant time, the overall time complexity is O(n).
90+
// Test cases
91+
String s1 = "abcabcbb";
92+
System.out.println("Example 1 Output: " + solution.lengthOfLongestSubstring(s1));
8893

89-
**Space Complexity (Big O Space):**
94+
String s2 = "bbbbb";
95+
System.out.println("Example 2 Output: " + solution.lengthOfLongestSubstring(s2));
9096

91-
The space complexity of this program is O(256) = O(1), as it uses a fixed-size array `lastIndices` of length 256 to store the last indices of characters. This array's size does not depend on the input size and remains constant.
97+
String s3 = "pwwkew";
98+
System.out.println("Example 3 Output: " + solution.lengthOfLongestSubstring(s3));
9299

93-
Additionally, the program uses a few integer variables and constant space to store the result. The space used for these variables does not depend on the input size and is also considered constant.
100+
String s4 = "";
101+
System.out.println("Example 4 Output: " + solution.lengthOfLongestSubstring(s4));
102+
}
103+
}
104+
```
94105

95-
Therefore, the space complexity is O(1), or more precisely, O(256), which is still considered constant because it doesn't grow with the input size.
106+
This implementation provides a solution to the Longest Substring Without Repeating Characters problem in Java.

0 commit comments

Comments
 (0)