Skip to content

Added tasks 19-33 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
19\. Remove Nth Node From End of List

Medium

Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg)

**Input:** head = [1,2,3,4,5], n = 2

**Output:** [1,2,3,5]

**Example 2:**

**Input:** head = [1], n = 1

**Output:** []

**Example 3:**

**Input:** head = [1,2], n = 1

**Output:** [1]

**Constraints:**

* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`

**Follow up:** Could you do this in one pass?

Here are the steps to solve the "Remove Nth Node From End of List" problem:

### Approach:

1. **Initialize Pointers:**
- Initialize two pointers, `fast` and `slow`, both initially pointing to the head of the linked list.

2. **Move Fast Pointer:**
- Move the `fast` pointer `n` nodes ahead.

3. **Handle Edge Case:**
- If the `fast` pointer becomes `None` after moving `n` nodes, it means the node to be removed is the head of the list. In this case, return `head.next`.

4. **Move Both Pointers Until Fast Reaches End:**
- Move both `fast` and `slow` pointers one node at a time until the `fast` pointer reaches the end of the list.

5. **Remove Nth Node:**
- Update the next pointer of the `slow` pointer to skip the node to be removed.

6. **Return Updated Head:**
- Return the head of the modified linked list.

### Python Code:

```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# Initialize pointers
fast = slow = head

# Move fast pointer n nodes ahead
for _ in range(n):
fast = fast.next

# Handle case where the node to be removed is the head
if not fast:
return head.next

# Move both pointers until fast reaches the end
while fast.next:
fast = fast.next
slow = slow.next

# Remove nth node
slow.next = slow.next.next

# Return updated head
return head

# Example Usage:
solution = Solution()

# Example 1:
head1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
n1 = 2
result1 = solution.removeNthFromEnd(head1, n1) # Output: ListNode(1, ListNode(2, ListNode(3, ListNode(5))))

# Example 2:
head2 = ListNode(1)
n2 = 1
result2 = solution.removeNthFromEnd(head2, n2) # Output: None (empty list)

# Example 3:
head3 = ListNode(1, ListNode(2))
n3 = 1
result3 = solution.removeNthFromEnd(head3, n3) # Output: ListNode(1)
```

This code defines a `ListNode` class representing a node in the linked list and a `Solution` class with a method `removeNthFromEnd` that takes the head of the linked list and an integer `n` as input, removes the `nth` node from the end of the list, and returns the head of the modified list. The example usage demonstrates how to create instances of the `ListNode` class and call the `removeNthFromEnd` method with different inputs.
117 changes: 117 additions & 0 deletions g0001_0100/s0020_valid_parentheses/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
20\. Valid Parentheses

Easy

Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

**Example 1:**

**Input:** s = "()"

**Output:** true

**Example 2:**

**Input:** s = "()[]{}"

**Output:** true

**Example 3:**

**Input:** s = "(]"

**Output:** false

**Example 4:**

**Input:** s = "([)]"

**Output:** false

**Example 5:**

**Input:** s = "{[]}"

**Output:** true

**Constraints:**

* <code>1 <= s.length <= 10<sup>4</sup></code>
* `s` consists of parentheses only `'()[]{}'`.

Here are the steps to solve the "Valid Parentheses" problem:

### Approach:

1. **Initialize Stack:**
- Initialize an empty stack to keep track of the opening brackets.

2. **Iterate Through Characters:**
- Iterate through each character in the input string `s`.

3. **Check for Opening Bracket:**
- If the current character is an opening bracket (`'('`, `'{'`, or `'['`), push it onto the stack.

4. **Check for Closing Bracket:**
- If the current character is a closing bracket (`')'`, `'}'`, or `']'`), check if the stack is empty. If it is, return `False` as there is no corresponding opening bracket.

5. **Check Matching Brackets:**
- Pop the top element from the stack and check if it matches the corresponding opening bracket for the current closing bracket. If not, return `False`.

6. **Check for Empty Stack:**
- After iterating through all characters, check if the stack is empty. If it is, return `True`; otherwise, return `False`.

### Python Code:

```python
class Solution:
def isValid(self, s: str) -> bool:
# Initialize stack
stack = []

# Define mapping of opening to closing brackets
bracket_mapping = {')': '(', '}': '{', ']': '['}

# Iterate through characters
for char in s:
# Check for opening bracket
if char in bracket_mapping.values():
stack.append(char)
else:
# Check for closing bracket
if not stack or stack.pop() != bracket_mapping[char]:
return False

# Check for empty stack
return not stack

# Example Usage:
solution = Solution()

# Example 1:
input1 = "()"
result1 = solution.isValid(input1) # Output: True

# Example 2:
input2 = "()[]{}"
result2 = solution.isValid(input2) # Output: True

# Example 3:
input3 = "(]"
result3 = solution.isValid(input3) # Output: False

# Example 4:
input4 = "([)]"
result4 = solution.isValid(input4) # Output: False

# Example 5:
input5 = "{[]}"
result5 = solution.isValid(input5) # Output: True
```

This code defines a `Solution` class with a method `isValid` that takes a string `s` as input and returns `True` if the parentheses in the input string are valid and `False` otherwise. The example usage demonstrates how to create an instance of the `Solution` class and call the `isValid` method with different inputs.
106 changes: 106 additions & 0 deletions g0001_0100/s0021_merge_two_sorted_lists/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
21\. Merge Two Sorted Lists

Easy

Merge two sorted linked lists and return it as a **sorted** list. The list should be made by splicing together the nodes of the first two lists.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg)

**Input:** l1 = [1,2,4], l2 = [1,3,4]

**Output:** [1,1,2,3,4,4]

**Example 2:**

**Input:** l1 = [], l2 = []

**Output:** []

**Example 3:**

**Input:** l1 = [], l2 = [0]

**Output:** [0]

**Constraints:**

* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `l1` and `l2` are sorted in **non-decreasing** order.

Here are the steps to solve the "Merge Two Sorted Lists" problem:

### Approach:

1. **Initialize Dummy Node:**
- Initialize a dummy node to simplify the code. The dummy node's next pointer will point to the head of the merged list.

2. **Initialize Pointers:**
- Initialize pointers `curr` and `prev` initially pointing to the dummy node.

3. **Merge Lists:**
- Iterate until either `l1` or `l2` becomes `None`. In each iteration:
- Compare the values of the current nodes in `l1` and `l2`.
- Connect the smaller node to the merged list.
- Move the corresponding pointer (`l1` or `l2`) to its next node.
- Move the `curr` pointer to the newly added node.

4. **Handle Remaining Nodes:**
- After the loop, if there are remaining nodes in either `l1` or `l2`, connect them to the merged list.

5. **Return Merged List:**
- Return the next of the dummy node, which is the head of the merged list.

### Python Code:

```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# Initialize dummy node
dummy = ListNode()
# Initialize pointers
curr = dummy
# Merge lists
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
# Handle remaining nodes
if l1:
curr.next = l1
elif l2:
curr.next = l2
# Return merged list
return dummy.next

# Example Usage:
solution = Solution()

# Example 1:
l1_1 = ListNode(1, ListNode(2, ListNode(4)))
l2_1 = ListNode(1, ListNode(3, ListNode(4)))
result1 = solution.mergeTwoLists(l1_1, l2_1) # Output: ListNode(1, ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(4))))))

# Example 2:
l1_2 = None
l2_2 = None
result2 = solution.mergeTwoLists(l1_2, l2_2) # Output: None (empty list)

# Example 3:
l1_3 = None
l2_3 = ListNode(0)
result3 = solution.mergeTwoLists(l1_3, l2_3) # Output: ListNode(0)
```

This code defines a `ListNode` class representing a node in the linked list and a `Solution` class with a method `mergeTwoLists` that takes two sorted linked lists (`l1` and `l2`) as input and returns a new sorted linked list obtained by merging the nodes of `l1` and `l2`. The example usage demonstrates how to create instances of the `ListNode` class and call the `mergeTwoLists` method with different inputs.
Loading