December 26, 2020

Maximum size square sub-matrix with all 1s

 

Maximum size square sub-matrix with all 1s

 Approach: Think how you what information you are getting while traversing  the matrix. I find that while traversing the matrix i try to store that how many ones i have encountered  in past. So that is the key of solve the problem, just use your memory/result to get the result. Maximum size square can find as maximum number in the result matrix.

it can used to print the small matrix, but in actual there can be multiple places where you can find the square size coordinates.so returning the maximum size can solve the problem. To get the coordinates we in count how many max size matrix we have then we can try to use it.that coordinates with max square sum.

complexity space:(m*n) time: O(m*n)

December 23, 2020

Print different views of Tree like a Top, Bottom, Left, Right?

Question: Print different views of Tree like a Top, Bottom, Left, Right?

Problem link: https://www.hackerrank.com/challenges/tree-top-view/problem
Answer 
I am using Recursive approach to solve this Question, As it is easier to understand and explain, but it can lend up in stack overflow problem in case of a huge tree. It is good if we have some idea about the iterative approach. Followup Question may be asked that is the internal working of TreeMap and its data structure and its time complexity of inserting the data and traversing it.
1. TopView
 
To solve this Question, First, start thinking about how we can traverse the tree.
We can use recursion with the base condition that starts traversing left part of the tree and then right part. Here we got the hit that if we maintain horizontal distance from the root node that can give us the Top/Bottom view tree. 
To get the particular tree we use the level to get the specific Top/Bottom view tree.
Pair is a class that holds the two number that is node value and its level.
Time Complexity: O(n)
Space Complexity: O(n)
2. Bottom View
Only this below condition is changed.In order to get the bottom view of tree.
!map.containsKey(dist) || level >= map.get(dist).level
Time Complexity: O(n)
Space Complexity: O(n)
3. Left View 
now, this becomes easier as here we just need to maintain the max level till now while doing pre-order traversal.
Time Complexity: O(n)
Space Complexity: O(1)
4.Right View
now, this becomes easier as here we just need to maintain the max level till now while doing post-order traversal.
Time Complexity: O(n)
Space Complexity: O(1)
Code Solution :
Console 
6
1 2 5 3 6 4
Tree:  
  1
    \
     2
      \
       5
      /  \
     3    6
      \
       4
Top View: 
1 2 5 6 
Bottom View: 
1 3 4 6 
Left View: 
1 2 5 3 4 
Right View: 
1 2 5 6 4