Problems
July 15, 2022
Reverse linked list
We start with a null node called previous, iterate through the list, and move it's next printer previous on and then repeat it till the end. Then we just return the previous which is not the current...
ReadJuly 14, 2022
Balanced binary tree
We will traverse the tree with DFS and also keep track of the depth. Then return both the balanced and depth from our DFS recursion. Then we just compare whether the difference between the left and...
ReadJuly 14, 2022
Construct binary tree from preorder and inorder traversal
The first element of the preorder traversal is always the root. So, if we know the root, we can then find the left and right sub tree from inorder traversal. We will then create the tree recursively...
ReadJuly 14, 2022
Diameter of binary tree
We can calculate the depth of a subtree with DFS. Then we add both subtree and store it in our running answer. After the whole tree traversal is done, we return our running answer. Time...
ReadJuly 14, 2022
Invert binary tree
We can take the left subtree and right subtree and swap their position. We will do it recursively for every subtree.
Time Complexity: O(n)
Space Complexity: O(n)
July 14, 2022
Maximum depth of binary tree
We will traverse the tree with DFS and keep a counter to keep track of every level. Then we will take the maximum from both subtree and return the counter.
Time Complexity: O(n)...
July 14, 2022
Maximum depth of n-ary tree
We will traverse the tree with DFS and keep a counter to keep track of every level. Then we will take the maximum from all of those level and return the counter.
Time Complexity: O(n)...
July 14, 2022
Same tree
We can traverse through the whole tree and compare each value. We are doing it with DFS for this solution.
We are traversing the thee once, so time complexity is O(n). The call stack...
July 14, 2022
Subtree of another tree
We can check whether two tree are same using the same logic from Same tree problem. Then we will check recursively for every subtree whether that is same as out target subtree. Time Complexity:...
ReadJuly 14, 2022
Two sum II - input array is sorted
As the array is sorted, we will take 2 pointer at the beginning and the end. If the sum of two numbers are equal to target, we return. If the sum is bigger than target, that means we need a smaller...
Read