Skip to content

Commit 91f9003

Browse files
committed
Added tasks 1-3
1 parent 3b37285 commit 91f9003

File tree

4 files changed

+343
-1
lines changed

4 files changed

+343
-1
lines changed

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2024 LeetCode-in-Python
3+
Copyright (c) 2024 Valentyn Kolesnikov
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

g0001_0100/s0001_two_sum/readme.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
1\. Two Sum
2+
3+
Easy
4+
5+
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
6+
7+
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
8+
9+
You can return the answer in any order.
10+
11+
**Example 1:**
12+
13+
**Input:** nums = [2,7,11,15], target = 9
14+
15+
**Output:** [0,1]
16+
17+
**Explanation:** Because nums[0] + nums[1] == 9, we return [0, 1].
18+
19+
**Example 2:**
20+
21+
**Input:** nums = [3,2,4], target = 6
22+
23+
**Output:** [1,2]
24+
25+
**Example 3:**
26+
27+
**Input:** nums = [3,3], target = 6
28+
29+
**Output:** [0,1]
30+
31+
**Constraints:**
32+
33+
* <code>2 <= nums.length <= 10<sup>4</sup></code>
34+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
35+
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
36+
* **Only one valid answer exists.**
37+
38+
**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code> time complexity?
39+
40+
### Approach:
41+
42+
1. **Create a Dictionary/HashMap:**
43+
- Initialize an empty dictionary to store the elements of the array and their corresponding indices.
44+
45+
2. **Iterate through the Array:**
46+
- Traverse through the given array `nums` using a loop.
47+
48+
3. **Check Complement:**
49+
- For each element `nums[i]`, calculate its complement (i.e., `target - nums[i]`).
50+
51+
4. **Check if Complement exists:**
52+
- Check if the complement is already in the dictionary.
53+
- If it is, return the indices `[dictionary[complement], i]`.
54+
- If not, add the current element and its index to the dictionary.
55+
56+
### Python Code:
57+
58+
```python
59+
from typing import List
60+
61+
class Solution:
62+
def twoSum(self, nums: List[int], target: int) -> List[int]:
63+
# Create a dictionary to store elements and their indices
64+
num_dict = {}
65+
66+
# Iterate through the array
67+
for i in range(len(nums)):
68+
# Check complement
69+
complement = target - nums[i]
70+
71+
# Check if complement exists in the dictionary
72+
if complement in num_dict:
73+
# Return the indices if complement is found
74+
return [num_dict[complement], i]
75+
76+
# Add the current element and its index to the dictionary
77+
num_dict[nums[i]] = i
78+
79+
# If no solution is found
80+
return None
81+
82+
# Example Usage:
83+
solution = Solution()
84+
85+
nums1 = [2, 7, 11, 15]
86+
target1 = 9
87+
print(solution.twoSum(nums1, target1)) # Output: [0, 1]
88+
89+
nums2 = [3, 2, 4]
90+
target2 = 6
91+
print(solution.twoSum(nums2, target2)) # Output: [1, 2]
92+
93+
nums3 = [3, 3]
94+
target3 = 6
95+
print(solution.twoSum(nums3, target3)) # Output: [0, 1]
96+
```
97+
98+
### Time Complexity:
99+
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.
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
2\. Add Two Numbers
2+
3+
Medium
4+
5+
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
6+
7+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
8+
9+
**Example 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg)
12+
13+
**Input:** l1 = [2,4,3], l2 = [5,6,4]
14+
15+
**Output:** [7,0,8]
16+
17+
**Explanation:** 342 + 465 = 807.
18+
19+
**Example 2:**
20+
21+
**Input:** l1 = [0], l2 = [0]
22+
23+
**Output:** [0]
24+
25+
**Example 3:**
26+
27+
**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
28+
29+
**Output:** [8,9,9,9,0,0,0,1]
30+
31+
**Constraints:**
32+
33+
* The number of nodes in each linked list is in the range `[1, 100]`.
34+
* `0 <= Node.val <= 9`
35+
* It is guaranteed that the list represents a number that does not have leading zeros.
36+
37+
### Approach:
38+
39+
1. **Initialize Pointers and Carry:**
40+
- 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.
41+
- Initialize `carry` to 0.
42+
43+
2. **Traverse Both Linked Lists:**
44+
- Traverse both linked lists until both pointers (`p1` and `p2`) reach the end.
45+
46+
3. **Calculate Sum and Carry:**
47+
- At each step, calculate the sum of the current digits and the carry from the previous step.
48+
- Update `carry` for the next iteration.
49+
50+
4. **Create New Node:**
51+
- Create a new node with the value as the sum % 10 and add it to the result linked list.
52+
53+
5. **Move Pointers:**
54+
- Move both pointers (`p1` and `p2`) to the next nodes in their respective linked lists.
55+
56+
6. **Handle Remaining Digits:**
57+
- After both linked lists are traversed, check if there is any remaining carry.
58+
- If there is, create a new node with the value of the carry and add it to the result linked list.
59+
60+
7. **Return Result:**
61+
- Return the next node of `dummy_head` as the head of the result linked list.
62+
63+
### Python Code:
64+
65+
```python
66+
# Definition for singly-linked list.
67+
class ListNode:
68+
def __init__(self, val=0, next=None):
69+
self.val = val
70+
self.next = next
71+
72+
class Solution:
73+
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
74+
dummy_head = ListNode()
75+
p1, p2, current = l1, l2, dummy_head
76+
carry = 0
77+
78+
while p1 or p2:
79+
# Get values and handle None cases
80+
x = p1.val if p1 else 0
81+
y = p2.val if p2 else 0
82+
83+
# Calculate sum and carry
84+
_sum = x + y + carry
85+
carry = _sum // 10
86+
87+
# Create new node with the sum % 10
88+
current.next = ListNode(_sum % 10)
89+
current = current.next
90+
91+
# Move pointers to the next nodes
92+
if p1:
93+
p1 = p1.next
94+
if p2:
95+
p2 = p2.next
96+
97+
# Handle remaining carry
98+
if carry > 0:
99+
current.next = ListNode(carry)
100+
101+
return dummy_head.next
102+
103+
# Example Usage:
104+
solution = Solution()
105+
106+
# Example 1:
107+
l1 = ListNode(2, ListNode(4, ListNode(3)))
108+
l2 = ListNode(5, ListNode(6, ListNode(4)))
109+
result = solution.addTwoNumbers(l1, l2)
110+
# Output: [7, 0, 8]
111+
112+
# Example 2:
113+
l1 = ListNode(0)
114+
l2 = ListNode(0)
115+
result = solution.addTwoNumbers(l1, l2)
116+
# Output: [0]
117+
118+
# Example 3:
119+
l1 = ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9)))))))
120+
l2 = ListNode(9, ListNode(9, ListNode(9, ListNode(9))))
121+
result = solution.addTwoNumbers(l1, l2)
122+
# Output: [8, 9, 9, 9, 0, 0, 0, 1]
123+
```
124+
125+
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.
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
3\. Longest Substring Without Repeating Characters
2+
3+
Medium
4+
5+
Given a string `s`, find the length of the **longest substring** without repeating characters.
6+
7+
**Example 1:**
8+
9+
**Input:** s = "abcabcbb"
10+
11+
**Output:** 3
12+
13+
**Explanation:** The answer is "abc", with the length of 3.
14+
15+
**Example 2:**
16+
17+
**Input:** s = "bbbbb"
18+
19+
**Output:** 1
20+
21+
**Explanation:** The answer is "b", with the length of 1.
22+
23+
**Example 3:**
24+
25+
**Input:** s = "pwwkew"
26+
27+
**Output:** 3
28+
29+
**Explanation:** The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
30+
31+
**Example 4:**
32+
33+
**Input:** s = ""
34+
35+
**Output:** 0
36+
37+
**Constraints:**
38+
39+
* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
40+
* `s` consists of English letters, digits, symbols and spaces.
41+
42+
### Approach:
43+
44+
1. **Initialize Pointers and Variables:**
45+
- Initialize two pointers, `start` and `end`, to define the current substring.
46+
- Initialize a dictionary `char_index` to store the last index of each character in the substring.
47+
- Initialize the variable `max_length` to track the length of the longest substring.
48+
49+
2. **Traverse the String:**
50+
- Use the `end` pointer to traverse through the string `s`.
51+
52+
3. **Check for Repeating Characters:**
53+
- If the character at the current `end` pointer is not in the substring (not in `char_index`), add it to the substring.
54+
- Update `max_length` if the length of the current substring is greater than the previous maximum.
55+
56+
4. **Adjust Start Pointer:**
57+
- If the character is already in the substring, move the `start` pointer to the right of the last occurrence of that character.
58+
- This ensures that the substring does not contain repeating characters.
59+
60+
5. **Update Character Index:**
61+
- Update the index of the current character in the `char_index` dictionary.
62+
63+
6. **Repeat Until End of String:**
64+
- Repeat steps 3-5 until the `end` pointer reaches the end of the string.
65+
66+
7. **Return Maximum Length:**
67+
- The maximum length of the substring without repeating characters is stored in the variable `max_length`.
68+
69+
### Python Code:
70+
71+
```python
72+
class Solution:
73+
def lengthOfLongestSubstring(self, s: str) -> int:
74+
# Initialize pointers and variables
75+
start, end = 0, 0
76+
char_index = {} # Dictionary to store the last index of each character
77+
max_length = 0
78+
79+
# Traverse the string
80+
while end < len(s):
81+
# Check for repeating characters
82+
if s[end] not in char_index or char_index[s[end]] < start:
83+
# Update max_length
84+
max_length = max(max_length, end - start + 1)
85+
else:
86+
# Adjust start pointer
87+
start = char_index[s[end]] + 1
88+
89+
# Update character index
90+
char_index[s[end]] = end
91+
92+
# Move end pointer to the next character
93+
end += 1
94+
95+
# Return the maximum length of the substring
96+
return max_length
97+
98+
# Example Usage:
99+
solution = Solution()
100+
101+
# Example 1:
102+
s1 = "abcabcbb"
103+
gprint(solution.lengthOfLongestSubstring(s1)) # Output: 3
104+
105+
# Example 2:
106+
s2 = "bbbbb"
107+
print(solution.lengthOfLongestSubstring(s2)) # Output: 1
108+
109+
# Example 3:
110+
s3 = "pwwkew"
111+
print(solution.lengthOfLongestSubstring(s3)) # Output: 3
112+
113+
# Example 4:
114+
s4 = ""
115+
print(solution.lengthOfLongestSubstring(s4)) # Output: 0
116+
```
117+
118+
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.

0 commit comments

Comments
 (0)