Leetcode – Linked List Cycle

Given a linked list, determine if it has a cycle in it. Analysis If we have 2 pointers – fast and slow. It is guaranteed that the fast one will meet the slow one if there exists a circle. The problem can be demonstrated in the following diagram: Java Solution public class Solution { public … Read more

Leetcode – Word Break (Java)

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = “leetcode”, dict = [“leet”, “code”]. Return true because “leetcode” can be segmented as “leet code”. 1. Naive Approach This problem can be solve by … Read more

Leetcode – Same Tree

Two binary trees are considered the same if they have identical structure and nodes have the same value. This problem can be solved by using a simple recursive function. public boolean isSameTree(TreeNode p, TreeNode q) { if(p==null && q==null){ return true; }else if(p==null || q==null){ return false; }   if(p.val==q.val){ return isSameTree(p.left, q.left) && isSameTree(p.right, … Read more

Leetcode – Binary Tree Inorder Traversal (Java)

There are 3 solutions for solving this problem. Java Solution 1 – Iterative The key to solve inorder traversal of binary tree includes the following: The order of “inorder” is: left child -> parent -> right child Use a stack to track nodes public List<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<>(); Stack<TreeNode> stack … Read more

Leetcode – Binary Tree Postorder Traversal (Java)

Among preoder, inorder and postorder binary tree traversal problems, postorder traversal is the most complicated one. For example, for the following tree, the post order traversal returns {4, 6, 5, 2, 3, 1}. Java Solution 1 The key to to iterative postorder traversal is the following: The order of “Postorder” is: left child -> right … Read more

LeetCode – Two Sum (Java)

Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not … Read more