title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
3,370
7
**NOTE - PLEASE READ INTUITION AND APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Intuition of this Problem :\n*The problem of determining whether two strings are scrambled versions of each other is a challenging one. One way to approach this problem is to use dynamic programming. The key idea is to divide the strings into two non-empty substrings at a random index, and recursively apply the same process to each of these substrings. If one or both of the substrings can be scrambled into the corresponding substrings of the other string, then the original strings can be scrambled into each other as well.*\n\n*To solve this problem using dynamic programming, we can define a 3D boolean array dp[l][i][j] that stores whether a substring of length l starting at index i of s1 and a substring of length l starting at index j of s2 can be scrambled into each other. We can use a bottom-up approach and fill the array dp in a way that depends on its smaller values, i.e., we start with dp[1][i][j] for all i and j, which is simply the base case where l is 1. We then compute dp[l][i][j] for l > 1 by trying all possible ways to divide the substrings into two non-empty parts and recursively checking if the two parts can be scrambled into each other. If we find such a way, we set dp[l][i][j] to true.*\n\n*Finally, the answer to the problem is the value of dp[n][0][0], where n is the length of the input strings. This is because we want to determine whether the entire strings s1 and s2 can be scrambled into each other, which corresponds to the case where we consider substrings of length n starting at the beginning of both strings. If dp[n][0][0] is true, then the answer is yes, otherwise it is no.*\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach for this Problem :\n1. Get the length of both strings s1 and s2 and check if they are equal. If not, return false.\n2. Define a 3D boolean array dp[n+1][n][n] to store the results, where n is the length of the strings.\n3. Initialize all values of dp to false using memset.\n4. For the base case where the length of strings is 1, loop through both strings and if the characters are equal, set dp[1][i][j] to true.\n5. For the general case where the length of strings is greater than 1, loop through all possible lengths of substrings (from 2 to n) and all possible starting positions of substrings (from 0 to n - length).\n6. Divide the strings into two substrings at all possible positions and check if they are scrambled strings of each other in both swapped and same order using dp[k][i][j] and dp[l-k][i+k][j+k] and dp[k][i][j+l-k] and dp[l-k][i+k][j] respectively. If any of these checks returns true, set dp[l][i][j] to true and break out of the loop.\n7. Return dp[n][0][0], which is the final result.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Code :\n```C++ []\nclass Solution {\npublic:\n bool isScramble(string s1, string s2) {\n int n = s1.length(); // Get the length of the strings\n if (n != s2.length()) { // If the lengths are not equal, return false\n return false;\n }\n bool dp[n + 1][n][n]; // Define a 3D boolean array to store the results\n memset(dp, false, sizeof(dp)); // Initialize all values to false\n for (int i = 0; i < n; i++) { // Base case: length 1\n for (int j = 0; j < n; j++) {\n if (s1[i] == s2[j]) { // If the characters are equal, set dp[1][i][j] to true\n dp[1][i][j] = true;\n }\n }\n }\n for (int l = 2; l <= n; l++) { // General case: length > 1\n for (int i = 0; i <= n - l; i++) {\n for (int j = 0; j <= n - l; j++) {\n for (int k = 1; k < l; k++) { // Divide the strings into two substrings at all possible positions\n if ((dp[k][i][j] && dp[l - k][i + k][j + k]) || // Check if the two substrings are scrambled strings of each other in swapped order\n (dp[k][i][j + l - k] && dp[l - k][i + k][j])) { // Check if the two substrings are scrambled strings of each other in same order\n dp[l][i][j] = true; // If any one of these checks returns true, set dp[l][i][j] to true\n break;\n }\n }\n }\n }\n }\n return dp[n][0][0]; // Return dp[n][0][0], which is the final result\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isScramble(String s1, String s2) {\n int n = s1.length();\n if (n != s2.length()) {\n return false;\n }\n boolean[][][] dp = new boolean[n + 1][n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (s1.charAt(i) == s2.charAt(j)) {\n dp[1][i][j] = true;\n }\n }\n }\n for (int l = 2; l <= n; l++) {\n for (int i = 0; i <= n - l; i++) {\n for (int j = 0; j <= n - l; j++) {\n for (int k = 1; k < l; k++) {\n if ((dp[k][i][j] && dp[l - k][i + k][j + k]) ||\n (dp[k][i][j + l - k] && dp[l - k][i + k][j])) {\n dp[l][i][j] = true;\n break;\n }\n }\n }\n }\n }\n return dp[n][0][0];\n }\n}\n\n```\n```Python []\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n n = len(s1)\n if n != len(s2):\n return False\n dp = [[[False for _ in range(n)] for _ in range(n)] for _ in range(n + 1)]\n for i in range(n):\n for j in range(n):\n if s1[i] == s2[j]:\n dp[1][i][j] = True\n for l in range(2, n + 1):\n for i in range(n - l + 1):\n for j in range(n - l + 1):\n for k in range(1, l):\n if (dp[k][i][j] and dp[l - k][i + k][j + k]) or (dp[k][i][j + l - k] and dp[l - k][i + k][j]):\n dp[l][i][j] = True\n break\n return dp[n][0][0]\n\n```\n\n# Time Complexity and Space Complexity:\n- **Time Complexity :** ***O(n^4)**, where n is the length of s1. This is because there are n^2 possible starting indices for the substrings, and for each pair (i,j), we iterate over k, which can take up to l-1 values. Therefore, the innermost loop runs at most (l-1) times for each pair (i,j). The total number of iterations of the innermost loop is bounded by the sum of (l-1) over all possible values of l, which is O(n^3). The initialization of dp takes O(n^3) time, so the overall time complexity of the algorithm is O(n^4).*\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space Complexity :** ***O(n^3)**, since we use a 3D array of size n+1 x n x n to store the intermediate results.*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
8,555
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
1,093
7
\n```\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n if len(s1)!=len(s2):\n return False\n m=dict()\n def f(a,b):\n if (a,b) in m:\n return m[(a,b)]\n if a==b:\n m[a,b]=True\n return True\n if len(a)!=len(b):\n m[(a,b)]=False\n return False\n \n for i in range(1,len(a)):\n if f(a[:i],b[:i]) and f(a[i:],b[i:]):\n m[(a,b)]=True\n return True\n if f(a[:i],b[-i:]) and f(a[i:],b[:len(a)-i]):\n m[(a,b)]=True\n return True\n \n m[(a,b)]=False\n return False\n return f(s1,s2)\n```
8,563
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
11,759
104
class Solution:\n # @return a boolean\n def isScramble(self, s1, s2):\n n, m = len(s1), len(s2)\n if n != m or sorted(s1) != sorted(s2):\n return False\n if n < 4 or s1 == s2:\n return True\n f = self.isScramble\n for i in range(1, n):\n if f(s1[:i], s2[:i]) and f(s1[i:], s2[i:]) or \\\n f(s1[:i], s2[-i:]) and f(s1[i:], s2[:-i]):\n return True\n return False
8,568
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
7,788
53
# DP \n def isScramble1(self, s1, s2):\n if len(s1) != len(s2):\n return False\n if s1 == s2:\n return True\n if sorted(s1) != sorted(s2): # prunning\n return False\n for i in xrange(1, len(s1)):\n if (self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:])) or \\\n (self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:-i])):\n return True\n return False\n \n # DP with memorization\n def __init__(self):\n self.dic = {}\n \n def isScramble(self, s1, s2):\n if (s1, s2) in self.dic:\n return self.dic[(s1, s2)]\n if len(s1) != len(s2) or sorted(s1) != sorted(s2): # prunning\n self.dic[(s1, s2)] = False\n return False\n if s1 == s2:\n self.dic[(s1, s2)] = True\n return True\n for i in xrange(1, len(s1)):\n if (self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:])) or \\\n (self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:-i])):\n return True\n self.dic[(s1, s2)] = False\n return False
8,579
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
846
5
***Hello it would be my pleasure to introduce myself Darian.***\n\n***Java***\n```\npublic class Solution {\n\tpublic boolean isScramble(String s1, String s2) {\n\t\tif (s1.length() != s2.length()) return false;\n\t\tint len = s1.length();\n\t\t/**\n\t\t * Let F(i, j, k) = whether the substring S1[i..i + k - 1] is a scramble of S2[j..j + k - 1] or not\n\t\t * Since each of these substrings is a potential node in the tree, we need to check for all possible cuts.\n\t\t * Let q be the length of a cut (hence, q < k), then we are in the following situation:\n\t\t * \n\t\t * S1 [ x1 | x2 ]\n\t\t * i i + q i + k - 1\n\t\t * \n\t\t * here we have two possibilities:\n\t\t * \n\t\t * S2 [ y1 | y2 ]\n\t\t * j j + q j + k - 1\n\t\t * \n\t\t * or \n\t\t * \n\t\t * S2 [ y1 | y2 ]\n\t\t * j j + k - q j + k - 1\n\t\t * \n\t\t * which in terms of F means:\n\t\t * \n\t\t * F(i, j, k) = for some 1 <= q < k we have:\n\t\t * (F(i, j, q) AND F(i + q, j + q, k - q)) OR (F(i, j + k - q, q) AND F(i + q, j, k - q))\n\t\t * \n\t\t * Base case is k = 1, where we simply need to check for S1[i] and S2[j] to be equal \n\t\t * */\n\t\tboolean [][][] F = new boolean[len][len][len + 1];\n\t\tfor (int k = 1; k <= len; ++k)\n\t\t\tfor (int i = 0; i + k <= len; ++i)\n\t\t\t\tfor (int j = 0; j + k <= len; ++j)\n\t\t\t\t\tif (k == 1)\n\t\t\t\t\t\tF[i][j][k] = s1.charAt(i) == s2.charAt(j);\n\t\t\t\t\telse for (int q = 1; q < k && !F[i][j][k]; ++q) {\n\t\t\t\t\t\tF[i][j][k] = (F[i][j][q] && F[i + q][j + q][k - q]) || (F[i][j + k - q][q] && F[i + q][j][k - q]);\n\t\t\t\t\t}\n\t\treturn F[0][0][len];\n\t}\n}\n```\n\n***C++***\n```\nclass Solution {\npublic:\n // checks if s2 is scrambled form of s1\n /*\n The idea is to find a position in string s1, from where scrambling must have\n started to create s2. So if k is the position, then s1[0-k] and s1[k+1, N-1]\n were the last scramble op. We do this recursively for the smaller substrings.\n \n */\n bool isScrambled(int s1_start, int s1_end, int s2_start, int s2_end,\n string& s1, string& s2, unordered_map<string, bool>& dp) {\n // create the current position combination\n string curr_cmb = to_string(s1_start) + \',\' + to_string(s1_end) + \n \',\' + to_string(s2_start) + \',\' + to_string(s2_end);\n // check if the values is in cache \n auto it = dp.find(curr_cmb);\n if(it != dp.end())\n return dp[curr_cmb];\n \n // base cases\n if(s1_end < s1_start || s2_end < s2_start)\n return false;\n // if the size of two strings is diff, then scrambling not poss\n if(s1_end - s1_start != s2_end - s2_start)\n return false;\n // if the two substrings match, then they are scrambled\n if(s1.substr(s1_start, s1_end - s1_start + 1) == s2.substr(s2_start, s2_end - s2_start + 1))\n return true;\n \n // check if the two substrings contains the same set of chars\n vector<int> char_freq(256, 0);\n for(int i = 0; i <= s1_end - s1_start; i++)\n char_freq[s1[s1_start + i]-\'a\']++, char_freq[s2[s2_start + i]-\'a\']--;\n for(int i = 0; i < 256; i++)\n if(char_freq[i]) \n\t\t\t\treturn false;\n \n // find a position which is the potential scramble point\n for(int k = 0; k < (s1_end - s1_start); k++) {\n // check for s1[start: k], s2[start:k] and s1[k+1 : end], s2[k+1 : end]\n if(isScrambled(s1_start, s1_start + k, s2_start, s2_start + k, s1, s2, dp) &&\n isScrambled(s1_start + k + 1, s1_end, s2_start + k + 1, s2_end, s1, s2, dp))\n return dp[curr_cmb] = true;\n // Now incase of s2, maybe scramble opertation was performed at k, so \n // now check if the other half of s2\n // check for s1[start: k], s2[end - k : end] and s1[k+1 : end], s2[s : end - k - 1]\n if(isScrambled(s1_start, s1_start + k, s2_end - k, s2_end, s1, s2, dp) &&\n isScrambled(s1_start + k + 1, s1_end, s2_start, s2_end - k - 1, s1, s2, dp))\n return dp[curr_cmb] = true;\n }\n return dp[curr_cmb] = false;\n }\n \n bool isScramble(string s1, string s2) {\n // DP cache: saves the result of (s1_start, s1_end, s2_start, s2_end) cmb\n unordered_map<string, bool> dp;\n return isScrambled(0, s1.size()-1, 0, s2.size()-1, s1, s2, dp);\n }\n};\n```\n\n***Python***\n```\nclass Solution(object):\n def isScramble(self, s1, s2):\n """\n :type s1: str\n :type s2: str\n :rtype: bool\n """\n if s1 == s2:\n return True\n if len(s1) != len(s2):\n return False\n \n # Check both strings have same count of letters\n count1 = collections.defaultdict(int)\n count2 = collections.defaultdict(int)\n for c1, c2 in zip(s1, s2):\n count1[c1] += 1\n count2[c2] += 1\n if count1 != count2: return False\n \n # Iterate through letters and check if it results in a partition of \n # string 1 where the collection of letters are the same\n # on the left (non-swapped) or right (swapped) sides of string 2\n # Then we recursively check these partitioned strings to see if they are scrambled\n lcount1 = collections.defaultdict(int) # s1 count from left\n lcount2 = collections.defaultdict(int) # s2 count from left\n rcount2 = collections.defaultdict(int) # s2 count from right\n for i in xrange(len(s1) - 1):\n lcount1[s1[i]] += 1 \n lcount2[s2[i]] += 1\n rcount2[s2[len(s1) - 1 - i]] += 1\n if lcount1 == lcount2: # Left sides of both strings have same letters\n if self.isScramble(s1[:i + 1], s2[:i + 1]) and \\\n self.isScramble(s1[i + 1:], s2[i + 1:]):\n return True\n elif lcount1 == rcount2: # Left side of s1 has same letters as right side of s2\n if self.isScramble(s1[:i + 1], s2[-(i + 1):]) and \\\n self.isScramble(s1[i + 1:], s2[:-(i + 1)]):\n return True\n return False\n```\n\n***JavaScript***\n```\nconst _isScramble = function (s1, s2, trackMap) { \n if (s1.length !== s2.length) return false;\n if (s1 === s2) return true;\n if (s1.length === 0 || s2.length === 0) return true;\n const trackKey = s1 + s2;\n if (trackKey in trackMap) return !!trackMap[trackKey];\n\n let result = false;\n let xorFW = 0;\n let xorBW = 0;\n\n for (var i = 0, j = s1.length - 1, iPlus = 1; i < s1.length - 1; i++, j--, iPlus++) {\n xorFW ^= s1.charCodeAt(i) ^ s2.charCodeAt(i);\n xorBW ^= s1.charCodeAt(i) ^ s2.charCodeAt(j);\n\n if (xorFW === 0 &&\n _isScramble(s1.substring(0, iPlus), s2.substring(0, iPlus), trackMap) &&\n _isScramble(s1.substring(iPlus), s2.substring(iPlus), trackMap)) {\n result = true;\n break;\n }\n\n if (xorBW === 0 &&\n _isScramble(s1.substring(0, iPlus), s2.substring(s1.length - iPlus), trackMap) &&\n _isScramble(s1.substring(iPlus), s2.substring(0, s1.length - iPlus), trackMap)) {\n result = true;\n break;\n }\n }\n\n trackMap[trackKey] = result;\n trackMap[s2 + s1] = result;\n return result;\n};\n\n/**\n * @param {string} s1\n * @param {string} s2\n * @return {boolean}\n */\nconst isScramble = function (s1, s2) {\n return _isScramble(s1, s2, {});\n};\n```\n\n***Kotlin***\n```\nclass Solution {\n val memo = mutableMapOf<String, Boolean>()\n \n fun isNotAnagram(s1: String, s2: String): Boolean {\n val f1 = MutableList(26) {0}\n val f2 = MutableList(26) {0}\n for (c in s1) {\n f1[(c-\'a\').toInt()]++\n }\n for (c in s2) {\n f2[(c-\'a\').toInt()]++\n }\n return f1.toString() != f2.toString()\n }\n \n fun isScramble(s1: String, s2: String): Boolean {\n if (s1 == s2) return true\n if (isNotAnagram(s1, s2)) return false\n memo["$s1*$s2"]?.let {\n return it\n }\n val n = s1.length\n for (i in 1 .. n-1) {\n \n if ((isScramble(s1.substring(0,i), s2.substring(0,i)) && isScramble(s1.substring(i,n), s2.substring(i,n))) || (isScramble(s1.substring(0,i), s2.substring(n-i,n)) && isScramble(s1.substring(i,n), s2.substring(0,n-i)))) {\n memo["$s1*$s2"] = true\n return true\n }\n }\n memo["$s1*$s2"] = false\n return false\n }\n}\n```\n\n***Swift***\n```\nclass Solution {\n func isScramble(_ s1: String, _ s2: String) -> Bool {\n var dp: [String: Bool] = [:]\n \n\n func _isScramble(_ chs1: [Character], _ chs2: [Character]) -> Bool {\n let key = String(chs1) + "-" + String(chs2)\n if let v = dp[key] { return v } \n if chs1.count == 1 { return chs1[0] == chs2[0] }\n var val = false\n\n for i in 1..<chs1.count {\n val = val || (_isScramble(Array(chs1[0..<i]), Array(chs2[0..<i])) \n && _isScramble(Array(chs1[i..<chs1.count]), Array(chs2[i..<chs2.count])))\n val = val || (_isScramble(Array(chs1[0..<i]), Array(chs2[chs2.count - i..<chs2.count]))\n && _isScramble(Array(chs1[i..<chs1.count]), Array(chs2[0..<chs2.count-i]))) \n }\n \n dp[key] = val\n return val\n }\n \n if s1.count != s2.count {\n return false\n } else {\n return _isScramble(Array(s1), Array(s2))\n }\n }\n \n}\n```\n\n***Consider upvote if useful! Hopefully it can be used in your advantage!***\n***Take care brother, peace, love!***\n***"Open your eyes."***
8,593
Merge Sorted Array
merge-sorted-array
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Array,Two Pointers,Sorting
Easy
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
265,181
1,919
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWe are given two sorted arrays nums1 and nums2 of sizes m and n, respectively. We need to merge these two arrays into a single sorted array, and the result should be stored inside nums1. Since nums1 is of size m+n, we can use this extra space to store the merged array. We can iterate through the arrays from the end and place the larger element in the end of nums1.\n\n---\n# Approach : ***Using STL***\n1. Traverse through nums2 and append its elements to the end of nums1 starting from index m.\n2. Sort the entire nums1 array using sort() function.\n\n# Complexity\n- Time complexity: O((m+n)log(m+n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n> *due to the sort() function*\n\n- Space complexity: O(1)\n> *We are not using any extra space, so the space complexity is O(1).*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {\n for (int j = 0, i = m; j<n; j++){\n nums1[i] = nums2[j];\n i++;\n }\n sort(nums1.begin(),nums1.end());\n }\n};\n```\n```java []\nclass Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n for (int j = 0, i = m; j < n; j++) {\n nums1[i] = nums2[j];\n i++;\n }\n Arrays.sort(nums1);\n }\n}\n\n\n```\n```python []\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n for j in range(n):\n nums1[m+j] = nums2[j]\n nums1.sort()\n\n```\n```javascript []\nvar merge = function(nums1, m, nums2, n) {\n for (let i = m, j = 0; j < n; i++, j++) {\n nums1[i] = nums2[j];\n }\n nums1.sort((a, b) => a - b);\n};\n\n```\n\n---\n\n\n\n# Approach : ***Two Pointer***\n<!-- Describe your approach to solving the problem. -->\n\nWe can start with two pointers i and j, initialized to m-1 and n-1, respectively. We will also have another pointer k initialized to m+n-1, which will be used to keep track of the position in nums1 where we will be placing the larger element. Then we can start iterating from the end of the arrays i and j, and compare the elements at these positions. We will place the larger element in nums1 at position k, and decrement the corresponding pointer i or j accordingly. We will continue doing this until we have iterated through all the elements in nums2. If there are still elements left in nums1, we don\'t need to do anything because they are already in their correct place.\n\n# Complexity\n- Time complexity: O(m+n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n> *We are iterating through both arrays once, so the time complexity is O(m+n).*\n\n- Space complexity: O(1)\n> *We are not using any extra space, so the space complexity is O(1).*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {\n int i = m - 1;\n int j = n - 1;\n int k = m + n - 1;\n \n while (j >= 0) {\n if (i >= 0 && nums1[i] > nums2[j]) {\n nums1[k--] = nums1[i--];\n } else {\n nums1[k--] = nums2[j--];\n }\n }\n }\n};\n```\n```java []\nclass Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n int i = m - 1;\n int j = n - 1;\n int k = m + n - 1;\n \n while (j >= 0) {\n if (i >= 0 && nums1[i] > nums2[j]) {\n nums1[k--] = nums1[i--];\n } else {\n nums1[k--] = nums2[j--];\n }\n }\n }\n}\n\n```\n```python []\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n i = m - 1\n j = n - 1\n k = m + n - 1\n \n while j >= 0:\n if i >= 0 and nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n i -= 1\n else:\n nums1[k] = nums2[j]\n j -= 1\n k -= 1\n\n```\n```javascript []\nvar merge = function(nums1, m, nums2, n) {\n let i = m - 1;\n let j = n - 1;\n let k = m + n - 1;\n \n while (j >= 0) {\n if (i >= 0 && nums1[i] > nums2[j]) {\n nums1[k--] = nums1[i--];\n } else {\n nums1[k--] = nums2[j--];\n }\n }\n};\n```\n\n\n---\n\n![upvote.jpeg]()\n\n---\n\n\n\n\n\n
8,600
Merge Sorted Array
merge-sorted-array
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Array,Two Pointers,Sorting
Easy
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
68,614
488
I was super confused why many solutions had a final check for a special case. This is in-place, and doesn\'t have a weird final loop to deal with any special cases.\n```\ndef merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n\ta, b, write_index = m-1, n-1, m + n - 1\n\n\twhile b >= 0:\n\t\tif a >= 0 and nums1[a] > nums2[b]:\n\t\t\tnums1[write_index] = nums1[a]\n\t\t\ta -= 1\n\t\telse:\n\t\t\tnums1[write_index] = nums2[b]\n\t\t\tb -= 1\n\n\t\twrite_index -= 1\n```\n\n*Note: edited since the variable names changed in the question*
8,610
Merge Sorted Array
merge-sorted-array
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Array,Two Pointers,Sorting
Easy
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
37,242
104
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n for i in range(m,m+n):\n nums1[i]=nums2[i-m]\n nums1.sort()\n #please upvote me it would encourage me alot\n\n\n```
8,619
Merge Sorted Array
merge-sorted-array
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Array,Two Pointers,Sorting
Easy
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
40,198
138
# **Java Solution (Two Pointers Approach):**\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.\n```\nclass Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n int i = m - 1 , j = n - 1;\n // Initialize a variable k to store the last index of the 1st array...\n int k = m + n - 1;\n // Create a loop until either of i or j becomes zero...\n while(i >= 0 && j >= 0) {\n if(nums1[i] >= nums2[j]) {\n nums1[k] = nums1[i];\n i--;\n } else {\n nums1[k] = nums2[j];\n j--;\n }\n k--;\n // Either of i or j is not zero, which means some elements are yet to be merged.\n // Being already in a sorted manner, append them to the 1st array in the front.\n }\n // While i does not become zero...\n while(i >= 0)\n nums1[k--] = nums1[i--];\n // While j does not become zero...\n while(j >= 0)\n nums1[k--] = nums2[j--];\n // Now 1st array has all the elements in the required sorted order...\n return;\n }\n}\n```\n\n# **C++ Solution (Sorting Function Approach):**\nRuntime: 0 ms, faster than 100.00% of C++ online submissions for Merge Sorted Array.\n```\nclass Solution {\npublic:\n void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {\n // Here, nums1 =1st array, nums2 = 2nd array...\n for(int i = 0 ; i < n ; i++)\n nums1[i + m] = nums2[i];\n // Sort the 1st array...\n sort(nums1.begin() , nums1.end());\n // Print the required result...\n return;\n }\n};\n```\n\n# **Python Solution:**\nRuntime: 23 ms, faster than 89.40% of Python online submissions for Merge Sorted Array.\n```\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n # Initialize nums1\'s index\n i = m - 1\n # Initialize nums2\'s index\n j = n - 1\n # Initialize a variable k to store the last index of the 1st array...\n k = m + n - 1\n while j >= 0:\n if i >= 0 and nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n k -= 1\n i -= 1\n else:\n nums1[k] = nums2[j]\n k -= 1\n j -= 1\n```\n \n# **JavaScript Solution:**\n```\nvar merge = function(nums1, m, nums2, n) {\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n let i = m - 1 , j = n - 1;\n // Initialize a variable k to store the last index of the 1st array...\n let k = m + n - 1;\n // Create a loop until either of i or j becomes zero...\n while(i >= 0 && j >= 0) {\n if(nums1[i] >= nums2[j]) {\n nums1[k] = nums1[i];\n i--;\n } else {\n nums1[k] = nums2[j];\n j--;\n }\n k--;\n // Either of i or j is not zero, which means some elements are yet to be merged.\n // Being already in a sorted manner, append them to the 1st array in the front.\n }\n // While i does not become zero...\n while(i >= 0)\n nums1[k--] = nums1[i--];\n // While j does not become zero...\n while(j >= 0)\n nums1[k--] = nums2[j--];\n // Now 1st array has all the elements in the required sorted order...\n return;\n};\n```\n\n# **C Language (Two Pointers Approach):**\n```\nvoid merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n int i = m - 1;\n int j = n -1;\n // Create a loop until either of i or j becomes zero...\n while(i>=0 && j>=0) {\n if(nums1[i] > nums2[j]) {\n nums1[i+j+1] = nums1[i];\n i--;\n } else {\n nums1[i+j+1] = nums2[j];\n j--;\n }\n }\n // While j does not become zero...\n while(j >= 0) {\n nums1[i+j+1] = nums2[j];\n j--;\n }\n}\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n idx = 0\n for i in range(len(nums1)):\n if idx >= n:\n break\n if nums1[i] == 0:\n nums1[i]=nums2[idx]\n idx += 1\n nums1.sort()\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
8,635
Merge Sorted Array
merge-sorted-array
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Array,Two Pointers,Sorting
Easy
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
1,254
13
# Intuition\nGiven two sorted arrays, nums1 and nums2, with respective sizes m and n, the goal is to merge them into a single sorted array within nums1, utilizing its allocated space. To achieve this efficiently, start from the end of both arrays. Compare elements from nums1 and nums2, and place the larger one at the end of nums1. Continue this process, working backwards, until all elements are merged. This way, we avoid overwriting elements in nums1 and ensure the result is sorted without the need for additional space. This approach leverages the inherent order of the arrays to perform the merge in O(m + n) time.\n# Approach\nThe approach involves merging two sorted arrays in-place using a two-pointer technique.\n# Complexity\n- Time complexity:\n O(m + n)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution {\n /**\n * @param Integer[] $nums1\n * @param Integer $m\n * @param Integer[] $nums2\n * @param Integer $n\n * @return NULL\n */\n function merge(&$nums1, $m, $nums2, $n) {\n $i = $m - 1;\n $j = $n - 1;\n $k = $m + $n - 1;\n \n while ($i >= 0 && $j >= 0) {\n if ($nums1[$i] > $nums2[$j]) {\n $nums1[$k] = $nums1[$i];\n $i--;\n } else {\n $nums1[$k] = $nums2[$j];\n $j--;\n }\n $k--;\n }\n \n // If there are remaining elements in nums2, copy them to nums1\n while ($j >= 0) {\n $nums1[$k] = $nums2[$j];\n $j--;\n $k--;\n }\n }\n}\n\n```\n![7410jl.jpg]()\n
8,641
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
3,206
32
The main idea is to use previously calculated values\nLook the examples in bit representation =>>\nn=0 => [0]\nn=1 => [0, 1] \nn=2 => [00, 01, 11, 10] => [00, 01] + [11, 01] => ( 0 + [result(n-1)] ) + ( 1 + [result(n-1)] )\nn=3 => [000, 001, 011, 010, 110, 111, 101, 100] => ( 0 + [result(n-1) ) + ( 1+ [result(n-1)] )\nso on ...\nNow we can implement the above pattern easily\nWe can make it more simple, if we observe that, Every time we just twiced the values in the prev result ans new values are just made on the folling pattern =>\nn=0 => [0000]\nn=1 => [0000, 0001] // observe the we had just set (n-1)th bit to 1, iterating from right in the prev result ;\nn=2 => [0000, 0001, 0011, 0010]\nn=3 => [0000, 0001, 0011, 0010, 0110, 0111, 0101, 0100]\nso on ...\nmask containes (n-1)th bit as 1, \nif result for n=2, 0001 => **mask = 0010** hence newRes = (**res | mask**) = 0011; \nHope it helped you to understand the logic.\n\n```\nclass Solution {\npublic:\n vector<int> grayCode(int n) {\n vector<int> result;\n result.push_back(0);\n \n for (int i = 1; i <= n; i++) {\n int prevLength = result.size();\n int mask = 1 << (i - 1);\n for (int j = prevLength - 1; j >= 0; j--) {\n result.push_back(mask + result[j]);\n }\n }\n return result;\n }\n};\n```\n\n**Python =>**\n```\nclass Solution:\n def grayCode(self, n: int) -> List[int]:\n arr = []\n arr.append(0)\n for i in range(1,n+1):\n prevLength = len(arr)\n mask = 1 << (i-1)\n for j in range(prevLength, 0, -1):\n arr.append(mask + arr[j-1])\n return arr\n```\n**If you find it helpful, plz upvote**
8,713
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
2,242
19
**Idea:** \nGray code for a number **```n```** is **```n^(n/2)```**, and we push the same for every number in range ```[0, pow(2,x))```.\n\n**Explanation**\nFor the explanation part, we copy the MSB from binary as it is in the code and xor the remaining bits **i.e. ```g[i] = b[i] ^ b[i-1]```.**\n\nLets take 13: 1101\nGray code will be:\n```1 + 1^1 + 0^1 + 1^0```\nIf you see carefully, the xored number is actually \'0110\' which is equal to n/2.\n\n**C++ Solution**\n```\nclass Solution {\npublic:\n vector<int> grayCode(int n) {\n vector<int> v;\n int p=(1<<n);\n for(int i=0; i<p; i++){\n v.push_back(i^(i/2));\n }\n return v;\n }\n};\n```\n\n**Python Solution**\n```\nclass Solution:\n def grayCode(self, n: int) -> List[int]:\n return [i^(i//2) for i in range(1<<n)]\n```
8,723
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
3,555
46
Fisrt, we can explore the data and try to figure out the pattern. \nFor example, when n=3, **results** start from 000, we can **XOR** last number in results with **X** .\n`result[i+1] = X[i] ^ result[i]`\nBelow we can figure out the pattern of **X**:\n```\nresult X Y\n0 0 0 0 0 1 0 0 1 (1)\n0 0 1 0 1 0 0 1 0 (2)\n0 1 1 0 0 1 0 1 1 (3)\n0 1 0 1 0 0 1 0 0 (4)\n1 1 0 0 0 1 1 0 1 (5)\n1 1 1 0 1 0 1 1 0 (6)\n1 0 1 0 0 1 1 1 1 (7)\n1 0 0\n```\nSo the keypoint is to generate **X** sequence. Here is the trick, actually **X** is **lowest one-bit** of **Y** (natural number set).\nAccording to bit-manipulation, we can get lowest one-bit of number by\n`X = Y & -Y`\nFinally, we can get this elegant and easy-understand solution:\n```\ndef grayCode(self, n: int) -> \'List[int]\':\n\tres = [0]\n\tfor i in range(1, 2**n):\n\t\tres.append(res[-1] ^ (i & -i))\n\treturn res\n```
8,730
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
2,487
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create an initial list with 0\n2. For each bit in n, starting from the 0th bit:\n 1. Traverse the current list in reverse and add the current bit to each number by doing bitwise OR with (1 << i)\n 2. This step is repeated until we have processed all the bits in n\n3. Return the final list as the result\n\nExample: n = 2\n\n- Initial list: [0]\n- 1st iteration: i = 0, [0, 1 | (1 << 0) = 1] = [0, 1]\n- 2nd iteration: i = 1, [0, 1, 3 | (1 << 1) = 3, 2 | (1 << 1) = 2] = [0, 1, 3, 2]\n- Result: [0, 1, 3, 2]\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def grayCode(self, n: int) -> List[int]:\n res = [0]\n for i in range(n):\n for j in range(len(res) - 1, -1, -1):\n res.append(res[j] | (1 << i))\n return res\n\n```
8,742
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
1,307
10
Using List Comprehension, we can easily solve this problem statement in 1 line.\n```\n# Gray Code Formula:\n# n <= 16\n# Gray_Code(n) = n XOR (n / 2)\n\nclass Solution:\n def grayCode(self, n: int) -> List[int]:\n result = [i ^ (i // 2) for i in range(pow(2, n))]\n return result\n```
8,756
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
904
15
This uses property of gray codes, that you can mirror and add prefix to get these codes. This is shown in the following image. \n\n\n![image]()\n\nThe code uses basic recursion to add the appropirate prefixes to the original codes and the mirrored codes [obtained by reversing the list of original codes.].\n\n```\n def grayCode(self, n: int) -> List[int]:\n if n==0:\n return [0]\n if n==1:\n return [0,1]\n if n==2:\n return [0,1,3,2]\n else:\n return self.grayCode(n-1) + [x + (2**(n-1)) for x in self.grayCode(n-1)[::-1]]\n```
8,762
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
3,229
28
For n=1: 0 1\n\nFor n=2: 00 01 11 10\n\nNotice that the second half (11 and 10) are mirror of the first half (0 1) with additional 1 before it (10 11).\nNow we have (00 01 11 10), in order to do n=3 we need to do the same. The 4 elements of n=2 will be our first half, to do the second half we mirror them to get (10 11 01 00) and add additional 1 before it (110 111 101 100). We get:\n\nFor n=3: 000 001 011 010 110 111 101 100\n\n\n def grayCode(n):\n if not n:\n return [0]\n res = [0,1]\n for i in range(2,n+1):\n for j in range(len(res)-1,-1,-1):\n res.append(res[j] | 1<<i-1)\n return res
8,774
Gray Code
gray-code
An n-bit gray code sequence is a sequence of 2n integers where: Given an integer n, return any valid n-bit gray code sequence.
Math,Backtracking,Bit Manipulation
Medium
null
1,122
10
Python O(2^n) by toggle bitmask\n\n---\n\nExample with n = 2:\n\n1st iteration\n```\n\u30000 0\n\u2295 0 0\n\u2014\u2014\u2014\u2014\u2014\n\u30000 0 \n```\n \n We get 0\'b 00 = **0**\n\n---\n\n2nd iteration\n```\n\u30000 1\n\u2295 0 0\n\u2014\u2014\u2014\u2014\u2014\n\u30000 1 \n```\n \n We get 0\'b 01 = **1**\n\n---\n\n3rd iteration\n```\n\u30001 0\n\u2295 0 1\n\u2014\u2014\u2014\u2014\u2014\n\u30001 1 \n```\n \n We get 0\'b 11 = **3**\n\n---\n\n4th iteration\n```\n\u30001 1\n\u2295 0 1\n\u2014\u2014\u2014\u2014\u2014\n\u30001 0 \n```\n \n We get 0\'b 10 = **2**\n \n---\n\nFinally, we have gray codes with n=2: \n[**0**, **1**, **3**, **2**]\n\n---\n\n**Implementation** in Python:\n\n```\nclass Solution:\n def grayCode(self, n: int) -> List[int]:\n \n # total 2^n codes for bit length n\n code_count = 1 << n\n \n # generate gray code from 0, and toggle 1 bit on each iteration\n # toggle mask: ( i >> 1 )\n \n gray_codes =[ i ^ ( i >> 1 ) for i in range(code_count) ]\n \n return gray_codes\n```\n\n---\n\nin **Javascript**:\n\n<details>\n\t<summary> Expand to see source code </summary>\n\n```\n\nvar grayCode = function(n) {\n\n // toal 2^n codes for bit length n\n const codeCount = 1 << n;\n \n let result = [];\n \n // generate gray code from 0, and toggle 1 bit on each iteration\n // toggle mask: ( i >> 1 )\n \n for(let i = 0 ; i < codeCount ; i++){\n \n code = i ^ ( i >> 1);\n result.push( code );\n }\n \n return result\n};\n```\n\n</details>\n\n---\n\nin **C++**:\n\n<details>\n\t<summary> Expand to see source code </summary>\n\n```\nclass Solution {\npublic:\n vector<int> grayCode(int n) {\n \n // toal 2^n codes for bit length n\n const int codeCount = 1 << n;\n \n vector<int> result;\n\n // generate gray code from 0, and toggle 1 bit on each iteration\n // toggle mask: ( i >> 1 )\n \n for( int i = 0 ; i < codeCount ; i++ ){\n \n int mask = i >> 1;\n result.push_back( i ^ mask );\n }\n \n return result;\n }\n};\n```\n\n</details>\n\n---\n\nin **Go**:\n\n<details>\n\t<summary> Expand to see source code </summary>\n\n\n```\nfunc grayCode(n int) []int {\n \n // total 2^n codes for bit length n\n code_count := 1 << n\n \n // slice to store gray codes\n gray_codes := make([]int, code_count)\n \n for i:=0 ; i < code_count ; i+=1 {\n \n toggle_mask := ( i >> 1 )\n \n gray_codes[ i ] = i ^ toggle_mask\n }\n \n return gray_codes\n}\n```\n\n</details>\n\n---\nReference:\n\n[1] [Wiki: Gray code]()\n
8,776
Subsets II
subsets-ii
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
1,088
6
# Intuition\nThe intuition behind the code is to use a recursive approach to generate subsets. At each step, we have two choices: either include the current element in the subset or exclude it. By making these choices for each element in the array, we can generate all possible subsets.\n\n# Approach\n**Sort the array nums** \nSorting the array ensures that duplicate elements will appear next to each other, making it easier to handle them later in the code.\n\n**Create the recursive function subsets** \nThis function takes two parameters: index (the current index being considered) and elements (the current subset being constructed).\n\n**Handle base case** \nIf the current index reaches the length of the array (index == len(nums)), it means we have processed all elements. At this point, we check if the elements subset is already present in the res list. If not, we append it to res. This check is necessary to avoid duplicate subsets.\n\n**Make recursive calls**\n**Not Pick**\nCall subsets recursively with the next index without picking the current element (subsets(index + 1, elements)). This represents the choice of excluding the current element from the subset.\n**Pick**\nCall subsets recursively with the next index, including the current element (subsets(index + 1, elements + [nums[index]])). This represents the choice of picking the current element and adding it to the subset.\n\n**Duplicate Check**\nThe code avoids duplicates by checking if a subset already exists in the res list before appending it. We sort the input array in the start to ensure that duplicate elements will be adjacent, simplifying the duplicate check.\n\nNow, we call the subsets function initially with index = 0 and an empty elements list.\n\nFinally, we return the final res list containing all the generated subsets.\n\n# Complexity\n- Time complexity: **O(2^n)** \n\n- Space complexity: **O(2^n)** \n\n# Code\n```\nclass Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n res = []\n nums.sort()\n def subsets(index, elements):\n # base case\n if index == len(nums):\n res.append(elements) if elements not in res else None\n return\n\n subsets(index + 1, elements) # not pick\n subsets(index + 1, elements + [nums[index]]) # pick\n\n subsets(0, [])\n return res\n```
8,842
Subsets II
subsets-ii
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
37,603
227
class Solution:\n # @param num, a list of integer\n # @return a list of lists of integer\n def subsetsWithDup(self, S):\n res = [[]]\n S.sort()\n for i in range(len(S)):\n if i == 0 or S[i] != S[i - 1]:\n l = len(res)\n for j in range(len(res) - l, len(res)):\n res.append(res[j] + [S[i]])\n return res\n\nif S[i] is same to S[i - 1], then it needn't to be added to all of the subset, just add it to the last l subsets which are created by adding S[i - 1]
8,847
Subsets II
subsets-ii
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
1,522
5
\n\n# Code\n```\nclass Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n nums = sorted(nums)\n res = []\n self.backtracking(res,0,[],nums)\n return res\n def backtracking(self,res,start,subset,nums):\n res.append(list(subset))\n for i in range(start,len(nums)):\n if i > start and nums[i] == nums[i-1]:\n continue\n self.backtracking(res,i+1,subset+[nums[i]],nums)\n\n```
8,853
Subsets II
subsets-ii
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
4,921
57
Constraints:\n\n**1 <= nums.length <= 10**\n-10 <= nums[i] <= 10\n\nthe input size give us a clear hint that it is a backtracking solution, if there were no duplicates then it would easy problem to backtrack, the trick is to skip the duplicates **except the first time**.\n**backTrack( index, currentList )** \n\nExample -> nums = [1,2,2,3]\n\n![image]()\n\n\nPython -\n```\nclass Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n result=[]\n nums.sort()#To handle duplicate first we sort the array ( adjacent elements will be similar )\n def backtrack(nums,index=0,arr=[]):\n result.append( arr.copy() )\n for i in range( index, len(nums)):\n if i != index and nums[i] ==nums[i-1]: #skip the duplicates, except for the first time\n continue\n arr.append(nums[i]) #include the element\n backtrack(nums,i+1,arr ) #explore\n arr.pop() #remove the element\n \n backtrack(nums)\n return result\n```\n\t\t\n\n\nJava version -\n\n```\nclass Solution {\n List<List<Integer>> output;\n public List<List<Integer>> subsetsWithDup(int[] nums) {\n Arrays.sort( nums ); //To handle duplicate first we sort the array ( adjacent elements will be similar )\n output = new ArrayList();\n backTracking( 0, nums, new ArrayList() );\n return output;\n }\n \n public void backTracking( int index, int[] nums, List<Integer> list )\n {\n output.add( new ArrayList(list) );\n for( int i = index;i < nums.length; i++ )\n {\n if( i != index && nums[i] == nums[i-1] ) //skip the duplicates, except for the first time\n continue;\n list.add( nums[i]); //include\n backTracking(i+1,nums,list); //explore\n list.remove( list.size()-1);//backtrack, remove the element\n }\n }\n}\n```\n![image]()\n\nPlease **upvote** if you find it **uselful**. Thanks.\n
8,854
Subsets II
subsets-ii
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
23,546
127
```\nclass Solution(object):\n def subsetsWithDup(self, nums):\n ret = []\n self.dfs(sorted(nums), [], ret)\n return ret\n \n def dfs(self, nums, path, ret):\n ret.append(path)\n for i in range(len(nums)):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n self.dfs(nums[i+1:], path+[nums[i]], ret)\n```
8,873
Subsets II
subsets-ii
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
8,692
64
I have taken solutions of @caikehe from frequently asked backtracking questions which I found really helpful and had copied for my reference. I thought this post will be helpful for everybody as in an interview I think these basic solutions can come in handy. Please add any more questions in comments that you think might be important and I can add it in the post.\n\n#### Combinations :\n```\ndef combine(self, n, k):\n res = []\n self.dfs(xrange(1,n+1), k, 0, [], res)\n return res\n \ndef dfs(self, nums, k, index, path, res):\n #if k < 0: #backtracking\n #return \n if k == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(nums)):\n self.dfs(nums, k-1, i+1, path+[nums[i]], res)\n``` \n\t\n#### Permutations I\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n res = []\n self.dfs(nums, [], res)\n return res\n\n def dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n #return # backtracking\n for i in range(len(nums)):\n self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)\n``` \n\n#### Permutations II\n```\ndef permuteUnique(self, nums):\n res, visited = [], [False]*len(nums)\n nums.sort()\n self.dfs(nums, visited, [], res)\n return res\n \ndef dfs(self, nums, visited, path, res):\n if len(nums) == len(path):\n res.append(path)\n return \n for i in xrange(len(nums)):\n if not visited[i]: \n if i>0 and not visited[i-1] and nums[i] == nums[i-1]: # here should pay attention\n continue\n visited[i] = True\n self.dfs(nums, visited, path+[nums[i]], res)\n visited[i] = False\n```\n\n \n#### Subsets 1\n\n\n```\ndef subsets1(self, nums):\n res = []\n self.dfs(sorted(nums), 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Subsets II \n\n\n```\ndef subsetsWithDup(self, nums):\n res = []\n nums.sort()\n self.dfs(nums, 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n if i > index and nums[i] == nums[i-1]:\n continue\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Combination Sum \n\n\n```\ndef combinationSum(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, nums, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return \n for i in xrange(index, len(nums)):\n self.dfs(nums, target-nums[i], i, path+[nums[i]], res)\n```\n\n \n \n#### Combination Sum II \n\n```\ndef combinationSum2(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, candidates, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(candidates)):\n if i > index and candidates[i] == candidates[i-1]:\n continue\n self.dfs(candidates, target-candidates[i], i+1, path+[candidates[i]], res)\n```
8,877
Decode Ways
decode-ways
A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The test cases are generated so that the answer fits in a 32-bit integer.
String,Dynamic Programming
Medium
null
53,083
519
*This is my first post. Please let me know if this is helpful and if there\'s anything I can do to improve.*\n\n**Problem Reduction:** variation of n-th staircase with n = [1, 2] steps. \n\n**Approach:** We generate a bottom up DP table.\n\nThe tricky part is handling the corner cases (e.g. s = "30"). \n\nMost elegant way to deal with those error/corner cases, is to allocate an extra space, dp[0].\n\nLet dp[ i ] = the number of ways to parse the string s[1: i + 1]\n\nFor example:\ns = "231"\nindex 0: extra base offset. dp[0] = 1\nindex 1: # of ways to parse "2" => dp[1] = 1\nindex 2: # of ways to parse "23" => "2" and "23", dp[2] = 2 \nindex 3: # of ways to parse "231" => "2 3 1" and "23 1" => dp[3] = 2 \n\n```\ndef numDecodings(s): \n\tif not s:\n\t\treturn 0\n\n\tdp = [0 for x in range(len(s) + 1)] \n\t\n\t# base case initialization\n\tdp[0] = 1 \n\tdp[1] = 0 if s[0] == "0" else 1 #(1)\n\n\tfor i in range(2, len(s) + 1): \n\t\t# One step jump\n\t\tif 0 < int(s[i-1:i]) <= 9: #(2)\n\t\t\tdp[i] += dp[i - 1]\n\t\t# Two step jump\n\t\tif 10 <= int(s[i-2:i]) <= 26: #(3)\n\t\t\tdp[i] += dp[i - 2]\n\treturn dp[len(s)]\n```\n\nNotes of Wisdom:\n**(1)**: Handling s starting with \'0\'. Alternative: I would recommend treating as an error condition and immediately returning 0. It\'s easier to keep track and it\'s an optimization.\n**(2) (3)**: Pay close attention to your comparators. For (1) you want 0 <, not 0 <= . For (2) you want 10 <=, not 10 <\n
8,908
Decode Ways
decode-ways
A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The test cases are generated so that the answer fits in a 32-bit integer.
String,Dynamic Programming
Medium
null
11,814
210
First, I build a tree of possible decodings I can do from a random string.\n* The number of leaves in the tree essentially is the number of ways the string can be decoded.\n* We are going to build our tree with DFS from our original string, trying to decode either as:\n\t* A single digit (and call dfs again with remaining string)\n\t* Both single digit and double digit, when the double digits are less than or equal to 26 (and call dfs again with remaining strings).\n\nOur base case is when we have only a single digit left in our string or when we have nothing left in the string. In that case, we return 1 back up the recursion stack.\n\n**Growing a tree**\n![image]()\n\n**Dyanmic Programming**\n\nWe can see that this type of tree has a lot of **redundant sub-trees**. Dynamic Programming to the rescue!! (In my code, I use `lru_cache` decorator which essentially memoizes the function calls with argument-returned value pairs. So, when I call the same function with same arguements, and if that recursive call has been made before, it is just retrieved from memoized pair).\n\n![image]()\n\n![image]()\n\n* After you have got a hang of the thinking process, we will have to handle issues with zeros.\n\t* Zeros can be in the middle or at the start.\n\t\t* If it is at the start, there is no way to decode the string.\n\t\t* If it is in the middle:\n\t\t\t* If it can be paired with the digit before zero (and is less than or equal to 26, then we can keep on growing our subtrees)\n\t\t\t* If it cannot be paired with the digit before zero, we have to destory that subtree. This might even render the whole string undecodable. \n\n\n``` python\nclass Solution:\n def numDecodings(self, s:str) -> int:\n if len(s) == 0 or s is None:\n return 0\n\n @lru_cache(maxsize=None)\n def dfs(string):\n if len(string)>0:\n if string[0] == \'0\':\n return 0\n if string == "" or len(string) == 1:\n return 1\n if int(string[0:2]) <= 26:\n first = dfs(string[1:])\n second = dfs(string[2:])\n return first+second\n else:\n return dfs(string[1:])\n\n result_sum = dfs(s)\n\n return result_sum\n```
8,922
Decode Ways
decode-ways
A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The test cases are generated so that the answer fits in a 32-bit integer.
String,Dynamic Programming
Medium
null
6,925
45
Please check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord]().\nIf you like it, please give a star, watch my [Github Repository]() and upvote this post.\n\n---\n\n<iframe src="" frameBorder="0" width="100%" height="500"></iframe>
8,943
Reverse Linked List II
reverse-linked-list-ii
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Linked List
Medium
null
16,731
103
# Interview Guide - Reversing a Sublist of a Linked List: A Comprehensive Analysis for Programmers\n\n## Introduction & Problem Statement\n\nWelcome to this detailed guide, where we delve into the fascinating problem of reversing a sublist within a singly-linked list. The challenge is not just to reverse a sublist but to do it efficiently, ideally in a single pass through the list. This guide is designed to arm you with multiple approaches for tackling this problem, each with its own unique advantages and considerations. Specifically, we will explore three distinct strategies: Two Pointers, Using a Stack, and Recursion.\n\n## Key Concepts and Constraints\n\n1. **Node Anatomy**: \n Let\'s start with the basics. In a singly-linked list, each node has an integer value and a `next` pointer that points to the subsequent node in the list.\n \n2. **Sublist Reversal**: \n The primary task is to reverse only the nodes between positions `left` and `right`, both inclusive, within the list.\n\n3. **Order Preservation**: \n While reversing the sublist, we must ensure that the relative order of all nodes outside this range remains unchanged.\n\n4. **Size Constraints**: \n The number of nodes in the list `n` can vary but will always be between 1 and 500, giving us more than enough to work with.\n\n# Live Coding & More\n\n\n- [\uD83D\uDC0D Two Pointers \uD83D\uDC49\uD83D\uDC48]()\n- [\uD83D\uDC0D Stack \uD83D\uDCDA]()\n- [\uD83D\uDC0D Recursion \uD83D\uDD01]()\n\n---\n# Strategies to Tackle the Problem: A Three-Pronged Approach\n\n## 1. Using Two Pointers (One-Pass)\n\n### Intuition and Logic Behind the Solution\n\nIn this efficient method, we employ two pointers to traverse and manipulate the linked list in one go. The clever use of a dummy node helps us elegantly handle edge cases, and tuple unpacking makes the code more Pythonic and straightforward.\n\n### Step-by-step Explanation\n\n1. **Initialization**: \n - Create a `dummy` node and connect its `next` to the head of the list.\n - Initialize a `prev` pointer to the `dummy` node.\n\n2. **Move to Start Position**: \n - Traverse the list until the node just before the `left`-th node is reached.\n\n3. **Execute Sublist Reversal**: \n - Use a `current` pointer to keep track of the first node in the sublist.\n - Reverse the sublist nodes using `prev` and `current`.\n\n4. **Link Back**: \n - Automatically link the reversed sublist back into the original list.\n\n### Complexity Analysis\n\n- **Time Complexity**: `O(n)` \u2014 A single traversal does the job.\n- **Space Complexity**: `O(1)` \u2014 Smart pointer manipulation eliminates the need for additional data structures.\n\n---\n\n## 2. Using a Stack\n\n### Intuition and Logic Behind the Solution\n\nThis approach uses a stack data structure to temporarily store and then reverse the sublist, making the logic easier to follow.\n\n### Step-by-step Explanation\n\n1. **Initialization**: \n - Like before, create a `dummy` node and set a `prev` pointer.\n\n2. **Populate the Stack**: \n - Traverse the list and populate the stack with the nodes falling within the `left` and `right` positions.\n\n3. **Perform Reversal and Relink Nodes**: \n - Pop nodes from the stack and relink them, essentially reversing the sublist.\n\n### Complexity Analysis\n\n- **Time Complexity**: `O(n)`\n- **Space Complexity**: `O(n)` \u2014 The stack takes extra space.\n\n---\n\n## 3. Using Recursion\n\n#### Intuition and Logic Behind the Solution\n\nIn this elegant method, the language\'s call stack is leveraged to reverse the sublist through recursive function calls.\n\n### Step-by-step Explanation\n\n1. **Define Recursive Function**: \n - Create a helper function that will do the heavy lifting, taking the node and its position as parameters.\n\n2. **Base and Recursive Cases**: \n - Implement base and recursive cases to control the flow and reversal.\n\n3. **Unwind and Relink**: \n - As the recursion unwinds, the nodes get relinked in the reversed order.\n\n### Complexity Analysis\n\n- **Time Complexity**: `O(n)`\n- **Space Complexity**: `O(n)` \u2014 The call stack consumes extra memory.\n\n## Code Highlights and Best Practices\n\n- The use of a `dummy` node is universal across all methods for handling edge cases gracefully.\n- Tuple unpacking in the Two-Pointer approach makes the code clean and Pythonic.\n- The Stack approach makes clever use of the stack data structure for sublist reversal.\n- The Recursion method leverages the language\'s call stack for a clean and elegant solution.\n\n---\n\n# Performance\n\n| Language | Fastest Runtime (ms) | Memory Usage (MB) | Method |\n|--------------|----------------------|-------------------|-------------|\n| Rust | 0 | 2.3 | Two-Pointers|\n| PHP | 0 | 18.9 | Two-Pointers|\n| Java | 0 | 40.8 | Two-Pointers|\n| Go | 1 | 2.1 | Two-Pointers|\n| C++ | 4 | 7.4 | Two-Pointers|\n| Python3 | 33 | 16.6 | Two-Pointers|\n| Python3 | 38 | 16.6 | Recursion |\n| Python3 | 39 | 16.3 | Stack |\n| JavaScript | 44 | 41.8 | Two-Pointers|\n| C# | 71 | 38.4 | Two-Pointers|\n \n![n4.png]()\n\n\n# Code Two Pointers\n``` Python []\nclass Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n if not head or left == right:\n return head\n \n dummy = ListNode(0, head)\n prev = dummy\n \n for _ in range(left - 1):\n prev = prev.next\n \n current = prev.next\n \n for _ in range(right - left):\n next_node = current.next\n current.next, next_node.next, prev.next = next_node.next, prev.next, next_node\n\n return dummy.next\n```\n``` Go []\nfunc reverseBetween(head *ListNode, left int, right int) *ListNode {\n if head == nil || left == right {\n return head\n }\n \n dummy := &ListNode{0, head}\n prev := dummy\n \n for i := 0; i < left - 1; i++ {\n prev = prev.Next\n }\n \n current := prev.Next\n \n for i := 0; i < right - left; i++ {\n nextNode := current.Next\n current.Next = nextNode.Next\n nextNode.Next = prev.Next\n prev.Next = nextNode\n }\n \n return dummy.Next\n}\n```\n``` Rust []\nimpl Solution {\n pub fn reverse_between(head: Option<Box<ListNode>>, left: i32, right: i32) -> Option<Box<ListNode>> {\n let mut dummy = Some(Box::new(ListNode {\n val: 0,\n next: head,\n }));\n let mut before = &mut dummy;\n for _ in 1..left {\n before = &mut before.as_mut()?.next;\n }\n\n let mut node = before.as_mut()?.next.take();\n let mut node2 = node.as_mut()?.next.take();\n for _ in left..right {\n let node3 = node2.as_mut()?.next.take();\n node2.as_mut()?.next = node;\n node = node2;\n node2 = node3;\n }\n\n let mut rev_tail = &mut node;\n for _ in left..right {\n rev_tail = &mut rev_tail.as_mut()?.next;\n }\n rev_tail.as_mut()?.next = node2;\n before.as_mut()?.next = node;\n\n dummy.unwrap().next\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n ListNode* reverseBetween(ListNode* head, int left, int right) {\n if (!head || left == right) return head;\n \n ListNode dummy(0);\n dummy.next = head;\n ListNode* prev = &dummy;\n \n for (int i = 0; i < left - 1; ++i) {\n prev = prev->next;\n }\n \n ListNode* current = prev->next;\n \n for (int i = 0; i < right - left; ++i) {\n ListNode* next_node = current->next;\n current->next = next_node->next;\n next_node->next = prev->next;\n prev->next = next_node;\n }\n \n return dummy.next;\n }\n};\n```\n``` Java []\nclass Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if (head == null || left == right) return head;\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prev = dummy;\n \n for (int i = 0; i < left - 1; ++i) {\n prev = prev.next;\n }\n \n ListNode current = prev.next;\n \n for (int i = 0; i < right - left; ++i) {\n ListNode nextNode = current.next;\n current.next = nextNode.next;\n nextNode.next = prev.next;\n prev.next = nextNode;\n }\n \n return dummy.next;\n }\n}\n```\n``` C# []\npublic class Solution {\n public ListNode ReverseBetween(ListNode head, int left, int right) {\n if (head == null || left == right) return head;\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prev = dummy;\n \n for (int i = 0; i < left - 1; ++i) {\n prev = prev.next;\n }\n \n ListNode current = prev.next;\n \n for (int i = 0; i < right - left; ++i) {\n ListNode nextNode = current.next;\n current.next = nextNode.next;\n nextNode.next = prev.next;\n prev.next = nextNode;\n }\n \n return dummy.next;\n }\n}\n```\n``` PHP []\nclass Solution {\n function reverseBetween($head, $left, $right) {\n if ($head == null || $left == $right) return $head;\n \n $dummy = new ListNode(0);\n $dummy->next = $head;\n $prev = $dummy;\n \n for ($i = 0; $i < $left - 1; ++$i) {\n $prev = $prev->next;\n }\n \n $current = $prev->next;\n \n for ($i = 0; $i < $right - $left; ++$i) {\n $nextNode = $current->next;\n $current->next = $nextNode->next;\n $nextNode->next = $prev->next;\n $prev->next = $nextNode;\n }\n \n return $dummy->next;\n }\n}\n```\n``` JavaScript []\nvar reverseBetween = function(head, left, right) {\n if (!head || left === right) return head;\n \n const dummy = new ListNode(0);\n dummy.next = head;\n let prev = dummy;\n \n for (let i = 0; i < left - 1; ++i) {\n prev = prev.next;\n }\n \n let current = prev.next;\n \n for (let i = 0; i < right - left; ++i) {\n const nextNode = current.next;\n current.next = nextNode.next;\n nextNode.next = prev.next;\n prev.next = nextNode;\n }\n \n return dummy.next;\n};\n```\n# Code Recursion\n``` Python []\nclass Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n if not (head and left < right):\n return head\n\n def helper(node, m):\n nonlocal left, right\n if m == left:\n prev = None\n current = node\n while m <= right:\n current.next, prev, current = prev, current, current.next\n m += 1\n node.next = current\n return prev\n elif m < left:\n node.next = helper(node.next, m + 1)\n return node\n\n return helper(head, 1)\n```\n``` Go []\nfunc reverseBetween(head *ListNode, left int, right int) *ListNode {\n if head == nil || left >= right {\n return head\n }\n\n var helper func(node *ListNode, m int) *ListNode\n helper = func(node *ListNode, m int) *ListNode {\n if m == left {\n var prev, current *ListNode = nil, node\n for m <= right {\n current.Next, prev, current = prev, current, current.Next\n m++\n }\n node.Next = current\n return prev\n } else if m < left {\n node.Next = helper(node.Next, m+1)\n }\n return node\n }\n\n return helper(head, 1)\n}\n\n```\n\n# Code Stack\n``` Python []\nclass Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n if not head or left == right:\n return head\n\n dummy = ListNode(0)\n dummy.next = head\n prev = dummy\n\n for _ in range(left - 1):\n prev = prev.next\n\n stack = []\n current = prev.next\n\n for _ in range(right - left + 1):\n stack.append(current)\n current = current.next\n\n while stack:\n prev.next = stack.pop()\n prev = prev.next\n\n prev.next = current\n\n return dummy.next\n```\n``` Go []\nfunc reverseBetween(head *ListNode, left int, right int) *ListNode {\n if head == nil || left == right {\n return head\n }\n\n dummy := &ListNode{Val: 0, Next: head}\n prev := dummy\n\n for i := 0; i < left-1; i++ {\n prev = prev.Next\n }\n\n stack := []*ListNode{}\n current := prev.Next\n\n for i := 0; i < right-left+1; i++ {\n stack = append(stack, current)\n current = current.Next\n }\n\n for len(stack) > 0 {\n last := len(stack) - 1\n prev.Next = stack[last]\n stack = stack[:last]\n prev = prev.Next\n }\n\n prev.Next = current\n\n return dummy.Next\n}\n\n```\n\n# Live Coding & More\n## Stack\n\n## Recursion\n\n\n## Final Thoughts\n\nEach of the three methods comes with its own set of pros and cons. Your choice would depend on various factors such as readability, space complexity, and the specific constraints of the problem at hand. This guide equips you with the knowledge to make that choice wisely.\n\nSo there you have it\u2014a multifaceted guide to tackling the problem of reversing a sublist in a singly-linked list. Armed with this knowledge, you\'re now better prepared to face linked list challenges in interviews and beyond. Happy coding!
9,006
Reverse Linked List II
reverse-linked-list-ii
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Linked List
Medium
null
4,100
34
This Python solution beats 97.21%.\n\n![Screen Shot 2023-09-07 at 9.31.46.png]()\n\n\n---\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 257 videos as of September 7th, 2023.\n\n### In the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\n\n\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2245\nThank you for your support!\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Check for base cases.\n - If the linked list is empty (`not head`) or `left` is equal to `right`, return the original `head` as there is no reversal needed.\n\n2. Initialize a `dummy` node to simplify edge cases and connect it to the head of the linked list.\n - Create a `dummy` node with a value of 0 and set its `next` pointer to the `head` of the linked list. This dummy node helps in handling the case when `left` is 1.\n\n3. Traverse the list to find the (left-1)-th node.\n - Initialize a `prev` pointer to `dummy`.\n - Loop `left - 1` times to move the `prev` pointer to the node just before the left-th node.\n\n4. Reverse the portion of the linked list from the left-th node to the right-th node.\n - Initialize a `cur` pointer to `prev.next`.\n - Loop `right - left` times to reverse the direction of the pointers in this portion of the linked list:\n - Store the next node (`temp`) of `cur` to avoid losing the reference.\n - Update the `cur.next` to point to `temp.next`, effectively reversing the direction.\n - Move `temp.next` to point to `prev.next`, effectively moving `temp` to the correct position in the reversed portion.\n - Update `prev.next` to point to `temp`, making `temp` the new next node of `prev`.\n\n5. Return the new head of the modified linked list.\n - `dummy.next` points to the head of the modified linked list, so return `dummy.next` as the result.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n\n if not head or left == right:\n return head\n\n dummy = ListNode(0, head)\n prev = dummy\n\n for _ in range(left - 1):\n prev = prev.next\n\n cur = prev.next\n for _ in range(right - left):\n temp = cur.next\n cur.next = temp.next\n temp.next = prev.next\n prev.next = temp\n\n return dummy.next\n```\n```javascript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\nvar reverseBetween = function(head, left, right) {\n if (!head || left === right) {\n return head;\n }\n\n const dummy = new ListNode(0, head);\n let prev = dummy;\n\n for (let i = 0; i < left - 1; i++) {\n prev = prev.next;\n }\n\n let cur = prev.next;\n\n for (let i = 0; i < right - left; i++) {\n const temp = cur.next;\n cur.next = temp.next;\n temp.next = prev.next;\n prev.next = temp;\n }\n\n return dummy.next; \n};\n```\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if (head == null || left == right) {\n return head;\n }\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prev = dummy;\n\n for (int i = 0; i < left - 1; i++) {\n prev = prev.next;\n }\n\n ListNode cur = prev.next;\n\n for (int i = 0; i < right - left; i++) {\n ListNode temp = cur.next;\n cur.next = temp.next;\n temp.next = prev.next;\n prev.next = temp;\n }\n\n return dummy.next; \n }\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseBetween(ListNode* head, int left, int right) {\n if (!head || left == right) {\n return head;\n }\n\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* prev = dummy;\n\n for (int i = 0; i < left - 1; i++) {\n prev = prev->next;\n }\n\n ListNode* cur = prev->next;\n\n for (int i = 0; i < right - left; i++) {\n ListNode* temp = cur->next;\n cur->next = temp->next;\n temp->next = prev->next;\n prev->next = temp;\n }\n\n return dummy->next; \n }\n};\n```\n
9,042
Reverse Linked List II
reverse-linked-list-ii
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Linked List
Medium
null
4,155
27
# intuition\n Just do manipulation of pointers and call reverse function.\n\n`for detailed explanation you can refer to my youtube channel` \n\n[ Video in Hindi click here]()\n\nor link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation.\n\n### Problem Description\n\nThe problem asks to reverse a specified portion of a singly linked list between positions `left` and `right`. You are given the head of the linked list and two integers, `left` and `right`, where `1 <= left <= right <= n` (n is the number of nodes in the linked list). Your task is to reverse the nodes between positions `left` and `right` and return the modified linked list.\n\n### Solution Explanation\n\n#### `rev` Function\n\nThe `rev` function is a helper function used to reverse a linked list. It takes the head of a linked list as input and returns the head of the reversed linked list.\n\nHere\'s how it works:\n\n1. If the input `head` is `NULL` or it has only one node (i.e., `head->next` is `NULL`), there\'s nothing to reverse, so it returns `head` as it is.\n\n2. Create three pointers: `curr` (current), `prev` (previous), and `nex` (next) to traverse the linked list.\n\n3. Start a `while` loop that continues until `curr` becomes `NULL`, which means we have traversed the entire original linked list.\n\n4. Inside the loop:\n - Save the next node in `nex`.\n - Update `curr->next` to point to the previous node (`prev`), effectively reversing the link.\n - Move `prev` to `curr` and `curr` to `nex` for the next iteration.\n\n5. Finally, return `prev` as the new head of the reversed linked list.\n\n#### `reverseBetween` Function\n\nThe `reverseBetween` function is the main function that solves the problem by reversing the specified portion of the linked list between positions `left` and `right`. It takes the head of the linked list, `left`, and `right` as input and returns the modified linked list.\n\nHere\'s how it works:\n\n1. Similar to the `rev` function, it first handles the base cases. If `head` is `NULL` or has only one node, it returns `head` as it is.\n\n2. If `left` is equal to `right`, it means there\'s no need to reverse anything, so it also returns `head` as it is.\n\n3. Initialize several pointers and a boolean variable `f`:\n - `curr` points to the current node while traversing the linked list.\n - `t` will eventually point to the node at position `left`.\n - `prev` is used to keep track of the previous node.\n - `s` will eventually point to the node at position `right + 1`.\n - `v` will point to the node just before position `left`.\n - `f` is a boolean flag that indicates whether `left` is equal to 1.\n\n4. If `left` is 1, set `f` to `true`, and `t` to `curr` initially. This is done to handle the case where we need to reverse from the beginning of the list.\n\n5. Use a loop to traverse the list:\n - When we reach `left`, set `v` to `prev` and `t` to `curr`. `v` is used to keep track of the node just before the reverse portion, and `t` is used to keep track of the first node in the reverse portion.\n - When we reach `right`, set `s` to `curr->next` and break the loop. This separates the portion to be reversed from the rest of the list.\n\n6. If `f` is `false`, it means `left` is not 1, so we need to disconnect the nodes before the reverse portion. Set `v->next` to `NULL`.\n\n7. Call the `rev` function to reverse the portion of the linked list starting from `t`. This returns the new head of the reversed portion.\n\n8. Connect the reversed portion to the rest of the list:\n - Set `t->next` to `s` to link the end of the reversed portion to the node at position `right + 1`.\n - If `f` is `false`, connect `v` to the new head of the reversed portion.\n\n9. If `f` is `true`, it means we reversed the portion starting from the beginning, so update `head` to point to the new head of the reversed portion.\n\n10. Return `head` as the final result.\n\n### Overall Explanation\n\nThe given code effectively reverses the portion of the linked list between positions `left` and `right` and returns the modified linked list. It uses the `rev` function to reverse a linked list and carefully handles the edge cases and pointer manipulation to achieve the desired result. The time complexity of this solution is O(n), where n is the number of nodes in the linked list.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1))$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode*rev(ListNode*head){\n if(head==NULL || head->next==NULL)\n return head;\n ListNode*curr=head;\n ListNode*prev=NULL;\n ListNode*nex=NULL;\n while(curr!=NULL){\n nex=curr->next;\n curr->next=prev;\n prev=curr;\n curr=nex;\n }\n return prev;\n }\n ListNode* reverseBetween(ListNode* head, int left, int right) {\n if(head==NULL || head->next==NULL)\n return head;\n if(left==right)\n return head;\n ListNode*curr=head;\n ListNode*t=NULL;\n ListNode*prev=NULL;\n ListNode*s=NULL;\n ListNode*v=NULL;\n bool f=0;\n if(left==1){\n f=1;\n t=curr;\n }\n int s1=1;\n while(curr!=NULL){\n if(s1==left&&f==0){\n v=prev;\n t=curr;\n }\n if(s1==right){\n s=curr->next;\n curr->next=NULL;\n break;\n }\n prev=curr;\n curr=curr->next;\n s1++;\n }\n if(f==0){\n v->next=NULL;\n }\n ListNode*ans=rev(t);\n t->next=s;\n if(f==0)\n v->next=ans;\n if(f==1)\n head=ans;\n return head;\n }\n};\n```\n``` Java []\nclass Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if (head == null || head.next == null)\n return head;\n if (left == right)\n return head;\n\n ListNode curr = head;\n ListNode t = null;\n ListNode prev = null;\n ListNode s = null;\n ListNode v = null;\n boolean f = false;\n\n if (left == 1) {\n f = true;\n t = curr;\n }\n\n int s1 = 1;\n\n while (curr != null) {\n if (s1 == left && !f) {\n v = prev;\n t = curr;\n }\n\n if (s1 == right) {\n s = curr.next;\n curr.next = null;\n break;\n }\n\n prev = curr;\n curr = curr.next;\n s1++;\n }\n\n if (!f) {\n v.next = null;\n }\n\n ListNode ans = reverseList(t);\n t.next = s;\n\n if (!f) {\n v.next = ans;\n }\n\n if (f) {\n head = ans;\n }\n\n return head;\n }\n\n public ListNode reverseList(ListNode head) {\n if (head == null || head.next == null)\n return head;\n\n ListNode curr = head;\n ListNode prev = null;\n ListNode next = null;\n\n while (curr != null) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n return prev;\n }\n}\n\n```\n``` Python []\nclass Solution:\n def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:\n if not head or not head.next:\n return head\n if left == right:\n return head\n\n curr = head\n t = None\n prev = None\n s = None\n v = None\n f = False\n\n if left == 1:\n f = True\n t = curr\n\n s1 = 1\n\n while curr:\n if s1 == left and not f:\n v = prev\n t = curr\n\n if s1 == right:\n s = curr.next\n curr.next = None\n break\n\n prev = curr\n curr = curr.next\n s1 += 1\n\n if not f:\n v.next = None\n\n ans = self.reverseList(t)\n t.next = s\n\n if not f:\n v.next = ans\n\n if f:\n head = ans\n\n return head\n\n def reverseList(self, head: ListNode) -> ListNode:\n if not head or not head.next:\n return head\n\n curr = head\n prev = None\n next_node = None\n\n while curr:\n next_node = curr.next\n curr.next = prev\n prev = curr\n curr = next_node\n\n return prev\n\n```
9,044
Reverse Linked List II
reverse-linked-list-ii
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Linked List
Medium
null
3,492
20
# PROBLEM UNDERSTANDING:\n- **The code appears** to be a C++ implementation of a function `reverseBetween `within a class `Solution`. \n- This function takes as input a singly-linked list represented by a `ListNode` and two integers, `left` and `right`. \n- It aims to reverse the elements of the linked list from the `left`-th node to the `right`-th node (inclusive).\n\n# Here\'s a step-by-step explanation of the code:\n**Step 1: Initializing Pointers**\n```\nListNode* temp = new ListNode(-1);\nListNode* prev = temp;\ntemp->next = head;\n\n```\n- `temp` is a new **ListNode created with a value of -1**. This is used as a dummy node to simplify the logic.\n- `prev` is initialized to `temp`, which **initially points to the same location as** `temp`.\n- `temp->next` is set to point to the head of the input linked list (`head`).\n\n**Step 2: Moving to the Left Position:**\n```\nfor (int i = 0; i < left - 1; i++) {\n prev = prev->next;\n}\n\n```\n- This loop moves the `prev` pointer to the node just before the `left`-th node in the linked list.\n\n**Step 3: Reversing the Nodes:**\n```\nListNode* cur = prev->next;\nfor (int i = 0; i < right - left; i++) {\n ListNode* ptr = prev->next;\n prev->next = cur->next;\n cur->next = cur->next->next;\n prev->next->next = ptr;\n}\n\n```\n- In this loop, a pointer `cur` is used to keep track of the current node.\n- For each iteration, a pointer `ptr` is used to temporarily store `prev->next`.\n- **The code then rearranges the pointers to reverse** the direction of the nodes between `left` and `right`.\n\n**Step 4: Returning the Result:**\n```\nreturn temp->next;\n\n```\n- Finally, the modified linked list is returned. `temp->next` points to the new head of the linked list after reversing the specified portion.\n\n# Strategy to Tackle the Problem:\n\n**1. Initialize a dummy node (`temp`) to simplify handling edge cases.**\n**1. Move `prev` to the node just before the `left`-th node using a loop.**\n**1. Reverse the nodes between left and right using a loop.**\n**1. Return the modified linked list.**\n\n\n\n\n\n\n\n# Intuition\n- The code employs a common technique for reversing a portion of a linked list. \n- It uses pointers (`prev`, `cur`, and `ptr`) to manipulate the connections between nodes, effectively reversing the direction of the nodes between `left` and `right`.\n\n# Approach\n- Initialize `temp` and `prev` pointers.\n- Move `prev` to the node before the `left`-th node.\n- Reverse nodes between `left` and `right` using a loop.\n- Return the modified linked list.\n\n# Complexity\n- **Time complexity:**\n 1. **Initialization:** The initialization part involves creating a dummy node (`temp`) and moving prev to the `left-1`-th node, both of which take constant time, `O(1)`.\n\n 1. **Reversing the Nodes:** The loop that reverses the nodes between `left` and right runs for `right - left` iterations. \n - Inside the loop, there are constant-time operations like pointer assignments. \n - Therefore, this part of the code also has a time complexity of `O(right - left)`, which can be simplified to `O(n)`, where n is the number of nodes in the linked list.\n\n**Overall, the time complexity of the code is `O(n)`, where n is the number of nodes in the linked list.**\n\n- **Space complexity:**\n1. **Additional Pointers:** The code uses a few extra pointers (`temp`, `prev`, `cur`, and `ptr`) to keep track of nodes and perform the reversal. These pointers occupy a constant amount of space regardless of the size of the linked list. \n2. Therefore, the `space complexity is O(1)`, indicating constant space usage.\n\n# PLEASE UPVOTE\uD83D\uDE0D\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseBetween(ListNode* head, int left, int right) {\n ListNode*temp= new ListNode(-1);\n ListNode*prev=temp;\n temp->next=head;\n for(int i=0;i<left-1;i++)\n {\n prev=prev->next;\n }\n ListNode*cur=prev->next;\n for(int i=0;i<right-left;i++)\n {\n ListNode *ptr = prev->next;\n prev->next = cur->next;\n cur->next = cur->next->next;\n prev->next->next = ptr;\n }\n return temp->next;\n }\n};\n```\n# JAVA\n```\npublic class Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n ListNode temp = new ListNode(-1);\n ListNode prev = temp;\n temp.next = head;\n \n for (int i = 0; i < left - 1; i++) {\n prev = prev.next;\n }\n \n ListNode cur = prev.next;\n \n for (int i = 0; i < right - left; i++) {\n ListNode ptr = prev.next;\n prev.next = cur.next;\n cur.next = cur.next.next;\n prev.next.next = ptr;\n }\n \n return temp.next;\n }\n}\n\n```\n# PYTHON\n```\nclass Solution:\n def reverseBetween(self, head, left, right):\n temp = ListNode(-1)\n prev = temp\n temp.next = head\n \n for i in range(left - 1):\n prev = prev.next\n \n cur = prev.next\n \n for i in range(right - left):\n ptr = prev.next\n prev.next = cur.next\n cur.next = cur.next.next\n prev.next.next = ptr\n \n return temp.next\n\n```\n# JAVASCRIPT\n```\nclass ListNode {\n constructor(val) {\n this.val = val;\n this.next = null;\n }\n}\n\nclass Solution {\n reverseBetween(head, left, right) {\n const temp = new ListNode(-1);\n let prev = temp;\n temp.next = head;\n\n for (let i = 0; i < left - 1; i++) {\n prev = prev.next;\n }\n\n let cur = prev.next;\n\n for (let i = 0; i < right - left; i++) {\n let ptr = prev.next;\n prev.next = cur.next;\n cur.next = cur.next.next;\n prev.next.next = ptr;\n }\n\n return temp.next;\n }\n}\n\n```\n# GO\n```\npackage main\n\ntype ListNode struct {\n Val int\n Next *ListNode\n}\n\nfunc reverseBetween(head *ListNode, left int, right int) *ListNode {\n temp := &ListNode{Val: -1}\n prev := temp\n temp.Next = head\n\n for i := 0; i < left-1; i++ {\n prev = prev.Next\n }\n\n cur := prev.Next\n\n for i := 0; i < right-left; i++ {\n ptr := prev.Next\n prev.Next = cur.Next\n cur.Next = cur.Next.Next\n prev.Next.Next = ptr\n }\n\n return temp.Next\n}\n\n```\n# \uD83D\uDC7E\u2763PLEASE UPVOTE\uD83D\uDE0D
9,052
Reverse Linked List II
reverse-linked-list-ii
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Linked List
Medium
null
373
5
# Intuition and Approach\n\n 1. Find left node indcated by index - l\n 2. Find right node indicated by index - r\n 3. Revers left node till right node\n 4. Link the broken links\n\n Note: Add a dummy head to track left_prev node in case left node is at head\n\n#### Please bear with my diagrams :)\n\nInput: head = ```[1,2,3,4,5]```, l = ```2``` (left index), r = ```4``` (right index)\nOutput: ```[1,4,3,2,5]```\n\n![20230907_111845_1.jpg]()\n\n\n# Complexity\n- Time complexity: $$O(2r - l))$$ ```r```= right index, ```l``` = left index\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# C++\n```cpp\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n\nclass Solution {\npublic:\n ListNode* reverseBetween(ListNode* head, int l, int r) {\n // Dummy head insertion\n ListNode* dummy_head = new ListNode(-1);\n dummy_head->next = head;\n\n // 1st while loop (spot left_prev, left nodes)\n ListNode* left_prev = dummy_head;\n ListNode* left = dummy_head->next;\n int left_count = 1; // we start with 1 because we have to stop previous to left (because dummy head added)\n while (left_count < l) {\n left_prev = left;\n left = left->next;\n left_count++;\n }\n // 2nd while loop (spot the right, right_next nodes)\n ListNode* right = left;\n ListNode* right_next = left->next;\n int right_count = 0;\n while (right_count < r - l) {\n right = right_next;\n right_next = right_next->next;\n right_count++;\n }\n // 3rd while loop (reverse element between left and right node)\n ListNode* cur = left;\n ListNode* pre = nullptr;\n while (cur != right_next) {\n ListNode* tmp = cur->next;\n cur->next = pre;\n pre = cur;\n cur = tmp;\n }\n // 4th fix breakage link\n left_prev->next = right;\n left->next = right_next;\n\n head = dummy_head->next;\n delete dummy_head;\n return head;\n }\n};\n```\n# Python3\n```python\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseBetween(self, head: Optional[ListNode], l: int, r: int) -> Optional[ListNode]:\n \n # Dummy head insertion\n dummy_head = ListNode(None)\n dummy_head.next = head\n\n # 1st while loop (spot left_prev, left nodes)\n left_prev = dummy_head\n left = dummy_head.next\n left_count = 1 # we start with 1 because we have to stop previous to left (because dummy head added)\n while left_count < l:\n left_prev = left\n left = left.next\n left_count += 1\n\n # 2nd while loop (spot the right, right_next nodes)\n right = left\n right_next = left.next\n right_count = 0\n while right_count < r - l:\n right = right_next\n right_next = right_next.next\n right_count += 1\n\n # 3rd while loop (reverse element between left and right node)\n cur = left\n pre = None\n while cur != right_next:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\n \n # 4th fix breakage link\n left_prev.next = right\n left.next = right_next\n\n head = dummy_head.next\n del dummy_head\n return head\n```\n# Java\n```java\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\n\npublic class Solution {\n public ListNode reverseBetween(ListNode head, int l, int r) {\n // Dummy head insertion\n ListNode dummyHead = new ListNode(-1);\n dummyHead.next = head;\n\n // 1st while loop (spot left_prev, left nodes)\n ListNode leftPrev = dummyHead;\n ListNode left = dummyHead.next;\n int leftCount = 1; // we start with 1 because we have to stop previous to left (because dummy head added)\n while (leftCount < l) {\n leftPrev = left;\n left = left.next;\n leftCount++;\n }\n\n // 2nd while loop (spot the right, right_next nodes)\n ListNode right = left;\n ListNode rightNext = left.next;\n int rightCount = 0;\n while (rightCount < r - l) {\n right = rightNext;\n rightNext = rightNext.next;\n rightCount++;\n }\n\n // 3rd while loop (reverse elements between left and right node)\n ListNode cur = left;\n ListNode pre = null;\n while (cur != rightNext) {\n ListNode tmp = cur.next;\n cur.next = pre;\n pre = cur;\n cur = tmp;\n }\n\n // 4th fix breakage link\n leftPrev.next = right;\n left.next = rightNext;\n\n head = dummyHead.next;\n // remove(dummyHead);\n return head;\n }\n}\n```
9,086
Restore IP Addresses
restore-ip-addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
String,Backtracking
Medium
null
3,478
29
\uD83D\uDD34 Check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord]() for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository]() and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast]() if you are interested.\n\n---\n\n**Iterative Approach**\n\n<iframe src="" frameBorder="0" width="100%" height="500"></iframe>
9,165
Restore IP Addresses
restore-ip-addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
String,Backtracking
Medium
null
9,641
82
# Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful.\n\n```\n# Intuition\n1. There needs to be 4 parts per IP. There are always three dots/four candidates (2.5.5.2.5.5.1.1.1.3.5 is not valid, neither is 1.1.1)\n2. When selecting a candidate, it can\'t have more than 3 characters (2552.55.111.35 is not valid)\n3. When selecting a candidate, its characters cant be above 255 (25.525.511.135 is not valid because of 525 and 511)\n4. When selecting a candidate, IF the candidate has 2 or more characters, then the first can\'t be a zero. (1.0.1.023 is not valid as member 023 is size>1 and leads with 0. But 0.0.0.0 is valid as each candidate is size 1)\n# Approach : Backtracking\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Helper function to check if a given string is a valid IP address segment\n bool valid(string temp){\n if(temp.size()>3 || temp.size()==0) return false; // segment length should be between 1 and 3\n if(temp.size()>1 && temp[0]==\'0\') return false; // segment should not start with 0, unless it is a single digit\n if(temp.size() && stoi(temp)>255) return false; // segment should not be greater than 255\n return true;\n }\n\n // Backtracking function to generate all possible IP addresses\n void solve(vector<string>& ans, string output, int ind, string s, int dots){\n if(dots == 3){ // if we have already added 3 dots, check if the remaining segment is valid\n if(valid(s.substr(ind)))\n ans.push_back(output+s.substr(ind));\n return;\n }\n int sz = s.size();\n for(int i=ind;i<min(ind+3, sz);i++){\n if(valid(s.substr(ind, i-ind+1))){\n output.push_back(s[i]);\n output.push_back(\'.\');\n solve(ans, output, i+1, s, dots+1);\n output.pop_back(); //backtrack\n }\n }\n\n }\n\n vector<string> restoreIpAddresses(string s) {\n vector<string> ans;\n string res;\n solve(ans, res, 0, s, 0);\n return ans;\n }\n};\n\n```\n```python []\nclass Solution:\n def valid(self, temp: str) -> bool:\n if len(temp) > 3 or len(temp) == 0:\n return False\n if len(temp) > 1 and temp[0] == \'0\':\n return False\n if len(temp) and int(temp) > 255:\n return False\n return True\n\n def solve(self, ans, output, ind, s, dots):\n if dots == 3:\n if self.valid(s[ind:]):\n ans.append(output + s[ind:])\n return\n for i in range(ind, min(ind+3, len(s))):\n if self.valid(s[ind:i+1]):\n new_output = output + s[ind:i+1] + \'.\'\n self.solve(ans, new_output, i+1, s, dots+1)\n\n def restoreIpAddresses(self, s: str) -> List[str]:\n ans = []\n self.solve(ans, "", 0, s, 0)\n return ans\n\n```\n```Java []\n private List<String> ipes;\n private int l;\n public List<String> restoreIpAddresses(String s) {\n ipes = new ArrayList<>();\n l = s.length();\n f(s, 0, "", 0);\n return ipes;\n }\n \n private boolean isIp(String ip){\n if(ip.length() > 3 || ip.length() == 0) return false;\n if(ip.length() > 1 && ip.charAt(0) == \'0\') return false;\n if(ip.length() > 0 && Integer.parseInt(ip) > 255) return false;\n return true; \n }\n\n private void f(String s, int index, String ip, int dot){\n //base case\n if(dot == 3){\n if(isIp(s.substring(index))) {\n ip += s.substring(index);\n ipes.add(ip);\n }\n return;\n }\n\n //do all the stuff\n for(int i = index; i < l; i++){\n if(isIp(s.substring(index, i +1))){\n int k = s.substring(index, i+1).length();\n ip += s.substring(index, i+1) + ".";\n f(s, i+1, ip, dot+1);\n ip = ip.substring(0, ip.length() - k -1);\n }\n }\n }\n}\n```\n```\n Give a \uD83D\uDC4D. It motivates me alot.\n```\nLet\'s Connect On [Linkedin]()\n\n
9,173
Restore IP Addresses
restore-ip-addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
String,Backtracking
Medium
null
1,744
23
# Intuition\n1. if length of string is greater than 12 then it never be a valid IP address.\n2. we will put dot for every point and for each dot we have 3 choices.\n![b58bfe69-5df9-4dfb-8d17-ea1cf7e3551b_1674264111.1136658.png]()\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize an empty list (or vector in C++), res, to store the valid IP addresses.\n2. Check if the length of the input string is greater than 12, if so return the empty list.\n3. Create a backtrack function that takes four parameters: s, i, dots, and currIp.\n4. s is the input string\n5. i is the current index of the string being processed\n6. dots represents the number of dots that have been added to the current IP address\n7. currIp represents the current IP address being formed\n8. Within the backtrack function, check if the number of dots is equal to 4 and the current index is equal to the length of the input string, in which case add the current IP address to the res list and return.\n9. Check if the number of dots is greater than 4, if so return.\n10. Iterate through the input string using a for loop, starting from the current index and ending at the minimum of current index plus 3 or the length of the input string.\n11. Within the for loop, check if the substring of the input string from the current index to the current loop index is less than 256 and either the current index is equal to the loop index or the character at the current index of the input string is not equal to 0.\n12. If the above conditions are met, recursively call the backtrack function, passing in the loop index plus 1, dots plus 1, current IP address concatenated with the substring of the input string and a dot as the parameters.\n13. After the for loop, return the res list.\n\nThis algorithm generates all possible valid IP addresses from the given string by adding dots between the substrings of the input string and then checks if it is a valid IP address.\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n void backtrack(string s, int i, int dots, string currIp, vector<string>& res) {\n if (dots == 4 && i == s.length()) {\n res.push_back(currIp.substr(0, currIp.length() - 1));\n return;\n }\n if (dots > 4) \n return;\n\n for (int j = i; j < min(i+3, (int)s.length()); j++) {\n //the i==j check is used to determine if the current substring being considered as a part of the IP address is a single digit or not. If i is equal to j, it means that the current substring is a single digit. This check is used in conjunction with the check s[i] != \'0\' to ensure that the IP address being considered is a valid one, where each segment is between 0-255 and no leading zeroes are present.\n if (stoi(s.substr(i, j-i+1)) < 256 && (i == j || s[i] != \'0\')) {\n backtrack(s, j+1, dots+1, currIp + s.substr(i, j-i+1) + ".", res);\n }\n }\n }\n vector<string> restoreIpAddresses(string s) {\n vector<string> res;\n if (s.length() > 12)\n return res;\n backtrack(s, 0, 0, "", res);\n return res;\n }\n};\n\n```\n```Java []\nclass Solution {\n public List<String> restoreIpAddresses(String s) {\n List<String> res = new ArrayList<>();\n if (s.length() > 12) return res;\n\n backtrack(s, 0, 0, "", res);\n return res;\n }\n \n public void backtrack(String s, int i, int dots, String currIp, List<String> res) {\n if (dots == 4 && i == s.length()) {\n res.add(currIp.substring(0, currIp.length() - 1));\n return;\n }\n if (dots > 4) return;\n\n for (int j = i; j < Math.min(i+3, s.length()); j++) {\n if (Integer.parseInt(s.substring(i, j+1)) < 256 && (i == j || s.charAt(i) != \'0\')) {\n backtrack(s, j+1, dots+1, currIp + s.substring(i, j+1) + ".", res);\n }\n }\n }\n}\n\n```\n```Python []\nclass Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n res = []\n if len(s) > 12:\n return res\n\n def backtrack(i , dots, currIp):\n if dots == 4 and i == len(s):\n res.append(currIp[:-1])\n return\n if dots > 4:\n return\n\n for j in range(i, min(i+3, len(s))):\n if int(s[i:j+1]) < 256 and (i == j or s[i] != "0"):\n backtrack(j + 1, dots + 1, currIp + s[i:j+1] + ".")\n\n backtrack(0, 0, "")\n return res\n```\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n![57jfh9.jpg]()\n\n# Complexity\n- Time complexity: **O(3^n)**\nThe time complexity of the above code is O(3^4) which is equivalent to O(81).\n\n**The reason is that for each character in the input string, there are 3 choices:**\n\n1. The character is the last character of an octet, the next octet starts from the next character.\n2. The character is the second last character of an octet, the next octet starts from the next character.\n3. The character is the third last character of an octet, the next octet starts from the next character.\n\n**As we are using backtracking and at most 4 octets are possible , so it will check all the possible combinations of 3^4 which is equal to 81.**\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n1. The space complexity of the code is O(n), where n is the length of the input string. This is because the maximum recursion depth is equal to the length of the input string and each level of recursion requires O(n) space to store the current IP address. The resultant list of IP addresses also takes O(n) space as the length of each IP address is equal to the length of the input string.\n2. It is worth noting that since we are keeping track of the number of dots and the current IP address, the actual space complexity is O(1) since the amount of extra space used does not depend on the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
9,188
Restore IP Addresses
restore-ip-addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
String,Backtracking
Medium
null
5,453
29
# Exaplanation to Approach :\n1. The main idea to solve this problem is to use Recursion.\n2. Consider every position of the input string and, there exist two possible cases:\n - Place a dot over the current position.\n - Take this character, i.e don\u2019t place the dot over this position.\n3. At every step of the recursion, we have the following data:\n - curr stores the string between two dots.\n - res stores the possible IP Address.\n - index stores the current position in the input string.\n4. At each index, first, add the character to curr and check whether the integer that we have is in the range [0,255] then, we can move further otherwise return.\n5. When we reach the end of the input string, we\u2019ll check whether we have a valid IP Address or not, If yes, insert the IP Address into our answer.\n\n# Request \uD83D\uDE0A :\n- If you find this solution easy to understand and helpful, then Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n![ezgif-3-22a360561c.gif]()\n\n# Code [C++] :\n```\nclass Solution {\npublic:\n vector<string> ans;\n void recurse(string res,string curr,int index,string s){\n if(index==s.length()){\n if(curr.empty() and count(res.begin(),res.end(),\'.\')==3){\n ans.push_back(res);\n }\n return;\n }\n if(!curr.empty() and stoi(curr)==0){\n return;\n }\n curr.push_back(s[index]);\n if(stoi(curr)>255){\n return;\n }\n recurse(res,curr,index+1,s);\n if(!res.empty()){\n recurse(res+"."+curr,"",index+1,s);\n }\n else{\n recurse(curr,"",index+1,s);\n }\n }\n vector<string> restoreIpAddresses(string s) {\n recurse("","",0,s);\n return ans;\n }\n};\n```\n# Code [Java] :\n```\nclass Solution {\n public List<String> restoreIpAddresses(String s) {\n List<String> ans = new ArrayList<String>();\n recurse(s, ans, 0, "", 0);\n return ans;\n }\n private void recurse(String curr, List<String> ans, int index, String temp, int count) {\n if (count > 4)\n return;\n if (count == 4 && index == curr.length())\n ans.add(temp);\n for (int i=1; i<4; i++) {\n if (index+i > curr.length()){\n break;\n }\n String s = curr.substring(index,index+i);\n if ((s.startsWith("0") && s.length()>1) || (i==3 && Integer.parseInt(s) >= 256)){\n continue;\n }\n recurse(curr, ans, index+i, temp+s+(count==3?"" : "."), count+1);\n }\n }\n}\n```\n# Code [Python3] :\n```\nclass Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n ans = []\n self.recurse(s, ans, 0, "", 0)\n return ans\n \n def recurse(self, curr, ans, index, temp, count):\n if count > 4:\n return\n if count == 4 and index == len(curr):\n ans.append(temp)\n for i in range(1, 4):\n if index + i > len(curr):\n break\n s = curr[index:index+i]\n if (s.startswith("0") and len(s) > 1) or (i == 3 and int(s) >= 256):\n continue\n self.recurse(curr, ans, index+i, temp + s + ("." if count < 3 else ""), count+1)\n\n```
9,193
Restore IP Addresses
restore-ip-addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
String,Backtracking
Medium
null
1,137
5
# Solution:\n\n``` C++ []\nclass Solution {\npublic:\n bool check(string s){\n int n=s.size();\n //if the size of string is 1 that is always possible so return true\n if(n==1){\n return true;\n }\n //if we have length >3 or string starts with 0 return false\n if(n>3||s[0]==\'0\'){\n return false;\n }\n //we are converting string to integer to check if it is less than equalto 255\n int val=stoi(s);\n if(val>255){\n return false;\n }\n //return true at last\n return true;\n }\n vector<string> restoreIpAddresses(string s) {\n int n=s.size();\n //we will store our ans in ans vector of strings\n vector<string>ans;\n //the max length of the ip address could be 12 as 255.255.255.255 so \n //all the string s with size greater than 12 can have ans\n if(n>12){\n return ans;\n }\n //now we have our string of length 12 or less than 12 so now \n //1. we have to spit the s in parts such that it satisfy the ip address conditions\n //2. if all 4 strings satisfy the condition we will push into ans vector\n \n for(int i=1;i<=3;i++){//for the length before first \'.\'\n for(int j=1;j<=3;j++){//for the length between first and second \'.\'\n for(int k=1;k<=3;k++){//for the length between second and third \'.\'\n //checking condition if the last segment is of length 3 or less\n if(i+j+k<n&&i+j+k+3>=n){\n //dividing the s int substrings \n string a=s.substr(0,i);\n string b=s.substr(i,j);\n string c=s.substr(j+i,k);\n string d=s.substr(i+j+k);\n //if all the substring satisfy the check function condition \n //then we will push into ans vector \n if(check(a)&&check(b)&&check(c)&&check(d)){\n ans.push_back(a+"."+b+"."+c+"."+d);\n }\n }\n }\n }\n }\n //return the ans vector\n return ans;\n }\n};\n```\n``` Python []\nclass Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n # Store all addresses in res\n res = []\n \n def BT(i,address):\n \n # No more digit, so no more state can be generated.\n if i==len(s):\n # It is possible that the address contains less than 4 numbers\n # We only store the valid ones.\n if len(address)==4:\n res.append( \'.\'.join(map(str,address)) )\n return\n \n # If the last number is 0, we can add the new digit to it (no leading zero)\n # After adding the new digit, the number has to be <= 255.\n if address[-1]!=0 and address[-1]*10+int(s[i]) <= 255:\n lastItem = address[-1]\n address[-1] = lastItem*10+int(s[i]) #change the current state to its neighboring state\n BT(i+1, address) #backtrack(state)\n address[-1] = lastItem #restore the state (backtrack)\n \n # The address can not contain more than 4 numbers.\n if len(address)<4:\n address.append(int(s[i])) #change the current state to its neighboring state\n BT(i+1,address) #backtrack(state)\n address.pop() #restore the state (backtrack)\n \n BT(1,[int(s[0])])\n return res\n```\n\n*Please upvote if helped*
9,196
Restore IP Addresses
restore-ip-addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
String,Backtracking
Medium
null
24,890
193
```\nclass Solution(object):\n def restoreIpAddresses(self, s):\n res = []\n self.dfs(s, 0, "", res)\n return res\n \n def dfs(self, s, idx, path, res):\n if idx > 4:\n return \n if idx == 4 and not s:\n res.append(path[:-1])\n return \n for i in range(1, len(s)+1):\n if s[:i]==\'0\' or (s[0]!=\'0\' and 0 < int(s[:i]) < 256):\n self.dfs(s[i:], idx+1, path+s[:i]+".", res)\n```
9,197
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
2,860
35
# Intuition\nWe should know how to implement inorder, preorder and postorder.\n\n# Approach\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline\n`0:04` How to implement inorder, preorder and postorder\n`1:16` Coding (Recursive)\n`2:14` Time Complexity and Space Complexity\n`2:37` Explain Stack solution\n`7:22` Coding (Stack)\n`8:45` Time Complexity and Space Complexity\n`8:59` Step by step algorithm with my stack solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 3,389\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n---\n\n## How we think about a solution\n\nTo be honest, we should know how to implement inorder, preorder and postorder.\n\n```\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nresult = []\n\ndef inorder(root):\n if not root:\n return []\n\n inorder(root.left)\n result.append(root.val)\n inorder(root.right)\n return result\n\ndef preorder(root):\n if not root:\n return []\n\n result.append(root.val)\n preorder(root.left)\n preorder(root.right)\n return result\n\ndef postorder(root):\n if not root:\n return []\n\n postorder(root.left)\n postorder(root.right)\n result.append(root.val)\n return result\n```\n\nLet\'s focus on `result.append(root.val)`\n\n---\n\n\u2B50\uFE0F Points\n\nFor `Inorder`, we do something `between` left and right.\nFor `Preorder`, we do something `before` left and right.\nFor `Postorder`, we do something `after` left and right.\n\n---\n\nWe use inorder this time, so do something between left and right.\n\n### \u2B50\uFE0F Questions related to inorder\n\n\u25A0 Find Mode in Binary Search Tree - LeetCode #501\n\npost\n\n\nvideo\n\n\n\n\u25A0 Construct Binary Tree from Preorder and Inorder Traversal - LeetCode #105\n\n\n\n---\n\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\nIn the worst case, we have skewed tree.\n\n```python []\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n\n def inorder(root):\n if not root:\n return\n inorder(root.left)\n res.append(root.val)\n inorder(root.right)\n \n inorder(root)\n return res\n```\n```javascript []\nvar inorderTraversal = function(root) {\n const res = [];\n\n function inorder(node) {\n if (!node) {\n return;\n }\n inorder(node.left);\n res.push(node.val);\n inorder(node.right);\n }\n\n inorder(root);\n return res; \n};\n```\n```java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n\n inorder(root, res);\n return res; \n }\n\n private void inorder(TreeNode node, List<Integer> res) {\n if (node == null) {\n return;\n }\n inorder(node.left, res);\n res.add(node.val);\n inorder(node.right, res);\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> res;\n inorder(root, res);\n return res; \n }\n\nprivate:\n void inorder(TreeNode* node, vector<int>& res) {\n if (!node) {\n return;\n }\n inorder(node->left, res);\n res.push_back(node->val);\n inorder(node->right, res);\n } \n};\n```\n\n\n---\n\n\n\n# Bonus - Stack solution\n\nI explain stack solution with visualization in the video above.\n\n```python []\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n # Initialize an empty list to store the result (in-order traversal)\n res = []\n \n # Initialize an empty stack for iterative traversal\n stack = []\n \n # Loop until either the current node is not None or the stack is not empty\n while root or stack:\n # Traverse to the leftmost node and push each encountered node onto the stack\n while root:\n stack.append(root)\n root = root.left\n\n # Pop the last node from the stack (most recently left-visited node)\n root = stack.pop()\n \n # Append the value of the popped node to the result list\n res.append(root.val)\n \n # Move to the right subtree to continue the in-order traversal\n root = root.right\n \n # Return the final result list\n return res\n\n```\n```javascript []\nvar inorderTraversal = function(root) {\n // Initialize an empty array to store the result (in-order traversal)\n const res = [];\n \n // Initialize an empty stack for iterative traversal\n const stack = [];\n\n // Loop until either the current node is not null or the stack is not empty\n while (root || stack.length > 0) {\n // Traverse to the leftmost node and push each encountered node onto the stack\n while (root) {\n stack.push(root);\n root = root.left;\n }\n\n // Pop the last node from the stack (most recently left-visited node)\n root = stack.pop();\n \n // Append the value of the popped node to the result array\n res.push(root.val);\n \n // Move to the right subtree to continue the in-order traversal\n root = root.right;\n }\n\n // Return the final result array\n return res; \n};\n\n```\n```java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n // Initialize an ArrayList to store the result (in-order traversal)\n List<Integer> res = new ArrayList<>();\n \n // Initialize a Stack for iterative traversal\n Stack<TreeNode> stack = new Stack<>();\n\n // Loop until either the current node is not null or the stack is not empty\n while (root != null || !stack.isEmpty()) {\n // Traverse to the leftmost node and push each encountered node onto the stack\n while (root != null) {\n stack.push(root);\n root = root.left;\n }\n\n // Pop the last node from the stack (most recently left-visited node)\n root = stack.pop();\n \n // Append the value of the popped node to the result list\n res.add(root.val);\n \n // Move to the right subtree to continue the in-order traversal\n root = root.right;\n }\n\n // Return the final result list\n return res; \n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n // Initialize a vector to store the result (in-order traversal)\n vector<int> res;\n \n // Initialize a stack for iterative traversal\n stack<TreeNode*> stack;\n\n // Loop until either the current node is not null or the stack is not empty\n while (root != nullptr || !stack.empty()) {\n // Traverse to the leftmost node and push each encountered node onto the stack\n while (root != nullptr) {\n stack.push(root);\n root = root->left;\n }\n\n // Pop the last node from the stack (most recently left-visited node)\n root = stack.top();\n stack.pop();\n \n // Append the value of the popped node to the result vector\n res.push_back(root->val);\n \n // Move to the right subtree to continue the in-order traversal\n root = root->right;\n }\n\n // Return the final result vector\n return res; \n }\n};\n\n```\n\n### Step by step Algorithm of stack solution\n\n1. **Initialization:**\n - Initialize an empty list `res` to store the result (in-order traversal).\n - Initialize an empty stack `stack` for iterative traversal.\n\n ```python\n res = []\n stack = []\n ```\n\n2. **Traversal Loop:**\n - Start a loop that continues until either the current node (`root`) is not `None` or the stack is not empty.\n - This loop handles both the traversal to the leftmost node and the backtracking to the parent node.\n\n ```python\n while root or stack:\n ```\n\n3. **Traverse to Leftmost Node:**\n - Within the loop, another nested loop is used to traverse to the leftmost node of the current subtree.\n - During this process, each encountered node is pushed onto the stack.\n - This ensures that we move as far left as possible in the tree.\n\n ```python\n while root:\n stack.append(root)\n root = root.left\n ```\n\n4. **Pop Node from Stack:**\n - Once we reach the leftmost node (or a leaf node), we pop the last node from the stack. This node is the most recently left-visited node.\n - We assign this node to `root`.\n\n ```python\n root = stack.pop()\n ```\n\n5. **Append Node Value to Result:**\n - Append the value of the popped node to the result list `res`. This is the in-order traversal order.\n\n ```python\n res.append(root.val)\n ```\n\n6. **Move to Right Subtree:**\n - Move to the right subtree of the current node. This step is crucial for continuing the in-order traversal.\n\n ```python\n root = root.right\n ```\n\n7. **End of Loop:**\n - Repeat the loop until all nodes are processed.\n\n8. **Return Result List:**\n - After the traversal is complete, return the final result list `res`.\n\n ```python\n return res\n ```\n\nThis algorithm performs an in-order traversal of a binary tree iteratively using a stack. It mimics the recursive approach but uses a stack to manage the traversal state explicitly. The core idea is to go as left as possible, visit the nodes along the way, backtrack to the parent, and then move to the right subtree. The stack helps in tracking the backtracking process.\n\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:04` Explain algorithm of Solution 1\n`1:12` Coding of solution 1\n`2:30` Time Complexity and Space Complexity of solution 1\n`2:54` Explain algorithm of Solution 2\n`3:49` Coding of Solution 2\n`4:53` Time Complexity and Space Complexity of Solution 2\n`5:12` Step by step algorithm with my stack solution code\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:05` How we create an output string\n`2:07` Coding\n`4:30` Time Complexity and Space Complexity\n`4:49` Step by step of recursion process\n`7:27` Step by step algorithm with my solution code\n\n\n
9,200
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
7,745
64
![Screenshot 2023-12-09 080341.png]()\n\n# YouTube Video Explanation:\n\n[]()\n<!-- **If you want a video for this question please write in the comments** -->\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Subscribe Goal: 700 Subscribers*\n*Current Subscribers: 689*\n\n---\n# Example Explanation\n\nLet\'s create a table to illustrate the inorder traversal of the binary tree:\n\n**Binary Tree: [1, null, 2, 3]**\n\n![]()\n\n\nTraversal Order:\n| Node | Operation | Result |\n|------|-----------|-----------|\n| 1 | Left | [] |\n| 1 | Visit 1 | [1] |\n| 1 | Right | [1] (Reaches Node 2) |\n| 2 | Left | [1] (Reaches Node 3) |\n| 3 | Visit | [1,3] |\n| 2 | Return & Visit 2 | [1, 3, 2] |\n\n\n\nFinal Result: [1, 3, 2]\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe inorder traversal of a binary tree visits the left subtree, the root, and then the right subtree. The goal is to accumulate the node values in the correct order.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We use a recursive helper function to perform the inorder traversal.\n2. In the helper function, we traverse the left subtree, add the root value to the result, and then traverse the right subtree.\n3. The base case ensures that the traversal stops when we reach a null node.\n\n# Complexity\n- Time Complexity: O(n), where n is the number of nodes in the binary tree. We visit each node once.\n- Space Complexity: O(h), where h is the height of the binary tree. The space is used for the recursive call stack, and in the worst case (skewed tree), it\'s O(n). In the average case (balanced tree), it\'s O(log n).\n\n# Code\n```java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n helper(root, res);\n return res;\n }\n\n public void helper(TreeNode root, List<Integer> res) {\n if (root != null) {\n helper(root.left, res);\n res.add(root.val);\n helper(root.right, res);\n }\n }\n}\n```\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> result;\n helper(root, result);\n return result;\n }\n\n void helper(TreeNode* root, vector<int>& result) {\n if (root != nullptr) {\n helper(root->left, result);\n result.push_back(root->val);\n helper(root->right, result);\n }\n }\n};\n```\n```Python []\nclass Solution(object):\n def inorderTraversal(self, root):\n def helper(root,result):\n if root != None:\n helper(root.left,result)\n result.append(root.val)\n helper(root.right,result) \n \n result = []\n helper(root,result)\n return result\n```\n```JavaScript []\nvar inorderTraversal = function(root) {\n const result = [];\n helper(root, result);\n return result;\n};\n\nfunction helper(root, result) {\n if (root !== null) {\n helper(root.left, result);\n result.push(root.val);\n helper(root.right, result);\n }\n}\n```\n![upvote.png]()\n
9,201
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
562
5
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Recursive Approach)***\n1. **printVector Function:**\n\n - This function takes a reference to a vector of integers as input and prints its elements in a specific format.\n - It iterates through the vector and prints each element.\n - Commas are added after each element except for the last one to maintain the proper array representation.\n1. **inorderTraversal Function:**\n\n - This function performs an inorder traversal of a binary tree recursively.\n - It takes a pointer to the root of the tree and a reference to a vector of integers (`res`) as parameters.\n - The traversal follows the left subtree, then visits the current node, and finally traverses the right subtree.\n - At each step, it appends the value of the current node to the `res` vector.\n1. **inorderTraversal (Overloaded) Function:**\n\n - This overloaded function serves as the entry point for initiating the inorder traversal.\n - It takes a pointer to the root of the tree as input.\n - It initializes an empty vector `res` to store the result of the inorder traversal.\n - Calls the `inorderTraversal` function with the root pointer and the empty `res` vector.\n - Finally, it returns the `res` vector containing the elements of the tree in inorder traversal order.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n// Function to print elements in a vector\n void printVector(vector<int>& vec) {\n cout << "[";\n for (int i = 0; i < vec.size(); ++i) {\n cout << vec[i];\n if (i != vec.size() - 1) {\n cout << ", ";\n }\n }\n cout << "]" << endl;\n }\n\n\n void inorderTraversal(TreeNode* root, vector<int>& res) {\n if (root != nullptr) {\n inorderTraversal(root->left, res);\n res.push_back(root->val);\n inorderTraversal(root->right, res);\n }\n }\n\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> res;\n inorderTraversal(root, res);\n return res;\n }\n};\n\n\n\n\n\n```\n```C []\nvoid printArray(int* arr, int size) {\n printf("[");\n for (int i = 0; i < size; ++i) {\n printf("%d", arr[i]);\n if (i != size - 1) {\n printf(", ");\n }\n }\n printf("]\\n");\n}\n\nvoid inorderTraversal(struct TreeNode* root, int* res, int* idx) {\n if (root != NULL) {\n inorderTraversal(root->left, res, idx);\n res[(*idx)++] = root->val;\n inorderTraversal(root->right, res, idx);\n }\n}\n\nint* inorderTraversalWrapper(struct TreeNode* root, int* returnSize) {\n int* res = (int*)malloc(1000 * sizeof(int)); // Allocate memory for result array\n int idx = 0; // Index to keep track of current position in the result array\n\n inorderTraversal(root, res, &idx); // Perform inorder traversal\n\n *returnSize = idx; // Set return size to the actual number of elements filled\n return res;\n}\n\n\n\n```\n```Java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n helper(root, res);\n return res;\n }\n\n public void helper(TreeNode root, List<Integer> res) {\n if (root != null) {\n helper(root.left, res);\n res.add(root.val);\n helper(root.right, res);\n }\n }\n}\n\n\n```\n```python3 []\n\n\n\nclass Solution:\n def inorderTraversal(self, root):\n res = []\n \n def inorder(root):\n if root:\n inorder(root.left)\n res.append(root.val)\n inorder(root.right)\n \n inorder(root)\n return res\n\n def printList(self, lst):\n print("[", end="")\n for i in range(len(lst)):\n print(lst[i], end="")\n if i != len(lst) - 1:\n print(", ", end="")\n print("]")\n\n```\n```javascript []\n// Definition for a binary tree node.\nfunction TreeNode(val) {\n this.val = val;\n this.left = this.right = null;\n}\n\n// Function to perform inorder traversal\nvar inorderTraversal = function(root) {\n let res = [];\n \n function traverse(node) {\n if (node !== null) {\n traverse(node.left);\n res.push(node.val);\n traverse(node.right);\n }\n }\n \n traverse(root);\n return res;\n};\n\n```\n---\n\n\n\n#### ***Approach 2(Iterating method using Stack)***\n1. **inorderTraversal Function:**\n\n - Performs iterative inorder traversal of a binary tree using a stack.\n - Starts at the root and goes to the leftmost node while pushing encountered nodes into a stack.\n - As it reaches the leftmost node, it pops nodes from the stack, appends their values to the result, and moves to their right children.\n - Continues this process until all nodes are visited, storing values in the `res` vector.\n1. **printVector Function:**\n\n - A utility function to print elements stored in a vector.\n - Outputs elements in a readable format, separated by commas, enclosed in square brackets.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Perform inorder traversal of a binary tree iteratively\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> res; // Vector to store inorder traversal result\n stack<TreeNode*> st; // Stack to assist in traversal\n TreeNode* curr = root; // Pointer to track the current node\n\n // Traverse the tree until current node is not null or stack is not empty\n while (curr != nullptr || !st.empty()) {\n // Traverse to the leftmost node of the current subtree\n while (curr != nullptr) {\n st.push(curr); // Push current node to stack\n curr = curr->left; // Move to the left child\n }\n\n curr = st.top(); // Get the top node from stack\n st.pop(); // Pop the top node\n res.push_back(curr->val);// Push the value of current node to result vector\n curr = curr->right; // Move to the right child to explore its subtree\n }\n return res; // Return the inorder traversal result\n }\n};\n\n// Function to print elements in a vector\nvoid printVector(vector<int>& vec) {\n cout << "["; // Output start of the vector representation\n for (int i = 0; i < vec.size(); ++i) {\n cout << vec[i]; // Output the current element\n if (i != vec.size() - 1) {\n cout << ", "; // Output comma if not the last element\n }\n }\n cout << "]" << endl; // Output end of the vector representation\n}\n\n\n\n```\n```C []\nstruct TreeNode {\n int val;\n struct TreeNode *left;\n struct TreeNode *right;\n};\n\n// Structure of the stack node\nstruct StackNode {\n struct TreeNode *node;\n struct StackNode *next;\n};\n\n// Function to create a new stack node\nstruct StackNode* createStackNode(struct TreeNode* node) {\n struct StackNode* stackNode = (struct StackNode*)malloc(sizeof(struct StackNode));\n stackNode->node = node;\n stackNode->next = NULL;\n return stackNode;\n}\n\n// Function to push an element into the stack\nvoid push(struct StackNode** root, struct TreeNode* node) {\n struct StackNode* stackNode = createStackNode(node);\n stackNode->next = *root;\n *root = stackNode;\n}\n\n// Function to check if the stack is empty\nint isEmpty(struct StackNode* root) {\n return !root;\n}\n\n// Function to pop an element from the stack\nstruct TreeNode* pop(struct StackNode** root) {\n if (isEmpty(*root)) return NULL;\n struct StackNode* temp = *root;\n *root = (*root)->next;\n struct TreeNode* popped = temp->node;\n free(temp);\n return popped;\n}\n\n// Perform inorder traversal of a binary tree iteratively\nint* inorderTraversal(struct TreeNode* root, int* returnSize) {\n int* res = (int*)malloc(100 * sizeof(int)); // Vector to store inorder traversal result\n struct StackNode* st = NULL; // Stack to assist in traversal\n struct TreeNode* curr = root; // Pointer to track the current node\n int index = 0; // Index to track the position in the result array\n\n // Traverse the tree until current node is not null or stack is not empty\n while (curr != NULL || !isEmpty(st)) {\n // Traverse to the leftmost node of the current subtree\n while (curr != NULL) {\n push(&st, curr); // Push current node to stack\n curr = curr->left; // Move to the left child\n }\n\n curr = pop(&st); // Get the top node from stack\n res[index++] = curr->val; // Store the value of current node in the result vector\n curr = curr->right; // Move to the right child to explore its subtree\n }\n\n *returnSize = index; // Set the size of the resulting array\n return res; // Return the inorder traversal result\n}\n\n// Function to print elements in an array\nvoid printArray(int* arr, int size) {\n printf("[");\n for (int i = 0; i < size; ++i) {\n printf("%d", arr[i]);\n if (i != size - 1) {\n printf(", ");\n }\n }\n printf("]\\n");\n}\n\n\n\n```\n```Java []\npublic class Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n Stack<TreeNode> stack = new Stack<>();\n TreeNode curr = root;\n while (curr != null || !stack.isEmpty()) {\n while (curr != null) {\n stack.push(curr);\n curr = curr.left;\n }\n curr = stack.pop();\n res.add(curr.val);\n curr = curr.right;\n }\n return res;\n }\n}\n\n\n```\n```python3 []\n\ndef inorderTraversal(root):\n res = [] # List to store inorder traversal result\n stack = [] # Stack to assist in traversal\n curr = root # Pointer to track the current node\n\n # Traverse the tree until current node is not None or stack is not empty\n while curr is not None or stack:\n # Traverse to the leftmost node of the current subtree\n while curr is not None:\n stack.append(curr) # Push current node to stack\n curr = curr.left # Move to the left child\n\n curr = stack.pop() # Get the top node from stack\n res.append(curr.val) # Append the value of current node to result list\n curr = curr.right # Move to the right child to explore its subtree\n\n return res # Return the inorder traversal result\n\n# Function to print elements in a list\ndef printList(lst):\n print("[", end="") # Output start of the list representation\n for i in range(len(lst)):\n print(lst[i], end="") # Output the current element\n if i != len(lst) - 1:\n print(", ", end="") # Output comma if not the last element\n print("]") # Output end of the list representation\n\n\n```\n```javascript []\n// Definition of the TreeNode structure\nclass TreeNode {\n constructor(val = 0, left = null, right = null) {\n this.val = val;\n this.left = left;\n this.right = right;\n }\n}\n\n// Perform inorder traversal of a binary tree iteratively\nvar inorderTraversal = function(root) {\n let res = []; // Array to store inorder traversal result\n let st = []; // Stack to assist in traversal\n let curr = root; // Pointer to track the current node\n\n // Traverse the tree until current node is not null or stack is not empty\n while (curr !== null || st.length !== 0) {\n // Traverse to the leftmost node of the current subtree\n while (curr !== null) {\n st.push(curr); // Push current node to stack\n curr = curr.left; // Move to the left child\n }\n\n curr = st.pop(); // Get the top node from stack\n res.push(curr.val); // Store the value of current node in the result array\n curr = curr.right; // Move to the right child to explore its subtree\n }\n\n return res; // Return the inorder traversal result\n};\n\n// Function to print elements\n\n\n```\n---\n\n#### ***Approach 3(Morris Traversal)***\n1. **norderTraversal Function:**\n\n - It takes the root of a binary tree as input and returns a vector containing elements in inorder traversal order.\n - `TreeNode* curr` represents the current node being processed.\n - `TreeNode* pre` helps to handle cases where a node has a left subtree.\n - It continuously loops while `curr` is not null.\n - If the current node\'s left child is null, it means there\'s no left subtree. In this case:\n - It adds the current node\'s value to the `res` vector.\n - Moves to the right child to continue the traversal.\n - If the current node has a left subtree:\n - It finds the rightmost node of the left subtree by traversing right until the right child is null (this is stored in `pre`).\n - Links the `pre->right` to the current node (`curr`) to establish a connection after the left subtree is traversed.\n - Moves the `curr` pointer to its left child, as the left subtree needs to be traversed next.\n - Sets the original left child of the `curr` node to null to avoid infinite loops in case of revisiting nodes.\n1. **printVector Function:**\n\n - It\'s a utility function used to print the elements stored in a vector `vec` in a specific format.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> res;\n TreeNode* curr = root;\n TreeNode* pre;\n\n while (curr != nullptr) {\n if (curr->left == nullptr) {\n res.push_back(curr->val);\n curr = curr->right; // move to next right node\n } else { // has a left subtree\n pre = curr->left;\n while (pre->right != nullptr) { // find rightmost\n pre = pre->right;\n }\n pre->right = curr; // put cur after the pre node\n TreeNode* temp = curr; // store cur node\n curr = curr->left; // move cur to the top of the new tree\n temp->left = nullptr; // original cur left be null, avoid infinite loops\n }\n }\n return res;\n }\n};\n\n// Function to print elements in a vector\nvoid printVector(vector<int>& vec) {\n cout << "[";\n for (int i = 0; i < vec.size(); ++i) {\n cout << vec[i];\n if (i != vec.size() - 1) {\n cout << ", ";\n }\n }\n cout << "]" << endl;\n}\n\n\n```\n```C []\nstruct TreeNode {\n int val;\n struct TreeNode *left;\n struct TreeNode *right;\n};\n\nstruct TreeNode* createNode(int val) {\n struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));\n newNode->val = val;\n newNode->left = NULL;\n newNode->right = NULL;\n return newNode;\n}\n\nvoid inorderTraversal(struct TreeNode* root, int* res, int* returnSize) {\n struct TreeNode* curr = root;\n struct TreeNode* pre;\n\n int index = 0;\n while (curr != NULL) {\n if (curr->left == NULL) {\n res[index++] = curr->val;\n curr = curr->right; // move to next right node\n } else { // has a left subtree\n pre = curr->left;\n while (pre->right != NULL) { // find rightmost\n pre = pre->right;\n }\n pre->right = curr; // put cur after the pre node\n struct TreeNode* temp = curr; // store cur node\n curr = curr->left; // move cur to the top of the new tree\n temp->left = NULL; // original cur left be null, avoid infinite loops\n }\n }\n *returnSize = index; // update the size of the result array\n}\n\n\n\n\n```\n```Java []\n\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n TreeNode curr = root;\n TreeNode pre;\n while (curr != null) {\n if (curr.left == null) {\n res.add(curr.val);\n curr = curr.right; // move to next right node\n } else { // has a left subtree\n pre = curr.left;\n while (pre.right != null) { // find rightmost\n pre = pre.right;\n }\n pre.right = curr; // put cur after the pre node\n TreeNode temp = curr; // store cur node\n curr = curr.left; // move cur to the top of the new tree\n temp.left = null; // original cur left be null, avoid infinite loops\n }\n }\n return res;\n }\n}\n\n```\n```python3 []\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef inorderTraversal(root):\n res = [] # List to store inorder traversal result\n curr = root\n pre = None\n\n while curr is not None:\n if curr.left is None:\n res.append(curr.val)\n curr = curr.right # Move to next right node\n else: # Node has a left subtree\n pre = curr.left\n while pre.right is not None: # Find rightmost node of left subtree\n pre = pre.right\n pre.right = curr # Link the current node after the rightmost node of the left subtree\n temp = curr # Store the current node\n curr = curr.left # Move current node to the top of the new tree\n temp.left = None # Set original left node to null to avoid infinite loops\n\n return res # Return the inorder traversal result\n\n# Function to print elements in a list\ndef printList(lst):\n print("[", end="")\n for i in range(len(lst)):\n print(lst[i], end="")\n if i != len(lst) - 1:\n print(", ", end="")\n print("]")\n\n\n```\n```javascript []\nfunction TreeNode(val) {\n this.val = val;\n this.left = this.right = null;\n}\n\nvar inorderTraversal = function(root) {\n const res = [];\n let curr = root;\n let pre;\n\n while (curr !== null) {\n if (curr.left === null) {\n res.push(curr.val);\n curr = curr.right; // move to next right node\n } else { // has a left subtree\n pre = curr.left;\n while (pre.right !== null) { // find rightmost\n pre = pre.right;\n }\n pre.right = curr; // put cur after the pre node\n let temp = curr; // store cur node\n curr = curr.left; // move cur to the top of the new tree\n temp.left = null; // original cur left be null, avoid infinite loops\n }\n }\n return res;\n};\n\n\n```\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
9,203
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
35,603
473
```C++ []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> ans;\n if (root == NULL) return ans;\n vector<int> left = inorderTraversal(root->left);\n ans.insert(ans.end(), left.begin(), left.end());\n ans.push_back(root->val);\n vector<int> right = inorderTraversal(root->right);\n ans.insert(ans.end(), right.begin(), right.end());\n return ans;\n}\n\n};\n```\n\n```Python3 []\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n st = []\n res = []\n\n while root or st:\n while root:\n st.append(root)\n root = root.left\n \n root = st.pop()\n res.append(root.val)\n\n root = root.right\n \n return res \n```\n\n```Java []\nclass Solution {\n private List<Integer> res = new ArrayList<>();\n public List<Integer> inorderTraversal(TreeNode root) {\n traverse(root);\n return res;\n }\n \n private void traverse(TreeNode root) {\n if (root == null) {\n return;\n }\n traverse(root.left);\n res.add(root.val);\n traverse(root.right);\n }\n}\n```\n
9,213
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
242
5
# \uD83C\uDF32 Exploring Inorder Tree Traversal \uD83C\uDF33\n\n---\n\n## \uD83D\uDCBB Solution\n\n### \uD83D\uDCA1Approach\n\nThe solution defines a class `Solution` with a method `inorderTraversal` for performing inorder tree traversal. The algorithm uses recursion to traverse the tree in an inorder manner, collecting node values in a vector.\n\n### \uD83D\uDCDDDry Run\n\nInput Tree:\n```\n 1\n / \\\n 2 3\n / \\\n 4 5\n```\n\n#### Steps:\n1. **Inorder Traversal:**\n - Traverse left subtree (2).\n - Traverse left subtree (4).\n - No left child.\n - Add 4 to the vector.\n - No right child.\n - Add 2 to the vector.\n - Traverse right subtree (5).\n - No left child.\n - Add 5 to the vector.\n - No right child.\n - Add 1 to the vector.\n - Traverse right subtree (3).\n - No left child.\n - Add 3 to the vector.\n - No right child.\n\n#### Final Output:\nThe vector is [4, 2, 5, 1, 3].\n\n### \uD83D\uDD0DEdge Cases\n\n- Handles scenarios with null nodes and varying tree structures.\n\n### \uD83D\uDD78\uFE0FComplexity Analysis\n- **Time Complexity:** O(N), where N is the number of nodes in the tree.\n- **Space Complexity:** O(N), as the algorithm uses a vector to store node values.\n\n### \uD83E\uDDD1\uD83C\uDFFB\u200D\uD83D\uDCBBCodes in (C++) (Java) (Python) (C#) (JavaScript)\n\n```cpp []\nclass Solution {\npublic:\n vector<int> ans;\n\n vector<int> inorderTraversal(TreeNode* root) {\n if(root == NULL) return {};\n inorderTraversal(root->left);\n ans.push_back(root->val);\n inorderTraversal(root->right);\n return ans;\n }\n};\n```\n\n```java []\nclass Solution {\n List<Integer> ans = new ArrayList<>();\n\n public List<Integer> inorderTraversal(TreeNode root) {\n if (root == null) return Collections.emptyList();\n inorderTraversal(root.left);\n ans.add(root.val);\n inorderTraversal(root.right);\n return ans;\n }\n}\n```\n\n```python []\nclass Solution:\n def inorderTraversal(self, root):\n ans = []\n def inorder(node):\n if node:\n inorder(node.left)\n ans.append(node.val)\n inorder(node.right)\n inorder(root)\n return ans\n```\n\n```csharp []\npublic class Solution {\n List<int> ans = new List<int>();\n\n public IList<int> InorderTraversal(TreeNode root) {\n if (root == null) return ans;\n InorderTraversal(root.left);\n ans.Add(root.val);\n InorderTraversal(root.right);\n return ans;\n }\n}\n```\n\n```javascript []\nvar inorderTraversal = function(root) {\n const ans = [];\n const inorder = (node) => {\n if (node) {\n inorder(node.left);\n ans.push(node.val);\n inorder(node.right);\n }\n };\n inorder(root);\n return ans;\n};\n```\n\n---\n# \uD83C\uDF32 Inorder Tree Traversal with Stack Exploration \uD83C\uDF33\n\n---\n\n## \uD83D\uDCBB Solution\n\n### \uD83D\uDCA1Approach 2: Iterative Approach with Stack\n\nThe iterative approach utilizes a stack to simulate the recursive call stack. It traverses the tree in an inorder manner, pushing nodes onto the stack until reaching the leftmost node. It then pops nodes, processes them, and moves to the right child if available.\n\n### \u2728Explanation\n\n1. Initialize an empty stack and an empty list to store the result.\n2. Start with the root node and iterate until the stack is empty or the current node is null.\n3. While the current node is not null, push it onto the stack and move to its left child.\n4. If the current node is null, pop a node from the stack, process it (add to the result list), and move to its right child.\n5. Repeat steps 3-4 until the stack is empty.\n\n### \uD83D\uDCDDDry Run\n\nInput Tree:\n```\n 1\n / \\\n 2 3\n / \\\n 4 5\n```\n\n#### Steps:\n1. Stack: [], Result: []\n2. Start with the root (1), push onto the stack, and move to the left child (2).\n3. Stack: [1], Result: []\n4. Move to the left child (4).\n5. Stack: [1, 2], Result: []\n6. Move to the left child (null), pop 4, process (add to result), move to the right child (null).\n7. Stack: [1], Result: [4]\n8. Move to the right child (2).\n9. Stack: [1, 2], Result: [4]\n10. Move to the left child (null), pop 2, process, move to the right child (5).\n11. Stack: [1], Result: [4, 2]\n12. Move to the left child (null), pop 1, process, move to the right child (3).\n13. Stack: [], Result: [4, 2, 1]\n14. Move to the left child (null), pop 3, process, move to the right child (null).\n15. Stack: [], Result: [4, 2, 1, 3]\n\n#### Final Output:\nThe result list is [4, 2, 1, 3].\n\n### \uD83D\uDD0DEdge Cases\n\n- Handles scenarios with null nodes and varying tree structures.\n\n### \uD83D\uDD78\uFE0FComplexity Analysis\n- **Time Complexity:** O(N), where N is the number of nodes in the tree.\n- **Space Complexity:** O(N), as the algorithm uses a stack to store nodes.\n\n### \uD83E\uDDD1\uD83C\uDFFB\u200D\uD83D\uDCBBCodes in (C++) (Java) (Python) (C#) (JavaScript)\n\n```cpp []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> result;\n stack<TreeNode*> st;\n\n while (root || !st.empty()) {\n while (root) {\n st.push(root);\n root = root->left;\n }\n root = st.top();\n st.pop();\n result.push_back(root->val);\n root = root->right;\n }\n\n return result;\n }\n};\n```\n\n```java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<>();\n Stack<TreeNode> stack = new Stack<>();\n\n while (root != null || !stack.isEmpty()) {\n while (root != null) {\n stack.push(root);\n root = root.left;\n }\n root = stack.pop();\n result.add(root.val);\n root = root.right;\n }\n\n return result;\n }\n}\n```\n\n```python []\nclass Solution:\n def inorderTraversal(self, root):\n result = []\n stack = []\n\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n result.append(root.val)\n root = root.right\n\n return result\n```\n\n```csharp []\npublic class Solution {\n public IList<int> InorderTraversal(TreeNode root) {\n List<int> result = new List<int>();\n Stack<TreeNode> stack = new Stack<TreeNode>();\n\n while (root != null || stack.Count > 0) {\n while (root != null) {\n stack.Push(root);\n root = root.left;\n }\n root = stack.Pop();\n result.Add(root.val);\n root = root.right;\n }\n\n return result;\n }\n}\n```\n\n```javascript []\nvar inorderTraversal = function(root) {\n const result = [];\n const stack = [];\n\n while (root || stack.length > 0) {\n while (root) {\n stack.push(root);\n root = root.left;\n }\n root = stack.pop();\n result.push(root.val);\n root = root.right;\n }\n\n return result;\n};\n```\n\n---\n# \uD83C\uDF32 Morris Traversal for Inorder Tree Traversal \uD83C\uDF33\n\n---\n\n## \uD83D\uDCBB Solution\n\n### \uD83D\uDCA1Approach 3: Morris Traversal\n\nMorris Traversal is an ingenious algorithm that enables efficient tree traversal without using a stack or recursion. It utilizes threaded binary trees by modifying the tree structure temporarily during the traversal.\n\n### \u2728Explanation\n\n1. Initialize the current node as the root.\n2. While the current node is not null:\n - If the current node has no left child:\n - Process the node.\n - Move to the right child.\n - If the current node has a left child:\n - Find the rightmost node in the left subtree (inorder predecessor).\n - If the rightmost node\'s right child is null:\n - Make the current node the right child of the rightmost node.\n - Move to the left child.\n - If the rightmost node\'s right child is the current node:\n - Revert the changes made in step 3.\n - Process the current node.\n - Move to the right child.\n\n### \uD83D\uDCDDDry Run\n\nInput Tree:\n```\n 1\n / \\\n 2 3\n / \\\n 4 5\n```\n\n#### Steps:\n1. Initialize: current = 1.\n2. Current has left child (2).\n - Find rightmost node in left subtree (5).\n - 5\'s right child is null, make 1 the right child of 5, move to left child (2).\n3. Current has left child (4).\n - Find rightmost node in left subtree (4).\n - 4\'s right child is null, make 2 the right child of 4, move to left child (null).\n4. Process 1, move to right child (3).\n5. Process 2, move to right child (4).\n6. Revert changes made in step 3.\n7. Process 3, move to right child (null).\n8. Process 4, move to right child (5).\n9. Revert changes made in step 2.\n10. Process 5, move to right child (null).\n\n#### Final Output:\nThe result list is [4, 2, 1, 3, 5].\n\n### \uD83D\uDD0DEdge Cases\n\n- Handles scenarios with null nodes and varying tree structures.\n\n### \uD83D\uDD78\uFE0FComplexity Analysis\n- **Time Complexity:** O(N), where N is the number of nodes in the tree.\n- **Space Complexity:** O(1), as the algorithm modifies the tree in-place.\n\n### \uD83E\uDDD1\uD83C\uDFFB\u200D\uD83D\uDCBBCodes in (C++) (Java) (Python) (C#) (JavaScript)\n\n```cpp []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> result;\n TreeNode* current = root;\n\n while (current) {\n if (!current->left) {\n result.push_back(current->val);\n current = current->right;\n } else {\n TreeNode* predecessor = current->left;\n\n while (predecessor->right && predecessor->right != current) {\n predecessor = predecessor->right;\n }\n\n if (!predecessor->right) {\n predecessor->right = current;\n current = current->left;\n } else {\n predecessor->right = nullptr;\n result.push_back(current->val);\n current = current->right;\n }\n }\n }\n\n return result;\n }\n};\n```\n\n```java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<>();\n TreeNode current = root;\n\n while (current != null) {\n if (current.left == null) {\n result.add(current.val);\n current = current.right;\n } else {\n TreeNode predecessor = current.left;\n\n while (predecessor.right != null && predecessor.right != current) {\n predecessor = predecessor.right;\n }\n\n if (predecessor.right == null) {\n predecessor.right = current;\n current = current.left;\n } else {\n predecessor.right = null;\n result.add(current.val);\n current = current.right;\n }\n }\n }\n\n return result;\n }\n}\n```\n\n```python []\nclass Solution:\n def inorderTraversal(self, root):\n result = []\n current = root\n\n while current:\n if not current.left:\n result.append(current.val)\n current = current.right\n else:\n predecessor = current.left\n\n while predecessor.right and predecessor.right != current:\n predecessor = predecessor.right\n\n if not predecessor.right:\n predecessor.right = current\n current = current.left\n else:\n predecessor.right = None\n result.append(current.val)\n current = current.right\n\n return result\n }\n```\n\n```csharp []\npublic class Solution {\n public IList<int> InorderTraversal(TreeNode root) {\n List<int> result = new List<int>();\n TreeNode current = root;\n\n while (current != null) {\n if (current.left == null) {\n result.Add(current.val);\n current = current.right;\n } else {\n TreeNode predecessor = current.left;\n\n while (predecessor.right != null && predecessor.right != current) {\n predecessor = predecessor.right;\n }\n\n if (predecessor.right == null) {\n predecessor.right = current;\n current = current\n\n.left;\n } else {\n predecessor.right = null;\n result.Add(current.val);\n current = current.right;\n }\n }\n }\n\n return result;\n }\n}\n```\n\n```javascript []\nvar inorderTraversal = function(root) {\n const result = [];\n let current = root;\n\n while (current) {\n if (!current.left) {\n result.push(current.val);\n current = current.right;\n } else {\n let predecessor = current.left;\n\n while (predecessor.right && predecessor.right !== current) {\n predecessor = predecessor.right;\n }\n\n if (!predecessor.right) {\n predecessor.right = current;\n current = current.left;\n } else {\n predecessor.right = null;\n result.push(current.val);\n current = current.right;\n }\n }\n }\n\n return result;\n};\n```\n\n---\n![image.png]()\n\n\n\n\n\n# \uD83E\uDDD1\u200D\uD83D\uDCBB Happy Coding! \uD83C\uDF1F\n\n -- *MR.ROBOT SIGNING OFF*\n
9,216
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
178
6
# Code #1 - Oneliner On Generator\n```\nclass Solution:\n def inorderTraversal(self, r: Optional[TreeNode]) -> List[int]:\n yield from chain(self.inorderTraversal(r.left), (r.val,), self.inorderTraversal(r.right)) if r else ()\n```\n\n# Code #2 - Classic Oneliner On Lists Concatenation\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def inorderTraversal(self, r: Optional[TreeNode]) -> List[int]:\n return (self.inorderTraversal(r.left) + [r.val] + self.inorderTraversal(r.right)) if r else []\n```
9,254
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
70,169
1,008
![image]()\n\n```\ndef preorder(root):\n return [root.val] + preorder(root.left) + preorder(root.right) if root else []\n```\n\n```\ndef inorder(root):\n return inorder(root.left) + [root.val] + inorder(root.right) if root else []\n```\n\n```\ndef postorder(root):\n return postorder(root.left) + postorder(root.right) + [root.val] if root else []\n```\n
9,257
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
28,800
351
[Python3] Pre, In, Post Iteratively Summarization\nIn preorder, the order should be\n\nroot -> left -> right\n\nBut when we use stack, the order should be reversed:\n\nright -> left -> root\n\nPre\n```\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n res, stack = [], [(root, False)]\n while stack:\n node, visited = stack.pop() # the last element\n if node:\n if visited: \n res.append(node.val)\n else: # preorder: root -> left -> right\n stack.append((node.right, False))\n stack.append((node.left, False))\n stack.append((node, True))\n return res\n```\n\n\nIn inorder, the order should be\nleft -> root -> right\n\nBut when we use stack, the order should be reversed:\n\nright -> root -> left\n\nIn\n```\nclass Solution:\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n res, stack = [], [(root, False)]\n while stack:\n node, visited = stack.pop() # the last element\n if node:\n if visited:\n res.append(node.val)\n else: # inorder: left -> root -> right\n stack.append((node.right, False))\n stack.append((node, True))\n stack.append((node.left, False))\n return res\n```\t\n\n\nIn postorder, the order should be\nleft -> right -> root\n\nBut when we use stack, the order should be reversed:\n\nroot -> right -> left\n\nPost\n```\nclass Solution:\n def postorderTraversal(self, root: TreeNode) -> List[int]:\n res, stack = [], [(root, False)]\n while stack:\n node, visited = stack.pop() # the last element\n if node:\n if visited:\n res.append(node.val)\n else: # postorder: left -> right -> root\n stack.append((node, True))\n stack.append((node.right, False))\n stack.append((node.left, False))\n return res\n```
9,271
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
2,727
16
# 1st Method :- Brute force\n\n## Code\n``` Java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n //store the elements of the binary tree in inorder traversal order.\n List<Integer> result = new ArrayList<>();\n inorderHelper(root, result);\n return result;\n }\n\n private void inorderHelper(TreeNode node, List<Integer> result) {\n if (node != null) {\n // Visit left subtree\n inorderHelper(node.left, result);\n \n // Visit the current node (root)\n result.add(node.val);\n \n // Visit right subtree\n inorderHelper(node.right, result);\n }\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> result;\n inorder(root, result);\n return result;\n }\n \n void inorder(TreeNode* node, vector<int>& result) {\n if (node == nullptr) {\n return;\n }\n \n // Traverse the left subtree\n inorder(node->left, result);\n \n // Visit the current node\n result.push_back(node->val);\n \n // Traverse the right subtree\n inorder(node->right, result);\n }\n};\n\n```\n``` Python []\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n result = []\n \n # Define a helper function to perform the recursive traversal\n def inorder(node):\n if node:\n # First, traverse the left subtree\n inorder(node.left)\n # Then, add the current node\'s value to the result\n result.append(node.val)\n # Finally, traverse the right subtree\n inorder(node.right)\n \n # Start the traversal from the root\n inorder(root)\n \n return result\n```\n``` JavaScript []\nvar inorderTraversal = function(root) {\n if (!root) {\n return [];\n }\n \n const result = [];\n \n function inorder(node) {\n if (node.left) {\n inorder(node.left);\n }\n result.push(node.val);\n if (node.right) {\n inorder(node.right);\n }\n }\n \n inorder(root);\n \n return result;\n\n};\n```\n\n# Complexity\n#### Time complexity: O(n) ;\nThe time complexity of this solution is O(N), where N is the number of nodes in the binary tree. This is because we visit each node exactly once during the traversal.\n\nThe recursive function `inorderHelper` is called for each node, and it performs three main operations for each node:\n\n1. Visiting the left subtree: In the worst case, this involves visiting all nodes on the left side of the tree, which takes O(N/2) time.\n\n2. Visiting the current node: This is a constant-time operation (adding the node\'s value to the result list).\n\n3. Visiting the right subtree: Similar to the left subtree, in the worst case, this involves visiting all nodes on the right side of the tree, which also takes O(N/2) time.\n\nSince all these operations are performed separately for each node, the overall time complexity is O(N).\n\n#### Space complexity: O(H) ;\nThe space complexity of this solution is O(H), where H is the height of the binary tree.\n\nIn the worst case, if the binary tree is completely unbalanced (e.g., a skewed tree where each node has only a left child or only a right child), the height of the tree can be equal to N (the number of nodes). In this case, the space required for the call stack during the recursive traversal would be O(N), which represents the space complexity.\n\n\n# 2nd Method :- Efficient Method\n\n>This code iteratively traverses a binary tree in an inorder manner using a stack to keep track of the nodes to be processed. It ensures that we visit the left subtree, then the current node, and then the right subtree, just like the recursive approach, but without the use of recursion. This approach is more memory-efficient and avoids stack overflow errors for large trees.\n\n1. **Initialize Data Structures**: \n - We start by initializing two data structures: a `List<Integer>` called `result` to store the inorder traversal result and a `Stack<TreeNode>` called `stack` to help us simulate the recursive process iteratively.\n - We also initialize a `TreeNode` called `curr` and set it to the `root` of the binary tree.\n\n2. **Main Loop**:\n - The main part of the code is a `while` loop that continues until `curr` becomes `null` (indicating we have traversed the entire tree) and the `stack` is empty (indicating we\'ve processed all nodes).\n\n3. **Traverse Left Subtree and Push Nodes onto the Stack**:\n - Within the `while` loop, we have another `while` loop to traverse the left subtree of the current node (`curr`) and push all encountered nodes onto the stack.\n - We keep going left as long as `curr` is not `null`, pushing each encountered node onto the `stack`. This is done to simulate the left subtree traversal.\n\n4. **Visit the Current Node and Move to the Right Subtree**:\n - Once we\'ve traversed all the way to the left (or if `curr` is `null`), we pop a node from the `stack`. This node represents the current root of a subtree that needs to be processed.\n - We add the value of the current node (`curr.val`) to the `result` list, as it\'s part of the inorder traversal.\n - We then update `curr` to point to the right child of the current node. This will ensure that if there\'s a right subtree, we\'ll traverse it next. If there\'s no right subtree, this step will essentially move us up in the tree to the parent of the current node.\n\n5. **Repeat**:\n - We repeat steps 3 and 4 until we\'ve traversed the entire binary tree. This process effectively simulates an inorder traversal iteratively using a stack.\n\n6. **Return Result**:\n - Finally, after the loop has finished, we return the `result` list, which contains the inorder traversal of the binary tree.\n\n## Code\n``` Java []\nclass Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n // store the inorder traversal result \n List<Integer> result = new ArrayList<>();\n \n //help us simulate the recursive process iteratively.\n Stack<TreeNode> stack = new Stack<>();\n TreeNode curr = root;\n \n while (curr != null || !stack.isEmpty()) {\n // Traverse left subtree and push nodes onto the stack\n while (curr != null) {\n stack.push(curr);\n curr = curr.left;\n }\n \n // Visit the current node (root) and move to the right subtree\n curr = stack.pop();\n result.add(curr.val);\n curr = curr.right;\n }\n \n return result;\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> result;\n stack<TreeNode*> st;\n TreeNode* curr = root;\n \n while (curr != nullptr || !st.empty()) {\n // Traverse left subtree and push nodes onto the stack\n while (curr != nullptr) {\n st.push(curr);\n curr = curr->left;\n }\n \n // Visit the current node (root) and move to the right subtree\n curr = st.top();\n st.pop();\n result.push_back(curr->val);\n curr = curr->right;\n }\n \n return result;\n }\n};\n```\n``` Python []\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n result = []\n stack = []\n curr = root\n \n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n result.append(curr.val)\n curr = curr.right\n \n return result\n```\n``` JavaScript []\nvar inorderTraversal = function(root) {\n const result = [];\n const stack = [];\n let curr = root;\n \n while (curr || stack.length > 0) {\n while (curr) {\n stack.push(curr);\n curr = curr.left;\n }\n curr = stack.pop();\n result.push(curr.val);\n curr = curr.right;\n }\n \n return result;\n};\n```\n# Complexity\n#### Time complexity: O(N) ;\n- In the worst-case scenario, where the binary tree is completely unbalanced and resembles a linked list, you would visit each node once. Therefore, the time complexity of this algorithm is O(N), where N is the number of nodes in the tree.\n\n#### Space complexity: O(N) ;\n- The space complexity is determined by the space used by the stack and the list to store the result.\n- The stack is used to keep track of nodes as you traverse the tree. In the worst case, if the tree is completely unbalanced, the stack could hold all N nodes. Therefore, the space used by the stack is O(N).\n- The result list is used to store the final inorder traversal result. In the worst case, you will store N elements in this list, so the space used by the result list is also O(N).\n- Additionally, you have a few variables like `curr` and `result` that consume constant space, so we don\'t need to consider them when analyzing space complexity.\n- The total space complexity is the sum of the space used by the stack and the result list, which is O(N + N) = O(N).\n
9,273
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
3,796
37
# 1. Recursive Approach\n```\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans=[]\n def inorder(root,ans):\n if not root:\n return None\n inorder(root.left,ans)\n ans.append(root.val)\n inorder(root.right,ans)\n inorder(root,ans)\n return ans\n```\n# 2. Iterative Approach\n```\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans=[]\n stack=[]\n cur=root\n while stack or cur:\n if cur:\n stack.append(cur)\n cur=cur.left\n else:\n cur=stack.pop()\n ans.append(cur.val)\n cur=cur.right\n return ans\n```\n# please upvote me it would encourage me alot\n
9,281
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
3,182
5
My Python approach for Morris Inorder Traversal.\nBased on [this]() video.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n cur = root\n while cur != None:\n #printing the leftmost node\n if not cur.left:\n ans.append(cur.val)\n cur = cur.right\n else:\n temp = cur\n temp = temp.left\n #going to the rightmost node in the left subtree (lets call it temp)\n while temp.right and temp.right != cur:\n temp = temp.right\n \n #2 conditions arise:\n \n #i. the right child of temp doesn\'t exist (The thread to the cur node has not been made)\n #in this case, point the right child of temp to cur and move cur to its left child\n if not temp.right:\n temp.right = cur\n cur = cur.left\n\n #ii. the thread has already been created so we break the thread\n #(pointing the temp\'s right child back to None)and print cur.\n #Finally, move cur to its right child \n else:\n ans.append(cur.val)\n temp.right = None\n cur = cur.right\n\n return ans\n```
9,291
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Stack,Tree,Depth-First Search,Binary Tree
Easy
null
96,221
490
\n # recursively\n def inorderTraversal1(self, root):\n res = []\n self.helper(root, res)\n return res\n \n def helper(self, root, res):\n if root:\n self.helper(root.left, res)\n res.append(root.val)\n self.helper(root.right, res)\n \n # iteratively \n def inorderTraversal(self, root):\n res, stack = [], []\n while True:\n while root:\n stack.append(root)\n root = root.left\n if not stack:\n return res\n node = stack.pop()\n res.append(node.val)\n root = node.right
9,299
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
9,620
78
Given an integer \\( n \\), the task is to return all the structurally unique BST\'s (binary search trees) that have exactly \\( n \\) nodes of unique values from \\( 1 \\) to \\( n \\).\n\n# Intuition Recursion & Dynamic Programming\nThe problem can be solved by utilizing the properties of a BST, where the left subtree has all values less than the root and the right subtree has values greater than the root. We can explore both recursive and dynamic programming (DP) approaches to generate all possible combinations of unique BSTs.\n\n# Live Coding & Explenation Recursion\n\n\n# n-th Catalan number\n\nIn the context of this task, the \\(n\\)-th Catalan number gives the number of distinct binary search trees that can be formed with \\(n\\) unique values. The \\(n\\)-th Catalan number is given by the formula:\n\n$$\nC_n = \\frac{1}{n+1} \\binom{2n}{n} = \\frac{(2n)!}{(n+1)!n!}\n$$\n\nThe time and space complexity of generating these trees are both $$O(C_n)$$, which is equivalent to $$O\\left(\\frac{4^n}{n\\sqrt{n}}\\right)$$.\n\nHere\'s how it relates to the task:\n\n1. **Choosing the Root**: For each root value, we\'re essentially dividing the problem into two subproblems (left and right subtrees), and the number of combinations for each division aligns with the recursive definition of the Catalan numbers.\n \n2. **Recursive and Dynamic Programming Solutions**: Both approaches inherently follow the recursive nature of the Catalan numbers. The recursive approach directly corresponds to the recursive formula for the Catalan numbers, while the dynamic programming approach leverages the computed results for smaller subproblems to build up to the solution.\n\n3. **Number of Unique BSTs**: The fact that there are \\(C_n\\) unique BSTs with \\(n\\) nodes is a direct application of the Catalan numbers. The complexity of generating all these trees is thus closely tied to the value of the \\(n\\)-th Catalan number.\n\nIn conclusion, the complexity of the problem is inherently linked to the Catalan numbers, as they precisely describe the number of unique structures that can be formed, which in turn dictates the computational resources required to enumerate them.\n\n# Approach Short\n\n1. **Recursion**: Recursively construct left and right subtrees and combine them with each root.\n2. **Dynamic Programming**: Use dynamic programming to store the result of subproblems (subtrees) and utilize them for constructing unique BSTs.\n\n## Approach Differences\nThe recursive approach constructs the trees from scratch every time, while the DP approach reuses previously computed subtrees to avoid redundant work.\n\n# Approach Recursion\n\nThe recursive approach involves the following steps:\n\n1. **Base Case**: If the start index is greater than the end index, return a list containing `None`. This represents an empty tree and serves as the base case for the recursion.\n\n2. **Choose Root**: For every number \\( i \\) in the range from `start` to `end`, consider \\( i \\) as the root of the tree.\n\n3. **Generate Left Subtrees**: Recursively call the function to generate all possible left subtrees using numbers from `start` to \\( i-1 \\). This forms the left child of the root.\n\n4. **Generate Right Subtrees**: Recursively call the function to generate all possible right subtrees using numbers from \\( i+1 \\) to `end`. This forms the right child of the root.\n\n5. **Combine Subtrees**: For each combination of left and right subtrees, create a new tree with \\( i \\) as the root and the corresponding left and right subtrees. Append this tree to the list of all possible trees.\n\n6. **Return Trees**: Finally, return the list of all trees generated.\n\n# Complexity Recursion\n- Time complexity: $$O(\\frac{4^n}{n\\sqrt{n}})$$\n- Space complexity: $$ O(\\frac{4^n}{n\\sqrt{n}}) $$\n\n# Performance Recursion\n\n| Language | Runtime (ms) | Beats (%) | Memory (MB) | Beats (%) |\n|------------|--------------|-----------|-------------|-----------|\n| Rust | 0 | 100 | 2.5 | 80 |\n| Java | 1 | 99.88 | 43.7 | 66.87 |\n| Go | 3 | 56.88 | 4.4 | 63.30 |\n| C++ | 16 | 75.53 | 16.2 | 20.99 |\n| Python3 | 53 | 97.4 | 18.1 | 27.83 |\n| JavaScript | 74 | 89.61 | 48.4 | 55.19 |\n| C# | 91 | 88.76 | 39.8 | 19.10 |\n\n![performance_recursion_updated.png]()\n\n\n# Code Recursion\n``` Python []\nclass Solution:\n def generateTrees(self, n: int):\n def generate_trees(start, end):\n if start > end:\n return [None,]\n \n all_trees = []\n for i in range(start, end + 1):\n left_trees = generate_trees(start, i - 1)\n right_trees = generate_trees(i + 1, end)\n \n for l in left_trees:\n for r in right_trees:\n current_tree = TreeNode(i)\n current_tree.left = l\n current_tree.right = r\n all_trees.append(current_tree)\n \n return all_trees\n \n return generate_trees(1, n) if n else []\n```\n``` C++ []\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return n ? generate_trees(1, n) : vector<TreeNode*>();\n }\n\nprivate:\n vector<TreeNode*> generate_trees(int start, int end) {\n if (start > end) return {nullptr};\n\n vector<TreeNode*> all_trees;\n for (int i = start; i <= end; i++) {\n vector<TreeNode*> left_trees = generate_trees(start, i - 1);\n vector<TreeNode*> right_trees = generate_trees(i + 1, end);\n\n for (TreeNode* l : left_trees) {\n for (TreeNode* r : right_trees) {\n TreeNode* current_tree = new TreeNode(i);\n current_tree->left = l;\n current_tree->right = r;\n all_trees.push_back(current_tree);\n }\n }\n }\n return all_trees;\n }\n};\n```\n``` Java []\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return n > 0 ? generate_trees(1, n) : new ArrayList<>();\n }\n\n private List<TreeNode> generate_trees(int start, int end) {\n List<TreeNode> all_trees = new ArrayList<>();\n if (start > end) {\n all_trees.add(null);\n return all_trees;\n }\n\n for (int i = start; i <= end; i++) {\n List<TreeNode> left_trees = generate_trees(start, i - 1);\n List<TreeNode> right_trees = generate_trees(i + 1, end);\n\n for (TreeNode l : left_trees) {\n for (TreeNode r : right_trees) {\n TreeNode current_tree = new TreeNode(i);\n current_tree.left = l;\n current_tree.right = r;\n all_trees.add(current_tree);\n }\n }\n }\n return all_trees;\n }\n}\n```\n``` JavaScript []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n function generate_trees(start, end) {\n if (start > end) return [null];\n\n const all_trees = [];\n for (let i = start; i <= end; i++) {\n const left_trees = generate_trees(start, i - 1);\n const right_trees = generate_trees(i + 1, end);\n\n for (const l of left_trees) {\n for (const r of right_trees) {\n const current_tree = new TreeNode(i);\n current_tree.left = l;\n current_tree.right = r;\n all_trees.push(current_tree);\n }\n }\n }\n return all_trees;\n }\n\n return generate_trees(1, n);\n};\n```\n``` C# []\npublic class Solution {\n public IList<TreeNode> GenerateTrees(int n) {\n return n > 0 ? GenerateTrees(1, n) : new List<TreeNode>();\n }\n\n private IList<TreeNode> GenerateTrees(int start, int end) {\n if (start > end) return new List<TreeNode> {null};\n\n var all_trees = new List<TreeNode>();\n for (int i = start; i <= end; i++) {\n var left_trees = GenerateTrees(start, i - 1);\n var right_trees = GenerateTrees(i + 1, end);\n\n foreach (var l in left_trees) {\n foreach (var r in right_trees) {\n var current_tree = new TreeNode(i, l, r);\n all_trees.Add(current_tree);\n }\n }\n }\n return all_trees;\n }\n}\n```\n``` Rust []\nuse std::rc::Rc;\nuse std::cell::RefCell;\n\nimpl Solution {\n pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if n == 0 {\n return Vec::new();\n }\n Self::generate(1, n)\n }\n\n fn generate(start: i32, end: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if start > end {\n return vec![None];\n }\n\n let mut all_trees = Vec::new();\n for i in start..=end {\n let left_trees = Self::generate(start, i - 1);\n let right_trees = Self::generate(i + 1, end);\n\n for l in &left_trees {\n for r in &right_trees {\n let current_tree = Some(Rc::new(RefCell::new(TreeNode::new(i))));\n current_tree.as_ref().unwrap().borrow_mut().left = l.clone();\n current_tree.as_ref().unwrap().borrow_mut().right = r.clone();\n all_trees.push(current_tree);\n }\n }\n }\n all_trees\n }\n}\n```\n``` Go []\nfunc generateTrees(n int) []*TreeNode {\n\tif n == 0 {\n\t\treturn []*TreeNode{}\n\t}\n\treturn generate(1, n)\n}\n\nfunc generate(start, end int) []*TreeNode {\n\tif start > end {\n\t\treturn []*TreeNode{nil}\n\t}\n\n\tvar allTrees []*TreeNode\n\tfor i := start; i <= end; i++ {\n\t\tleftTrees := generate(start, i-1)\n\t\trightTrees := generate(i+1, end)\n\n\t\tfor _, l := range leftTrees {\n\t\t\tfor _, r := range rightTrees {\n\t\t\t\tcurrentTree := &TreeNode{Val: i, Left: l, Right: r}\n\t\t\t\tallTrees = append(allTrees, currentTree)\n\t\t\t}\n\t\t}\n\t}\n\treturn allTrees\n}\n```\n\n# Approach Dynamic Programming\n\n1. **Initialization**: Create a DP table `dp` where `dp[i]` will store all the unique BSTs with `i` nodes. Initialize `dp[0]` with a single `None` value representing an empty tree.\n\n2. **Iterate Over Number of Nodes**: For every number `nodes` from 1 to `n`, iterate and construct all possible trees with `nodes` number of nodes.\n\n3. **Choose Root**: For every possible root value within the current `nodes`, iterate and use the root to build trees.\n\n4. **Use Previously Computed Subtrees**: For the chosen root, use the previously computed `dp[root - 1]` for left subtrees and `dp[nodes - root]` for right subtrees.\n\n5. **Clone Right Subtree**: Since the right subtree\'s values will be affected by the choice of the root, clone the right subtree with an offset equal to the root value. The `clone` function handles this.\n\n6. **Combine Subtrees**: Create a new tree by combining the current root with the left and right subtrees. Append this tree to `dp[nodes]`.\n\n7. **Return Result**: Finally, return the trees stored in `dp[n]`.\n\n# Complexity Dynamic Programming\n- Time complexity: $$O(\\frac{4^n}{n\\sqrt{n}})$$\n- Space complexity: $$ O(\\frac{4^n}{n\\sqrt{n}}) $$\n\n# Performance Dynamic Programming\n\n| Language | Runtime (ms) | Beats (%) | Memory (MB) | Beats (%) |\n|------------|--------------|-----------|-------------|-----------|\n| Rust | 0 | 100 | 2.7 | 20 |\n| Java | 1 | 99.88 | 44.1 | 8.87 |\n| Go | 3 | 56.88 | 4.2 | 90.83 |\n| C++ | 10 | 96.72 | 12.5 | 86.56 |\n| JavaScript | 67 | 96.75 | 48.5 | 55.19 |\n| Python3 | 49 | 98.84 | 18.1 | 21.91 |\n| C# | 91 | 88.76 | 38.5 | 80.90 |\n\n![performance_dynamic_programming.png]()\n\n\n# Code Dynamic Programming\n``` Python []\nclass Solution:\n def generateTrees(self, n: int):\n if n == 0:\n return []\n\n dp = [[] for _ in range(n + 1)]\n dp[0].append(None)\n for nodes in range(1, n + 1):\n for root in range(1, nodes + 1):\n for left_tree in dp[root - 1]:\n for right_tree in dp[nodes - root]:\n root_node = TreeNode(root)\n root_node.left = left_tree\n root_node.right = self.clone(right_tree, root)\n dp[nodes].append(root_node)\n return dp[n]\n \n def clone(self, n: TreeNode, offset: int) -> TreeNode:\n if n:\n node = TreeNode(n.val + offset)\n node.left = self.clone(n.left, offset)\n node.right = self.clone(n.right, offset)\n return node\n return None\n```\n``` C++ []\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) return {};\n\n vector<vector<TreeNode*>> dp(n + 1);\n dp[0].push_back(nullptr);\n for (int nodes = 1; nodes <= n; nodes++) {\n for (int root = 1; root <= nodes; root++) {\n for (TreeNode* left_tree : dp[root - 1]) {\n for (TreeNode* right_tree : dp[nodes - root]) {\n TreeNode* root_node = new TreeNode(root);\n root_node->left = left_tree;\n root_node->right = clone(right_tree, root);\n dp[nodes].push_back(root_node);\n }\n }\n }\n }\n return dp[n];\n }\n\nprivate:\n TreeNode* clone(TreeNode* n, int offset) {\n if (n == nullptr) return nullptr;\n TreeNode* node = new TreeNode(n->val + offset);\n node->left = clone(n->left, offset);\n node->right = clone(n->right, offset);\n return node;\n }\n};\n```\n``` Java []\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) return new ArrayList<>();\n\n List<TreeNode>[] dp = new ArrayList[n + 1];\n dp[0] = new ArrayList<>();\n dp[0].add(null);\n for (int nodes = 1; nodes <= n; nodes++) {\n dp[nodes] = new ArrayList<>();\n for (int root = 1; root <= nodes; root++) {\n for (TreeNode left_tree : dp[root - 1]) {\n for (TreeNode right_tree : dp[nodes - root]) {\n TreeNode root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].add(root_node);\n }\n }\n }\n }\n return dp[n];\n }\n\n private TreeNode clone(TreeNode n, int offset) {\n if (n == null) return null;\n TreeNode node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n }\n}\n```\n``` JavaScript []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n const dp = Array.from({ length: n + 1 }, () => []);\n dp[0].push(null);\n for (let nodes = 1; nodes <= n; nodes++) {\n for (let root = 1; root <= nodes; root++) {\n for (const left_tree of dp[root - 1]) {\n for (const right_tree of dp[nodes - root]) {\n const root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].push(root_node);\n }\n }\n }\n }\n return dp[n];\n};\n\nfunction clone(n, offset) {\n if (n === null) return null;\n const node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n}\n```\n``` C# []\npublic class Solution {\n public IList<TreeNode> GenerateTrees(int n) {\n if (n == 0) return new List<TreeNode>();\n\n var dp = new List<TreeNode>[n + 1];\n dp[0] = new List<TreeNode> { null };\n for (int nodes = 1; nodes <= n; nodes++) {\n dp[nodes] = new List<TreeNode>();\n for (int root = 1; root <= nodes; root++) {\n foreach (var left_tree in dp[root - 1]) {\n foreach (var right_tree in dp[nodes - root]) {\n TreeNode root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = Clone(right_tree, root);\n dp[nodes].Add(root_node);\n }\n }\n }\n }\n return dp[n];\n }\n\n private TreeNode Clone(TreeNode n, int offset) {\n if (n == null) return null;\n TreeNode node = new TreeNode(n.val + offset);\n node.left = Clone(n.left, offset);\n node.right = Clone(n.right, offset);\n return node;\n }\n}\n```\n``` Rust []\nuse std::rc::Rc;\nuse std::cell::RefCell;\n\nimpl Solution {\n pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if n == 0 {\n return Vec::new();\n }\n\n let mut dp = vec![Vec::new(); (n + 1) as usize];\n dp[0].push(None);\n for nodes in 1..=n {\n let mut trees_per_node = Vec::new();\n for root in 1..=nodes {\n let left_trees = &dp[(root - 1) as usize];\n let right_trees = &dp[(nodes - root) as usize];\n for left_tree in left_trees {\n for right_tree in right_trees {\n let root_node = Some(Rc::new(RefCell::new(TreeNode::new(root))));\n root_node.as_ref().unwrap().borrow_mut().left = left_tree.clone();\n root_node.as_ref().unwrap().borrow_mut().right = Solution::clone(right_tree.clone(), root);\n trees_per_node.push(root_node);\n }\n }\n }\n dp[nodes as usize] = trees_per_node;\n }\n dp[n as usize].clone()\n }\n\n fn clone(tree: Option<Rc<RefCell<TreeNode>>>, offset: i32) -> Option<Rc<RefCell<TreeNode>>> {\n tree.map(|node| {\n Rc::new(RefCell::new(TreeNode {\n val: node.borrow().val + offset,\n left: Solution::clone(node.borrow().left.clone(), offset),\n right: Solution::clone(node.borrow().right.clone(), offset),\n }))\n })\n }\n}\n```\n``` Go []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n const dp = Array.from({ length: n + 1 }, () => []);\n dp[0].push(null);\n for (let nodes = 1; nodes <= n; nodes++) {\n for (let root = 1; root <= nodes; root++) {\n for (const left_tree of dp[root - 1]) {\n for (const right_tree of dp[nodes - root]) {\n const root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].push(root_node);\n }\n }\n }\n }\n return dp[n];\n};\n\nfunction clone(n, offset) {\n if (n === null) return null;\n const node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n}\n```\n\nThe time and space complexity for both approaches are the same. The $$ O(\\frac{4^n}{n\\sqrt{n}}) $$ complexity arises from the Catalan number, which gives the number of BSTs for a given \\( n \\).\n\nI hope you find this solution helpful in understanding how to generate all structurally unique Binary Search Trees (BSTs) for a given number n. If you have any further questions or need additional clarifications, please don\'t hesitate to ask. If you understood the solution and found it beneficial, please consider giving it an upvote. Happy coding, and may your coding journey be filled with success and satisfaction! \uD83D\uDE80\uD83D\uDC68\u200D\uD83D\uDCBB\uD83D\uDC69\u200D\uD83D\uDCBB
9,328
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
2,514
12
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n Map<Pair<Integer, Integer>, List<TreeNode>> dp; \n public List<TreeNode> generateTrees(int n) {\n dp = new HashMap<>();\n return helper(1, n);\n }\n \n public List<TreeNode> helper(int start, int end) {\n List<TreeNode> variations = new ArrayList<>();\n if (start > end) {\n variations.add(null);\n return variations;\n }\n if (dp.containsKey(new Pair<>(start, end))) {\n return dp.get(new Pair<>(start, end));\n }\n for (int i = start; i <= end; ++i) {\n List<TreeNode> leftSubTrees = helper(start, i - 1);\n List<TreeNode> rightSubTrees = helper(i + 1, end);\n for (TreeNode left: leftSubTrees) {\n for (TreeNode right: rightSubTrees) {\n TreeNode root = new TreeNode(i, left, right);\n variations.add(root);\n }\n }\n }\n dp.put(new Pair<>(start, end), variations);\n return variations;\n } \n}\n```\n\n```\nclass Solution {\npublic:\n map<pair<int, int>, vector<TreeNode*>> dp; \n \n vector<TreeNode*> generateTrees(int n) {\n return helper(1, n);\n }\n \n vector<TreeNode*> helper(int start, int end) {\n vector<TreeNode*> variations;\n if (start > end) {\n variations.push_back(nullptr);\n return variations;\n }\n if (dp.find(make_pair(start, end)) != dp.end()) {\n return dp[make_pair(start, end)];\n }\n for (int i = start; i <= end; ++i) {\n vector<TreeNode*> leftSubTrees = helper(start, i - 1);\n vector<TreeNode*> rightSubTrees = helper(i + 1, end);\n for (TreeNode* left : leftSubTrees) {\n for (TreeNode* right : rightSubTrees) {\n TreeNode* root = new TreeNode(i);\n root->left = left;\n root->right = right;\n variations.push_back(root);\n }\n }\n }\n dp[make_pair(start, end)] = variations;\n return variations;\n }\n};\n\n```\n\n```\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def helper(start, end):\n variations = []\n if start > end:\n variations.append(None)\n return variations\n if (start, end) in dp:\n return dp[(start, end)]\n for i in range(start, end + 1):\n leftSubTrees = helper(start, i - 1)\n rightSubTrees = helper(i + 1, end)\n for left in leftSubTrees:\n for right in rightSubTrees:\n root = TreeNode(i)\n root.left = left\n root.right = right\n variations.append(root)\n dp[(start, end)] = variations\n return variations\n \n dp = {}\n return helper(1, n)\n\n```
9,333
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
2,842
24
# Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculation of the range. left range should be between start and current root - 1 as end value because all values of left side must be smaller than current root. right range should be between current root + 1 and end becuase all values on the right side should be greater than current root value.\n\nThrid is we call the same funtion recursively, so it\'s good idea to keep results of current start and end, so that we can use the results later. It\'s time saving.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\n\n\n# Subscribe to my channel from here. I have 240 videos as of August 5th\n\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Define a class `Solution` containing a method `generateTrees` which takes an integer `n` as input and returns a list of optional `TreeNode` objects.\n\n2. Check if `n` is 0. If it is, return an empty list since there are no possible trees with 0 nodes.\n\n3. Initialize an empty dictionary called `memo`. This dictionary will be used to store previously computed results for specific ranges of values to avoid redundant calculations.\n\n4. Define an inner function called `generate_trees` that takes two parameters: `start` and `end`, which represent the range of values for which binary search trees need to be generated.\n\n5. Inside the `generate_trees` function:\n - Check if the tuple `(start, end)` exists as a key in the `memo` dictionary. If it does, return the corresponding value from the `memo` dictionary.\n - Initialize an empty list called `trees`. This list will store the generated trees for the current range.\n - If `start` is greater than `end`, append `None` to the `trees` list, indicating an empty subtree, and return the `trees` list.\n - Loop through each value `root_val` in the range `[start, end]` (inclusive):\n - Recursively call the `generate_trees` function for the left subtree with the range `[start, root_val - 1]` and store the result in `left_trees`.\n - Recursively call the `generate_trees` function for the right subtree with the range `[root_val + 1, end]` and store the result in `right_trees`.\n - Nested loop through each combination of `left_tree` in `left_trees` and `right_tree` in `right_trees`:\n - Create a new `TreeNode` instance with `root_val` as the value, `left_tree` as the left child, and `right_tree` as the right child.\n - Append the new `TreeNode` to the `trees` list.\n - Store the `trees` list in the `memo` dictionary with the key `(start, end)`.\n - Return the `trees` list.\n\n6. Outside the `generate_trees` function, call `generate_trees` initially with arguments `1` and `n` to generate all unique binary search trees with `n` nodes.\n\n7. Return the list of generated trees.\n\nThis algorithm generates all possible unique binary search trees with `n` nodes by considering different ranges of root values and recursively generating left and right subtrees for each possible root value. The `memo` dictionary is used to store previously computed results, reducing redundant calculations and improving the efficiency of the algorithm.\n\n# Complexity\n- Time complexity: O(C(n))\nC is Catalan number.\n\n- Space complexity: O(C(n))\nC is Catalan number.\n\nCatalan number\n\n\n```python []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n if n == 0:\n return []\n \n memo = {}\n\n def generate_trees(start, end):\n if (start, end) in memo:\n return memo[(start, end)]\n \n trees = []\n if start > end:\n trees.append(None)\n return trees\n \n for root_val in range(start, end + 1):\n left_trees = generate_trees(start, root_val - 1)\n right_trees = generate_trees(root_val + 1, end)\n \n for left_tree in left_trees:\n for right_tree in right_trees:\n root = TreeNode(root_val, left_tree, right_tree)\n trees.append(root)\n \n memo[(start, end)] = trees\n return trees\n\n return generate_trees(1, n)\n```\n```javascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {number} n\n * @return {TreeNode[]}\n */\nvar generateTrees = function(n) {\n if (n === 0) {\n return [];\n }\n \n const memo = new Map();\n\n function generateTreesHelper(start, end) {\n if (memo.has(`${start}-${end}`)) {\n return memo.get(`${start}-${end}`);\n }\n \n const trees = [];\n if (start > end) {\n trees.push(null);\n return trees;\n }\n \n for (let rootVal = start; rootVal <= end; rootVal++) {\n const leftTrees = generateTreesHelper(start, rootVal - 1);\n const rightTrees = generateTreesHelper(rootVal + 1, end);\n \n for (const leftTree of leftTrees) {\n for (const rightTree of rightTrees) {\n const root = new TreeNode(rootVal, leftTree, rightTree);\n trees.push(root);\n }\n }\n }\n \n memo.set(`${start}-${end}`, trees);\n return trees;\n }\n\n return generateTreesHelper(1, n); \n};\n```\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n \n Map<String, List<TreeNode>> memo = new HashMap<>();\n\n return generateTreesHelper(1, n, memo); \n }\n\n private List<TreeNode> generateTreesHelper(int start, int end, Map<String, List<TreeNode>> memo) {\n String key = start + "-" + end;\n if (memo.containsKey(key)) {\n return memo.get(key);\n }\n \n List<TreeNode> trees = new ArrayList<>();\n if (start > end) {\n trees.add(null);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n List<TreeNode> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n List<TreeNode> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode leftTree : leftTrees) {\n for (TreeNode rightTree : rightTrees) {\n TreeNode root = new TreeNode(rootVal);\n root.left = leftTree;\n root.right = rightTree;\n trees.add(root);\n }\n }\n }\n \n memo.put(key, trees);\n return trees;\n }\n}\n```\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) {\n return vector<TreeNode*>();\n }\n \n unordered_map<string, vector<TreeNode*>> memo;\n\n return generateTreesHelper(1, n, memo); \n }\n\nprivate:\n vector<TreeNode*> generateTreesHelper(int start, int end, unordered_map<string, vector<TreeNode*>>& memo) {\n string key = to_string(start) + "-" + to_string(end);\n if (memo.find(key) != memo.end()) {\n return memo[key];\n }\n \n vector<TreeNode*> trees;\n if (start > end) {\n trees.push_back(nullptr);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n vector<TreeNode*> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n vector<TreeNode*> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode* leftTree : leftTrees) {\n for (TreeNode* rightTree : rightTrees) {\n TreeNode* root = new TreeNode(rootVal);\n root->left = leftTree;\n root->right = rightTree;\n trees.push_back(root);\n }\n }\n }\n \n memo[key] = trees;\n return trees;\n } \n};\n```\n
9,337
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
33,589
191
If only LeetCode had a `TreeNode(val, left, right)` constructor... sigh. Then I wouldn't need to provide my own and my solution would be six lines instead of eleven.\n\n def generateTrees(self, n):\n def node(val, left, right):\n node = TreeNode(val)\n node.left = left\n node.right = right\n return node\n def trees(first, last):\n return [node(root, left, right)\n for root in range(first, last+1)\n for left in trees(first, root-1)\n for right in trees(root+1, last)] or [None]\n return trees(1, n)\n\nOr even just **four** lines, if it's not forbidden to add an optional argument:\n\n def node(val, left, right):\n node = TreeNode(val)\n node.left = left\n node.right = right\n return node\n \n class Solution:\n def generateTrees(self, last, first=1):\n return [node(root, left, right)\n for root in range(first, last+1)\n for left in self.generateTrees(root-1, first)\n for right in self.generateTrees(last, root+1)] or [None]\n\nJust another version, using loops instead of list comprehension:\n\n def generateTrees(self, n):\n def generate(first, last):\n trees = []\n for root in range(first, last+1):\n for left in generate(first, root-1):\n for right in generate(root+1, last):\n node = TreeNode(root)\n node.left = left\n node.right = right\n trees += node,\n return trees or [None]\n return generate(1, n)
9,352
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
4,561
41
**Idea:**\nWe will use a recursive helper function that recieves a range (within n) and returns all subtrees in that range.\nWe have a few cases:\n1. if `start > end`, which is not supposed to happen, we return a list that contains only a null.\n2. if `start == end` it means we reached a leaf and we will return a list containing a tree that has only that node.\n3. Otherwise:\nfor each option of root, we get all possible subtrees with that root for `left` and `right` children.\nThen for each possible pair of `left` and `right` we add to the result a new tree.\n\n**C++:**\n```\nclass Solution {\npublic:\n vector<TreeNode*> rec(int start, int end) {\n vector<TreeNode*> res;\n if (start > end) return {NULL};\n \n if (start == end) return {new TreeNode(start)};\n \n for (int i = start; i <= end; i++) {\n vector<TreeNode*> left = rec(start, i-1), right = rec(i+1, end);\n \n for (auto l : left)\n for (auto r : right)\n res.push_back(new TreeNode(i, l, r));\n }\n return res;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n vector<TreeNode*> res = rec(1, n);\n return res;\n }\n};\n```\n**Python:**\n```\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def rec(start, end):\n\t\t\n if start > end:\n return [None]\n\t\t\t\t\n if start == end:\n return [TreeNode(start)]\n ret_list = []\n\t\t\t\n for i in range(start, end+1):\n left = rec(start, i-1)\n right = rec(i+1, end)\n for pair in product(left, right):\n ret_list.append(TreeNode(i, pair[0], pair[1]))\n \n return ret_list\n \n res = rec(1,n)\n return res\n```\n**Like it? please upvote!**
9,361
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
2,934
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo generate all structurally unique BST\'s with n nodes, we can use a recursive approach. The idea is to fix each number i (1 <= i <= n) as the root of the tree and then recursively generate all the left and right subtrees that can be formed using the remaining numbers (1, 2, ..., i-1) and (i+1, i+2, ..., n) respectively.\n\nFor example, to generate all the BST\'s with 3 nodes, we can fix 1 as the root and recursively generate all the BST\'s with 0 and 2 nodes respectively. Then we can fix 2 as the root and recursively generate all the BST\'s with 1 node on the left and 1 node on the right. Finally, we can fix 3 as the root and recursively generate all the BST\'s with 2 and 0 nodes respectively.\n\nTo avoid generating duplicate trees, we can use memoization to store the trees generated for each combination of left and right subtree sizes.\n\n# Complexity\n- Time complexity:\nBeats\n89.57%\n\n- Space complexity:\nBeats\n94.15%\n\n# Code\n```\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def generateTrees(self, n: \'int\') -> \'List[TreeNode]\':\n memo = {}\n \n def generate_trees_helper(start: int, end: int) -> List[TreeNode]:\n if start > end:\n return [None]\n \n if (start, end) in memo:\n return memo[(start, end)]\n \n result = []\n \n for i in range(start, end+1):\n left_subtrees = generate_trees_helper(start, i-1)\n right_subtrees = generate_trees_helper(i+1, end)\n \n for left in left_subtrees:\n for right in right_subtrees:\n root = TreeNode(i)\n root.left = left\n root.right = right\n result.append(root)\n \n memo[(start, end)] = result\n \n return result\n \n return generate_trees_helper(1, n)\n```
9,369
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
null
14,522
70
class Solution(object):\n def generateTrees(self, n):\n """\n :type n: int\n :rtype: List[TreeNode]\n """\n if n == 0:\n return [[]]\n return self.dfs(1, n+1)\n \n def dfs(self, start, end):\n if start == end:\n return None\n result = []\n for i in xrange(start, end):\n for l in self.dfs(start, i) or [None]:\n for r in self.dfs(i+1, end) or [None]:\n node = TreeNode(i)\n node.left, node.right = l, r\n result.append(node)\n return result\n\nUse start/end instead of actual nodes to bosst the program.
9,385
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
5,427
85
First of all, I am so happy because I was able to solve this problem without any help :) So, I am going to explained how I improved my DP skills. Of course, this is a "medium" question and I still struggle with the hard ones but I can see some improvement and I want to share my tips with you.\n\n***How to understand if a problem is DP problem?***\nWell, I still struggle to understand that for some problem types but basically if you think that you can solve the problem easily by knowing the solution for previous values(like the solution on the previous grids for 2D cases or the solution for n-1 etc.), it is probably a DP problem.\n\nDP problems are usually an iterative version of a recursive solution. I find it easy to think about recursive solution first and then convert it to DP. \n\n**1. Recursive + Memoization**\n\nWe need to calculate how many possible trees can be made. \nIf there is only ```1``` node then it is easy. The answer is 1. \nFor ```2``` we can construct ```2``` different trees: One of the node is root, the second one can either be a left child or right child.\n```\nn = 2\n\n 1 1\n / or \\\n2\t 2\n```\nEasy!\nWhat about n=3?\n```\n 1 3 3 2 1\n \\ / / / \\ \\\n\t---------------------------------- Let\'s cut the trees from here\n 3 2 1 1 3 2\n / / \\ \\\n 2 1 2 3\n ```\nAs you can see, from where we cut, the bottom of the tree is actually another tree where the same logic applies. So the only thing we need to decide is how to distrubute the remaining nodes to childs of the root. The options can be:\n```\n------num of nodes------\nleft_child right_child\n 0 2 --> These are the subtrees, like the new trees with n = 0 and n = 2\n 1 1\n 2 0\n```\nTo find how many possible solutions are there for n=3, add up all these possibilities . We can call the same function for calculating the values in all the options because it is actually the same problem. \nTo sum up, we picked the root and then we need to decide on how the left and right subtrees will look like. The options are how many nodes can be on the left and right subtree at the same time.\n\n```\n -------------- 3 ---------------\n\t /\t\t | \\\n / \\\t / \\\t \t /\t \\\n 0 --2-- 1 1 --2-- 0\n / \\ / \\ \n\t /\\ /\\ /\\ /\\\n\t1 0 0 1 1 0 0 1\n\n```\nHere is my attempt to draw the recursion tree. Even for a small n value there are multiple overlapping problems. So I used a memoization table and saved the values on that table before returning the total value from the function and if the value that we are looking for exists on the table, return that value without doing any extra calculations.\n\nHere is the code:\n\n```\nclass Solution:\n def numTrees(self, n: int) -> int:\n self.table = [-1] * (n+1)\n self.table[0] = 1\n return self.numTreesRec(n)\n \n def numTreesRec(self, n):\n if self.table[n] != -1:\n return self.table[n]\n total = 0\n for m in range(n):\n total += (self.numTreesRec(n-1-m) * self.numTreesRec(m))\n self.table[n] = total\n return total\n```\n\n**2. Dynamic Programming**\nNow, we have our recursive solution. As you can see from the above recursion tree, values are calculated starting from 0 and then 1 and goes like this until n. The means we can do it iteratively. We can start from 1 (n=0 are our base case) and calculate the values upto n. So, I created a dp table and the solution for n = i is stored at dp[i]. Now, if we go back to our example, for n=3:\n```\n0 2 \n1 1\n2 0\n```\nWe have these options for distributing the remaining nodes to subtrees. We already calculated the values for 0, 1 and 2 because we used iterative approach. Therefore solution for dp[3] will be\n```\ndp[3] = dp[0] * dp[2] + dp[1] * dp[1] + dp[2] * dp[0]\n```\n\nwhich is done by the inner for loop in the code.\n\nHere is the code:\n\n```\nclass Solution:\n def numTrees(self, n: int) -> int:\n dp = [0] * (n+1)\n dp[0] = 1\n for i in range(1, n+1):\n for j in range(i):\n dp[i] += dp[j] * dp[i- 1 - j]\n return dp[n]\n```\n\nThe time complexity is O(n^2) and the space complexity is O(n). There is a better solution by using catalan numbers. \n\nI tried my best to explain how I think when solving a dp problem. Hope that it helps and don\'t worry if you are having diffuculties. Practice makes perfect!
9,434
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
4,419
25
# **Java Solution (Dynamic Programming Approach):**\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Unique Binary Search Trees.\n```\nclass Solution {\n public int numTrees(int n) {\n // Create \'sol\' array of length n+1...\n int[] sol = new int[n+1];\n // The value of the first index will be 1.\n sol[0] = 1;\n // Run a loop from 1 to n+1...\n for(int i = 1; i <= n; i++) {\n // Within the above loop, run a nested loop from 0 to i...\n for(int j = 0; j < i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n }\n}\n```\n\n# **C++ Solution (Dynamic Programming Approach):**\n```\nclass Solution {\npublic:\n int numTrees(int n) {\n // If n <= 1, then return 1\n if (n <= 1) {\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0return 1;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n // Create \'sol\' array of length n+1...\n vector<int> sol(n+1, 0);\n // The value of the first and second index will be 1.\n sol[0] = sol[1] = 1;\n // Run a loop from 2 to n...\n for (int i = 2; i <= n; ++i) {\n // within the above loop, run a nested loop from 0 to i...\n for (int j = 0; j < i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n }\n};\n```\n\n# **Python Solution (Dynamic Programming Approach):**\nRuntime: 17 ms, faster than 90.77% of Python online submissions for Unique Binary Search Trees.\n```\nclass Solution(object):\n def numTrees(self, n):\n if n == 0 or n == 1:\n return 1\n # Create \'sol\' array of length n+1...\n sol = [0] * (n+1)\n # The value of the first index will be 1.\n sol[0] = 1\n # Run a loop from 1 to n+1...\n for i in range(1, n+1):\n # Within the above loop, run a nested loop from 0 to i...\n for j in range(i):\n # Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1]\n # Return the value of the nth index of the array to get the solution...\n return sol[n]\n```\n \n# **JavaScript Solution (Dynamic Programmming Approach):**\n```\nvar numTrees = function(n) {\n // Create \'sol\' array to store the solution...\n var sol = [1, 1];\n // Run a loop from 2 to n...\n for (let i = 2; i <= n; i++) {\n sol[i] = 0;\n // Within the above loop, run a nested loop from 1 to i...\n for (let j = 1; j <= i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[i - j] * sol[j - 1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n};\n```\n\n# **C Language (Catalan Math Approach):**\nRuntime: 0 ms, faster than 100.00% of C online submissions for Unique Binary Search Trees.\n```\nint numTrees(int n){\n long sol = 1;\n for (int i = 0; i < n; ++i) {\n sol = sol * 2 * (2 * i + 1) / (i + 2);\n }\n return (int) sol;\n}\n```\n\n# **Python3 Solution (Catalan Math Approach):**\n```\nclass Solution:\n def numTrees(self, n: int) -> int:\n sol = 1\n for i in range (0, n):\n sol = sol * 2 * (2 * i + 1) / (i + 2)\n return int(sol)\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
9,439
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
21,322
103
\n # DP\n def numTrees1(self, n):\n res = [0] * (n+1)\n res[0] = 1\n for i in xrange(1, n+1):\n for j in xrange(i):\n res[i] += res[j] * res[i-1-j]\n return res[n]\n \n # Catalan Number (2n)!/((n+1)!*n!) \n def numTrees(self, n):\n return math.factorial(2*n)/(math.factorial(n)*math.factorial(n+1))
9,458
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
1,086
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSolution for Leetcode 96. Unique Binary Search Trees:\n\nTo solve this problem, we can use the dynamic programming approach. Let\'s create an array dp of size n + 1, where dp[i] represents the number of unique BSTs that can be formed using i nodes.\n\nThe base cases are dp[0] = 1 and dp[1] = 1, as there is only one unique BST that can be formed using zero and one node(s) respectively.\n\nFor i nodes, we can select a root node in i different ways, and then recursively calculate the number of unique BSTs in the left and right subtrees. Finally, we can multiply the number of unique BSTs in the left and right subtrees and add it to the total count.\n\nTherefore, for i nodes, the number of unique BSTs that can be formed is given by the formula:\n```\ndp[i] = dp[0]*dp[i-1] + dp[1]*dp[i-2] + ... + dp[i-1]*dp[0]\n```\nThe above formula takes into account all the possible combinations of left and right subtrees.\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n) Beats\n95.38%\n\n# Code\n```\nclass Solution:\n def numTrees(self, n: int) -> int:\n # initialize the dp array with base cases\n dp = [0] * (n + 1)\n dp[0] = dp[1] = 1\n \n # calculate the number of unique BSTs for i nodes\n for i in range(2, n + 1):\n for j in range(1, i + 1):\n dp[i] += dp[j - 1] * dp[i - j]\n \n return dp[n]\n\n```
9,462
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
8,364
69
Let\'s look at a naive recursive algorithm:\n\nSuppose you are given 1--n, and you want to generate all binary search trees. How do you do it? Suppose you put number i on the root, then simply\n\n 1. Generate all BST on the left branch by running the same algorithm\n with 1--(i-1), \n 2. Generate all BST on the right branch by running the\n same algorithm with (i+1)--n.\n 3. Take all combinations of left branch\n and right branch, and that\'s it for i on the root.\n\nThen you let i go from 1 to n. And that\'s it. If you want to write it in code, it\'s like\n\n def countTrees(n):\n if n == 0:\n return 1\n if n == 1:\n return 1\n \n Result = 0\n for i in xrange(n):\n LeftTrees = countTrees(i)\n RightTrees = countTrees(n - i - 1)\n Result += LeftTrees * RightTrees\n return Result\n\nThe only problem is, it\'s very slow, because for large n, you\'ll need to calculate `countTrees(i)` many many times, where i is a small number. Naturally, to speed it up, you just need to remember the result of `countTrees(i)`, so that when you need it next time, you don\'t need to calculate. Let\'s do that explicitly by having a list of n+1 numbers to store the calculation result!\n\n def countTrees(n, cache):\n if n == 0:\n return 1\n if n == 1:\n return 1\n \n if cache[n] != -1: # -1 means we don\'t know countTrees(n) yet.\n return cache[n]\n \n Result = 0\n for i in xrange(n):\n LeftTrees = countTrees(i, cache)\n RightTrees = countTrees(n - i - 1, cache)\n Result += LeftTrees * RightTrees\n cache[n] = Result\n return Result
9,477
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
2,260
19
Hi,\n\nI solved this problem by using recursion + memoization.\nThe result is close to the DP solution.\n\n```\ndef numTrees(self, n: int) -> int:\n return self.count_bsts(1, n, {})\n \ndef count_bsts(self, min_val: int, max_val: int, memo: dict) -> int:\n\tif min_val >= max_val:\n\t\treturn 1\n\n\telif (min_val, max_val) in memo:\n\t\treturn memo[(min_val, max_val)]\n\n\tbsts_count = 0\n\tfor val in range(min_val, max_val + 1):\n\n\t\tleft_subtrees_count = self.count_bsts(min_val, val - 1, memo)\n\t\tright_subtrees_count = self.count_bsts(val + 1, max_val, memo)\n\n\t\tbsts_count += left_subtrees_count * right_subtrees_count\n\n\tmemo[(min_val, max_val)] = bsts_count\n \n\treturn bsts_count\n\t\n```
9,497
Unique Binary Search Trees
unique-binary-search-trees
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
null
297
5
```\n/*\n if we try to break this problem, we realize we can solve this using recursion\n for n = 1, number of trees that can be formed is 1\n for n = 2, number of trees that can be formed is 2\n for n = 3,\n we have to consider three cases:\n when root is 1:\n left subtree is empty\n right subtree can have two nodes 2, 3 so possible trees that can be made is 2\n \n when root is 2\n left subtree can have 1 node i.e. 1\n right subtree can have 1 node i.e. 3\n hence total trees with root as 2 can be 1\n \n when root is 3\n left subtree can have two nodes i.e. 1, 2 so possible trees that can be made using\n the two nodes will be 2\n hence there can be 2 subtrees with root as 3\n total trees with n=3 will be 2 + 1 + 2 = 5\n \n we apply the same logic for greater values of n\n we can use memoization to avoid solving the same overlapping problem again\n \n */\n```\n\n```\nclass Solution:\n\n def numTrees(self, n: int) -> int:\n question_bank = {}\n def fun(n):\n if n == 0 or n == 1:\n return 1\n if n == 2:\n return 2\n if n in question_bank:\n return question_bank[n]\n count = 0\n for i in range(1, n+1):\n left = i - 1\n right = n - i \n sub_left = fun(left)\n sub_right = fun(right)\n count += sub_left * sub_right\n question_bank[n] = count\n return question_bank[n]\n return fun(n)\n```
9,498
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
18,973
185
# Interview Guide: "Interleaving String" Problem\n\n## Problem Understanding\n\nIn the "Interleaving String" problem, you are given three strings: `s1`, `s2`, and `s3`. Your task is to determine whether `s3` can be formed by interleaving `s1` and `s2`. For example, if `s1 = "aabcc"` and `s2 = "dbbca"`, then `s3 = "aadbbcbcac"` should return `true`, but `s3 = "aadbbbaccc"` should return `false`.\n\n## Key Points to Consider\n\n### 1. Understand the Constraints\n\nBefore diving into the solution, make sure you understand the problem\'s constraints. The lengths of the strings will not be more than 100 for `s1` and `s2`, and not more than 200 for `s3`. This can help you gauge the time complexity you should aim for.\n\n### 2. Multiple Approaches\n\nThere are multiple ways to solve this problem, including:\n\n - 2D Dynamic Programming\n - 1D Dynamic Programming\n - Recursion with Memoization\n\nEach method has its own time and space complexity, so choose based on the problem\'s constraints.\n\n### 3. Space Optimization\n\nWhile 2D Dynamic Programming is the most intuitive approach, you can reduce the space complexity to \\(O(\\min(m, n))\\) by employing 1D Dynamic Programming. In an interview setting, discussing this optimization can impress your interviewer.\n\n### 4. Early Exit\n\nIf the sum of the lengths of `s1` and `s2` does not match the length of `s3`, you can immediately return `false`. This can save computation time and demonstrate that you\'re mindful of edge cases.\n\n### 5. Explain Your Thought Process\n\nAlways explain your thought process and why you chose a particular approach. Discuss the trade-offs you\'re making in terms of time and space complexity.\n\n## Conclusion\n\nThe "Interleaving String" problem is an excellent example of a problem that can be tackled through Dynamic Programming or Recursion. Knowing the trade-offs between different approaches and optimizing for space can give you an edge in interviews. By taking the time to understand the problem, choosing the appropriate data structures, and optimizing your approach, you\'ll not only solve the problem but also demonstrate a well-rounded skill set.\n\n---\n\n# Live Coding & Explenation: 1D Dynamic Programming\n\n\n---\n\n# Approach: 2D Dynamic Programming \n\nTo solve the "Interleaving String" problem using 2D Dynamic Programming, we utilize a 2D array `dp[i][j]` to represent whether the substring `s3[:i+j]` can be formed by interleaving `s1[:i]` and `s2[:j]`.\n\n## Key Data Structures:\n- **dp**: A 2D list to store the results of subproblems.\n\n## Enhanced Breakdown:\n\n1. **Initialization**:\n - Calculate lengths of `s1`, `s2`, and `s3`.\n - If the sum of lengths of `s1` and `s2` is not equal to the length of `s3`, return false.\n - Initialize the `dp` array with dimensions `(m+1) x (n+1)`, setting `dp[0][0] = True`.\n \n2. **Base Cases**:\n - Fill in the first row of `dp` array, considering only the characters from `s1`.\n - Fill in the first column of `dp` array, considering only the characters from `s2`.\n \n3. **DP Loop**:\n - Loop through each possible `(i, j)` combination, starting from `(1, 1)`.\n - Update `dp[i][j]` based on the transition `dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1])`.\n\n4. **Wrap-up**:\n - Return the value stored in `dp[m][n]`, which indicates whether `s3` can be formed by interleaving `s1` and `s2`.\n\n# Complexity:\n\n**Time Complexity:** \n- The solution iterates over each possible $$ (i, j) $$ combination, leading to a time complexity of $$ O(m \\times n) $$.\n\n**Space Complexity:** \n- The space complexity is $$ O(m \\times n) $$ due to the 2D $$ dp $$ array.\n\n---\n\n# Approach: 1D Dynamic Programming \n\nThe optimization from 2D to 1D DP is based on the observation that the state of `dp[i][j]` in the 2D DP array depends only on `dp[i-1][j]` and `dp[i][j-1]`. Therefore, while iterating through the strings, the current state only depends on the states in the previous row of the 2D DP array, which means we can optimize our space complexity by just keeping track of one row (1D DP).\n\n## Key Data Structures:\n\n- **dp**: A 1D list that stores whether the substring `s3[:i+j]` can be formed by interleaving `s1[:i]` and `s2[:j]`. Initially, all values are set to `False` except `dp[0]`, which is set to `True`.\n\n## Enhanced Breakdown:\n\n1. **Initialization**:\n - First, calculate the lengths of `s1`, `s2`, and `s3`.\n - Check if the sum of the lengths of `s1` and `s2` equals the length of `s3`. If it doesn\'t, return `False` as `s3` cannot be formed by interleaving `s1` and `s2`.\n\n2. **Optimization Check**:\n - If `m < n`, swap `s1` and `s2`. This is to ensure that `s1` is not longer than `s2`, which helps in optimizing the space complexity to `O(min(m, n))`.\n\n3. **Base Cases**:\n - Initialize a 1D array `dp` of length `n+1` with `False`.\n - Set `dp[0] = True` because an empty `s1` and `s2` can interleave to form an empty `s3`.\n\n4. **Single-Row DP Transition**:\n - Iterate through `s1` and `s2` to update the `dp` array.\n - For each character in `s1`, iterate through `s2` and update the `dp` array based on the transition rule: `dp[j] = (dp[j] and s1[i] == s3[i+j]) or (dp[j-1] and s2[j] == s3[i+j])`.\n - The transition rule checks if the current `s3[i+j]` can be matched by either `s1[i]` or `s2[j]`, relying solely on the previous values in the `dp` array.\n\n5. **Wrap-up**:\n - The final value in the `dp` array will indicate whether the entire `s3` can be formed by interleaving `s1` and `s2`.\n - Return `dp[n]`.\n\n\n\n# Complexity:\n\nThe primary advantage of this 1D DP approach is its space efficiency. While it maintains the same time complexity as the 2D DP approach $$O(m \\times n)$$, the space complexity is optimized to $$O(\\min(m, n))$$.\n\n**Time Complexity:** \n- The solution iterates over each character of `s1` and `s2` once, leading to a complexity of $$O(m \\times n)$$.\n\n**Space Complexity:** \n- The space complexity is optimized to $$O(\\min(m,n))$$ as we\'re only using a single 1D array instead of a 2D matrix.\n\n---\n\n# Approach: Recursion with Memoization\n\nIn this approach, we recursively check whether the substring `s3[k:]` can be formed by interleaving `s1[i:]` and `s2[j:]`. We store the results of these sub-problems in a dictionary named `memo`.\n\n## Key Data Structures:\n- **memo**: A dictionary to store the results of subproblems.\n\n## Enhanced Breakdown:\n\n1. **Initialization**:\n - Calculate lengths of `s1`, `s2`, and `s3`.\n - If the sum of lengths of `s1` and `s2` is not equal to the length of `s3`, return false.\n \n2. **Recursive Function**:\n - Define a recursive function `helper` which takes indices `i`, `j`, and `k` as inputs.\n - The function checks whether the substring `s3[k:]` can be formed by interleaving `s1[i:]` and `s2[j:]`.\n - Store the result of each subproblem in the `memo` dictionary.\n\n3. **Wrap-up**:\n - Return the result of the recursive function for the initial values `i=0, j=0, k=0`.\n\n# Complexity:\n\n**Time Complexity:** \n- Each combination of (i, j) is computed once and stored in the memo, leading to a time complexity of $$O(m \\times n)$$.\n\n**Space Complexity:** \n- The space complexity is $$O(m \\times n)$$ for storing the memoization results.\n\n---\n\n# Performance\n\n| Language | Runtime (ms) | Memory (MB) |\n|-----------|--------------|-------------|\n| Rust | 0 | 2.1 |\n| C++ | 0 | 6.4 |\n| Go | 1 | 1.9 |\n| Java | 3 | 40.5 |\n| Python3 (1D DP) | 31 | 16.4 |\n| Python3 (2D DP) | 34 | 16.5 |\n| Python3 (Recursion) | 45 | 17.4 |\n| C# | 54 | 38.4 |\n| JavaScript| 61 | 43.1 |\n\n![ir.png]()\n\n# Code 1D Dynamic Programming \n``` Python []\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m, n, l = len(s1), len(s2), len(s3)\n if m + n != l:\n return False\n \n if m < n:\n return self.isInterleave(s2, s1, s3)\n \n dp = [False] * (n + 1)\n dp[0] = True\n \n for j in range(1, n + 1):\n dp[j] = dp[j-1] and s2[j-1] == s3[j-1]\n \n for i in range(1, m + 1):\n dp[0] = dp[0] and s1[i-1] == s3[i-1]\n for j in range(1, n + 1):\n dp[j] = (dp[j] and s1[i-1] == s3[i+j-1]) or (dp[j-1] and s2[j-1] == s3[i+j-1])\n \n return dp[n]\n```\n``` C++ []\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n int m = s1.length(), n = s2.length(), l = s3.length();\n if (m + n != l) return false;\n \n if (m < n) return isInterleave(s2, s1, s3);\n\n vector<bool> dp(n + 1, false);\n dp[0] = true;\n\n for (int j = 1; j <= n; ++j) {\n dp[j] = dp[j - 1] && s2[j - 1] == s3[j - 1];\n }\n\n for (int i = 1; i <= m; ++i) {\n dp[0] = dp[0] && s1[i - 1] == s3[i - 1];\n for (int j = 1; j <= n; ++j) {\n dp[j] = (dp[j] && s1[i - 1] == s3[i + j - 1]) || (dp[j - 1] && s2[j - 1] == s3[i + j - 1]);\n }\n }\n \n return dp[n];\n }\n};\n```\n``` Java []\npublic class Solution {\n public boolean isInterleave(String s1, String s2, String s3) {\n int m = s1.length(), n = s2.length(), l = s3.length();\n if (m + n != l) return false;\n\n boolean[] dp = new boolean[n + 1];\n dp[0] = true;\n\n for (int j = 1; j <= n; ++j) {\n dp[j] = dp[j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);\n }\n\n for (int i = 1; i <= m; ++i) {\n dp[0] = dp[0] && s1.charAt(i - 1) == s3.charAt(i - 1);\n for (int j = 1; j <= n; ++j) {\n dp[j] = (dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));\n }\n }\n \n return dp[n];\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {\n let (m, n, l) = (s1.len(), s2.len(), s3.len());\n if m + n != l { return false; }\n\n let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());\n let mut dp = vec![false; n + 1];\n dp[0] = true;\n\n for j in 1..=n {\n dp[j] = dp[j - 1] && s2[j - 1] == s3[j - 1];\n }\n\n for i in 1..=m {\n dp[0] = dp[0] && s1[i - 1] == s3[i - 1];\n for j in 1..=n {\n dp[j] = (dp[j] && s1[i - 1] == s3[i + j - 1]) || (dp[j - 1] && s2[j - 1] == s3[i + j - 1]);\n }\n }\n \n dp[n]\n }\n}\n```\n``` Go []\nfunc isInterleave(s1 string, s2 string, s3 string) bool {\n m, n, l := len(s1), len(s2), len(s3)\n if m + n != l {\n return false\n }\n\n dp := make([]bool, n+1)\n dp[0] = true\n\n for j := 1; j <= n; j++ {\n dp[j] = dp[j-1] && s2[j-1] == s3[j-1]\n }\n\n for i := 1; i <= m; i++ {\n dp[0] = dp[0] && s1[i-1] == s3[i-1]\n for j := 1; j <= n; j++ {\n dp[j] = (dp[j] && s1[i-1] == s3[i+j-1]) || (dp[j-1] && s2[j-1] == s3[i+j-1])\n }\n }\n \n return dp[n]\n}\n```\n``` C# []\npublic class Solution {\n public bool IsInterleave(string s1, string s2, string s3) {\n int m = s1.Length, n = s2.Length, l = s3.Length;\n if (m + n != l) return false;\n\n bool[] dp = new bool[n + 1];\n dp[0] = true;\n\n for (int j = 1; j <= n; ++j) {\n dp[j] = dp[j - 1] && s2[j - 1] == s3[j - 1];\n }\n\n for (int i = 1; i <= m; ++i) {\n dp[0] = dp[0] && s1[i - 1] == s3[i - 1];\n for (int j = 1; j <= n; ++j) {\n dp[j] = (dp[j] && s1[i - 1] == s3[i + j - 1]) || (dp[j - 1] && s2[j - 1] == s3[i + j - 1]);\n }\n }\n \n return dp[n];\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string} s1\n * @param {string} s2\n * @param {string} s3\n * @return {boolean}\n */\nvar isInterleave = function(s1, s2, s3) {\n let m = s1.length, n = s2.length, l = s3.length;\n if (m + n !== l) return false;\n\n let dp = new Array(n + 1).fill(false);\n dp[0] = true;\n\n for (let j = 1; j <= n; ++j) {\n dp[j] = dp[j - 1] && s2[j - 1] === s3[j - 1];\n }\n\n for (let i = 1; i <= m; ++i) {\n dp[0] = dp[0] && s1[i - 1] === s3[i - 1];\n for (let j = 1; j <= n; ++j) {\n dp[j] = (dp[j] && s1[i - 1] === s3[i + j - 1]) || (dp[j - 1] && s2[j - 1] === s3[i + j - 1]);\n }\n }\n \n return dp[n];\n};\n```\n\n# Code 2D Dynamic Programming \n``` Python []\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m, n, l = len(s1), len(s2), len(s3)\n if m + n != l:\n return False\n \n dp = [[False] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = True\n \n for i in range(1, m + 1):\n dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]\n \n for j in range(1, n + 1):\n dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]\n \n for i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1])\n \n return dp[m][n]\n\n```\n# Code Recursion with Memoization\n``` Python []\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m, n, l = len(s1), len(s2), len(s3)\n if m + n != l:\n return False\n \n memo = {} \n \n def helper(i: int, j: int, k: int) -> bool:\n if k == l:\n return True\n \n if (i, j) in memo:\n return memo[(i, j)]\n \n ans = False\n if i < m and s1[i] == s3[k]:\n ans = ans or helper(i + 1, j, k + 1)\n \n if j < n and s2[j] == s3[k]:\n ans = ans or helper(i, j + 1, k + 1)\n \n memo[(i, j)] = ans\n return ans\n \n return helper(0, 0, 0)\n```\n\nBoth the given approaches provide efficient ways to solve the problem, with the first approach focusing on optimizing space and the second leveraging the power of memoization to save time. Choosing between them depends on the specific constraints and requirements of the application. \uD83D\uDCA1\uD83C\uDF20\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB
9,508
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
6,504
35
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\njust explore all the option -> take if current character is same with any of the string current character string 1 and string 2.\n\n[ Video in Hindi click here]()\n\nor link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The `solve` function is a recursive helper function that takes the current indices `ind1` and `ind2` for strings `s1` and `s2` respectively, along with a memoization table `dp`. The purpose of this function is to check if it\'s possible to create the remaining part of `s3` (starting from `ind1+ind2` position) using the remaining parts of `s1` (starting from `ind1` position) and `s2` (starting from `ind2` position).\n\n2. The base case for the recursion is when the sum of `ind1` and `ind2` equals the length of `s3`, meaning all characters of `s3` have been matched successfully. In this case, the function returns `true`.\n\n3. Before proceeding with the actual computation, the function checks if the result for the current `ind1` and `ind2` indices has already been computed and stored in the memoization table `dp`. If so, it returns the precomputed result.\n\n4. The function initializes a boolean variable `ans` to `false`. It then checks two conditions:\n - If `ind1` is within bounds of `s1` and the character at `s1[ind1]` matches the character at `s3[ind1+ind2]`, it recursively calls `solve` by moving the index `ind1` of `s1` one step forward.\n - If `ind2` is within bounds of `s2` and the character at `s2[ind2]` matches the character at `s3[ind1+ind2]`, it recursively calls `solve` by moving the index `ind2` of `s2` one step forward.\n \n The `ans` is updated using the bitwise OR operation (`|`) to retain any previous `true` value and to combine the results of the two recursive calls.\n\n5. Finally, the function stores the computed `ans` in the memoization table `dp` for the current `ind1` and `ind2` indices and returns this result.\n\n6. The `isInterleave` function is the main function that\'s called to determine whether `s3` can be formed by interleaving characters from `s1` and `s2`. It first checks if the total length of `s1` and `s2` matches the length of `s3`. If not, it returns `false` as it\'s impossible to form `s3`.\n\n7. It initializes a 2D vector `dp` to store the memoization table. The dimensions of this table are `(s1.size() + 1)` rows and `(s2.size() + 1)` columns, with all values initialized to `-1`.\n\n8. It then calls the `solve` function with initial indices `ind1` and `ind2` set to `0`, along with the memoization table `dp`. The result of this call indicates whether it\'s possible to form `s3` by interleaving `s1` and `s2`.\n\n9. The `isInterleave` function returns the result obtained from the `solve` function.\n\n# Complexity\n- Time complexity:$$O(n*m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n*m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n![Screenshot (313).png]()\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool solve(string &s1, string &s2, string &s3,int ind1,int ind2,vector<vector<int>>&dp)\n{\n if(ind1+ind2==s3.size()) return 1;\n if(dp[ind1][ind2]!=-1) return dp[ind1][ind2];\n bool ans=0; \n if(ind1<s1.size() && s1[ind1]==s3[ind1+ind2]) \n ans=(ans | solve(s1,s2,s3,ind1+1,ind2,dp));\n if(ind2<s2.size() && s2[ind2]==s3[ind1+ind2])\n ans=(ans | solve(s1,s2,s3,ind1,ind2+1,dp));\n return dp[ind1][ind2]=ans;\n}\n bool isInterleave(string s1, string s2, string s3) {\n if(s1.size()+s2.size()!=s3.size()) return false;\n vector<vector<int>>dp(s1.size()+1,vector<int>(s2.size()+1,-1));\n return solve(s1,s2,s3,0,0,dp);\n }\n};\n```\n```java []\nclass Solution {\n public boolean solve(String s1, String s2, String s3, int ind1, int ind2, int[][] dp) {\n if (ind1 + ind2 == s3.length()) return true;\n if (dp[ind1][ind2] != -1) return dp[ind1][ind2] == 1;\n boolean ans = false;\n \n if (ind1 < s1.length() && s1.charAt(ind1) == s3.charAt(ind1 + ind2)) {\n ans |= solve(s1, s2, s3, ind1 + 1, ind2, dp);\n }\n \n if (ind2 < s2.length() && s2.charAt(ind2) == s3.charAt(ind1 + ind2)) {\n ans |= solve(s1, s2, s3, ind1, ind2 + 1, dp);\n }\n \n dp[ind1][ind2] = ans ? 1 : 0;\n return ans;\n }\n \n public boolean isInterleave(String s1, String s2, String s3) {\n if (s1.length() + s2.length() != s3.length()) {\n return false;\n }\n \n int[][] dp = new int[s1.length() + 1][s2.length() + 1];\n for (int i = 0; i <= s1.length(); i++) {\n Arrays.fill(dp[i], -1);\n }\n \n return solve(s1, s2, s3, 0, 0, dp);\n }\n}\n\n```\n```python []\nclass Solution:\n def solve(self, s1: str, s2: str, s3: str, ind1: int, ind2: int, dp: List[List[int]]) -> bool:\n if ind1 + ind2 == len(s3):\n return True\n if dp[ind1][ind2] != -1:\n return dp[ind1][ind2] == 1\n ans = False\n \n if ind1 < len(s1) and s1[ind1] == s3[ind1 + ind2]:\n ans |= self.solve(s1, s2, s3, ind1 + 1, ind2, dp)\n \n if ind2 < len(s2) and s2[ind2] == s3[ind1 + ind2]:\n ans |= self.solve(s1, s2, s3, ind1, ind2 + 1, dp)\n \n dp[ind1][ind2] = 1 if ans else 0\n return ans\n \n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3):\n return False\n \n dp = [[-1] * (len(s2) + 1) for _ in range(len(s1) + 1)]\n return self.solve(s1, s2, s3, 0, 0, dp)\n\n```\n\n
9,525
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
1,258
23
# Intuition\nEasy Best Approach!!!\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDynamic Programming Approach:\n\nThe key insight in this problem is to use dynamic programming to check if a certain interleaving of s1 and s2 can form s3. The DP array will be used to keep track of whether a certain prefix of s3 can be formed by interleaving a prefix of s1 and a prefix of s2.\n\nHere\'s how the dynamic programming approach works:\n\nInitialization: Create a DP array dp of dimensions (len_s1 + 1) \xD7 (len_s2 + 1). dp[i][j] will be True if the first i characters of s1 and the first j characters of s2 can interleave to form the first i + j characters of s3. Initialize dp[0][0] to True since two empty strings can form an empty string.\n\nBase Cases: Initialize the first row and the first column of the DP array. dp[0][j] is True if dp[0][j-1] is True and s2[j-1] matches s3[j-1]. Similarly, dp[i][0] is True if dp[i-1][0] is True and s1[i-1] matches s3[i-1].\n\nFilling the DP Array: Loop through the remaining cells of the DP array (starting from i = 1 and j = 1). The idea is to check if the current character in s3, which is s3[i+j-1], can be formed by either appending a character from s1 or a character from s2 to the previously formed interleaved strings.\n\nIf s1[i-1] matches s3[i+j-1] and dp[i-1][j] is True, then dp[i][j] is True.\nIf s2[j-1] matches s3[i+j-1] and dp[i][j-1] is True, then dp[i][j] is True.\nFinal Result: After filling the DP array, the value of dp[len_s1][len_s2] will indicate whether the entire strings s1 and s2 can interleave to form the entire string s3.\n\nThis approach ensures that you\'re considering all possible interleavings and checking if each character in s3 can be formed by interweaving characters from s1 and s2 in a valid manner.\n\nRemember, this is just one way to approach the problem using dynamic programming. There might be other creative ways to solve this problem as well.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(len_s1 * len_s2)\n- $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(len_s1 * len_s2)\n- $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n len_s1, len_s2, len_s3 = len(s1), len(s2), len(s3)\n \n # If the total length of s1 and s2 is not equal to s3, it\'s impossible\n if len_s1 + len_s2 != len_s3:\n return False\n \n # Create a 2D DP array to store intermediate results\n dp = [[False] * (len_s2 + 1) for _ in range(len_s1 + 1)]\n \n # Base case: empty strings can always interleave to form an empty string\n dp[0][0] = True\n \n # Fill the first row\n for j in range(1, len_s2 + 1):\n dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]\n \n # Fill the first column\n for i in range(1, len_s1 + 1):\n dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]\n \n # Fill the DP array\n for i in range(1, len_s1 + 1):\n for j in range(1, len_s2 + 1):\n # Check if the current position in s3 can be formed by interleaving\n dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or \\\n (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])\n \n return dp[len_s1][len_s2]\n\n```
9,535
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
11,659
169
Given three strings `s1`, `s2` and `s3`, we need to check if `s3` can be formed by an interleaving of `s1` and `s2`.\n\nAn **interleaving** of two strings, `s1` and `s2`, means that `s1` is divided into `x` and `s2` is divided into `y` contiguous substrings, respectively. Then those substrings are concatenated without changing the order of their occurrence in `s1` and `s2`.\nNote that the condition `|x - y| <=1` always holds true.\n<details>\n<summary><strong>Proof:</strong></summary>\n<br/>\nLet\'s say <code>s1 = "abcde"</code> and <code>s2 = "fgh"</code>. We divide <code>s1</code> into four parts and <code>s2</code> into two parts.\nSo, <code>x - y = 2</code>.\n<br/>\n<code>s1 = "ab" + "c" + "d" + "e" and s2 = "f" + "gh"</code>.\n<br/>\n<code>s3 = "ab" + "f" + "c" + "gh" + "d" + "e"</code>.\n<br/>\nThe above can rewritten as <code>s3 = "ab" + "f" + "c" + "gh" + "de"</code>, which is basically\ndividing <code>s1</code> into three parts and <code>s2</code> into two parts. And hence, the condition <code>|x - y| <=1</code> holds true.\n\nThere are stricter proofs, but I tried to provide an intuitive one.\n</details>\n\n___\n___\n\u274C **Solution I: Recursion [TLE]**\n\nWe don\'t know the size of each substring or the number of substrings beforehand. So, we can take all possible substrings of `s1` and `s2` and check if `s3` can be formed by interleaving them. At each step, we have two options: choose a character from `s1` or `s2`. Let\'s call our recursive function `dfs(i, j)`. Then the two choices can be represented as:\n\n1. `dfs(i + 1, j)`: Choose a character at `i`th index from `s1`\n2. `dfs(i, j + 1)`: Choose a character at `j`th index from `s2`\n\nActually, we can make this choice more smartly. Instead of considering all possibilities, we can make either/both choice(s) only when it matches the character at the `i + j`th index of `s3`.\n\n```python\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3):\n return False\n\n def dfs(i, j):\n if i == len(s1) and j == len(s2):\n return True\n choose_s1, choose_s2 = False, False\n if i < len(s1) and s1[i] == s3[i + j]:\n choose_s1 = dfs(i + 1, j)\n if j < len(s2) and s2[j] == s3[i + j]:\n choose_s2 = dfs(i, j + 1)\n\n return choose_s1 or choose_s2\n\n return dfs(0, 0)\n```\n\nWhy have I named the inside function as `dfs`? Because if we trace our actions, we can observe that it forms a binary tree. **Don\'t worry** if you are not familiar with this term. The following visualization will help you to understand what I mean.\n\n```text\n \u250F\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 0, 0 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E\n \u2502 \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2502\n \u250F\u2501\u2501\u2501\u2537\u2501\u2501\u2513 \u250F\u2501\u2501\u2537\u2501\u2501\u2501\u2513 \n \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 1, 0 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 0, 1 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E \n \u2502 \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2502 \u2502 \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2502 \n \u250F\u2501\u2501\u2501\u2537\u2501\u2501\u2513 \u250F\u2501\u2501\u2537\u2501\u2501\u2501\u2513 \u250F\u2501\u2501\u2501\u2537\u2501\u2501\u2513 \u250F\u2501\u2501\u2537\u2501\u2501\u2501\u2513 \n \u2503 2, 0 \u2503 \u2503 1, 1 \u2503 \u2503 1, 1 \u2503 \u2503 0, 2 \u2503 \n \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u251B \n . . . .\n . . . .\n . . . .\n\n```\n\nIn dfs, we traverse all the paths one by one. So, here our paths will be:\n\n1. (0, 0) -> (1, 0) -> (2, 0) -> ...\n2. (0, 0) -> (1, 0) -> (1, 1) -> ...\n3. (0, 0) -> (0, 1) -> (1, 1) -> ...\n4. (0, 0) -> (0, 1) -> (0, 2) -> ...\n.\n.\n.\n\n- **Time Complexity:** <code>O(2<sup>m + n</sup>)</code>\n > At each step, we have two choices, so 2 * 2 * 2 ... (m + n) times.\n- **Space Complexity:** `O(m + n)`\n > Recursion stack space.\n\n___\n\u2705 **Solution II: Dynamic Programming - Memoization [Accepted]**\n\nWe are doing a lot of repetitive work in the above recursive solution. How?\nHave a look at the above example. The subtree with the head `[1, 1]` is repeated twice. Instead of computing it again, we store the result of that state and directly use it.\nWe can use the decorator `@cache` in Python to achieve this.\n\n```python\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3):\n return False\n @cache\n def dfs(i, j):\n if i == len(s1) and j == len(s2):\n return True\n choose_s1, choose_s2 = False, False\n if i < len(s1) and s1[i] == s3[i + j]:\n choose_s1 = dfs(i + 1, j)\n if j < len(s2) and s2[j] == s3[i + j]:\n choose_s2 = dfs(i, j + 1)\n\n return choose_s1 or choose_s2\n\n return dfs(0, 0)\n```\n\n- **Time Complexity:** `O(m * n)`\n- **Space Complexity:** `O(m * n)`\n\n___\n\u2705 **Solution III(a): Dynamic Programming - Tabulation [Accepted]**\n\nRecursion is generally slower than its iterative counterpart. So, we can further optimize the above solution by using tabulation. Coming up with this solution is a bit difficult, and it requires practice. Try to find similarities with the memoization approach. The value `dp[i][j]` gives the information if we can form `s3[0...(i+j-1)]` from interleaving `s1[0...(i-1)]` and `s2[0...(j-1)]`. The first column represents interleving of `s1` and an empty string, and similarly, the first row represents interleaving of `s2` and and an empty string.\n\n```python\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m, n = len(s1), len(s2)\n if m + n != len(s3):\n return False\n dp = [[False] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = True\n for i in range(1, m + 1):\n dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]\n for j in range(1, n + 1):\n dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n choose_s1, choose_s2 = False, False\n if s1[i - 1] == s3[i + j - 1]:\n choose_s1 = dp[i - 1][j]\n if s2[j - 1] == s3[i + j - 1]:\n choose_s2 = dp[i][j - 1]\n dp[i][j] = choose_s1 or choose_s2\n\n return dp[m][n]\n\n```\n\n- **Time Complexity:** `O(m * n)`\n- **Space Complexity:** `O(m * n)`\n\n___\n\u2705 **Solution III(b): Dynamic Programming - Tabulation (Space Optimized) [Accepted]**\n\nNotice that we only require the information from the cells `dp[i - 1][j]` and `dp[i][j - 1]`, i.e. the cell above the current row and the cell to the left of the current column. So, no need to use a matrix. The code can be shortened, but for the sake of understandability, I decided to leave it as it is.\n\n```python\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m, n = len(s1), len(s2)\n if m + n != len(s3):\n return False\n if n > m:\n m, n = n, m\n s1, s2 = s2, s1\n dp = [False] * (n + 1)\n dp[0] = True\n for j in range(1, n + 1):\n dp[j] = dp[j - 1] and s2[j - 1] == s3[j - 1]\n for i in range(1, m + 1):\n dp[0] = dp[0] and s1[i - 1] == s3[i - 1]\n for j in range(1, n + 1):\n choose_s1, choose_s2 = False, False\n if s1[i - 1] == s3[i + j - 1]:\n choose_s1 = dp[j]\n if s2[j - 1] == s3[i + j - 1]:\n choose_s2 = dp[j - 1]\n dp[j] = choose_s1 or choose_s2\n\n return dp[-1]\n```\n\n- **Time Complexity:** `O(m * n)`\n- **Space Complexity:** `O(min(m, n))`\n\n___\n___\nIf you like the solution, please **upvote**! \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
9,537
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
2,493
15
```Python3 []\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3):\n return False\n\n dp = [ [False] * (len(s2) + 1) for i in range(len(s1) + 1)]\n dp[len(s1)][len(s2)] = True\n\n for i in range(len(s1), -1, -1):\n for j in range(len(s2), -1, -1):\n if i < len(s1) and s1[i] == s3[i +j] and dp[i + 1][j]:\n dp[i][j] = True\n if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:\n dp[i][j] = True\n return dp[0][0]\n\n\n\n dp = {}\n def dfs(i, j):\n if i == len(s1) and j == len(s2):\n return True\n if (i, j) in dp:\n return dp[(i, j)]\n\n if i < len(s1) and s1[i] == s3[i+j] and dfs(i + 1, j):\n return True\n \n if j < len(s2) and s2[j] == s3[i + j] and dfs(i, j + 1):\n return True\n \n dp[(i, j)] = False\n return False\n return dfs(0, 0)\n```\n```python []\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3):\n return False\n\n dp = [ [False] * (len(s2) + 1) for i in range(len(s1) + 1)]\n dp[len(s1)][len(s2)] = True\n\n for i in range(len(s1), -1, -1):\n for j in range(len(s2), -1, -1):\n if i < len(s1) and s1[i] == s3[i +j] and dp[i + 1][j]:\n dp[i][j] = True\n if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:\n dp[i][j] = True\n return dp[0][0]\n\n\n\n dp = {}\n def dfs(i, j):\n if i == len(s1) and j == len(s2):\n return True\n if (i, j) in dp:\n return dp[(i, j)]\n\n if i < len(s1) and s1[i] == s3[i+j] and dfs(i + 1, j):\n return True\n \n if j < len(s2) and s2[j] == s3[i + j] and dfs(i, j + 1):\n return True\n \n dp[(i, j)] = False\n return False\n return dfs(0, 0)\n```\n```C# []\npublic class Solution {\n public bool IsInterleave(string s1, string s2, string s3) {\n if (s1.Length + s2.Length != s3.Length) {\n return false;\n }\n\n bool[,] dp = new bool[s1.Length + 1, s2.Length + 1];\n dp[s1.Length, s2.Length] = true;\n\n for (int i = s1.Length; i >= 0; i--) {\n for (int j = s2.Length; j >= 0; j--) {\n if (i < s1.Length && s1[i] == s3[i + j] && dp[i + 1, j]) {\n dp[i, j] = true;\n }\n if (j < s2.Length && s2[j] == s3[i + j] && dp[i, j + 1]) {\n dp[i, j] = true;\n }\n }\n }\n return dp[0, 0];\n }\n\n private Dictionary<(int, int), bool> dp = new Dictionary<(int, int), bool>();\n private bool DFS(int i, int j, string s1, string s2, string s3) {\n if (i == s1.Length && j == s2.Length) {\n return true;\n }\n if (dp.ContainsKey((i, j))) {\n return dp[(i, j)];\n }\n\n bool result = false;\n if (i < s1.Length && s1[i] == s3[i + j] && DFS(i + 1, j, s1, s2, s3)) {\n result = true;\n }\n if (j < s2.Length && s2[j] == s3[i + j] && DFS(i, j + 1, s1, s2, s3)) {\n result = true;\n }\n\n dp[(i, j)] = result;\n return result;\n }\n}\n```\n```C++ []\n#include <unordered_map>\nusing namespace std;\n\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n if (s1.length() + s2.length() != s3.length()) {\n return false;\n }\n\n vector<vector<bool>> dp(s1.length() + 1, vector<bool>(s2.length() + 1, false));\n dp[s1.length()][s2.length()] = true;\n\n for (int i = s1.length(); i >= 0; i--) {\n for (int j = s2.length(); j >= 0; j--) {\n if (i < s1.length() && s1[i] == s3[i + j] && dp[i + 1][j]) {\n dp[i][j] = true;\n }\n if (j < s2.length() && s2[j] == s3[i + j] && dp[i][j + 1]) {\n dp[i][j] = true;\n }\n }\n }\n return dp[0][0];\n }\n\nprivate:\n struct PairHash {\n template <class T1, class T2>\n size_t operator() (const pair<T1, T2>& p) const {\n auto h1 = hash<T1>{}(p.first);\n auto h2 = hash<T2>{}(p.second);\n return h1 ^ (h2 << 1);\n }\n };\n \n unordered_map<pair<int, int>, bool, PairHash> dp;\n bool dfs(int i, int j, string& s1, string& s2, string& s3) {\n if (i == s1.length() && j == s2.length()) {\n return true;\n }\n if (dp.find({i, j}) != dp.end()) {\n return dp[{i, j}];\n }\n\n bool result = false;\n if (i < s1.length() && s1[i] == s3[i + j] && dfs(i + 1, j, s1, s2, s3)) {\n result = true;\n }\n if (j < s2.length() && s2[j] == s3[i + j] && dfs(i, j + 1, s1, s2, s3)) {\n result = true;\n }\n\n dp[{i, j}] = result;\n return result;\n }\n};\n```\n```Java []\nimport java.util.HashMap;\nimport java.util.Map;\n\nclass Solution {\n public boolean isInterleave(String s1, String s2, String s3) {\n if (s1.length() + s2.length() != s3.length()) {\n return false;\n }\n\n boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];\n dp[s1.length()][s2.length()] = true;\n\n for (int i = s1.length(); i >= 0; i--) {\n for (int j = s2.length(); j >= 0; j--) {\n if (i < s1.length() && s1.charAt(i) == s3.charAt(i + j) && dp[i + 1][j]) {\n dp[i][j] = true;\n }\n if (j < s2.length() && s2.charAt(j) == s3.charAt(i + j) && dp[i][j + 1]) {\n dp[i][j] = true;\n }\n }\n }\n return dp[0][0];\n }\n\n private Map<Pair, Boolean> dp = new HashMap<>();\n private boolean dfs(int i, int j, String s1, String s2, String s3) {\n if (i == s1.length() && j == s2.length()) {\n return true;\n }\n Pair pair = new Pair(i, j);\n if (dp.containsKey(pair)) {\n return dp.get(pair);\n }\n\n boolean result = false;\n if (i < s1.length() && s1.charAt(i) == s3.charAt(i + j) && dfs(i + 1, j, s1, s2, s3)) {\n result = true;\n }\n if (j < s2.length() && s2.charAt(j) == s3.charAt(i + j) && dfs(i, j + 1, s1, s2, s3)) {\n result = true;\n }\n\n dp.put(pair, result);\n return result;\n }\n\n private class Pair {\n int first;\n int second;\n\n Pair(int first, int second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public int hashCode() {\n return first * 31 + second;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null || getClass() != obj.getClass()) return false;\n Pair other = (Pair) obj;\n return first == other.first && second == other.second;\n }\n }\n}\n```\n![Screenshot 2023-08-20 065922.png]()\n
9,547
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
1,528
7
# Intuition\nThe problem of determining whether one string is an interleaving of two others can be approached using dynamic programming. The core intuition lies in breaking down the problem into smaller subproblems. Essentially, we want to determine if the characters from both strings, s1 and s2, can be interwoven to create the target string s3. We aim to build a dynamic programming matrix that stores the state of the interleaving at different points, helping us track the possibilities.\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 247 videos as of August 25th.\n\n**\u25A0 Subscribe URL**\n\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Initialize `dp` array: Create an array `dp` of size `(len(s2) + 1)` to store whether substrings of `s1` and `s2` can interleave to form substrings of `s3`.\n\n2. Check total length: If the sum of the lengths of `s1` and `s2` is not equal to the length of `s3`, return `False` since it\'s impossible for `s1` and `s2` to interleave to form `s3`.\n\n3. Initialization: Set `dp[0]` to `True` to indicate that an empty `s1` and empty `s2` can interleave to form an empty `s3`.\n\n4. Loop through `s1` and `s2`: Use nested loops to iterate through all possible combinations of substrings of `s1` and `s2` to check if they can interleave to form `s3`.\n\n5. Base cases handling:\n - If `i` is `0` and `j` is `0`, it means both `s1` and `s2` are empty. Set `dp[j]` to `True`.\n - If `i` is `0`, update `dp[j]` using the previous value of `dp[j - 1]` and check if the character in `s2` at index `j - 1` matches the character in `s3` at index `i + j - 1`.\n - If `j` is `0`, update `dp[j]` using the current value of `dp[j]` and check if the character in `s1` at index `i - 1` matches the character in `s3` at index `i + j - 1`.\n\n6. General case:\n - For all other cases (when both `i` and `j` are not `0`), update `dp[j]` using the following conditions:\n - `dp[j]` should be the result of `(dp[j] and s1[i - 1] == s3[i + j - 1])`, meaning that the current character in `s1` matches the current character in `s3`, and the previous substring also interleave to form the previous part of `s3`.\n - `dp[j - 1]` should be the result of `(dp[j - 1] and s2[j - 1] == s3[i + j - 1])`, meaning that the current character in `s2` matches the current character in `s3`, and the previous substring of `s2` can interleave to form the previous part of `s3`.\n\n7. Return result: The final result is stored in `dp[len(s2)]`, which indicates whether `s1` and `s2` can interleave to form `s3`.\n\n8. The function returns the value of `dp[len(s2)]` as the final result.\n\nIn summary, the algorithm uses dynamic programming to determine whether substrings of `s1` and `s2` can be interleaved to form substrings of `s3`. The `dp` array stores whether the substrings can interleave at each position.\n\n# Complexity\n- Time complexity: O(m * n)\nm is the length of string s1 and n is the length of string s2. This is because we iterate through each character of s1 and s2 once while constructing the dynamic programming matrix.\n\n- Space complexity: O(n),\nn is the length of string s2. We only use a dynamic programming array of length n+1 to store the state transitions.\n\n```python []\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n # Check if the combined length of s1 and s2 matches the length of s3\n if len(s1) + len(s2) != len(s3):\n return False\n \n # Initialize a dynamic programming array dp\n # dp[j] will store whether s1[0:i] and s2[0:j] can form s3[0:i+j]\n dp = [False] * (len(s2) + 1)\n \n for i in range(len(s1) + 1):\n for j in range(len(s2) + 1):\n if i == 0 and j == 0:\n # Base case: Both s1 and s2 are empty, so s3 is also empty.\n # Set dp[j] to True.\n dp[j] = True\n elif i == 0:\n # Base case: s1 is empty, so check if the previous dp[j-1]\n # is True and if s2[j-1] matches s3[i+j-1].\n dp[j] = dp[j - 1] and s2[j - 1] == s3[i + j - 1]\n elif j == 0:\n # Base case: s2 is empty, so check if the current dp[j]\n # is True and if s1[i-1] matches s3[i+j-1].\n dp[j] = dp[j] and s1[i - 1] == s3[i + j - 1]\n else:\n # General case: Check if either the previous dp[j] or dp[j-1]\n # is True and if the corresponding characters match s3[i+j-1].\n dp[j] = (dp[j] and s1[i - 1] == s3[i + j - 1]) or (dp[j - 1] and s2[j - 1] == s3[i + j - 1])\n\n # Return the result stored in dp[len(s2)], which indicates whether\n # s1 and s2 can form s3 by interleaving characters.\n return dp[len(s2)]\n\n```\n```javascript []\n/**\n * @param {string} s1\n * @param {string} s2\n * @param {string} s3\n * @return {boolean}\n */\nvar isInterleave = function(s1, s2, s3) {\n if (s1.length + s2.length !== s3.length) {\n return false;\n }\n \n const dp = new Array(s2.length + 1).fill(false);\n \n for (let i = 0; i <= s1.length; i++) {\n for (let j = 0; j <= s2.length; j++) {\n if (i === 0 && j === 0) {\n dp[j] = true;\n } else if (i === 0) {\n dp[j] = dp[j - 1] && s2[j - 1] === s3[i + j - 1];\n } else if (j === 0) {\n dp[j] = dp[j] && s1[i - 1] === s3[i + j - 1];\n } else {\n dp[j] = (dp[j] && s1[i - 1] === s3[i + j - 1]) || (dp[j - 1] && s2[j - 1] === s3[i + j - 1]);\n }\n }\n }\n \n return dp[s2.length]; \n};\n```\n```java []\nclass Solution {\n public boolean isInterleave(String s1, String s2, String s3) {\n if (s1.length() + s2.length() != s3.length()) {\n return false;\n }\n \n boolean[] dp = new boolean[s2.length() + 1];\n \n for (int i = 0; i <= s1.length(); i++) {\n for (int j = 0; j <= s2.length(); j++) {\n if (i == 0 && j == 0) {\n dp[j] = true;\n } else if (i == 0) {\n dp[j] = dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);\n } else if (j == 0) {\n dp[j] = dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);\n } else {\n dp[j] = (dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));\n }\n }\n }\n \n return dp[s2.length()]; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n if (s1.length() + s2.length() != s3.length()) {\n return false;\n }\n \n vector<bool> dp(s2.length() + 1, false);\n \n for (int i = 0; i <= s1.length(); i++) {\n for (int j = 0; j <= s2.length(); j++) {\n if (i == 0 && j == 0) {\n dp[j] = true;\n } else if (i == 0) {\n dp[j] = dp[j - 1] && s2[j - 1] == s3[i + j - 1];\n } else if (j == 0) {\n dp[j] = dp[j] && s1[i - 1] == s3[i + j - 1];\n } else {\n dp[j] = (dp[j] && s1[i - 1] == s3[i + j - 1]) || (dp[j - 1] && s2[j - 1] == s3[i + j - 1]);\n }\n }\n }\n \n return dp[s2.length()]; \n }\n};\n```\n
9,557
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
25,833
257
\n # O(m*n) space\n def isInterleave1(self, s1, s2, s3):\n r, c, l= len(s1), len(s2), len(s3)\n if r+c != l:\n return False\n dp = [[True for _ in xrange(c+1)] for _ in xrange(r+1)]\n for i in xrange(1, r+1):\n dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]\n for j in xrange(1, c+1):\n dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]\n for i in xrange(1, r+1):\n for j in xrange(1, c+1):\n dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i-1+j]) or \\\n (dp[i][j-1] and s2[j-1] == s3[i-1+j])\n return dp[-1][-1]\n\n # O(2*n) space\n def isInterleave2(self, s1, s2, s3):\n l1, l2, l3 = len(s1)+1, len(s2)+1, len(s3)+1\n if l1+l2 != l3+1:\n return False\n pre = [True for _ in xrange(l2)]\n for j in xrange(1, l2):\n pre[j] = pre[j-1] and s2[j-1] == s3[j-1]\n for i in xrange(1, l1):\n cur = [pre[0] and s1[i-1] == s3[i-1]] * l2\n for j in xrange(1, l2):\n cur[j] = (cur[j-1] and s2[j-1] == s3[i+j-1]) or \\\n (pre[j] and s1[i-1] == s3[i+j-1])\n pre = cur[:]\n return pre[-1]\n \n # O(n) space\n def isInterleave3(self, s1, s2, s3):\n r, c, l= len(s1), len(s2), len(s3)\n if r+c != l:\n return False\n dp = [True for _ in xrange(c+1)] \n for j in xrange(1, c+1):\n dp[j] = dp[j-1] and s2[j-1] == s3[j-1]\n for i in xrange(1, r+1):\n dp[0] = (dp[0] and s1[i-1] == s3[i-1])\n for j in xrange(1, c+1):\n dp[j] = (dp[j] and s1[i-1] == s3[i-1+j]) or (dp[j-1] and s2[j-1] == s3[i-1+j])\n return dp[-1]\n \n # DFS \n def isInterleave4(self, s1, s2, s3):\n r, c, l= len(s1), len(s2), len(s3)\n if r+c != l:\n return False\n stack, visited = [(0, 0)], set((0, 0))\n while stack:\n x, y = stack.pop()\n if x+y == l:\n return True\n if x+1 <= r and s1[x] == s3[x+y] and (x+1, y) not in visited:\n stack.append((x+1, y)); visited.add((x+1, y))\n if y+1 <= c and s2[y] == s3[x+y] and (x, y+1) not in visited:\n stack.append((x, y+1)); visited.add((x, y+1))\n return False\n \n # BFS \n def isInterleave(self, s1, s2, s3):\n r, c, l= len(s1), len(s2), len(s3)\n if r+c != l:\n return False\n queue, visited = [(0, 0)], set((0, 0))\n while queue:\n x, y = queue.pop(0)\n if x+y == l:\n return True\n if x+1 <= r and s1[x] == s3[x+y] and (x+1, y) not in visited:\n queue.append((x+1, y)); visited.add((x+1, y))\n if y+1 <= c and s2[y] == s3[x+y] and (x, y+1) not in visited:\n queue.append((x, y+1)); visited.add((x, y+1))\n return False
9,560
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
3,215
18
**Interleaving String**\n<img src="" width="800px" height="400px" alt="R8_gcn_test" align=center />\n\n\n\n\nAs problem name suggest we need to check interleaving of strings in another string and if it\'s not the case then return false. \n\nWe can try on 3 approaches : 1. Bruteforce 2. Iterative / Recursive 3. Dynamic programming\n\n**Bruteforce approach 1** : TLE \uD83D\uDE36\n\nC++ || PYTHON\n```\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n int m = s1.size(), n = s2.size(), k = s3.size();\n if (m + n != k) return false;\n while(m > 0 && n > 0 && s1[m-1] == s2[n-1] && s1[m-1] == s3[k-1]) {\n m--;\n n--;\n k--;\n }\n while(m > 0 && s1[m-1] == s3[k-1]) {\n m--;\n k--;\n }\n while(n > 0 && s2[n-1] == s3[k-1]) {\n n--;\n k--;\n }\n if (m == 0 && n == 0) return true;\n if (m == 0) return s2.substr(0, n) == s3.substr(0, n);\n if (n == 0) return s1.substr(0, m) == s3.substr(0, m);\n return s1.substr(0, m) == s3.substr(0, m) && s2.substr(0, n) == s3.substr(m, n); \n }\n};\n```\n\n\n```\nclass Solution(object):\n def isInterleave(self, s1, s2, s3):\n f1 = list(s1)\n f2 = list(s2)\n f3 = list(s3)\n\n if len(f1) + len(f2) != len(f3):\n return False\n\n if len(f1) == 0:\n return f2 == f3\n\n if len(f2) == 0:\n return f1 == f3\n\n if len(f1) == 1:\n return f1[0] == f3[0] and f2 == f3[1:]\n\n if len(f2) == 1:\n return f1 == f3[0:] and f2[0] == f3[-1]\n\n\n for i in range(len(f1)):\n if f1[i] not in f3:\n return False\n\n for i in range(len(f2)):\n if f2[i] not in f3:\n return False\n \n i =0\n\n while(i != len(s3)):\n if s1[i] == s3[i]:\n i += 1\n if s2[i] == s3[i]:\n i += 1\n \n if s1[i] != s3[i] or s2[i] != s3[i]:\n return False\n \n return True \n```\n\n**Approach 2 Iterative** \n\nFor recursive approach we will use same manner as we did in bruteforce but here the stopping condition will work for us :\n\nWe will call the function by comparing between the string s1 and s2 whether they are folowing the order or not. \n\n**Time complexity** : O(2^m+n) where m & n are size of both strings \n\nexponential of 2 as each character in s3 has 2 option everytime it is moving. \n\n C++ || Python\n \n```\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n int m = s1.size(), n = s2.size(), k = s3.size();\n if (m + n != k) return false;\n while(m > 0 && n > 0 && s1[m-1] == s2[n-1] && s1[m-1] == s3[k-1]) {\n m--;\n n--;\n k--;\n }\n if (m == 0 && n == 0) return true;\n if (m == 0) return s2.substr(0, n) == s3.substr(0, n);\n if (n == 0) return s1.substr(0, m) == s3.substr(0, m);\n if (s1[m-1] == s3[k-1]) return isInterleave(s1.substr(0, m-1), s2, s3.substr(0, k-1));\n\n if (s2[n-1] == s3[k-1]) return isInterleave(s1, s2.substr(0, n-1), s3.substr(0, k-1));\n return false;\n }\n};\n```\n\n \n \n```\nclass Solution(object):\n def isInterleave(self, s1, s2, s3):\n if len(s1) + len(s2) !=len(s3):\n return False\n\n if len(s1) == 0:\n return s2 == s3\n if len(s2) == 0:\n return s1 == s3\n\n if s1[0] == s2[0] and s1[0] == s3[0]:\n return self.isInterleave(s1[1:], s2, s3[1:]) or self.isInterleave(s1, s2[1:], s3[1:])\n elif s1[0] == s3[0]:\n return self.isInterleave(s1[1:], s2, s3[1:])\n elif s2[0] == s3[0]:\n return self.isInterleave(s1, s2[1:], s3[1:])\n else:\n return False\n```\n\n**Dynamic programming** \n\nThe DP approach(Momoisation) is easy here as we only need to store the order and if order change we will change the subsequence that we are following and move to next subsequence.\n\n**Time complexity** : O(m.n) \n\nThe image showing if we use to traverse all the branches in the tree and not storing the information from each levels in the worst case we might need to traverse all the paths when no element is matching or interleaving in the next string.\n\n**IF WE DO NOT STORE IN ANY COLLECTION** : Each level in tree showing the char positions in s3 and total number of level are equal to the length of the string s3. For example root level 1st char and 2nd level 2nd char and so on. When ever we have a match we start it as either in s1 or s2 if match in s1 we will start that path if match in s2 we will take that path and traverse untill mismatch occur. In this order we need to parse every path. \n\n\n\n<img src=" " width="800px" height="800px" alt="R8_gcn_test" align=center />\n\nC++ || PYTHON \n```\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n int m = s1.size(), n = s2.size(), k = s3.size();\n if (m + n != k) return false;\n vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));\n for (int i = 0; i <= m; i++) {\n for (int j = 0; j <= n; j++) {\n if (i == 0 && j == 0) dp[i][j] = true;\n else if (i == 0) dp[i][j] = dp[i][j - 1] && s2[j - 1] == s3[i + j - 1];\n else if (j == 0) dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1];\n else dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]);\n }\n }\n return dp[m][n];\n }\n};\n```\n\n\n\n```\nclass Solution(object):\n def isInterleave(self, s1, s2, s3):\n if len(s1) + len(s2) != len(s3):\n return False\n dp = [[False for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)]\n for i in range(len(s1) + 1):\n for j in range(len(s2) + 1):\n if i == 0 and j == 0:\n dp[i][j] = True\n elif i == 0:\n dp[i][j] = dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]\n elif j == 0:\n dp[i][j] = dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]\n else:\n dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])\n return dp[len(s1)][len(s2)]\n```\n \n**Consider upvote if you find it useful\uD83D\uDE03** \n\n**Thanks in advance \u2764\uFE0F\u2764\uFE0F\u2764\uFE0F**\n\n
9,562
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
501
5
\n```\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n n1=len(s1)\n n2=len(s2)\n n3=len(s3)\n @cache\n def isInter(i1,i2,i3):\n if i1==n1 and i2==n2 and i3==n3:\n return True\n\n return i3<n3 and (i1<n1 and s1[i1]==s3[i3] and isInter(i1+1,i2,i3+1) or i2<n2 and s2[i2]==s3[i3] and isInter(i1,i2+1,i3+1))\n\n return isInter(0,0,0) \n```
9,568
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
3,036
17
**Upvote** if you like efficient solution code!\n\n**Join our discord** to meet other people preparing for interviews!\n****\n\n**C++**\n```\nclass Solution {\npublic:\n bool isInterleave(string s1, string s2, string s3) {\n\t\tif (s1.length() + s2.length() != s3.length()) return false;\n\t\tif (s1.length() < s2.length()) swap(s1, s2);\n\t\tint m = s1.length(), n = s2.length();\n\t\t\t\n vector<bool> dp(n + 1, false);\n dp[0] = true;\n for (int j = 1; j <= n; j++) {\n dp[j] = s3[j - 1] == s2[j - 1] && dp[j - 1];\n }\n\n for (int i = 1; i <= m; i++) {\n dp[0] = s3[i - 1] == s1[i - 1] && dp[0];\n for (int j = 1; j <= n; j++) {\n dp[j] = (s3[i + j - 1] == s1[i - 1] && dp[j]);\n dp[j] = dp[j] || (s3[i + j - 1] == s2[j - 1] && dp[j - 1]);\n }\n }\n return dp.back();\n }\n};\n```\n\n**Python3**\n```\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3):\n return False\n if len(s1) < len(s2):\n s1, s2 = s2, s1\n m, n = len(s1), len(s2)\n \n dp = [True] + [False] * n\n for j in range(1, n + 1):\n dp[j] = s2[j - 1] == s3[j - 1] and dp[j - 1]\n\n for i in range(1, m + 1):\n dp[0] = s1[i - 1] == s3[i - 1] and dp[0]\n for j in range(1, n + 1):\n dp[j] = (s1[i - 1] == s3[i + j - 1] and dp[j])\n dp[j] = dp[j] or (s2[j - 1] == s3[i + j - 1] and dp[j - 1])\n return dp[-1]\n```\n\n**Time Complexity** O(mn) - A for-loop running `m` iterations with another for-loop running `n` iterations nested inside.\n**Space Complexity** O(n) - A single array of size `n`.
9,583
Interleaving String
interleaving-string
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: Note: a + b is the concatenation of strings a and b.
String,Dynamic Programming
Medium
null
1,540
10
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nOne way to form s3 from s1 and s2 is to take one character from s1 or s2 at a time and append it to s3. We can keep track of the index of the last character from s1 and s2 that was appended to s3. If at any point, we cannot append a character to s3, we backtrack and try a different path.\n\nTo optimize this approach, we can use dynamic programming. We can define a 2D boolean array dp, where dp[i][j] is true if s3[0:i+j] can be formed by an interleaving of s1[0:i] and s2[0:j].\n\nThe base case is when i = j = 0, and dp[0][0] is true. If either i or j is zero, then dp[i][j] is true if s3[0:i+j] is equal to either s1[0:i] or s2[0:j].\n\nFor the general case, if the last character of s1 matches the last character of s3, then we can append it to s3 and check if dp[i-1][j] is true. Similarly, if the last character of s2 matches the last character of s3, then we can append it to s3 and check if dp[i][j-1] is true.\n\nThe final answer is dp[m][n], where m is the length of s1 and n is the length of s2.\n\nTime complexity: O(mn), where m is the length of s1 and n is the length of s2.\nSpace complexity: O(mn), where m is the length of s1 and n is the length of s2.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m, n = len(s1), len(s2)\n if m + n != len(s3):\n return False\n \n dp = [[False] * (n+1) for _ in range(m+1)]\n dp[0][0] = True\n \n for i in range(m+1):\n for j in range(n+1):\n if i > 0 and s1[i-1] == s3[i+j-1]:\n dp[i][j] = dp[i][j] or dp[i-1][j]\n if j > 0 and s2[j-1] == s3[i+j-1]:\n dp[i][j] = dp[i][j] or dp[i][j-1]\n \n return dp[m][n]\n\n\n```
9,595
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
31,167
464
```C++ []\nclass Solution {\n\nbool isPossible(TreeNode* root, long long l, long long r){\n if(root == nullptr) return true;\n if(root->val < r and root->val > l)\n return isPossible(root->left, l, root->val) and \n isPossible(root->right, root->val, r);\n else return false;\n}\n\npublic:\n bool isValidBST(TreeNode* root) {\n long long int min = -1000000000000, max = 1000000000000;\n return isPossible(root, min, max);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n prev = float(\'-inf\')\n def inorder(node):\n nonlocal prev\n if not node:\n return True\n if not (inorder(node.left) and prev < node.val):\n return False\n prev = node.val\n return inorder(node.right)\n return inorder(root)\n```\n\n```Java []\nclass Solution {\n private long minVal = Long.MIN_VALUE;\n public boolean isValidBST(TreeNode root) {\n if (root == null) return true; \n if (!isValidBST(root.left)) return false;\n \n if (minVal >= root.val) return false; \n\n minVal = root.val;\n\n if (!isValidBST(root.right)) return false;\n\n return true;\n } \n}\n```\n
9,600
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
30,601
410
Please feel free to suggest similar problems in the comment section.\n\nThere are three types of Tree traversal: Inorder, Preorder and Postorder\n\n* **Inorder:** left, root, right\n* **Preorder:** root, left child, right child **OR** root, right child, left child\t\t\t\n* **Postorder:** left child, right child, root **OR** right child, left child, root\n\t\t\t\t\t\t\t\n\t\t\t\t\n\n**INORDER TRAVERSAL**\n\n**98. Validate Binary Search Tree**\n\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def isValidBST(self, root):\n """\n :type root: TreeNode\n :rtype: bool\n """\n output =[]\n self.inorder(root, output)\n \n for i in range(1, len(output)):\n\t\t\tif output[i-1]>= output[i]:\n\t\t\t\treturn False\n \n return True\n \n # Time complexity of inorder traversal is O(n)\n # Fun fact: Inorder traversal leads to a sorted array if it is \n # a Valid Binary Search. Tree.\n def inorder(self, root, output):\n if root is None:\n return\n \n self.inorder(root.left, output)\n output.append(root.val)\n self.inorder(root.right, output)\n \n```\n**94. Binary Tree Inorder Traversal**\n\n\n```\n# Recursive: runtime-16ms\n\nclass Solution(object):\n def inorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n output = []\n self.inorder(root, output)\n return output\n \n def inorder(self, root, output):\n if root is None:\n return\n \n self.inorder(root.left, output)\n output.append(root.val)\n self.inorder(root.right, output)\n\n\n# Iterative Runtime: 20 ms, faster than 70.13%\n\nclass Solution(object):\n def inorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n output = []\n stack=[]\n \n while stack or root:\n \n if root:\n stack.append(root)\n root =root.left\n \n else:\n temp =stack.pop()\n output.append(temp.val)\n root= temp.right\n \n return output\n```\n\n**PREORDER TRAVERSAL**\n\n**589. N-ary Tree Preorder Traversal**\n\n\n```\n## Recursive Solution: Runtime: 36 ms, faster than 97.16%\n"""\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\nclass Solution(object):\n def preorder(self, root):\n """\n :type root: Node\n :rtype: List[int]\n """\n \n output =[]\n \n # perform dfs on the root and get the output stack\n self.dfs(root, output)\n \n # return the output of all the nodes.\n return output\n \n def dfs(self, root, output):\n \n # If root is none return \n if root is None:\n return\n \n # for preorder we first add the root val\n output.append(root.val)\n \n # Then add all the children to the output\n for child in root.children:\n self.dfs(child, output)\n \n\t \n\t \n# Iterative Solution- Runtime: 40 ms, faster than 91.86% \n\n"""\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\n\nclass Solution(object):\n def preorder(self, root):\n """\n :type root: Node\n :rtype: List[int]\n """\n if root is None:\n return []\n \n stack = [root]\n output = []\n \n # Till there is element in stack the loop runs.\n while stack:\n \n #pop the last element from the stack and store it into temp.\n temp = stack.pop()\n \n # append. the value of temp to output\n output.append(temp.val)\n \n #add the children of the temp into the stack in reverse order.\n # children of 1 = [3,2,4], if not reveresed then 4 will be popped out first from the stack.\n # if reversed then stack = [4,2,3]. Here 3 will pop out first.\n # This continues till the stack is empty.\n stack.extend(temp.children[::-1])\n \n #return the output\n return output\n \n```\n\n\n\n**144. Binary Tree Preorder Traversal**\n\n\n```\n# Recursive solution\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n output =[]\n self.dfs(root, output)\n return output\n \n def dfs(self, root, output):\n if root is None:\n return\n \n output.append(root.val)\n self.dfs(root.left, output)\n self.dfs(root.right, output)\n \n\t \n# Iterative Solution- Runtime: 12 ms, faster than 97.82%\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n output =[]\n stack = [root]\n \n while stack:\n temp=stack.pop()\n if temp:\n output.append(temp.val)\n stack.append(temp.right)\n stack.append(temp.left)\n \n return output\n```\n**257. Binary Tree Paths** : Runtime: 16 ms, faster than 93.92% of Python \n\n\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def binaryTreePaths(self, root):\n """\n :type root: TreeNode\n :rtype: List[str]\n """\n if root is None:\n return []\n \n result = []\n self.dfs(root, "", result)\n return result\n\n def dfs(self, root, path, result):\n if not root.left and not root.right:\n result.append(path + str(root.val))\n \n if root.left:\n self.dfs(root.left, path + str(root.val) + "->" , result)\n if root.right:\n self.dfs(root.right, path + str(root.val) + "->", result)\n \n```\n\n\n**POSTORDER TRAVERSAL**\n\n**590. N-ary Tree Postorder Traversal**\n```\n# Recursive : Runtime: 40 ms, faster than 89.79% \n"""\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\n\nclass Solution(object):\n def postorder(self, root):\n """\n :type root: Node\n :rtype: List[int]\n """\n output =[]\n self.dfs(root, output)\n return output\n \n def dfs(self, root, output):\n if root is None:\n return\n for child in root.children:\n self.dfs(child, output)\n \n output.append(root.val)\n \n \n # Iterative Solution: Runtime: 48 ms, faster than 62.81%\n \n `"""\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\n\nclass Solution(object):\n def postorder(self, root):\n """\n :type root: Node\n :rtype: List[int]\n """\n output =[]\n stack = [root]\n \n while stack:\n root = stack.pop()\n if root:\n output.append(root.val)\n stack += root.children\n \n return output[::-1]`\n \n```\n\n**145. Binary Tree Postorder Traversal**\n\n```\n# Recursive solution\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def postorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n output = []\n self.dfs(root, output)\n return output\n \n def dfs(self, root, output):\n if root is None:\n return\n self.dfs(root.left, output)\n self.dfs(root.right, output) \n output.append(root.val)\n\t\t\n\t\t\n# Iterative solution: Runtime: 12 ms, faster than 98.10%\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def postorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n output = []\n stack =[root]\n \n if not root:\n return None\n \n # iterate only when there is elements inside the stack.\n while stack:\n \n # pop the element from stack and stored it into temp\n temp=stack.pop()\n \n #append the value of temp to output\n output.append(temp.val)\n \n #Now traverse through left node and add the node to stack\n if temp.left:\n stack.append(temp.left)\n \n #else traverse through right node and add to stack\n if temp.right:\n stack.append(temp.right)\n \n # After iterating through the stack, print the result in reverse order. \n return output[::-1]\n \n \n# Example: Iteration 1 : #stack=[1] - first iteration, temp =1, \n #output[1]\n #temp.left is Null\n #temp.right is [2]\n # stack =[2]\n\n```\n\n**LEVEL ORDER TRAVERSAL**\n\n**102. Binary Tree Level Order Traversal**\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def levelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n output =[]\n self.dfs(root, 0, output)\n return output\n \n def dfs(self, root, level, output):\n \n if not root:\n return\n \n if len(output) < level+1:\n output.append([])\n \n output[level].append(root.val) \n self.dfs(root.left, level+1, output)\n self.dfs(root.right, level+1, output)\n \n```\n\n**107. Binary Tree Level Order Traversal II**\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def levelOrderBottom(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n output = []\n self.dfs(root, 0, output)\n return output[::-1]\n \n def dfs(self, root, level, output):\n if root is None:\n return\n \n if len(output) < level+1:\n output.append([])\n \n output[level].append(root.val)\n self.dfs(root.left, level+1, output)\n self.dfs(root.right, level+1, output)\n```\n\n**429. N-ary Tree Level Order Traversal**\n```\n"""\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\n\nclass Solution(object):\n def levelOrder(self, root):\n """\n :type root: Node\n :rtype: List[List[int]]\n """\n output=[]\n self.dfs(root, 0, output)\n return output\n \n def dfs(self, root, level ,output):\n if root is None:\n return\n if len(output)< level+1:\n output.append([])\n \n output[level].append(root.val)\n for child in root.children:\n self.dfs(child, level+1, output)\n \n```\n\n**103. Binary Tree Zigzag Level Order Traversal**\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n output=[]\n self.dfs(root, 0, output)\n \n for i in range(len(output)):\n if i % 2 !=0:\n output[i].reverse()\n else:\n continue\n return output\n \n def dfs(self, root, level, output):\n if root is None:\n return\n \n if len(output) < level+1:\n output.append([])\n \n output[level].append(root.val)\n self.dfs(root.left, level+1, output)\n self.dfs(root.right, level+1, output)\n \n```\n\n\n**BINARY TREE CONSTRUCTION**\n\n\n**105. Construct Binary Tree from Preorder and Inorder Traversal**\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def buildTree(self, preorder, inorder):\n """\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n """\n \n if not inorder or not preorder:\n return None\n \n #pattern is preorder=[root, left, right]\n #inorder = [left, root, right], so find index and value using root.\n \n root = TreeNode(preorder[0])\n \n root_index= 0\n \n #iterate through inorder list and find the list index of the root.\n for i in range(len(inorder)):\n if inorder[i]== root.val:\n root_index = i\n else:\n continue\n \n #slice the inorder list into left and right. \n left_inorder = inorder[:root_index]\n right_inorder = inorder[root_index+1:]\n \n #slice the preorder list into left and right.\n left_preorder = preorder[1:len(left_inorder)+1]\n right_preorder = preorder[len(left_preorder)+1:]\n \n #append by updating preorder and inorder lists\n root.left = self.buildTree(left_preorder, left_inorder)\n root.right = self.buildTree(right_preorder, right_inorder)\n \n return root\n```\n\n**106. Construct Binary Tree from Inorder and Postorder Traversal**\n\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def buildTree(self, inorder, postorder):\n """\n :type inorder: List[int]\n :type postorder: List[int]\n :rtype: TreeNode\n """\n # PATTERN\n # inorder: l, root, right\n # postorder: l,r,root\n # the last element of postorder is root\n \n if not inorder or not postorder:\n return None\n \n root_index=0\n \n # Build the data structure based on root value\n root = TreeNode(postorder.pop())\n \n for i in range(len(inorder)):\n if inorder[i]==root.val:\n root_index=i\n else:\n continue\n \n left_in=inorder[:root_index]\n right_in = inorder[root_index+1:]\n \n root.right = self.buildTree(right_in, postorder)\n root.left = self.buildTree(left_in, postorder)\n\n return root\n \n```\n\n**889. Construct Binary Tree from Preorder and Postorder Traversal:** \nRuntime: 40 ms, faster than 80.14%\n\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def constructFromPrePost(self, pre, post):\n """\n :type pre: List[int]\n :type post: List[int]\n :rtype: TreeNode\n """\n if not pre:\n return None\n \n root = TreeNode(post.pop())\n \n if len(pre) == 1:\n return root\n \n # Find the index of the root value from pre\n for i in range(len(pre)):\n if pre[i]==post[-1]:\n root_index= i\n else:\n continue\n \n root.right = self.constructFromPrePost(pre[root_index:], post) \n root.left = self.constructFromPrePost(pre[1:root_index],post) \n \n return root \n \n# Explanation: root=1, root_index = 0, root.right=(pre(1,2,3,4,5,6,7)) [1, 2,3,4,5,6,7] vii\n\t\t\t\t\t\t\t\t\t# root = 3, root_index= 4, root.right=(pre(3,6,7)) [3,4,5,6,7] v\n\t\t\t\t\t\t\t\t\t\t\t# root=7, root_index=2, root.right= pre(7), now len(pre) == 1, return 7 ---[7] i\n\t\t\t\t\t\t\t\t\t\t\t# root =6, root_index=1, root.left= pre(6), now len(pre)==1, return 6 -----[6,7] ii \n\n\t\t\t\t\t\t\t\t\t# root =2, root_index= 1, root.right= pre(2,4,5) [2,3,4,5,6,7] vi \n\t\t\t\t\t\t\t\t\t\t\t# root = 5, root_index=2, root.right= pre(5) now len(pre)==1, return 5 ----[5,6,7] iii\n\t\t\t\t\t\t\t\t\t\t\t# root = 4, root_index=1, root.right= pre(4) now len(pre)==1, return 4-----[4,5,6,7] iv\n\n```\n=========================================================\nHope you\'ve found the solutions useful. Please do UPVOTE, it only motivates me to write more such posts. Thanks!
9,604
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
947
5
# Intuition\nThe problem requires checking whether a binary tree is a valid binary search tree (BST). A BST is a binary tree where for each node, the values of all nodes in its left subtree are less than the node\'s value, and the values of all nodes in its right subtree are greater than the node\'s value.\n\n# Approach\nThe approach is based on a recursive algorithm. At each node, we check if its value lies within a certain range, which is determined by its position in the tree. The initial range for the root is (-\u221E, +\u221E). As we traverse the tree, the range narrows down for each node based on its value and position.\n\n1. **Initialization**: Start with the root of the binary tree and an initial range of (-\u221E, +\u221E).\n\n **Reason**: We begin the recursive check from the root with an unbounded range.\n\n2. **Range Check**: For each node, check if its value lies within the current range. If the value is not within the range, return false.\n\n **Reason**: A binary tree is a valid BST only if the values of its nodes satisfy the BST property.\n\n3. **Recursive Check**: Recursively check the left and right subtrees of the current node, updating the range accordingly.\n\n **Reason**: We need to check the left and right subtrees to ensure the entire tree satisfies the BST property.\n\n4. **Termination Condition**: If we reach a null node, return true, as a null node is a valid BST.\n\n **Reason**: The recursion should terminate when we reach the end of a branch.\n\n5. **Result**: The final result is the boolean value returned by the recursive function.\n\n **Reason**: The result indicates whether the entire binary tree is a valid BST.\n\n# Complexity\n- **Time complexity**: O(n)\n - We visit each node once during the recursive check.\n- **Space complexity**: O(h)\n - The maximum depth of the recursion stack is the height of the binary tree. In the worst case, the space complexity is proportional to the height of the tree.\n\n# Code\n\n\n<details open>\n <summary>Python Solution</summary>\n\n```python\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def bst(root, min_val=float(\'-inf\'), max_val=float(\'inf\')):\n if root == None:\n return True\n\n if not (min_val < root.val < max_val):\n return False\n\n return (bst(root.left, min_val, root.val) and\n bst(root.right, root.val, max_val))\n\n return bst(root)\n```\n</details>\n\n<details open>\n <summary>C++ Solution</summary>\n\n```cpp\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n return bst(root, LLONG_MIN, LLONG_MAX);\n }\n\n bool bst(TreeNode* root, long long min_val, long long max_val) {\n if (root == NULL) {\n return true;\n }\n\n if (!(min_val < root->val && root->val < max_val)) {\n return false;\n }\n\n return bst(root->left, min_val, root->val) && bst(root->right, root->val, max_val);\n }\n};\n```\n</details>\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n
9,611
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
9,672
86
There are two steps:\n1. set a range (at first we set it to (-infinity, infinity)\n2. see if every node is in their own range\n![image]()\nHere\'s the one line code:\n```\nclass Solution:\n def isValidBST(self, node: Optional[TreeNode],low=-inf, high=inf) -> bool:\n return (not node) or ((low < node.val < high) and self.isValidBST(node.left, low, node.val) and self.isValidBST(node.right, node.val, high))\n```\n\nHere\'s the code for better understand:\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n def helper(node, low, high):\n if not node:\n return True\n if not (low < node.val < high):\n return False\n return helper(node.left, low, node.val) and helper(node.right, node.val, high)\n \n return helper(root, -inf, inf)\n```\n**Please UPVOTE if you LIKE!!**\n![image]()\n
9,617
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
8,041
40
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.***\n**Also you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n**C++**\n```\nclass Solution {\npublic:\n void helper(TreeNode* root, vector<int> & ans){\n if(root==NULL ) return;\n helper(root->left, ans);\n ans.push_back(root->val);\n helper(root->right, ans);\n \n }\n bool isValidBST(TreeNode* root) {\n vector<int> ans;\n helper(root, ans);\n for(int i=0; i<ans.size()-1; i++){\n if( ans[i]>= ans[i+1] ) return false;\n }\n return true;\n }\n};\n```\n\n**PYTHON**\n\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def valid_bst(root, min_val, max_val):\n if root is None:\n return True\n if root.val <= min_val or root.val >= max_val:\n return False\n return valid_bst(root.left, min_val, root.val) and valid_bst(root.right, root.val, max_val)\n return valid_bst(root, -2**31-1, 2**31)\n```\n**JAVA**\n\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n \n return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE);\n }\n \n public boolean isValidBST(TreeNode root,long minval,long maxval){\n if(root == null) return true;\n if(root.val >= maxval || root.val <= minval) return false;\n \n return isValidBST(root.left,minval,root.val) && isValidBST(root.right,root.val,maxval);\n }\n}\n```\n**Please UPVOTE if you LIKE!!**
9,628
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
945
7
**If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n def solve(root, min_val, max_val):\n if root is None:\n return True\n \n if root.val <= min_val or root.val >= max_val:\n return False\n\n left = solve(root.left, min_val, root.val)\n right = solve(root.right, root.val, max_val)\n return left and right \n\n return solve(root, float(\'-inf\'), float(\'inf\'))\n```
9,630
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
2,474
22
Method: `recursion`\n```\ndef isValidBST(self, root: Optional[TreeNode]) -> bool:\n\tdef check_validate(root, lower, upper):\n\t\tif not root:\n\t\t\treturn True\n\t\tif lower >= root.val or upper <= root.val:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn check_validate(root.left, lower, root.val) and check_validate(\n\t\t\t\troot.right, root.val, upper\n\t\t\t)\n\n\treturn check_validate(root, -math.inf, math.inf)\n```\n\n**Time Complexity**: `O(n)`\n**Space Complexity**: `O(n)`\n<br/>\nUsing `in-order`, much more easy-understanding\n```\nlast = -math.inf\nended = False\ndef isValidBST(self, root: Optional[TreeNode]) -> bool:\n\tdef check_validate(cur):\n\t\tif self.ended:\n\t\t\treturn \n\t\tif cur.left:\n\t\t\tcheck_validate(cur.left)\n\n\t\tif not(cur.val > self.last):\n\t\t\tself.ended = True\n\t\t\treturn\n\n\t\tself.last = cur.val\n\t\tif cur.right:\n\t\t\tcheck_validate(cur.right)\n\tcheck_validate(root)\n\treturn not self.ended\n```\n\n**Time Complexity**: `O(n)`\n**Space Complexity**: `O(n)`\n<br/>\n
9,631
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
704
6
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.***\n**Also you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n**C++**\n```\nclass Solution {\npublic:\n void helper(TreeNode* root, vector<int> & ans){\n if(root==NULL ) return;\n helper(root->left, ans);\n ans.push_back(root->val);\n helper(root->right, ans);\n \n }\n bool isValidBST(TreeNode* root) {\n vector<int> ans;\n helper(root, ans);\n for(int i=0; i<ans.size()-1; i++){\n if( ans[i]>= ans[i+1] ) return false;\n }\n return true;\n }\n};\n```\n\n**PYTHON**\n\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def valid_bst(root, min_val, max_val):\n if root is None:\n return True\n if root.val <= min_val or root.val >= max_val:\n return False\n return valid_bst(root.left, min_val, root.val) and valid_bst(root.right, root.val, max_val)\n return valid_bst(root, -2**31-1, 2**31)\n```\n**JAVA**\n\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n \n return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE);\n }\n \n public boolean isValidBST(TreeNode root,long minval,long maxval){\n if(root == null) return true;\n if(root.val >= maxval || root.val <= minval) return false;\n \n return isValidBST(root.left,minval,root.val) && isValidBST(root.right,root.val,maxval);\n }\n}\n```\n**Please UPVOTE if you LIKE!!**
9,646
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
1,866
12
```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def BST(root,mx,mi):\n if not root:\n return True\n elif root.val>=mx or root.val<=mi:\n return False\n else:\n return BST(root.left,root.val,mi) and BST(root.right,mx,root.val)\n return BST(root,float(\'inf\'),float(\'-inf\'))\n```\n# please upvote me it would encourage me alot\n
9,647
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
17,886
102
O( n ) sol. by divide-and-conquer.\n\n[\u672C\u984C\u5C0D\u61C9\u7684\u4E2D\u6587\u89E3\u984C\u6587\u7AE0]()\n\n---\n\n**Hint**:\n\nThink of BST rule:\n**Left sub-tree** nodes\' value **< current** node value\n**Right sub-tree** nodes\' value **> current** node value\n\n---\n\n**Algorithm**:\n\nStep_#1:\nSet upper bound as maximum integer, and lower bound as minimum integer in run-time environment.\n\nStep_#2:\nStart DFS traversal from root node, and check whether each level follow BST rules or not.\nUpdate lower bound and upper bound before going down to next level.\n\nStep_#3:\nOnce we find the violation, reject and early return False.\nOtherwise, accept and return True if all tree nodes follow BST rule.\n\n---\n\nPython\n\n```\nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n \n # Use maximal system integer to represent infinity\n INF = sys.maxsize\n \n def helper(node, lower, upper):\n \n if not node:\n\t\t\t\t# empty node or empty tree\n return True\n \n if lower < node.val < upper:\n\t\t\t\t# check if all tree nodes follow BST rule\n return helper(node.left, lower, node.val) and helper(node.right, node.val, upper)\n \n else:\n\t\t\t\t# early reject when we find violation\n return False\n \n # ----------------------------------\n \n return helper( node=root, lower=-INF, upper=INF )\n```\n\n---\n\nJava\n\n<details>\n\t<summary>Click to show source code\n\t</summary>\n\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n \n return checker( -INF, INF, root);\n }\n \n private boolean checker( long lower, long upper, TreeNode node ){\n \n if( node == null ){\n return true;\n }\n \n if( (lower < node.val) && ( node.val < upper ) ){\n return checker(lower, node.val, node.left) && checker(node.val, upper, node.right);\n }\n \n return false;\n }\n \n private long INF = Long.MAX_VALUE;\n\n}\n```\n\n</details>\n\n---\n\nC++\n\n<details>\n\t<summary>Click to show source code\n\t</summary>\n\t\n```\n\tclass Solution {\n\tpublic:\n\t\tbool isValidBST(TreeNode* root) {\n\n\t\t\treturn validate(root, std::numeric_limits<long>::min(), std::numeric_limits<long>::max() );\n\t\t}\n\n\tprivate:\n\t\tbool validate(TreeNode* node, long lower, long upper){\n\n\t\t\tif( node == NULL ){\n\n\t\t\t\t// empty node or empty tree is valid always\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif( (lower < node->val) && (node->val < upper) ){\n\n\t\t\t\t// check if all tree nodes follow BST rule\n\t\t\t\treturn validate(node->left, lower, node->val) && validate(node->right, node->val, upper);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t// early reject when we find violation\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t}\n\t};\n```\n\n</details>\n\n,or\n\n<details>\n\t<summary>Click to show source code\n\t</summary>\n\t\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n \n prev = NULL;\n \n return validate(root );\n }\n \nprivate:\n TreeNode *prev;\n bool validate(TreeNode* node){\n \n if( node == NULL ){\n \n // empty node or empty tree is valid always\n return true;\n }\n \n \n if( !validate(node->left ) ){\n return false;\n }\n \n if( prev != NULL && (node->val <= prev -> val) ){\n return false;\n }\n prev = node;\n \n return validate(node->right);\n \n }\n};\n```\n\n</details>\n\n\n\n---\nGo\n\n<details>\n\t<summary>Click to show source code\n\t</summary>\n\t\n```\nfunc isValidBST(root *TreeNode) bool {\n \n return validate( root, math.MinInt, math.MaxInt)\n}\n\nfunc validate(node *TreeNode, lower int, upper int)bool{\n \n if node == nil{\n \n //empty node or empty tree is always valid\n return true\n }\n \n if( (lower < node.Val) && (node.Val < upper) ){\n \n // check if all tree nodes follow BST rule\n return validate( node.Left, lower, node.Val ) && validate( node.Right, node.Val, upper )\n }else{\n \n // early reject when we find violation\n return false\n }\n \n}\n```\n\n</details>\n\n---\n\nJavascript\n\n<details>\n\t<summary>Click to show source code\n\t</summary>\n\t\n```\nvar isValidBST = function(root) {\n \n return validate(root, -Infinity, Infinity);\n};\n\n\nvar validate = function(node, lower,upper){\n \n if ( node == null ){\n \n // empty node or empty tree\n return true;\n }\n \n if( (lower < node.val) && ( node.val < upper ) ){\n \n // check if all tree nodes follow BST rule\n return validate( node.left, lower, node.val) && validate( node.right, node.val, upper);\n }else{\n \n // early reject when we find violation\n return false;\n }\n \n}\n```\n\n</details>\n\n---\n\nShare anotehr implementation with well-ordered property of BST\'s inorder traversal\n\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n def checker(node):\n \n if not node:\n\t\t\t\t## Base case\n # empty node or empty tree\n yield True\n \n else:\n ## General cases:\n\n yield from checker(node.left)\n\n if checker.prev and (checker.prev.val >= node.val):\n # previous node should be smaller then current node\n # find violation\n yield False\n\n checker.prev = node\n\n yield from checker(node.right)\n \n return\n # ---------------------------------------\n \n # use the property that inorder traversla of BST outputs sorted ascending sequence naturally\n checker.prev = None\n return all( checker(root) )\n```\n\n---\n\nRelative leetcode challenge\n\n[Leetcode #99 Recover Binary Search Tree]()\n\n[Leetcode #700 Search in a Binary Search Tree]()
9,651
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
1,227
10
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.***\n**Also you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n**C++**\n```\nclass Solution {\npublic:\n void helper(TreeNode* root, vector<int> & ans){\n if(root==NULL ) return;\n helper(root->left, ans);\n ans.push_back(root->val);\n helper(root->right, ans);\n \n }\n bool isValidBST(TreeNode* root) {\n vector<int> ans;\n helper(root, ans);\n for(int i=0; i<ans.size()-1; i++){\n if( ans[i]>= ans[i+1] ) return false;\n }\n return true;\n }\n};\n```\n\n**PYTHON**\n\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def valid_bst(root, min_val, max_val):\n if root is None:\n return True\n if root.val <= min_val or root.val >= max_val:\n return False\n return valid_bst(root.left, min_val, root.val) and valid_bst(root.right, root.val, max_val)\n return valid_bst(root, -2**31-1, 2**31)\n```\n**JAVA**\n\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n \n return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE);\n }\n \n public boolean isValidBST(TreeNode root,long minval,long maxval){\n if(root == null) return true;\n if(root.val >= maxval || root.val <= minval) return false;\n \n return isValidBST(root.left,minval,root.val) && isValidBST(root.right,root.val,maxval);\n }\n}\n```\n**Please UPVOTE if you LIKE!!**
9,657
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
2,078
9
\n def dfs(lower,upper,node):\n if not node:\n return True\n elif node.val<=lower or node.val>=upper:\n return False\n else:\n return dfs(lower,node.val,node.left) and dfs(node.val,upper,node.right)\n return dfs(float(\'-inf\'),float(\'inf\'),root) \n```
9,658
Validate Binary Search Tree
validate-binary-search-tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows:
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
377
5
Take the time to read the post, it explains the intuition fully. Practice makes perfect :)\n\nIf you found this post helpful, please upvote <3\n\n<hr />\n\n# Terminology\nFirst, let\'s recall what is a `binary search tree`.\n\nBinary search tree is simply a binary tree where all values to the **left are smaller** than the current node\'s value, and all values to the **right are bigger** than the current node\'s value.\n\nSome examples of BSTs:\n\n![image]()\n\nNow with this understanding, let\'s tackle the problem.\n\n# Intuition\n\nKnowing what is a BST, we need to think about the **local constraints** for each subtree.\n\nWhenever we are working with binary trees (or any recursive data structure) we should think how to "validate" a subtree (subproblem), and return that answer to the parent to recursively continue the process.\n\n\nLet\'s take the previous tree as an example:\n\n**EDIT:** the arrows may confuse some readers. The current value must be smaller than the green arrow, and bigger than blue arrow.\n\n![image]()\n\n\nWe know that the current subtree of value 4, must bigger than 3, but also smaller than the parent that branched left (because all values on the left are smaller), which is 5.\n\nLet\'s call them `parent_minimum` and `parent_maximum` values.\n\nLet\'s take the another example:\n\n![image]()\n\nWe know that the subtree with value 6 must be smaller than 7, because 7 is located to the right of that subtree. But also 6 must be greater than 5, because 5 is located to the left, hence the values is smaller.\n\nWith this idea we have everything to write the code\n\n# Algorithm\nThe algorithm will run a post order DFS traversal, to first validate left and right subtrees.\n\nIf both subtrees are valid, we will check the constraints discussed above.\n\nWhenever we branch left, the current node value is the `parent_maximum`, because all values to the left must be smaller.\n\nWhenever we branch right, the current node value is the `parent_minimum`, because all values to the right must be greater.\n\n# Code\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n def is_valid_root(node, parent_maximum, parent_minimum):\n if not node: return True\n \n # Check left side\n if not is_valid_root(node.left, node.val, parent_minimum): return False\n \n # Check right side\n if not is_valid_root(node.right, parent_maximum ,node.val): return False\n \n # Check constraints with current node\n if node.val >= parent_maximum or node.val <= parent_minimum: return False\n \n # Otherwise we are good\n return True\n \n \n return is_valid_root(root, float(\'inf\'), float(\'-inf\'))\n```\n
9,664
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
4,140
52
Pretty sure mine is the easiest one to understand. \n\nIf you do not want to spend much time on that, you could read the examples below the orange highlight line and get the idea.\n\nIf you do not think so, please comment.\n\nIf you have additional questions, please let me know\n\n**Please upvote me if you think this is helpful :) Much Appreciated!**\n\n![image]()\n\n****\n\nPython Solution\n```\nclass Solution(object):\n def recoverTree(self, root):\n\t\n # the idea is the in order BST is always increasing, if not, then there is something wrong\n def inorderBST(root):\n if not root: return\n \n # track left side to start with min\n inorderBST(root.left)\n\n # so that the first prev is the smallest node\n # and update each time\n if self.prev:\n \n # when order is wrong\n\t\t\t\t# check the examples in the illustration\n if self.prev.val > root.val:\n if not self.first:\n self.first = self.prev\n self.second = root\n \n # update the prev node\n self.prev = root\n \n # check right side\n inorderBST(root.right)\n \n \n self.first = self.second = self.prev = None\n inorderBST(root)\n \n # swap the two wrong ones\n self.first.val, self.second.val = self.second.val, self.first.val\n \n return\n```\n\n****\n\nCompressed 11-line Python Solution\n```\nclass Solution(object):\n def recoverTree(self, root):\n\n def inorderBST(root):\n if not root: return\n \n inorderBST(root.left)\n\n if self.prev and self.prev.val > root.val:\n if not self.first: self.first = self.prev\n self.second = root\n self.prev = root\n\n inorderBST(root.right)\n \n \n self.first = self.second = self.prev = None\n inorderBST(root)\n self.first.val, self.second.val = self.second.val, self.first.val\n```
9,712
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
74,001
284
Wrote some tools for my own local testing. For example `deserialize('[1,2,3,null,null,4,null,null,5]')` will turn that into a tree and return the root [as explained in the FAQ](). I also wrote a visualizer. Two examples:\n\n`drawtree(deserialize('[1,2,3,null,null,4,null,null,5]'))`:\n\n![enter image description here][1]\n\n`drawtree(deserialize('[2,1,3,0,7,9,1,2,null,1,0,null,null,8,8,null,null,null,null,7]'))`:\n\n![enter image description here][2]\n\nHere's the code. If you save it as a Python script and run it, it should as a demo show the above two pictures in turtle windows (one after the other). And you can of course import it from other scripts and then it will only provide the class/functions and not show the demo.\n\n class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n def __repr__(self):\n return 'TreeNode({})'.format(self.val)\n \n def deserialize(string):\n if string == '{}':\n return None\n nodes = [None if val == 'null' else TreeNode(int(val))\n for val in string.strip('[]{}').split(',')]\n kids = nodes[::-1]\n root = kids.pop()\n for node in nodes:\n if node:\n if kids: node.left = kids.pop()\n if kids: node.right = kids.pop()\n return root\n \n def drawtree(root):\n def height(root):\n return 1 + max(height(root.left), height(root.right)) if root else -1\n def jumpto(x, y):\n t.penup()\n t.goto(x, y)\n t.pendown()\n def draw(node, x, y, dx):\n if node:\n t.goto(x, y)\n jumpto(x, y-20)\n t.write(node.val, align='center', font=('Arial', 12, 'normal'))\n draw(node.left, x-dx, y-60, dx/2)\n jumpto(x, y-20)\n draw(node.right, x+dx, y-60, dx/2)\n import turtle\n t = turtle.Turtle()\n t.speed(0); turtle.delay(0)\n h = height(root)\n jumpto(0, 30*h)\n draw(root, 0, 30*h, 40*h)\n t.hideturtle()\n turtle.mainloop()\n \n if __name__ == '__main__':\n drawtree(deserialize('[1,2,3,null,null,4,null,null,5]'))\n drawtree(deserialize('[2,1,3,0,7,9,1,2,null,1,0,null,null,8,8,null,null,null,null,7]'))\n\n [1]: \n [2]:
9,716
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
3,411
45
![image]()\n\nCASE 1:\n4, 15, 7, 10, 14, 5, 17\nWe reach 7, prev.val(15) >root.val(7) VIOLATION! Hence, found first.\nfirst = 15(prev) and second = 7(root)\nWe go to 7,10,14... all obey the sorted order.\nWe reach 5, prev.val(14) > root.val(5) VIOLATION! Hence, found second.\nsecond = 5 (root)\nEverything else in the array is fine.\nSwap first and second. Done!\n\nCase 2:\n4,5, 7, 10, 15, 14, 17\nReaches upto 15 safely.\nComes to 14, VIOLATION. Found first.\nfirst = 15(prev) and second = 14(root)\nEverything else works fine.\nSwap first and second. Done!\n\n\n```\nclass Solution(object):\n def recoverTree(self, root):\n """\n :type root: TreeNode\n :rtype: None Do not return anything, modify root in-place instead.\n """\n self.first, self.second, self.prevNode = None, None, None # Create three nodes.\n self.inOrder(root) # Calling the function\n self.first.val, self.second.val = self.second.val, self.first.val \n # Swapping the two elements needed to be swapped\n \n def inOrder(self, root):\n if not root:\n return\n self.inOrder(root.left)\n \n if self.prevNode: # To handle the case of first node, because we make it prev to begin with\n if self.prevNode.val > root.val: # Check property violation\n if not self.first: \n self.first = self.prevNode # Found first pair\n self.second = root # If the second pair is found then simply assign the smaller element of the pair as the second guy, it works for single pair easily, as it wont get updated again in that case.\n \n self.prevNode = root\n \n self.inOrder(root.right)\n \n```
9,735
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
2,289
6
```\nclass Solution:\n def recoverTree(self, root: Optional[TreeNode]) -> None:\n done = True\n def recur(node, not_less_than, not_greater_than):\n nonlocal done\n if not_less_than and node.val < not_less_than.val:\n node.val, not_less_than.val = not_less_than.val, node.val\n done = True \n if not_greater_than and node.val > not_greater_than.val:\n node.val, not_greater_than.val = not_greater_than.val, node.val\n done = True \n if not done and node.left: recur(node.left, not_less_than, node)\n if not done and node.right: recur(node.right, node, not_greater_than)\n while done: \n done = False\n recur(root, None, None)\n```
9,736
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
2,210
20
The space taken by the recursion call is not considered as a space complexity here.\nThe extra space is usually used to store the inorder traversal list. which is not used in this solution.\n\nInOrder traversal for BST means the tree is traversed in sorted order, so if any node breaks the sorted order that wll be our node to swap.\nthat is the first and last node which breaks the sorting is our culprit !!\n\n```\ndef recoverTree(self, root: Optional[TreeNode]) -> None:\n \n res = [] \n startnode = None\n prev = None\n lastnode = None\n \n def dfs(root):\n nonlocal res, startnode, prev, lastnode\n if not root:\n return \n # go to left (inorder step 1) \n dfs(root.left)\n\t\t\t\n # do processing....(inorder step 2)\n\t\t\t# get the first node where the sorted order is broken the first time and the last time\n if prev and prev.val > root.val:\n if not startnode:\n startnode = prev\n lastnode = root\n \n prev = root\n\t\t\t\n # go to right (inorder step 3) \n dfs(root.right)\n \n \n dfs(root)\n # swap the nodes that are not in place\n if startnode and lastnode:\n startnode.val, lastnode.val = lastnode.val, startnode.val\n```\n\n***Please upvote for motivation***
9,757
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
1,552
13
This solution compares the in-order traversal of the tree, which in a correct binary tree should return the elements sorted in ascending order. We then compare this against the sorted elements and swap as soon as we find a mismatch.\n\n```python\n def recoverTree(self, root: Optional[TreeNode]) -> None:\n in_order = []\n def inOrder(node):\n if node is None:\n return\n inOrder(node.left)\n in_order.append(node)\n inOrder(node.right)\n \n inOrder(root)\n\n sorted_order = sorted(in_order, key=lambda x:x.val)\n for i in range(len(in_order)):\n if in_order[i] != sorted_order[i]:\n in_order[i].val, sorted_order[i].val = sorted_order[i].val, in_order[i].val\n return\n```
9,763
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
10,233
55
```\n\nclass Solution(object): \n def recoverTree(self, root): # O(lg(n)) space\n pre = first = second = None\n stack = []\n while True:\n while root:\n stack.append(root)\n root = root.left\n if not stack:\n break\n node = stack.pop()\n if not first and pre and pre.val > node.val:\n first = pre\n if first and pre and pre.val > node.val:\n second = node\n pre = node\n root = node.right\n first.val, second.val = second.val, first.val\n \n def recoverTree1(self, root): # O(n+lg(n)) space \n res = []\n self.dfs(root, res)\n first, second = None, None\n for i in range(len(res)-1):\n if res[i].val > res[i+1].val and not first:\n first = res[i]\n if res[i].val > res[i+1].val and first:\n second = res[i+1]\n first.val, second.val = second.val, first.val\n \n def dfs(self, root, res):\n if root:\n self.dfs(root.left, res)\n res.append(root)\n self.dfs(root.right, res)\n```
9,782
Recover Binary Search Tree
recover-binary-search-tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
1,945
15
### Main idea - __*Inorder Traversal*__\n\n![image]()\n![image]()\n![image]()\n![image]()\n![image]()\n![image]()\n\ncode - \n\n```java\n\nclass Solution{\npublic static ArrayList<TreeNode> arr;\n\n public static void dfs(TreeNode root) {\n if (root == null) return;\n dfs(root.left);\n arr.add(root);\n dfs(root.right);\n }\n\n public static void solve(TreeNode root) {\n arr = new ArrayList<TreeNode>();\n dfs(root);\n TreeNode a = null;\n TreeNode b = null;\n int n = arr.size();\n for (int i = 0; i < n; i++) {\n int left = i - 1 >= 0 ? arr.get(i - 1).val : Integer.MIN_VALUE;\n int right = i + 1 < n ? arr.get(i + 1).val : Integer.MAX_VALUE;\n int curr = arr.get(i).val;\n if (curr > left && curr > right && left < right) {\n a = arr.get(i);\n } else if (curr < left && curr < right && left < right) {\n b = arr.get(i);\n }\n }\n if (a != null && b != null) {\n int temp = a.val;\n a.val = b.val;\n b.val = temp;\n }\n }\n}\n\n```\n\n\n\n
9,785
Same Tree
same-tree
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
112
5
\n\nWe\'ll use recursion to perform a depth-first search of both trees and compare the nodes, p and q, at each step. This recursive algorithm has three base cases:\n1. Are both p and q None? If so, then return True. This is because this only happens when we\'ve reached the end of a branch, and all the nodes so far have matched.\n\nIf that wasn\'t true, then now we know that either p or q is a Node. But are they both nodes or is only one of them None? This leads to the second base case:\n\n2. Is either p or q None? If so, then return False, since that means one of them is None and one of them is a node, and those are clearly different from each other.\n\nIf that wasn\'t true, then at this point we know that both p and q are nodes, so let\'s compare their values:\n\n3. Are the values of p and q different? If so, return False.\n\nIf that wasn\'t true, then at this point we know that both p and q are nodes and their values are the same. So then we make two recursive calls. We\'ll pass in `p.left` and `q.left` for the first call to check the left subtree, and pass in `p.right` and `q.right` for the right subtree. For a visualization of the recursion, please see the video. But the idea is that both left subtrees and right subtrees must be the same, which is why the two recursive calls are connected with an `and`.\n\n# Code\n```\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n # Are both p and q None?\n if not p and not q:\n return True\n\n # Is one of them None?\n if not p or not q:\n return False\n\n # Are their values different?\n if p.val != q.val:\n return False\n\n # Recursive call to the next level down\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n```\n
9,801
Same Tree
same-tree
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
20,078
301
## ***Please Upvote my solution, if you find it helpful ;)***\n\n# Intuition\nThe intuition behind the solution is to recursively check if two binary trees are identical. If both trees are empty (null), they are considered identical. If only one tree is empty or the values of the current nodes are different, the trees are not identical. Otherwise, we recursively check if the left and right subtrees of both trees are identical.\n\n# Approach\n1. Check the base case: if both trees are null, return true.\n1. Check if only one tree is null or the values of the current nodes are different, return false.\n1. Recursively check if the left subtrees of both trees are identical.\n1. Recursively check if the right subtrees of both trees are identical.\n1. Return the logical AND of the results from steps 3 and 4.\n\n Complexity\n- Time complexity:\nThe time complexity of the solution is $$O(min(N, M))$$, where N and M are the number of nodes in the two trees, respectively. This is because we need to visit each node once in order to compare their values. In the worst case, where both trees have the same number of nodes, the time complexity would be O(N).\n\n- Space complexity:\nThe space complexity of the solution is$$O(min(H1, H2))$$, where H1 and H2 are the heights of the two trees, respectively. This is because the space used by the recursive stack is determined by the height of the smaller tree. In the worst case, where one tree is significantly larger than the other, the space complexity would be closer to O(N) or O(M), depending on which tree is larger.\n\n# Code\n```java []\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n // Base case: if both trees are null, they are identical\n if (p == null && q == null) {\n return true;\n }\n // If only one tree is null or the values are different, they are not identical\n if (p == null || q == null || p.val != q.val) {\n return false;\n }\n // Recursively check if the left and right subtrees are identical\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n }\n}\n\n```\n```python []\nclass Solution:\n def isSameTree(self, p, q):\n # If both nodes are None, they are identical\n if p is None and q is None:\n return True\n # If only one of the nodes is None, they are not identical\n if p is None or q is None:\n return False\n # Check if values are equal and recursively check left and right subtrees\n if p.val == q.val:\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n # Values are not equal, they are not identical\n return False\n```\n```C++ []\nclass Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n // If both nodes are NULL, they are identical\n if (p == NULL && q == NULL) {\n return true;\n }\n // If only one of the nodes is NULL, they are not identical\n if (p == NULL || q == NULL) {\n return false;\n }\n // Check if values are equal and recursively check left and right subtrees\n if (p->val == q->val) {\n return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n }\n // Values are not equal, they are not identical\n return false;\n }\n};\n```\n## ***Please Upvote my solution, if you find it helpful ;)***\n![6a87bc25-d70b-424f-9e60-7da6f345b82a_1673875931.8933976.jpeg]()\n
9,802
Same Tree
same-tree
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
2,249
43
### My aim is to explain this problem using multiple approaches because I was asked to solve it that way during an interview.\n\n# 1st Method :- Recursive (DFS) Preorder traversal \uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe code is designed to determine if two binary trees `p` and `q` are identical or not. To consider the trees as identical, they must have the same structure, and corresponding nodes must have the same values.\n\n## Approach \uD83D\uDE80\n1. **Base Cases:**\n - The code starts with two base cases. If both `p` and `q` are `null`, this means both trees are empty, and they are considered identical. In this case, it returns `true`.\n - If one of the trees is `null` while the other is not, the trees cannot be identical, so it returns `false`.\n\n2. **Value Comparison:**\n - After handling the base cases, the code compares the values of the current nodes of `p` and `q`. If the values do not match, it means the trees are not identical, and it returns `false`.\n\n3. **Recursive Check of Left and Right Subtrees:**\n - If the values of the current nodes match, the code proceeds to recursively check the left and right subtrees of both trees.\n - The recursive call for the left subtree compares the left child of `p` with the left child of `q`.\n - The recursive call for the right subtree compares the right child of `p` with the right child of `q`.\n - The final result is computed by using the `&&` (logical AND) operator to ensure that both left and right subtrees are identical for the entire tree to be identical.\n\nBy following these steps, the code effectively checks the structure and values of the two trees to determine if they are identical or not. If all nodes match in terms of values and the tree structures are the same, it returns `true`, indicating that the trees are identical; otherwise, it returns `false`.\n\n# Code\n``` Java []\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n // Base case: If both trees are empty, they are identical.\n if (p == null && q == null) {\n return true;\n }\n // If one of the trees is empty and the other is not, they are not identical.\n if (p == null || q == null) {\n return false;\n }\n \n // Compare the values of the current nodes.\n if (p.val != q.val) {\n return false;\n }\n \n // Recursively check the left and right subtrees.\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n } \n}\n```\n``` C++ []\nclass Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n // Base case: If both trees are empty, they are identical.\n if (p == nullptr && q == nullptr) {\n return true;\n }\n // If one of the trees is empty and the other is not, they are not identical.\n if (p == nullptr || q == nullptr) {\n return false;\n }\n \n // Compare the values of the current nodes.\n if (p->val != q->val) {\n return false;\n }\n \n // Recursively check the left and right subtrees.\n return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n }\n};\n```\n``` Python []\nclass Solution:\n def isSameTree(self, p, q):\n # Base case: If both trees are empty, they are identical.\n if not p and not q:\n return True\n # If one of the trees is empty and the other is not, they are not identical.\n if not p or not q:\n return False\n \n # Compare the values of the current nodes.\n if p.val != q.val:\n return False\n \n # Recursively check the left and right subtrees.\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n\n```\n``` JavaScript []\nvar isSameTree = function(p, q) {\n // Base case: If both trees are empty, they are identical.\n if (p === null && q === null) {\n return true;\n }\n\n // If one of the trees is empty and the other is not, they are not identical.\n if (p === null || q === null) {\n return false;\n }\n\n // Compare the values of the current nodes.\n if (p.val !== q.val) {\n return false;\n }\n\n // Recursively check the left and right subtrees.\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n}\n```\n``` C# []\npublic class Solution {\n public bool IsSameTree(TreeNode p, TreeNode q) {\n // Base case: If both trees are empty, they are identical.\n if (p == null && q == null) {\n return true;\n }\n\n // If one of the trees is empty and the other is not, they are not identical.\n if (p == null || q == null) {\n return false;\n }\n\n // Compare the values of the current nodes.\n if (p.val != q.val) {\n return false;\n }\n\n // Recursively check the left and right subtrees.\n return IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);\n }\n}\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(n)\nThe time complexity of this code is O(n), where \'n\' is the number of nodes in the larger of the two trees. In the worst case, it needs to visit every node in both trees to determine if they are identical. The function performs a preorder traversal of the trees, and each node is visited exactly once.\n\n### \uD83C\uDFF9Space complexity: O(n)\nThe space complexity is O(h), where \'h\' is the height of the tree, and it represents the maximum depth of the recursion stack. In the worst case, when the trees are completely unbalanced and have a height of \'n\', the space complexity becomes O(n). However, for balanced trees, such as binary search trees, the space complexity is O(log n), where \'log n\' is the height of the tree.\n\nIt\'s important to note that the space complexity depends on the height of the tree, not just the number of nodes, and it\'s determined by the depth of the recursive function calls on the stack.\n\n![vote.jpg]()\n\n---\n\n# 2nd Method :- level-order traversal using Queues\uD83D\uDD25\nlevel-order traversal approach to determine if two trees are the same.\n\n## Approach \uD83D\uDE80\n1. Two queues, `queue1` and `queue2`, are used to perform a level-order traversal of both trees `p` and `q`. Level-order traversal visits the nodes level by level, starting from the root.\n\n2. The root nodes of both trees `p` and `q` are added to their respective queues to begin the traversal.\n\n3. The while loop continues until both queues are empty or until a mismatch is detected.\n\n4. Inside the loop, it dequeues nodes from both queues: `node1` from `queue1` and `node2` from `queue2`.\n\n5. It checks if the values of the current nodes are equal. If they are not, the trees are not identical, and it returns `false`.\n\n6. If the values match and the nodes are not null, the left and right children of both nodes are enqueued in their respective queues.\n\n7. The traversal continues level by level until all nodes have been compared.\n\n8. After the while loop, if both queues are empty, it means that the trees are identical, and it returns `true`. If one queue is not empty while the other is, the trees are not identical, and it returns `false`.\n\nThis level-order traversal approach efficiently checks whether two trees are identical in terms of structure and values. It is based on a breadth-first search of the trees.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n // Create queues for both trees.\n Queue<TreeNode> queue1 = new LinkedList<>();\n Queue<TreeNode> queue2 = new LinkedList<>();\n\n // Start by adding the root nodes of both trees to their respective queues.\n queue1.offer(p);\n queue2.offer(q);\n\n while (!queue1.isEmpty() && !queue2.isEmpty()) {\n TreeNode node1 = queue1.poll();\n TreeNode node2 = queue2.poll();\n\n // If the values of the current nodes are not equal, the trees are not identical.\n if (node1 == null && node2 == null) {\n continue;\n }\n if (node1 == null || node2 == null || node1.val != node2.val) {\n return false;\n }\n\n // Add the left and right children of both nodes to their respective queues.\n queue1.offer(node1.left);\n queue1.offer(node1.right);\n queue2.offer(node2.left);\n queue2.offer(node2.right);\n }\n\n // If both queues are empty, the trees are identical.\n return queue1.isEmpty() && queue2.isEmpty();\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n // Create queues for both trees.\n std::queue<TreeNode*> queue1;\n std::queue<TreeNode*> queue2;\n\n // Start by adding the root nodes of both trees to their respective queues.\n queue1.push(p);\n queue2.push(q);\n\n while (!queue1.empty() && !queue2.empty()) {\n TreeNode* node1 = queue1.front();\n TreeNode* node2 = queue2.front();\n queue1.pop();\n queue2.pop();\n\n // If the values of the current nodes are not equal, the trees are not identical.\n if (node1 == NULL && node2 == NULL) {\n continue;\n }\n if (node1 == NULL || node2 == NULL || node1->val != node2->val) {\n return false;\n }\n\n // Add the left and right children of both nodes to their respective queues.\n queue1.push(node1->left);\n queue1.push(node1->right);\n queue2.push(node2->left);\n queue2.push(node2->right);\n }\n\n // If both queues are empty, the trees are identical.\n return queue1.empty() && queue2.empty();\n }\n};\n```\n``` Python []\nclass Solution:\n def isSameTree(self, p, q):\n # Create queues for both trees.\n queue1 = deque()\n queue2 = deque()\n\n # Start by adding the root nodes of both trees to their respective queues.\n queue1.append(p)\n queue2.append(q)\n\n while queue1 and queue2:\n node1 = queue1.popleft()\n node2 = queue2.popleft()\n\n # If the values of the current nodes are not equal, the trees are not identical.\n if not node1 and not node2:\n continue\n if not node1 or not node2 or node1.val != node2.val:\n return False\n\n # Add the left and right children of both nodes to their respective queues.\n queue1.append(node1.left)\n queue1.append(node1.right)\n queue2.append(node2.left)\n queue2.append(node2.right)\n\n # If both queues are empty, the trees are identical.\n return not queue1 and not queue2\n```\n``` JavaScript []\nvar isSameTree = function(p, q) {\n // Create queues for both trees.\n const queue1 = [p];\n const queue2 = [q];\n\n while (queue1.length > 0 && queue2.length > 0) {\n const node1 = queue1.shift();\n const node2 = queue2.shift();\n\n // If the values of the current nodes are not equal, the trees are not identical.\n if (!node1 && !node2) {\n continue;\n }\n if (!node1 || !node2 || node1.val !== node2.val) {\n return false;\n }\n\n // Add the left and right children of both nodes to their respective queues.\n queue1.push(node1.left);\n queue1.push(node1.right);\n queue2.push(node2.left);\n queue2.push(node2.right);\n }\n\n // If both queues are empty, the trees are identical.\n return queue1.length === 0 && queue2.length === 0;\n}\n```\n``` C# []\npublic class Solution {\n public bool IsSameTree(TreeNode p, TreeNode q) {\n // Create queues for both trees.\n Queue<TreeNode> queue1 = new Queue<TreeNode>();\n Queue<TreeNode> queue2 = new Queue<TreeNode>();\n\n // Start by adding the root nodes of both trees to their respective queues.\n queue1.Enqueue(p);\n queue2.Enqueue(q);\n\n while (queue1.Count > 0 && queue2.Count > 0) {\n TreeNode node1 = queue1.Dequeue();\n TreeNode node2 = queue2.Dequeue();\n\n // If the values of the current nodes are not equal, the trees are not identical.\n if (node1 == null && node2 == null) {\n continue;\n }\n if (node1 == null || node2 == null || node1.val != node2.val) {\n return false;\n }\n\n // Add the left and right children of both nodes to their respective queues.\n queue1.Enqueue(node1.left);\n queue1.Enqueue(node1.right);\n queue2.Enqueue(node2.left);\n queue2.Enqueue(node2.right);\n }\n\n // If both queues are empty, the trees are identical.\n return queue1.Count == 0 && queue2.Count == 0;\n }\n}\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(N)\nThe code uses a level-order traversal approach, also known as a breadth-first search, to compare the two trees. In the worst case, the code visits every node once, making the time complexity O(N), where N is the total number of nodes in the larger of the two trees. This is because the code processes each node exactly once and does a constant amount of work for each node.\n\n### \uD83C\uDFF9Space complexity: O(N)\nThe space complexity of the code is determined by the space used by the two queues. In the worst case, both queues can hold all nodes of the two trees at the same level. Therefore, the space complexity is O(maxWidth), where maxWidth is the maximum width of the binary trees, which can be roughly proportional to the number of nodes at the widest level. In the worst case, the space complexity can be O(N), where N is the total number of nodes in the larger tree.\n\n\n![vote.jpg]()\n\n---\n# 3rd Method :- level-order traversal using Stack\uD83D\uDD25\n\n## Approach \uD83D\uDE80\nThis approach is called **iterative traversal-based approach** to determine if two trees are the same. Specifically, it is using **stacks** to perform a **level-order traversal** of the trees and compare the nodes iteratively.\n\nHere\'s how the code works:\n\n1. Two stacks, `stack1` and `stack2`, are used to perform a level-order traversal of the trees, starting with the root nodes `p` and `q`.\n\n2. In the while loop, the code pops the top nodes from both stacks and compares their values.\n - If both nodes are `null`, they are considered identical, and the traversal continues.\n - If one of the nodes is `null` or the values are different, the trees are not identical, and the function returns `false`.\n\n3. The code then pushes the left children of both nodes onto `stack1` and `stack2`.\n\n4. Next, it pushes the right children of both nodes onto the stacks.\n\n5. The loop continues until both stacks are empty or until a mismatch is found. If the loop completes without any mismatches and both stacks are empty, the trees are considered identical, and the function returns `true`.\n\nThis approach provides an alternative way to check if two trees are identical without using recursive function calls, making use of stacks for an iterative traversal of the trees.\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n Stack<TreeNode> stack1 = new Stack<>();\n Stack<TreeNode> stack2 = new Stack<>();\n\n // Push the root nodes of both trees onto their respective stacks.\n stack1.push(p);\n stack2.push(q);\n\n while (!stack1.isEmpty() && !stack2.isEmpty()) {\n TreeNode node1 = stack1.pop();\n TreeNode node2 = stack2.pop();\n\n // Compare the values of the current nodes.\n if (node1 == null && node2 == null) {\n // Both nodes are null, so they match.\n continue;\n } else if (node1 == null || node2 == null || node1.val != node2.val) {\n // Nodes are not identical, return false.\n return false;\n }\n\n // Push the left children onto the stacks.\n stack1.push(node1.left);\n stack2.push(node2.left);\n\n // Push the right children onto the stacks.\n stack1.push(node1.right);\n stack2.push(node2.right);\n }\n\n // If both stacks are empty, and no mismatches have been found, the trees are identical.\n return stack1.isEmpty() && stack2.isEmpty();\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n std::stack<TreeNode*> stack1, stack2;\n\n // Push the root nodes of both trees onto their respective stacks.\n stack1.push(p);\n stack2.push(q);\n\n while (!stack1.empty() && !stack2.empty()) {\n TreeNode* node1 = stack1.top();\n stack1.pop();\n TreeNode* node2 = stack2.top();\n stack2.pop();\n\n // Compare the values of the current nodes.\n if (!node1 && !node2) {\n // Both nodes are null, so they match.\n continue;\n } else if (!node1 || !node2 || node1->val != node2->val) {\n // Nodes are not identical, return false.\n return false;\n }\n\n // Push the left children onto the stacks.\n stack1.push(node1->left);\n stack2.push(node2->left);\n\n // Push the right children onto the stacks.\n stack1.push(node1->right);\n stack2.push(node2->right);\n }\n\n // If both stacks are empty, and no mismatches have been found, the trees are identical.\n return stack1.empty() && stack2.empty();\n }\n};\n```\n``` Python []\nclass Solution:\n def isSameTree(self, p, q):\n stack1, stack2 = [p], [q]\n\n while stack1 and stack2:\n node1 = stack1.pop()\n node2 = stack2.pop()\n\n if not node1 and not node2:\n # Both nodes are None, so they match.\n continue\n elif not node1 or not node2 or node1.val != node2.val:\n # Nodes are not identical, return False.\n return False\n\n # Push the left children onto the stacks.\n stack1.append(node1.left)\n stack2.append(node2.left)\n\n # Push the right children onto the stacks.\n stack1.append(node1.right)\n stack2.append(node2.right)\n\n # If both stacks are empty, and no mismatches have been found, the trees are identical.\n return not stack1 and not stack2\n```\n``` JavaScript []\nvar isSameTree = function(p, q) {\n const stack1 = [p];\n const stack2 = [q];\n\n while (stack1.length > 0 && stack2.length > 0) {\n const node1 = stack1.pop();\n const node2 = stack2.pop();\n\n if (!node1 && !node2) {\n continue;\n } else if (!node1 || !node2 || node1.val !== node2.val) {\n return false;\n }\n\n stack1.push(node1.left);\n stack2.push(node2.left);\n stack1.push(node1.right);\n stack2.push(node2.right);\n }\n\n return stack1.length === 0 && stack2.length === 0;\n}\n```\n``` C# []\npublic class Solution {\n public bool IsSameTree(TreeNode p, TreeNode q) {\n Stack<TreeNode> stack1 = new Stack<TreeNode>();\n Stack<TreeNode> stack2 = new Stack<TreeNode>();\n\n stack1.Push(p);\n stack2.Push(q);\n\n while (stack1.Count > 0 && stack2.Count > 0) {\n TreeNode node1 = stack1.Pop();\n TreeNode node2 = stack2.Pop();\n\n if (node1 == null && node2 == null) {\n continue;\n } else if (node1 == null || node2 == null || node1.val != node2.val) {\n return false;\n }\n\n stack1.Push(node1.left);\n stack2.Push(node2.left);\n stack1.Push(node1.right);\n stack2.Push(node2.right);\n }\n\n return stack1.Count == 0 && stack2.Count == 0;\n }\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(N)\nThe algorithm involves a stack-based traversal of both trees. In the worst case, it will visit each node once. The while loop iterates through the nodes, and the key operations inside the loop (pushing and popping nodes from the stacks and comparing values) have constant time complexity. Therefore, the time complexity is linear, O(n).\n\n### \uD83C\uDFF9Space complexity: O(N)\nThe space complexity is determined by the space required for the two stacks. In the worst case, both stacks can contain all nodes of the trees. If the trees are completely unbalanced (e.g., skewed trees), both stacks can hold \'n\' nodes, leading to a space complexity of O(n).\n\nIt\'s worth noting that in the best-case scenario, where the trees are identical and perfectly balanced, the space complexity could be less than O(n). However, the worst-case space complexity is O(n) to account for all possible scenarios.\n\n![vote.jpg]()\n\n---\n# 4th Method :- Tree Hashing\uD83D\uDD25\n\n## Approach \uD83D\uDE80\nThis approach involves generating a unique hash value for each tree by recursively encoding the structure and values of its nodes. The trees are then considered identical if their hash values are the same. Here\'s how this approach works:\n\n1. **Create a Hash for Each Tree:**\n - The `isSameTree` function takes two tree nodes, `p` and `q`, as input.\n - It calculates the hash value for each tree by calling the `computeTreeHash` function for both `p` and `q`.\n\n2. **Recursively Compute Tree Hash:**\n - The `computeTreeHash` function takes a tree node as input.\n - If the node is `null`, it returns the string "null" to represent an empty node.\n - For non-null nodes, it calculates the hash value by recursively computing the hash values of the left and right subtrees and concatenating them with the current node\'s value inside parentheses.\n\n3. **Compare Hash Values:**\n - After computing the hash values for both trees, the code compares these hash values using the `equals` method.\n - If the hash values are equal, the code returns `true`, indicating that the trees are identical; otherwise, it returns `false`.\n\nThis approach relies on the uniqueness and quality of the hash function to accurately determine if two trees are identical. It\'s important to choose a good hashing method that minimizes the risk of hash collisions. While this approach can be used to check tree identity, it may not always be as efficient as traversal-based methods for large or complex trees, as computing and comparing hash values can be time-consuming.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n String hash1 = computeTreeHash(p);\n String hash2 = computeTreeHash(q);\n return hash1.equals(hash2);\n }\n \n private String computeTreeHash(TreeNode node) {\n if (node == null) {\n return "null";\n }\n String leftHash = computeTreeHash(node.left);\n String rightHash = computeTreeHash(node.right);\n return "(" + node.val + leftHash + rightHash + ")";\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n std::string hash1 = computeTreeHash(p);\n std::string hash2 = computeTreeHash(q);\n return hash1 == hash2;\n }\n\nprivate:\n std::string computeTreeHash(TreeNode* node) {\n if (node == nullptr) {\n return "null";\n }\n std::string leftHash = computeTreeHash(node->left);\n std::string rightHash = computeTreeHash(node->right);\n return "(" + std::to_string(node->val) + leftHash + rightHash + ")";\n }\n};\n```\n``` Python []\nclass Solution:\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n hash1 = self.computeTreeHash(p)\n hash2 = self.computeTreeHash(q)\n return hash1 == hash2\n\n def computeTreeHash(self, node: TreeNode) -> str:\n if node is None:\n return "null"\n left_hash = self.computeTreeHash(node.left)\n right_hash = self.computeTreeHash(node.right)\n return f"({node.val}{left_hash}{right_hash})"\n```\n``` JavaScript []\nvar isSameTree = function(p, q) {\n const hash1 = computeTreeHash(p);\n const hash2 = computeTreeHash(q);\n return hash1 === hash2;\n}\n\nfunction computeTreeHash(node) {\n if (node === null) {\n return "null";\n }\n const leftHash = computeTreeHash(node.left);\n const rightHash = computeTreeHash(node.right);\n return `(${node.val}${leftHash}${rightHash})`;\n}\n```\n``` C# []\npublic class Solution {\n public bool IsSameTree(TreeNode p, TreeNode q) {\n string hash1 = ComputeTreeHash(p);\n string hash2 = ComputeTreeHash(q);\n return hash1.Equals(hash2);\n }\n\n private string ComputeTreeHash(TreeNode node) {\n if (node == null) {\n return "null";\n }\n string leftHash = ComputeTreeHash(node.left);\n string rightHash = ComputeTreeHash(node.right);\n return $"({node.val}{leftHash}{rightHash})";\n }\n}\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(N)\n- The `computeTreeHash` function performs a recursive traversal of both trees.\n- In the worst case, it visits every node of both trees.\n- The time complexity is O(n), where \'n\' is the total number of nodes in the trees.\n\n### \uD83C\uDFF9Space complexity: O(N)\n- The space complexity is determined by the space used by the recursive function calls and the space used for the string representations (hashes) of the trees.\n- In the worst case, the maximum depth of the recursion is equal to the height of the trees, which can be O(n) in an unbalanced tree.\n- Additionally, the space used for the hash strings is also O(n).\n- Therefore, the space complexity is O(n) in the worst case.\n\n---\n# Same as 1st Method but in short\n\n``` Java []\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n \n if (p == null || q == null) { return p == q;}\n \n return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); \n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n if (!p || !q) {\n return p == q;\n }\n return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n }\n};\n```\n``` Python []\nclass Solution:\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n if not p or not q:\n return p == q\n return (p.val == q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n```\n``` JavaScript []\nvar isSameTree = function(p, q) {\n if (!p || !q) {\n return p === q;\n }\n return (p.val === q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n}\n```\n``` C# []\npublic class Solution {\n public bool IsSameTree(TreeNode p, TreeNode q) {\n if (p == null || q == null) {\n return p == q;\n }\n return (p.val == q.val) && IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);\n }\n}\n```\n\n![upvote.png]()\n\n# Up Vote Guys\n\n
9,804
Same Tree
same-tree
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,395
10
**Plz Upvote ..if you got help from this.**\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n if p is None or q is None:\n return p == q\n return (p.val== q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n \n```
9,882