diff --git a/dsa-solutions/lc-solutions/0100-0199/0156-binary-tree-upside-down.md b/dsa-solutions/lc-solutions/0100-0199/0156-binary-tree-upside-down.md new file mode 100644 index 000000000..a157e0f81 --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0156-binary-tree-upside-down.md @@ -0,0 +1,136 @@ +--- +id: binary-tree-upside-down +title: Binary Tree Upside Down +sidebar_label: 0156-Binary Tree Upside Down +tags: + - Binary Tree + - Leet code +description: "Solution to leetocde 156" +--- + +## Problem Description + +Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. + +### Example: + +``` +Input: [1,2,3,4,5] + + 1 + / \ + 2 3 + / \ +4 5 + +Output: return the root of the binary tree [4,5,2,#,#,3,1] + + 4 + / \ + 5 2 + / \ + 3 1 +``` + +### Algorithm + +1. **Base Case**: If the root is `None` or the root has no left child, return the root. +2. **Recursive Case**: Recursively process the left child of the root. +3. **Reassign Pointers**: Once you reach the new root, start reassigning the pointers: + - The left child's left pointer should point to the original root's right child. + - The left child's right pointer should point to the original root. +4. **Clear Original Pointers**: Set the original root's left and right pointers to `None`. +5. **Return the New Root**: Return the new root of the upside-down tree. + +### Python + +```python +from typing import Optional + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root is None or root.left is None: + return root + new_root = self.upsideDownBinaryTree(root.left) + root.left.right = root + root.left.left = root.right + root.left = None + root.right = None + return new_root +``` + +### C++ + +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode* upsideDownBinaryTree(TreeNode* root) { + if (root == nullptr || root->left == nullptr) + return root; + TreeNode* new_root = upsideDownBinaryTree(root->left); + root->left->right = root; + root->left->left = root->right; + root->left = nullptr; + root->right = nullptr; + return new_root; + } +}; +``` + +### Java + +```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +public class Solution { + public TreeNode upsideDownBinaryTree(TreeNode root) { + if (root == null || root.left == null) return root; + TreeNode newRoot = upsideDownBinaryTree(root.left); + root.left.left = root.right; + root.left.right = root; + root.left = null; + root.right = null; + return newRoot; + } +} +``` + +### JavaScript + +```javascript +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +var upsideDownBinaryTree = function (root) { + if (root === null || root.left === null) return root; + let newRoot = upsideDownBinaryTree(root.left); + root.left.left = root.right; + root.left.right = root; + root.left = null; + root.right = null; + return newRoot; +}; +``` diff --git a/dsa-solutions/lc-solutions/0100-0199/0157-Read-n-characters-given.md b/dsa-solutions/lc-solutions/0100-0199/0157-Read-n-characters-given.md new file mode 100644 index 000000000..ffd24f391 --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0157-Read-n-characters-given.md @@ -0,0 +1,219 @@ +--- +id: read-n-characters-given +title: Read N characters Given +sidebar_label: 0157-Read N Characters Given +tags: + - Leet code +description: "Solution to leetocde 157" +--- + +### Problem Description + +Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters. + +### Examples + +Example 1: + +``` +Input: file = "abc", n = 4 +Output: 3 +Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3. Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to. +``` + +Example 2: + +``` +Input: file = "abcde", n = 5 +Output: 5 +Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5. +``` + +Example 3: + +``` +Input: file = "abcdABCD1234", n = 12 +Output: 12 +Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12. +``` + +Example 4: + +``` +Input: file = "leetcode", n = 5 +Output: 5 +Explanation: After calling your read method, buf should contain "leetc". We read a total of 5 characters from the file, so return 5. +``` + +### Note: + +- Consider that you cannot manipulate the file directly, the file is only accesible for read4 but not for read. +- The read function will only be called once for each test case. +- You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters. + +### Algorithm + +1. **Initialization**: + + - `buf4`: A temporary buffer that stores the characters read by `read4`. + - `i4`: Index for iterating over `buf4`. + - `n4`: Number of characters actually read by `read4`. + - `i`: Index for iterating over the destination buffer `buf`. + +2. **Reading Characters**: + + - The loop continues until `i` (number of characters written to `buf`) reaches `n` (the requested number of characters). + - If all characters in `buf4` are consumed (`i4 == n4`), `read4` is called again to refill `buf4` and reset `i4`. + - If `read4` returns 0 (`n4 == 0`), it means the end of the file has been reached, and the function returns the number of characters read so far. + - Characters from `buf4` are copied to `buf` one by one, and both indices (`i` and `i4`) are incremented accordingly. + +3. **Return**: + - The function returns the total number of characters read, which is the value of `i`. + +### Code Implementation + +### C++ + +```cpp + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } +}; +``` + +### Python + +```python +class Solution: + def __init__(self): + self.buf4 = [''] * 4 # Temporary buffer to store characters read by read4 + self.i4 = 0 # Index for iterating over buf4 + self.n4 = 0 # Number of characters actually read by read4 + + def read4(self, buf4): + # This method is provided in the parent class or environment. + pass + + def read(self, buf, n): + i = 0 # Index for the destination buffer buf + + while i < n: + if self.i4 == self.n4: + self.n4 = self.read4(self.buf4) + self.i4 = 0 + if self.n4 == 0: + break + + while i < n and self.i4 < self.n4: + buf[i] = self.buf4[self.i4] + i += 1 + self.i4 += 1 + + return i +``` + +### Java + +```java +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char[] buf4); + */ + +public class Solution extends Reader4 { + private char[] buf4 = new char[4]; + private int i4 = 0; + private int n4 = 0; + + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + public int read(char[] buf, int n) { + int i = 0; + + while (i < n) { + if (i4 == n4) { + n4 = read4(buf4); + i4 = 0; + if (n4 == 0) { + break; + } + } + + while (i < n && i4 < n4) { + buf[i++] = buf4[i4++]; + } + } + + return i; + } +} +``` + +### JavaScript + +```javascript +/** + * Definition for read4 API + * read4 = function(buf4) { + * // Reads 4 characters at a time and writes to buf4 + * // Returns the number of characters actually read + * } + */ + +var Solution = function () { + this.buf4 = new Array(4); + this.i4 = 0; + this.n4 = 0; +}; + +/** + * @param {character[]} buf Destination buffer + * @param {number} n Number of characters to read + * @return {number} The number of actual characters read + */ +Solution.prototype.read = function (buf, n) { + let i = 0; + + while (i < n) { + if (this.i4 === this.n4) { + this.n4 = read4(this.buf4); + this.i4 = 0; + if (this.n4 === 0) { + break; + } + } + + while (i < n && this.i4 < this.n4) { + buf[i++] = this.buf4[this.i4++]; + } + } + + return i; +}; +``` diff --git a/dsa-solutions/lc-solutions/0100-0199/0159-longest-substring-with-at.md b/dsa-solutions/lc-solutions/0100-0199/0159-longest-substring-with-at.md new file mode 100644 index 000000000..5225c9ccf --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0159-longest-substring-with-at.md @@ -0,0 +1,169 @@ +--- +id: longest-substring-with-at +title: Longest Substring Given At +sidebar_label: 0159-Longest Substring Given At +tags: + - Leet code +description: "Solution to leetocde 159" +--- + +### Problem Description + +Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. + +### Examples + +**Example 1:** + +``` +Input: "eceba" +Output: 3 +Explanation: t is "ece" which its length is 3. +``` + +**Example 2:** + +``` +Input: "ccaabbb" +Output: 5 +Explanation: t is "aabbb" which its length is 5. +``` + +Certainly! Below is the complete algorithm with explanations, followed by the implementations in C++, Python, Java, and JavaScript. + +### Algorithm + +1. **Initialize**: + + - A hash map to count characters in the current window. + - Two pointers, `i` and `j`, to represent the current window. `i` is the right pointer, and `j` is the left pointer. + - A variable to keep track of the maximum length of the substring. + +2. **Expand the Window**: + + - Move the right pointer `i` to expand the window. + - Add the current character to the hash map and update its count. + +3. **Shrink the Window if Necessary**: + + - If the number of distinct characters in the hash map exceeds 2, move the left pointer `j` to shrink the window until the number of distinct characters is at most 2. + - Decrease the count of the character at the left pointer `j` in the hash map and remove it if its count becomes 0. + +4. **Update the Maximum Length**: + + - Update the maximum length of the substring after adjusting the window. + +5. **Return the Result**: + - Return the maximum length of the substring with at most two distinct characters. + +### C++ + +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + int lengthOfLongestSubstringTwoDistinct(string s) { + unordered_map cnt; + int n = s.size(); + int ans = 0; + int j = 0; + + for (int i = 0; i < n; ++i) { + cnt[s[i]]++; + while (cnt.size() > 2) { + cnt[s[j]]--; + if (cnt[s[j]] == 0) { + cnt.erase(s[j]); + } + ++j; + } + ans = max(ans, i - j + 1); + } + + return ans; + } +}; +``` + +### Python + +```python +class Solution: + def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: + from collections import defaultdict + + cnt = defaultdict(int) + n = len(s) + ans = 0 + j = 0 + + for i in range(n): + cnt[s[i]] += 1 + while len(cnt) > 2: + cnt[s[j]] -= 1 + if cnt[s[j]] == 0: + del cnt[s[j]] + j += 1 + ans = max(ans, i - j + 1) + + return ans +``` + +### Java + +```java +import java.util.HashMap; + +public class Solution { + public int lengthOfLongestSubstringTwoDistinct(String s) { + HashMap cnt = new HashMap<>(); + int n = s.length(); + int ans = 0; + int j = 0; + + for (int i = 0; i < n; ++i) { + cnt.put(s.charAt(i), cnt.getOrDefault(s.charAt(i), 0) + 1); + while (cnt.size() > 2) { + cnt.put(s.charAt(j), cnt.get(s.charAt(j)) - 1); + if (cnt.get(s.charAt(j)) == 0) { + cnt.remove(s.charAt(j)); + } + ++j; + } + ans = Math.max(ans, i - j + 1); + } + + return ans; + } +} +``` + +### JavaScript + +```javascript +var lengthOfLongestSubstringTwoDistinct = function (s) { + let cnt = new Map(); + let n = s.length; + let ans = 0; + let j = 0; + + for (let i = 0; i < n; ++i) { + cnt.set(s[i], (cnt.get(s[i]) || 0) + 1); + while (cnt.size > 2) { + cnt.set(s[j], cnt.get(s[j]) - 1); + if (cnt.get(s[j]) === 0) { + cnt.delete(s[j]); + } + ++j; + } + ans = Math.max(ans, i - j + 1); + } + + return ans; +}; +``` diff --git a/dsa-solutions/lc-solutions/0100-0199/0160-intersection-of-two-linked-list.md b/dsa-solutions/lc-solutions/0100-0199/0160-intersection-of-two-linked-list.md new file mode 100644 index 000000000..8cd920405 --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0160-intersection-of-two-linked-list.md @@ -0,0 +1,213 @@ +--- +id: intersection-of-two-linked-list. +title: Intersection of Two Linked Lists +sidebar_label: 0160-Intersection of Two Linked Lists +tags: + - Linked List + - Leet code +description: "Solution to leetocde 160" +--- + +### Problem Description + +Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. + +For example, the following two linked lists begin to intersect at node c1: + +The test cases are generated such that there are no cycles anywhere in the entire linked structure. + +Note that the linked lists must retain their original structure after the function returns. + +**Custom Judge:** + +The inputs to the judge are given as follows (your program is not given these inputs): + +- intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node. +- listA - The first linked list. +- listB - The second linked list. +- skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node. +- skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node. +- The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted. + +**Example 1:** + +``` +Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 +Output: Intersected at '8' +Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. + +- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. +``` + +**Example 2:** + +``` +Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 +Output: Intersected at '2' +Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. +``` + +**Example 3:** + +``` +Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 +Output: No intersection +Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. +Explanation: The two lists do not intersect, so return null. +``` + +### Constraints: + +- The number of nodes of listA is in the m. +- The number of nodes of listB is in the n. +- $1 <= m, n <= 3*10^4$ +- $1 <= Node.val <= 10^5$ +- $0 <= skipA < m$ +- $0 <= skipB < n$ +- $intersectVal is 0 if listA and listB do not intersect.$ +- $intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.$ + +### Algorithm + +The algorithm to find the intersection of two linked lists uses the following steps: + +1. **Traverse the First List**: + + - Store each node in a hash map (or set). + +2. **Traverse the Second List**: + - Check if any node is already present in the hash map (or set). If found, that node is the intersection. + +### C++ Implementation + +```cpp +#include + +// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(nullptr) {} +}; + +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + std::unordered_map mpp; + + // Traverse list A and store each node in the map + for (ListNode *p = headA; p != nullptr; p = p->next) { + mpp[p] = p->val; + } + + // Traverse list B and check if any node is in the map + for (ListNode *p = headB; p != nullptr; p = p->next) { + if (mpp.find(p) != mpp.end()) { + return p; + } + } + + return nullptr; + } +}; +``` + +### Python Implementation + +```python +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + node_set = set() + + # Traverse list A and store each node in the set + p = headA + while p: + node_set.add(p) + p = p.next + + # Traverse list B and check if any node is in the set + p = headB + while p: + if p in node_set: + return p + p = p.next + + return None +``` + +### Java Implementation + +```java +import java.util.HashSet; + +class ListNode { + int val; + ListNode next; + ListNode(int x) { + val = x; + next = null; + } +} + +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + HashSet nodeSet = new HashSet<>(); + + // Traverse list A and store each node in the set + ListNode p = headA; + while (p != null) { + nodeSet.add(p); + p = p.next; + } + + // Traverse list B and check if any node is in the set + p = headB; + while (p != null) { + if (nodeSet.contains(p)) { + return p; + } + p = p.next; + } + + return null; + } +} +``` + +### JavaScript Implementation + +```javascript +function ListNode(val) { + this.val = val; + this.next = null; +} + +var getIntersectionNode = function (headA, headB) { + let nodeSet = new Set(); + + // Traverse list A and store each node in the set + let p = headA; + while (p !== null) { + nodeSet.add(p); + p = p.next; + } + + // Traverse list B and check if any node is in the set + p = headB; + while (p !== null) { + if (nodeSet.has(p)) { + return p; + } + p = p.next; + } + + return null; +}; +```