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; +}; +```