Categories
Interview Questions

Lowest Common Ancestor of a Binary Tree

class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root==null || root==p || root==q) return root; TreeNode left = lowestCommonAncestor(root.left,p,q); TreeNode right = lowestCommonAncestor(root.right,p,q); if ((left==p && right==q) || (left==q && right==p)) return root; if (left!=null) return left; return right; } } Since for every node in a binary tree it […]

Categories
Interview Questions

Making A Large Island

class Solution { public int largestIsland(int[][] grid) { if (grid.length==0) return 0; Map map = mapIslands(grid); int max = map.values().stream().reduce(Integer::max).get(); for (int i = 0; i

Categories
Interview Questions

Best Time to Buy and Sell Stock with K transaction

The original question can be found here.  Lets start from an elegant the solution : class Solution { public int maxProfit(int k,int[] prices) { if (prices.length