Problems
July 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
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
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
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
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 13, 2022
Valid sudoku
We can use 3 hashmap to store the values of rows, colums and square. For rows and columns hashmap we will use the row and column number as key. For square hashmap, we can use the integer division of...
ReadJuly 13, 2022
Single number
We can iterate through the entire array and XOR everything. For starter we start our result to 0, as it has no effect on our XOR operation. If we XOR the same numbers, it turns into 0. So, every pair...
ReadJuly 13, 2022
Binary tree level order traversal
This is a classing BFS problem. We should traverse the whole tree with BFS, and store the values level by level to a list. Then combine each level to a list and return. This is very efficient....
Read