Medium Flashcards
medium probs
Print a binary tree in an m*n 2D string array following these rules:
In every recursive call, we do as follows:
If we’ve reached the end of the tree, i.e. if root==null, return.
Determine the column in which the current element(root) needs to be filled, which is the middle of ll and rr, given by say, j. The row number is same as ii. Put the current element at res[i][j]res[i][j].
Make the recursive call for the left child of the rootroot using fill(res, root.left, i + 1, l, (l + r) / 2).
Make the recursive call for the right child of the rootroot using fill(res, root.right, i + 1, (l + r + 1) / 2, r).
How to find the height of a tree from a root.
public int getHeight(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}
fill function usage in java
String[][] res = new String[height][(1 << height) - 1];
for(String[] arr:res)
Arrays.fill(arr,””);
1 << x
2^x
2^x
1 << x
< List < List > > ans
= new ArrayList<>()
Random Pick Index
public int pick(int target) {
int result = -1; int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != target)
continue;
if (rnd.nextInt(++count) == 0)
result = i;
}
return result;
}
< List > ans
= new ArrayList<>()
Exclusive Time of Functions
Time complexity : O(n). We iterate over the entire logslogs array just once. Here, n refers to the number of elements in the logs list.
Space complexity : The stack can grow upto a depth of atmost n/2. Here, nn refers to the number of elements in the given logslogs list.
How to initialize a stack in java
Stack<integer> st = new Stack<>();</integer>
How to split a string with delimiter :
String[] s = log.split(“:”);
How to convert string to integer in java
int curr = Integer.parseInt(s[2]);
or
int curr = Integer.parseInt(“2”);
how to find if stack is empty in java
st.isEmpty()
stack operstions in java
st. peek()
st. push(1); or st.push(Integer.parseInt(s[0]));
st,pop()
create array of size n in java
int [] res = new int[n];