Skip to content

Commit db4ec05

Browse files
authored
Updated readmes
1 parent 6fccd5a commit db4ec05

File tree

20 files changed

+1461
-1281
lines changed

20 files changed

+1461
-1281
lines changed

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

Lines changed: 59 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -37,64 +37,65 @@ You can return the answer in any order.
3737

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

40-
To solve the Two Sum problem in Java using a `Solution` class, we'll follow these steps:
41-
42-
1. Define a `Solution` class with a method named `twoSum`.
43-
2. Inside the `twoSum` method, create a hashmap to store elements and their indices.
44-
3. Iterate through the array:
45-
- For each element, calculate the complement required to reach the target sum.
46-
- Check if the complement exists in the hashmap.
47-
- If found, return the indices of the current element and the complement.
48-
- If not found, add the current element and its index to the hashmap.
49-
4. Handle edge cases:
50-
- If no solution is found, return an empty array or null (depending on the problem requirements).
51-
52-
Here's the implementation:
53-
54-
```java
55-
import java.util.HashMap;
56-
57-
public class Solution {
58-
59-
public int[] twoSum(int[] nums, int target) {
60-
// Create a hashmap to store elements and their indices
61-
HashMap<Integer, Integer> map = new HashMap<>();
62-
63-
// Iterate through the array
64-
for (int i = 0; i < nums.length; i++) {
65-
int complement = target - nums[i];
66-
// Check if the complement exists in the hashmap
67-
if (map.containsKey(complement)) {
68-
// Return the indices of the current element and the complement
69-
return new int[]{map.get(complement), i};
70-
}
71-
// Add the current element and its index to the hashmap
72-
map.put(nums[i], i);
73-
}
74-
// If no solution is found, return an empty array or null
75-
return new int[]{};
76-
}
77-
78-
public static void main(String[] args) {
79-
Solution solution = new Solution();
40+
Here are the steps to solve the Two Sum problem:
41+
42+
### Approach:
43+
44+
1. **Create a Dictionary/HashMap:**
45+
- Initialize an empty dictionary to store the elements of the array and their corresponding indices.
46+
47+
2. **Iterate through the Array:**
48+
- Traverse through the given array `nums` using a loop.
49+
50+
3. **Check Complement:**
51+
- For each element `nums[i]`, calculate its complement (i.e., `target - nums[i]`).
52+
53+
4. **Check if Complement exists:**
54+
- Check if the complement is already in the dictionary.
55+
- If it is, return the indices `[dictionary[complement], i]`.
56+
- If not, add the current element and its index to the dictionary.
57+
58+
### Python Code:
59+
60+
```python
61+
from typing import List
62+
63+
class Solution:
64+
def twoSum(self, nums: List[int], target: int) -> List[int]:
65+
# Create a dictionary to store elements and their indices
66+
num_dict = {}
67+
68+
# Iterate through the array
69+
for i in range(len(nums)):
70+
# Check complement
71+
complement = target - nums[i]
72+
73+
# Check if complement exists in the dictionary
74+
if complement in num_dict:
75+
# Return the indices if complement is found
76+
return [num_dict[complement], i]
77+
78+
# Add the current element and its index to the dictionary
79+
num_dict[nums[i]] = i
8080

81-
// Test cases
82-
int[] nums1 = {2, 7, 11, 15};
83-
int target1 = 9;
84-
int[] result1 = solution.twoSum(nums1, target1);
85-
System.out.println("Example 1 Output: [" + result1[0] + ", " + result1[1] + "]");
86-
87-
int[] nums2 = {3, 2, 4};
88-
int target2 = 6;
89-
int[] result2 = solution.twoSum(nums2, target2);
90-
System.out.println("Example 2 Output: [" + result2[0] + ", " + result2[1] + "]");
91-
92-
int[] nums3 = {3, 3};
93-
int target3 = 6;
94-
int[] result3 = solution.twoSum(nums3, target3);
95-
System.out.println("Example 3 Output: [" + result3[0] + ", " + result3[1] + "]");
96-
}
97-
}
81+
# If no solution is found
82+
return None
83+
84+
# Example Usage:
85+
solution = Solution()
86+
87+
nums1 = [2, 7, 11, 15]
88+
target1 = 9
89+
print(solution.twoSum(nums1, target1)) # Output: [0, 1]
90+
91+
nums2 = [3, 2, 4]
92+
target2 = 6
93+
print(solution.twoSum(nums2, target2)) # Output: [1, 2]
94+
95+
nums3 = [3, 3]
96+
target3 = 6
97+
print(solution.twoSum(nums3, target3)) # Output: [0, 1]
9898
```
9999

100-
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.
100+
### Time Complexity:
101+
The time complexity of this algorithm is O(n), where n is the number of elements in the array. The dictionary lookup operation is constant time.

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

Lines changed: 89 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -34,100 +34,94 @@ You may assume the two numbers do not contain any leading zero, except the numbe
3434
* `0 <= Node.val <= 9`
3535
* It is guaranteed that the list represents a number that does not have leading zeros.
3636

37-
To solve the Add Two Numbers problem in Java using a `Solution` class, we'll follow these steps:
38-
39-
1. Define a `ListNode` class to represent nodes in a linked list.
40-
2. Define a `Solution` class with a method named `addTwoNumbers`.
41-
3. Inside the `addTwoNumbers` method, traverse both input linked lists simultaneously:
42-
- Keep track of a carry variable to handle cases where the sum of two digits exceeds 9.
43-
- Calculate the sum of the current nodes' values along with the carry.
44-
- Update the carry for the next iteration.
45-
- Create a new node with the sum % 10 and attach it to the result linked list.
46-
- Move to the next nodes in both input lists.
47-
4. After finishing the traversal, check if there is any remaining carry. If so, add a new node with the carry to the result.
48-
5. Return the head of the result linked list.
49-
50-
Here's the implementation:
51-
52-
```java
53-
class ListNode {
54-
int val;
55-
ListNode next;
56-
57-
ListNode() {}
58-
59-
ListNode(int val) {
60-
this.val = val;
61-
}
62-
63-
ListNode(int val, ListNode next) {
64-
this.val = val;
65-
this.next = next;
66-
}
67-
}
68-
69-
public class Solution {
70-
71-
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
72-
ListNode dummyHead = new ListNode();
73-
ListNode curr = dummyHead;
74-
int carry = 0;
75-
76-
while (l1 != null || l2 != null) {
77-
int sum = carry;
78-
if (l1 != null) {
79-
sum += l1.val;
80-
l1 = l1.next;
81-
}
82-
if (l2 != null) {
83-
sum += l2.val;
84-
l2 = l2.next;
85-
}
86-
curr.next = new ListNode(sum % 10);
87-
curr = curr.next;
88-
carry = sum / 10;
89-
}
90-
91-
if (carry > 0) {
92-
curr.next = new ListNode(carry);
93-
}
94-
95-
return dummyHead.next;
96-
}
97-
98-
// Helper method to print a linked list
99-
public void printList(ListNode head) {
100-
ListNode curr = head;
101-
while (curr != null) {
102-
System.out.print(curr.val + " ");
103-
curr = curr.next;
104-
}
105-
System.out.println();
106-
}
107-
108-
public static void main(String[] args) {
109-
Solution solution = new Solution();
110-
111-
// Test cases
112-
ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
113-
ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
114-
ListNode result1 = solution.addTwoNumbers(l1, l2);
115-
System.out.print("Example 1 Output: ");
116-
solution.printList(result1);
117-
118-
ListNode l3 = new ListNode(0);
119-
ListNode l4 = new ListNode(0);
120-
ListNode result2 = solution.addTwoNumbers(l3, l4);
121-
System.out.print("Example 2 Output: ");
122-
solution.printList(result2);
123-
124-
ListNode l5 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
125-
ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));
126-
ListNode result3 = solution.addTwoNumbers(l5, l6);
127-
System.out.print("Example 3 Output: ");
128-
solution.printList(result3);
129-
}
130-
}
37+
Here are the steps to solve the "Add Two Numbers" problem:
38+
39+
### Approach:
40+
41+
1. **Initialize Pointers and Carry:**
42+
- Initialize three pointers, `p1` for the first linked list (`l1`), `p2` for the second linked list (`l2`), and `dummy_head` for the dummy node of the result linked list.
43+
- Initialize `carry` to 0.
44+
45+
2. **Traverse Both Linked Lists:**
46+
- Traverse both linked lists until both pointers (`p1` and `p2`) reach the end.
47+
48+
3. **Calculate Sum and Carry:**
49+
- At each step, calculate the sum of the current digits and the carry from the previous step.
50+
- Update `carry` for the next iteration.
51+
52+
4. **Create New Node:**
53+
- Create a new node with the value as the sum % 10 and add it to the result linked list.
54+
55+
5. **Move Pointers:**
56+
- Move both pointers (`p1` and `p2`) to the next nodes in their respective linked lists.
57+
58+
6. **Handle Remaining Digits:**
59+
- After both linked lists are traversed, check if there is any remaining carry.
60+
- If there is, create a new node with the value of the carry and add it to the result linked list.
61+
62+
7. **Return Result:**
63+
- Return the next node of `dummy_head` as the head of the result linked list.
64+
65+
### Python Code:
66+
67+
```python
68+
# Definition for singly-linked list.
69+
class ListNode:
70+
def __init__(self, val=0, next=None):
71+
self.val = val
72+
self.next = next
73+
74+
class Solution:
75+
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
76+
dummy_head = ListNode()
77+
p1, p2, current = l1, l2, dummy_head
78+
carry = 0
79+
80+
while p1 or p2:
81+
# Get values and handle None cases
82+
x = p1.val if p1 else 0
83+
y = p2.val if p2 else 0
84+
85+
# Calculate sum and carry
86+
_sum = x + y + carry
87+
carry = _sum // 10
88+
89+
# Create new node with the sum % 10
90+
current.next = ListNode(_sum % 10)
91+
current = current.next
92+
93+
# Move pointers to the next nodes
94+
if p1:
95+
p1 = p1.next
96+
if p2:
97+
p2 = p2.next
98+
99+
# Handle remaining carry
100+
if carry > 0:
101+
current.next = ListNode(carry)
102+
103+
return dummy_head.next
104+
105+
# Example Usage:
106+
solution = Solution()
107+
108+
# Example 1:
109+
l1 = ListNode(2, ListNode(4, ListNode(3)))
110+
l2 = ListNode(5, ListNode(6, ListNode(4)))
111+
result = solution.addTwoNumbers(l1, l2)
112+
# Output: [7, 0, 8]
113+
114+
# Example 2:
115+
l1 = ListNode(0)
116+
l2 = ListNode(0)
117+
result = solution.addTwoNumbers(l1, l2)
118+
# Output: [0]
119+
120+
# Example 3:
121+
l1 = ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9)))))))
122+
l2 = ListNode(9, ListNode(9, ListNode(9, ListNode(9))))
123+
result = solution.addTwoNumbers(l1, l2)
124+
# Output: [8, 9, 9, 9, 0, 0, 0, 1]
131125
```
132126

133-
This implementation provides a solution to the Add Two Numbers problem using linked lists in Java.
127+
This code defines a `ListNode` class for the singly-linked list and a `Solution` class with a method `addTwoNumbers` that takes two linked lists as input and returns the result as a linked list. The example usage demonstrates how to create instances of the `ListNode` class and call the `addTwoNumbers` method with different inputs.

0 commit comments

Comments
 (0)