Skip to content

Commit ff5b457

Browse files
authored
Updated readmes
1 parent ef2eda1 commit ff5b457

File tree

51 files changed

+2983
-598
lines changed

Some content is hidden

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

51 files changed

+2983
-598
lines changed

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

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,69 @@ 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+
Here are the steps to solve the Two Sum problem:
44+
45+
### Approach:
46+
47+
1. **Create a Dictionary/HashMap:**
48+
- Initialize an empty dictionary to store the elements of the array and their corresponding indices.
49+
50+
2. **Iterate through the Array:**
51+
- Traverse through the given array `nums` using a loop.
52+
53+
3. **Check Complement:**
54+
- For each element `nums[i]`, calculate its complement (i.e., `target - nums[i]`).
55+
56+
4. **Check if Complement exists:**
57+
- Check if the complement is already in the dictionary.
58+
- If it is, return the indices `[dictionary[complement], i]`.
59+
- If not, add the current element and its index to the dictionary.
60+
61+
### Python Code:
62+
63+
```python
64+
from typing import List
65+
66+
class Solution:
67+
def twoSum(self, nums: List[int], target: int) -> List[int]:
68+
# Create a dictionary to store elements and their indices
69+
num_dict = {}
70+
71+
# Iterate through the array
72+
for i in range(len(nums)):
73+
# Check complement
74+
complement = target - nums[i]
75+
76+
# Check if complement exists in the dictionary
77+
if complement in num_dict:
78+
# Return the indices if complement is found
79+
return [num_dict[complement], i]
80+
81+
# Add the current element and its index to the dictionary
82+
num_dict[nums[i]] = i
83+
84+
# If no solution is found
85+
return None
86+
87+
# Example Usage:
88+
solution = Solution()
89+
90+
nums1 = [2, 7, 11, 15]
91+
target1 = 9
92+
print(solution.twoSum(nums1, target1)) # Output: [0, 1]
93+
94+
nums2 = [3, 2, 4]
95+
target2 = 6
96+
print(solution.twoSum(nums2, target2)) # Output: [1, 2]
97+
98+
nums3 = [3, 3]
99+
target3 = 6
100+
print(solution.twoSum(nums3, target3)) # Output: [0, 1]
101+
```
102+
103+
### Time Complexity:
104+
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.
105+
43106
## Solution
44107

45108
```python

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

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,98 @@ 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+
Here are the steps to solve the "Add Two Numbers" problem:
41+
42+
### Approach:
43+
44+
1. **Initialize Pointers and Carry:**
45+
- 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.
46+
- Initialize `carry` to 0.
47+
48+
2. **Traverse Both Linked Lists:**
49+
- Traverse both linked lists until both pointers (`p1` and `p2`) reach the end.
50+
51+
3. **Calculate Sum and Carry:**
52+
- At each step, calculate the sum of the current digits and the carry from the previous step.
53+
- Update `carry` for the next iteration.
54+
55+
4. **Create New Node:**
56+
- Create a new node with the value as the sum % 10 and add it to the result linked list.
57+
58+
5. **Move Pointers:**
59+
- Move both pointers (`p1` and `p2`) to the next nodes in their respective linked lists.
60+
61+
6. **Handle Remaining Digits:**
62+
- After both linked lists are traversed, check if there is any remaining carry.
63+
- If there is, create a new node with the value of the carry and add it to the result linked list.
64+
65+
7. **Return Result:**
66+
- Return the next node of `dummy_head` as the head of the result linked list.
67+
68+
### Python Code:
69+
70+
```python
71+
# Definition for singly-linked list.
72+
class ListNode:
73+
def __init__(self, val=0, next=None):
74+
self.val = val
75+
self.next = next
76+
77+
class Solution:
78+
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
79+
dummy_head = ListNode()
80+
p1, p2, current = l1, l2, dummy_head
81+
carry = 0
82+
83+
while p1 or p2:
84+
# Get values and handle None cases
85+
x = p1.val if p1 else 0
86+
y = p2.val if p2 else 0
87+
88+
# Calculate sum and carry
89+
_sum = x + y + carry
90+
carry = _sum // 10
91+
92+
# Create new node with the sum % 10
93+
current.next = ListNode(_sum % 10)
94+
current = current.next
95+
96+
# Move pointers to the next nodes
97+
if p1:
98+
p1 = p1.next
99+
if p2:
100+
p2 = p2.next
101+
102+
# Handle remaining carry
103+
if carry > 0:
104+
current.next = ListNode(carry)
105+
106+
return dummy_head.next
107+
108+
# Example Usage:
109+
solution = Solution()
110+
111+
# Example 1:
112+
l1 = ListNode(2, ListNode(4, ListNode(3)))
113+
l2 = ListNode(5, ListNode(6, ListNode(4)))
114+
result = solution.addTwoNumbers(l1, l2)
115+
# Output: [7, 0, 8]
116+
117+
# Example 2:
118+
l1 = ListNode(0)
119+
l2 = ListNode(0)
120+
result = solution.addTwoNumbers(l1, l2)
121+
# Output: [0]
122+
123+
# Example 3:
124+
l1 = ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9)))))))
125+
l2 = ListNode(9, ListNode(9, ListNode(9, ListNode(9))))
126+
result = solution.addTwoNumbers(l1, l2)
127+
# Output: [8, 9, 9, 9, 0, 0, 0, 1]
128+
```
129+
130+
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.
131+
40132
## Solution
41133

42134
```python

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

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,86 @@ 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+
Here are the steps to solve the "Longest Substring Without Repeating Characters" problem:
46+
47+
### Approach:
48+
49+
1. **Initialize Pointers and Variables:**
50+
- Initialize two pointers, `start` and `end`, to define the current substring.
51+
- Initialize a dictionary `char_index` to store the last index of each character in the substring.
52+
- Initialize the variable `max_length` to track the length of the longest substring.
53+
54+
2. **Traverse the String:**
55+
- Use the `end` pointer to traverse through the string `s`.
56+
57+
3. **Check for Repeating Characters:**
58+
- If the character at the current `end` pointer is not in the substring (not in `char_index`), add it to the substring.
59+
- Update `max_length` if the length of the current substring is greater than the previous maximum.
60+
61+
4. **Adjust Start Pointer:**
62+
- If the character is already in the substring, move the `start` pointer to the right of the last occurrence of that character.
63+
- This ensures that the substring does not contain repeating characters.
64+
65+
5. **Update Character Index:**
66+
- Update the index of the current character in the `char_index` dictionary.
67+
68+
6. **Repeat Until End of String:**
69+
- Repeat steps 3-5 until the `end` pointer reaches the end of the string.
70+
71+
7. **Return Maximum Length:**
72+
- The maximum length of the substring without repeating characters is stored in the variable `max_length`.
73+
74+
### Python Code:
75+
76+
```python
77+
class Solution:
78+
def lengthOfLongestSubstring(self, s: str) -> int:
79+
# Initialize pointers and variables
80+
start, end = 0, 0
81+
char_index = {} # Dictionary to store the last index of each character
82+
max_length = 0
83+
84+
# Traverse the string
85+
while end < len(s):
86+
# Check for repeating characters
87+
if s[end] not in char_index or char_index[s[end]] < start:
88+
# Update max_length
89+
max_length = max(max_length, end - start + 1)
90+
else:
91+
# Adjust start pointer
92+
start = char_index[s[end]] + 1
93+
94+
# Update character index
95+
char_index[s[end]] = end
96+
97+
# Move end pointer to the next character
98+
end += 1
99+
100+
# Return the maximum length of the substring
101+
return max_length
102+
103+
# Example Usage:
104+
solution = Solution()
105+
106+
# Example 1:
107+
s1 = "abcabcbb"
108+
gprint(solution.lengthOfLongestSubstring(s1)) # Output: 3
109+
110+
# Example 2:
111+
s2 = "bbbbb"
112+
print(solution.lengthOfLongestSubstring(s2)) # Output: 1
113+
114+
# Example 3:
115+
s3 = "pwwkew"
116+
print(solution.lengthOfLongestSubstring(s3)) # Output: 3
117+
118+
# Example 4:
119+
s4 = ""
120+
print(solution.lengthOfLongestSubstring(s4)) # Output: 0
121+
```
122+
123+
This code defines a `Solution` class with a method `lengthOfLongestSubstring` that takes a string `s` as input and returns the length of the longest substring without repeating characters. The example usage demonstrates how to create an instance of the `Solution` class and call the `lengthOfLongestSubstring` method with different inputs.
124+
45125
## Solution
46126

47127
```python

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,72 @@ The overall run time complexity should be `O(log (m+n))`.
5252
* `1 <= m + n <= 2000`
5353
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>
5454

55+
Here are the steps to solve the "Median of Two Sorted Arrays" problem:
56+
57+
### Approach:
58+
59+
1. **Combine Arrays:**
60+
- Combine the two sorted arrays (`nums1` and `nums2`) into a single sorted array (`merged`).
61+
- This can be done by merging the arrays while maintaining the sorted order.
62+
63+
2. **Find Median:**
64+
- If the length of the combined array is odd, the median is the middle element.
65+
- If the length is even, the median is the average of the two middle elements.
66+
67+
3. **Handle Empty Arrays:**
68+
- If one of the arrays is empty, find the median of the non-empty array.
69+
- If both arrays are empty, return 0.
70+
71+
### Python Code:
72+
73+
```python
74+
class Solution:
75+
def findMedianSortedArrays(self, nums1, nums2):
76+
# Combine arrays
77+
merged = sorted(nums1 + nums2)
78+
79+
# Find median
80+
length = len(merged)
81+
if length % 2 == 1:
82+
# Odd length
83+
return float(merged[length // 2])
84+
else:
85+
# Even length
86+
mid1 = merged[length // 2 - 1]
87+
mid2 = merged[length // 2]
88+
return (mid1 + mid2) / 2.0
89+
90+
# Example Usage:
91+
solution = Solution()
92+
93+
# Example 1:
94+
nums1_1 = [1, 3]
95+
nums2_1 = [2]
96+
print(solution.findMedianSortedArrays(nums1_1, nums2_1)) # Output: 2.00000
97+
98+
# Example 2:
99+
nums1_2 = [1, 2]
100+
nums2_2 = [3, 4]
101+
print(solution.findMedianSortedArrays(nums1_2, nums2_2)) # Output: 2.50000
102+
103+
# Example 3:
104+
nums1_3 = [0, 0]
105+
nums2_3 = [0, 0]
106+
print(solution.findMedianSortedArrays(nums1_3, nums2_3)) # Output: 0.00000
107+
108+
# Example 4:
109+
nums1_4 = []
110+
nums2_4 = [1]
111+
print(solution.findMedianSortedArrays(nums1_4, nums2_4)) # Output: 1.00000
112+
113+
# Example 5:
114+
nums1_5 = [2]
115+
nums2_5 = []
116+
print(solution.findMedianSortedArrays(nums1_5, nums2_5)) # Output: 2.00000
117+
```
118+
119+
This code defines a `Solution` class with a method `findMedianSortedArrays` that takes two sorted arrays (`nums1` and `nums2`) as input and returns the median of the combined sorted array. The example usage demonstrates how to create an instance of the `Solution` class and call the `findMedianSortedArrays` method with different inputs.
120+
55121
## Solution
56122

57123
```python

0 commit comments

Comments
 (0)