├── .Reverse Linked List.java.swp ├── .Reverse Nodes in k-Group.java.swp ├── 3Sum Closest.java ├── 3Sum.java ├── 4Sum.java ├── Add Binary.java ├── Add Two Numbers.java ├── Anagrams.java ├── Balanced Binary Tree.java ├── Best Time to Buy and Sell Stock II.java ├── Best Time to Buy and Sell Stock III.java ├── Best Time to Buy and Sell Stock.java ├── Binary Tree Inorder Traversal.java ├── Binary Tree Level Order Traversal II.java ├── Binary Tree Level Order Traversal.java ├── Binary Tree Maximum Path Sum.java ├── Binary Tree Postorder Traversal.java ├── Binary Tree Preorder Traversal.java ├── Binary Tree Zigzag Level Order Traversal.java ├── Breadth:Depth First Search.java ├── Candy.java ├── CircularArray.java ├── Climbing Stairs.java ├── Clone Graph.java ├── Combination Sum ii.java ├── Combination Sum.java ├── Combinations.java ├── Construct Binary Tree from Inorder and Postorder Traversal.java ├── Construct Binary Tree from Preorder and Inorder Traversal.java ├── Container with Most Water.java ├── Convert Sorted Array to Binary Search Tree.java ├── Convert Sorted List to Binary Search Tree.java ├── Copy List with Random Pointer.java ├── Count and Say.java ├── Decode Ways.java ├── Distinct Subsequences.java ├── Divide Two Integer.java ├── Edit Distance.java ├── Evaluate Reverse Polish Notation.java ├── Find missing term in Arithmetic Progress.java ├── First Missing Positive.java ├── Flatten Binary Tree To Linked List.java ├── Gas Station.java ├── Generate Parentheses.java ├── Gray Code.java ├── Implement strStr().java ├── Insert Interval.java ├── Insertion Sort List.jaa ├── Insertion Sort List.java ├── Interleaving String.java ├── Jump Game ii.java ├── Jump Game.java ├── LRU cache.java ├── Largest Rectangle in Histogram.java ├── Length of Last Word.java ├── Letter Combinations of a Phone Number.java ├── Linked List Cycle II.java ├── Linked List Cycle.java ├── Longest Common Prefix.java ├── Longest Consecutive Sequence.java ├── Longest Palindromic Substring.java ├── Longest Substring Without Repeating Characters.java ├── Longest Valid Parentheses.java ├── Maximal Rectangle.java ├── Maximum Depth of Binary Tree.java ├── Maximum Subarray Sum.java ├── Maximum Subarray.java ├── Median of Two Sorted Arrays.java ├── Merge Intervals.java ├── Merge K Sorted Lists.java ├── Merge Sorted Array.java ├── Merge Two Sorted Lists.java ├── Minimum Depth of Binary Tree.java ├── Minimum Path Sum.java ├── Minimum Window Substring.java ├── Multiply Strings.java ├── N queens ii.java ├── N queens.java ├── Next Permutation.java ├── Palindrome Number.java ├── Palindrome Partitioning II.java ├── Palindrome Partitioning.java ├── Partition List.java ├── Pascal's Triangle ii.java ├── Pascal's Triangle.java ├── Path Sum II.java ├── Path Sum.java ├── Permutation Sequence.java ├── Permutation ii.java ├── Permutations.java ├── Plus One.java ├── Populating Next Right Pointers in Each Node II.java ├── Populating Next Right Pointers in Each Node.java ├── Pow(x, n).java ├── README.md ├── Recover Binary Search Tree.java ├── Regular Expression Matching.java ├── Remove Duplicates From Sorted Array ii.java ├── Remove Duplicates from Sorted Array.java ├── Remove Duplicates from Sorted List ii.java ├── Remove Duplicates from Sorted List.java ├── Remove Element.java ├── Remove Nth Node From End of List.java ├── Reorder List.java ├── Restore IP Address.java ├── Reverse Integer.java ├── Reverse Linked List ii.java ├── Reverse Linked List.java ├── Reverse Nodes in k-Group.java ├── Rotate Image.java ├── Rotate List.java ├── Same Tree.java ├── Scramble String.java ├── Search Insert Position.java ├── Search a 2D Matrix.java ├── Search for A Range.java ├── Search in Rotated Array.java ├── Set Matrix Zeros.java ├── Simplify Path.java ├── Single Number II.java ├── Single Number III.java ├── Single Number.java ├── Sort Colors.java ├── Sort List.java ├── Spiral Matrix ii.java ├── Spiral Matrix.java ├── Sqrt.java ├── String to Integer atoi.java ├── SubSet ii.java ├── Subsets.java ├── Substring with Concatenantion of All Words.java ├── Sudoku Solver.java ├── Sum Root to Leaf Numbers.java ├── Surrounded Regions.java ├── Swap Nodes in Pairs.java ├── Symmetric Tree.java ├── Text Justification.java ├── Trapping Rain Water.java ├── Triangle.java ├── Two Sum.java ├── Unique Binary Search Trees II.java ├── Unique Binary Search Trees.java ├── Unique Paths ii.java ├── Unique Paths.java ├── Valid Number.java ├── Valid Palindrome.java ├── Valid Parentheses.java ├── Valid Sudoku.java ├── Validate Binary Search Tree.java ├── Word Break ii.java ├── Word Break.java ├── Word Ladder.java ├── Word Search.java └── Zigzag Conversion.java /.Reverse Linked List.java.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paopao2/Algorithm-Practice/ff438b7f6c68013d2608f92659d8449d79dc5ba8/.Reverse Linked List.java.swp -------------------------------------------------------------------------------- /.Reverse Nodes in k-Group.java.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paopao2/Algorithm-Practice/ff438b7f6c68013d2608f92659d8449d79dc5ba8/.Reverse Nodes in k-Group.java.swp -------------------------------------------------------------------------------- /3Sum Closest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 3 | 4 | For example, given array S = {-1 2 1 -4}, and target = 1. 5 | 6 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 7 | */ 8 | 9 | public class Solution { 10 | public int threeSumClosest(int[] num, int target) { 11 | // Note: The Solution object is instantiated only once and is reused by each test case. 12 | if(num.length < 3) 13 | return 0; 14 | 15 | Arrays.sort(num); 16 | int res = num[0] + num[1] + num[2]; 17 | for(int i = 0; i < num.length; i++) { 18 | int start = i + 1; 19 | int end = num.length - 1; 20 | while(start < end) { 21 | int temp = num[i] + num[start] + num[end]; 22 | if(temp == target) { 23 | return temp; 24 | } 25 | 26 | if(Math.abs(temp - target) < Math.abs(res - target)) { 27 | res = temp; 28 | } 29 | 30 | if(temp < target) 31 | start++; 32 | else 33 | end--; 34 | } 35 | } 36 | return res; 37 | } 38 | } -------------------------------------------------------------------------------- /3Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 3 | 4 | Note: 5 | Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) 6 | The solution set must not contain duplicate triplets. 7 | For example, given array S = {-1 0 1 2 -1 -4}, 8 | 9 | A solution set is: 10 | (-1, 0, 1) 11 | (-1, -1, 2) 12 | */ 13 | 14 | public class Solution { 15 | public ArrayList> threeSum(int[] num) { 16 | // IMPORTANT: Please reset any member data you declared, as 17 | // the same Solution instance will be reused for each test case. 18 | 19 | ArrayList> result = new ArrayList>(); 20 | Arrays.sort(num); 21 | 22 | for (int i = 0; i < num.length; i++) { 23 | if(i > 0 && num[i] == num[i - 1]) { 24 | continue; 25 | } 26 | for (int j = i + 1; j < num.length; j++) { 27 | int cur = num[i] + num[j]; 28 | int remainder = 0 - cur; 29 | if (findTarget(num, j + 1, num.length - 1, remainder)) { 30 | ArrayList temp = new ArrayList(); 31 | temp.add(num[i]); 32 | temp.add(num[j]); 33 | temp.add(remainder); 34 | if (!result.contains(temp)) { 35 | result.add(temp); 36 | } 37 | 38 | } 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | 45 | public boolean findTarget(int[] num, int startIndex, int endIndex, int target) { 46 | if (startIndex < 0 || endIndex >= num.length || startIndex > endIndex || target < num[startIndex] || target > num[endIndex]) { 47 | return false; 48 | } 49 | 50 | while (startIndex <= endIndex) { 51 | int midIndex = (startIndex + endIndex)/2; 52 | int cur = num[midIndex]; 53 | if (cur == target) { 54 | return true; 55 | } else if (cur < target) { 56 | startIndex = midIndex + 1; 57 | } else { 58 | endIndex = midIndex - 1; 59 | } 60 | } 61 | 62 | return false; 63 | } 64 | } -------------------------------------------------------------------------------- /4Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 3 | 4 | Note: 5 | Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 6 | The solution set must not contain duplicate quadruplets. 7 | For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 8 | 9 | A solution set is: 10 | (-1, 0, 0, 1) 11 | (-2, -1, 1, 2) 12 | (-2, 0, 0, 2) 13 | */ 14 | 15 | public class Solution { 16 | public ArrayList> fourSum(int[] num, int target) { 17 | // IMPORTANT: Please reset any member data you declared, as 18 | // the same Solution instance will be reused for each test case. 19 | 20 | Arrays.sort(num); 21 | ArrayList> result = new ArrayList>(); 22 | int length = num.length; 23 | if (length < 4) { 24 | return result; 25 | } 26 | 27 | for (int i = 0; i < length - 3; i++) { 28 | if (i != 0 && num[i] == num[i - 1]) { 29 | continue; 30 | } 31 | for (int j = length - 1; j >= 2 ; j--) { 32 | if (j != length - 1 && num[j] == num[j + 1]) { 33 | continue; 34 | } 35 | int L = i + 1; 36 | int R = j - 1; 37 | int cur = num[i] + num[j]; 38 | int remainder = target - cur; 39 | while (L < R) { 40 | if (L != i + 1 && num[L] == num[L - 1]) { 41 | L++; 42 | continue; 43 | } 44 | if (R != j - 1 && num[R] == num[R + 1]) { 45 | R--; 46 | continue; 47 | } 48 | int temp = num[L] + num[R]; 49 | if (temp == remainder) { 50 | ArrayList list = new ArrayList(); 51 | list.add(num[i]); 52 | list.add(num[L]); 53 | list.add(num[R]); 54 | list.add(num[j]); 55 | result.add(list); 56 | L++; 57 | R--; 58 | } else if (temp < remainder) { 59 | L++; 60 | } else { 61 | R--; 62 | } 63 | } 64 | } 65 | } 66 | return result; 67 | } 68 | } -------------------------------------------------------------------------------- /Add Binary.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | For example, 5 | a = "11" 6 | b = "1" 7 | Return "100". 8 | */ 9 | 10 | public class Solution { 11 | public String addBinary(String a, String b) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | if (a == null || a.equals("")) return b; 15 | if (b == null || b.equals("")) return a; 16 | 17 | int length1 = a.length() - 1; 18 | int length2 = b.length() - 1; 19 | int carry = 0; 20 | StringBuilder sb = new StringBuilder(); 21 | while(length1 >= 0 || length2 >= 0 || carry != 0) { 22 | char a1,b1; 23 | if (length1 < 0) a1 = '0'; 24 | else a1 = a.charAt(length1); 25 | if (length2 < 0) b1 = '0'; 26 | else b1 = b.charAt(length2); 27 | int sum = (int) (a1 - '0' + b1 - '0' + carry); 28 | carry = sum / 2; 29 | sb.insert(0, sum % 2); 30 | length1--; 31 | length2--; 32 | } 33 | return sb.toString(); 34 | } 35 | } -------------------------------------------------------------------------------- /Add Two Numbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 3 | 4 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 5 | Output: 7 -> 0 -> 8 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode(int x) { 14 | * val = x; 15 | * next = null; 16 | * } 17 | * } 18 | */ 19 | public class Solution { 20 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 21 | // IMPORTANT: Please reset any member data you declared, as 22 | // the same Solution instance will be reused for each test case. 23 | int carry = 0; 24 | ListNode node = null; 25 | ListNode head = null; 26 | while(l1 != null || l2 != null || carry != 0) { 27 | int val = carry; 28 | val += l1 == null? 0 : l1.val; 29 | val += l2 == null? 0 : l2.val; 30 | if (val > 9) { 31 | val -= 10; 32 | carry = 1; 33 | } else { 34 | carry = 0; 35 | } 36 | if (node == null) { 37 | node = new ListNode(val); 38 | head = node; 39 | } else { 40 | ListNode cur = new ListNode(val); 41 | node.next = cur; 42 | node = cur; 43 | } 44 | l1 = l1 == null? null : l1.next; 45 | l2 = l2 == null? null : l2.next; 46 | } 47 | 48 | return head; 49 | } 50 | } -------------------------------------------------------------------------------- /Anagrams.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of strings, return all groups of strings that are anagrams. 3 | 4 | Note: All inputs will be in lower-case. 5 | */ 6 | 7 | public class Solution { 8 | public ArrayList anagrams(String[] strs) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | 12 | ArrayList results = new ArrayList(); 13 | HashMap> anagramsMap = new HashMap>(); 14 | 15 | for (int i = 0; i < strs.length; i++) { 16 | String cur = strs[i]; 17 | char[] temp = cur.toCharArray(); 18 | Arrays.sort(temp); 19 | String key = new String(temp); 20 | 21 | if (anagramsMap.containsKey(key)) { 22 | anagramsMap.get(key).add(cur); 23 | } else { 24 | ArrayList newGroup = new ArrayList(); 25 | newGroup.add(cur); 26 | anagramsMap.put(key, newGroup); 27 | } 28 | } 29 | 30 | for (ArrayList s : anagramsMap.values()) { 31 | if (s.size() > 1) { 32 | results.addAll(s); 33 | } 34 | } 35 | return results; 36 | } 37 | } -------------------------------------------------------------------------------- /Balanced Binary Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | */ 6 | 7 | /** 8 | * Definition for binary tree 9 | * public class TreeNode { 10 | * int val; 11 | * TreeNode left; 12 | * TreeNode right; 13 | * TreeNode(int x) { val = x; } 14 | * } 15 | */ 16 | public class Solution { 17 | public boolean isBalanced(TreeNode root) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | if (root == null) { 21 | return true; 22 | } 23 | int diff = getHeight(root.left) - getHeight(root.right); 24 | if (Math.abs(diff) > 1) { 25 | return false; 26 | } else { 27 | return isBalanced(root.left) && isBalanced(root.right); 28 | } 29 | } 30 | 31 | public int getHeight(TreeNode node) { 32 | if (node == null) { 33 | return 0; 34 | } 35 | int left = getHeight(node.left) + 1; 36 | int right = getHeight(node.right) + 1; 37 | return left > right? left : right; 38 | } 39 | } -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 5 | */ 6 | 7 | public class Solution { 8 | public int maxProfit(int[] prices) { 9 | // Note: The Solution object is instantiated only once and is reused by each test case. 10 | int min = Integer.MAX_VALUE; 11 | int max = Integer.MIN_VALUE; 12 | boolean bought = false; 13 | int profit = 0; 14 | 15 | if(prices.length == 0||prices.length == 1) { 16 | return 0; 17 | } 18 | 19 | for(int i = 0; i < prices.length - 1; i++) { 20 | if(!bought) { 21 | if(prices[i] <= min) { 22 | min = prices[i]; 23 | if(prices[i+1] > min) { 24 | bought = true; 25 | profit -= min; 26 | } 27 | } 28 | 29 | } 30 | else { 31 | if(prices[i] >= max) { 32 | max = prices[i]; 33 | if(prices[i+1] < max) { 34 | bought = false; 35 | profit += max; 36 | min = Integer.MAX_VALUE; 37 | max = Integer.MIN_VALUE; 38 | } 39 | } 40 | 41 | } 42 | } 43 | if(bought) { 44 | max = prices[prices.length - 1]; 45 | profit += max; 46 | } 47 | 48 | return profit; 49 | } 50 | } -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock III.java: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: 7 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 8 | */ 9 | public class Solution { 10 | public int maxProfit(int[] prices) { 11 | // IMPORTANT: Please reset any member data you declared, as 12 | // the same Solution instance will be reused for each test case. 13 | int length = prices.length; 14 | if (length == 0) { 15 | return 0; 16 | } 17 | int[] historyProfit = new int[length]; 18 | int[] futureProfit = new int[length]; 19 | 20 | int valley = prices[0]; 21 | int peak = prices[length - 1]; 22 | int max = 0; 23 | 24 | for (int i = 1; i < length; i++) { 25 | if (valley > prices[i]) { 26 | valley = prices[i]; 27 | } 28 | historyProfit[i] = Math.max(historyProfit[i - 1], prices[i] - valley); 29 | } 30 | 31 | for (int j = length - 2; j >= 0; j--) { 32 | if (peak < prices[j]) { 33 | peak = prices[j]; 34 | } 35 | futureProfit[j] = Math.max(futureProfit[j + 1], peak - prices[j]); 36 | max = Math.max(max, futureProfit[j] + historyProfit[j]); 37 | } 38 | 39 | return max; 40 | } 41 | } -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 5 | */ 6 | 7 | public class Solution { 8 | public int maxProfit(int[] prices) { 9 | // Note: The Solution object is instantiated only once and is reused by each test case. 10 | int min = 0; 11 | int maxDiff = 0; 12 | for(int sell = 1; sell < prices.length; sell++) { 13 | if(prices[sell] < prices[min]) { 14 | min = sell; 15 | continue; 16 | } 17 | 18 | int temp = prices[sell] - prices[min]; 19 | if(temp > maxDiff) { 20 | maxDiff = temp; 21 | } 22 | } 23 | 24 | return maxDiff; 25 | } 26 | } -------------------------------------------------------------------------------- /Binary Tree Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [1,3,2]. 12 | 13 | Note: Recursive solution is trivial, could you do it iteratively? 14 | 15 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 16 | 17 | 18 | OJ's Binary Tree Serialization: 19 | The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 20 | 21 | Here's an example: 22 | 1 23 | / \ 24 | 2 3 25 | / 26 | 4 27 | \ 28 | 5 29 | The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 30 | */ 31 | 32 | /** 33 | * Definition for binary tree 34 | * public class TreeNode { 35 | * int val; 36 | * TreeNode left; 37 | * TreeNode right; 38 | * TreeNode(int x) { val = x; } 39 | * } 40 | */ 41 | 42 | //iterative 43 | public class Solution { 44 | public ArrayList inorderTraversal(TreeNode root) { 45 | // IMPORTANT: Please reset any member data you declared, as 46 | // the same Solution instance will be reused for each test case. 47 | ArrayList result = new ArrayList(); 48 | Stack stack = new Stack(); 49 | 50 | TreeNode node = root; 51 | while (!stack.isEmpty() || node != null) { 52 | if (node != null) { 53 | stack.push(node); 54 | node = node.left; 55 | } else { 56 | node = stack.pop(); 57 | result.add(node.val); 58 | node = node.right; 59 | } 60 | } 61 | return result; 62 | } 63 | } 64 | 65 | //Recursive 66 | public class Solution { 67 | public ArrayList inorderTraversal(TreeNode root) { 68 | // IMPORTANT: Please reset any member data you declared, as 69 | // the same Solution instance will be reused for each test case. 70 | ArrayList result = new ArrayList(); 71 | helper(root, result); 72 | return result; 73 | } 74 | 75 | public void helper(TreeNode root, ArrayList result) { 76 | if (root == null) return; 77 | helper(root.left, result); 78 | result.add(root.val); 79 | helper(root.right, result); 80 | } 81 | } -------------------------------------------------------------------------------- /Binary Tree Level Order Traversal II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its bottom-up level order traversal as: 12 | [ 13 | [15,7] 14 | [9,20], 15 | [3], 16 | ] 17 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 18 | 19 | 20 | OJ's Binary Tree Serialization: 21 | The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 22 | 23 | Here's an example: 24 | 1 25 | / \ 26 | 2 3 27 | / 28 | 4 29 | \ 30 | 5 31 | The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 32 | */ 33 | 34 | /** 35 | * Definition for binary tree 36 | * public class TreeNode { 37 | * int val; 38 | * TreeNode left; 39 | * TreeNode right; 40 | * TreeNode(int x) { val = x; } 41 | * } 42 | */ 43 | public class Solution { 44 | public ArrayList> levelOrderBottom(TreeNode root) { 45 | // Note: The Solution object is instantiated only once and is reused by each test case. 46 | 47 | ArrayList> result = new ArrayList>(); 48 | if (root == null) { 49 | return result; 50 | } 51 | ArrayList list = new ArrayList(); 52 | list.add(root); 53 | ArrayList parent = list; 54 | while(!parent.isEmpty()) { 55 | 56 | ArrayList cur = new ArrayList(); 57 | ArrayList parentData = new ArrayList(); 58 | for (TreeNode n : parent) { 59 | parentData.add(n.val); 60 | if (n.left != null) { 61 | cur.add(n.left); 62 | } 63 | if (n.right != null) { 64 | cur.add(n.right); 65 | } 66 | } 67 | result.add(0, parentData); 68 | parent = cur; 69 | 70 | } 71 | return result; 72 | 73 | } 74 | } -------------------------------------------------------------------------------- /Binary Tree Level Order Traversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | [ 13 | [3], 14 | [9,20], 15 | [15,7] 16 | ] 17 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 18 | 19 | 20 | OJ's Binary Tree Serialization: 21 | The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 22 | 23 | Here's an example: 24 | 1 25 | / \ 26 | 2 3 27 | / 28 | 4 29 | \ 30 | 5 31 | The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 32 | 33 | */ 34 | 35 | public class Solution { 36 | public ArrayList> levelOrder(TreeNode root) { 37 | // Note: The Solution object is instantiated only once and is reused by each test case. 38 | ArrayList> result = new ArrayList>(); 39 | if (root == null) { 40 | return result; 41 | } 42 | 43 | ArrayList currentList = new ArrayList(); 44 | currentList.add(root); 45 | 46 | 47 | while (currentList.size() != 0) { 48 | ArrayList nextLevelList = new ArrayList(); 49 | ArrayList parentLevelData = new ArrayList(); 50 | 51 | for (TreeNode s : currentList) { 52 | parentLevelData.add(s.val); 53 | if (s.left != null) { 54 | nextLevelList.add(s.left); 55 | } 56 | if (s.right != null) { 57 | nextLevelList.add(s.right); 58 | } 59 | } 60 | result.add(parentLevelData); 61 | //currentList = new ArrayList(nextLevelList); 62 | currentList = nextLevelList; 63 | } 64 | 65 | return result; 66 | } 67 | } -------------------------------------------------------------------------------- /Binary Tree Maximum Path Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find the maximum path sum. 3 | 4 | The path may start and end at any node in the tree. 5 | 6 | For example: 7 | Given the below binary tree, 8 | 9 | 1 10 | / \ 11 | 2 3 12 | Return 6. 13 | */ 14 | 15 | /** 16 | * Definition for binary tree 17 | * public class TreeNode { 18 | * int val; 19 | * TreeNode left; 20 | * TreeNode right; 21 | * TreeNode(int x) { val = x; } 22 | * } 23 | */ 24 | public class Solution { 25 | public int maxPathSum(TreeNode root) { 26 | // IMPORTANT: Please reset any member data you declared, as 27 | // the same Solution instance will be reused for each test case. 28 | ArrayList curMax = new ArrayList(1); 29 | curMax.add(Integer.MIN_VALUE); 30 | subPath(root, curMax); 31 | //getMaxSum(root, curMax); 32 | return curMax.get(0); 33 | } 34 | 35 | public int subPath(TreeNode root, ArrayList curMax) { 36 | if (root == null) return 0; 37 | int left = Math.max(0, subPath(root.left, curMax)); 38 | int right = Math.max(0, subPath(root.right, curMax)); 39 | int max = root.val + left + right; 40 | //use set(0, value) can't pass large test 41 | curMax.add(0, Math.max(curMax.get(0), max)); 42 | //can only return one path (left or right) for recursion use 43 | return root.val + Math.max(left, right); 44 | } 45 | } -------------------------------------------------------------------------------- /Binary Tree Preorder Traversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the preorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | return [1,2,3]. 14 | 15 | Note: Recursive solution is trivial, could you do it iteratively? 16 | */ 17 | 18 | //recursive 19 | /** 20 | * Definition for binary tree 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | public ArrayList preorderTraversal(TreeNode root) { 30 | // IMPORTANT: Please reset any member data you declared, as 31 | // the same Solution instance will be reused for each test case. 32 | ArrayList result = new ArrayList(); 33 | helper(root, result); 34 | return result; 35 | } 36 | 37 | public void helper(TreeNode root, ArrayList result) { 38 | if (root == null) { 39 | return; 40 | } 41 | result.add(root.val); 42 | helper(root.left, result); 43 | helper(root.right, result); 44 | } 45 | } 46 | 47 | //iterative 48 | public class Solution { 49 | public ArrayList preorderTraversal(TreeNode root) { 50 | // IMPORTANT: Please reset any member data you declared, as 51 | // the same Solution instance will be reused for each test case. 52 | ArrayList result = new ArrayList(); 53 | if (root == null) { 54 | return result; 55 | } 56 | Stack stack = new Stack(); 57 | stack.push(root); 58 | while(!stack.isEmpty()) { 59 | TreeNode node = stack.pop(); 60 | result.add(node.val); 61 | if (node.right != null) { 62 | stack.push(node.right); 63 | } 64 | if (node.left != null) { 65 | stack.push(node.left); 66 | } 67 | } 68 | return result; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Breadth:Depth First Search.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Breadth First Search, Depth First Search 3 | * */ 4 | 5 | import java.util.*; 6 | 7 | import sun.tools.tree.Node; 8 | 9 | class Main { 10 | public void bfs() { 11 | Queue queue = new LinkedList(); 12 | queue.add(this.rootNode); 13 | printNode(this.rootNode); 14 | rootNode.visited = true; 15 | while(!queue.isEmpty()) { 16 | Node node = (Node) queue.remove(); 17 | Node child = null; 18 | while ((child=getUnvisitedChildNode(node))!=null) { 19 | child.visited=true; 20 | printNode(child); 21 | queue.add(child); 22 | } 23 | 24 | } 25 | clearNodes(); 26 | } 27 | 28 | public void dfs() { 29 | Stack stack = new Stack(); 30 | stack.push(this.rootNode); 31 | rootNode.visited = true; 32 | printNode(rootNode); 33 | while(!stack.isEmpty()) { 34 | Node node = (Node) stack.peek(); 35 | Node child = getUnvisitedChildNode(n); 36 | if(child != null) { 37 | child.visited = true; 38 | printNode(child); 39 | stack.push(child); 40 | } 41 | else { 42 | stack.pop(); 43 | } 44 | } 45 | clearNodes(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /CircularArray.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | 4 | public class CircularArray implements Iterable{ 5 | 6 | /** 7 | * @param args 8 | */ 9 | private T[] items; 10 | private int head = 0; 11 | 12 | public CircularArray(int size) { 13 | items = (T[]) new Object[size]; 14 | } 15 | 16 | private int convert(int index) { 17 | if (index < 0) { 18 | index += items.length; 19 | } 20 | return (head + index) % items.length; 21 | } 22 | 23 | public void rotate(int shiftRight) { 24 | head = convert(shiftRight); 25 | } 26 | 27 | public T get(int i) { 28 | if (i < 0 || i >= items.length) { 29 | throw new java.lang.IndexOutOfBoundsException("..."); 30 | } 31 | return items[convert(i)]; 32 | } 33 | 34 | public void set(int i, T item) { 35 | items[convert(i)] = item; 36 | } 37 | 38 | public Iterator iterator() { 39 | return new CircularArrayIterator(this); 40 | } 41 | 42 | private class CircularArrayIterator implements Iterator { 43 | private int _current = -1; 44 | private TI[] _items; 45 | 46 | public CircularArrayIterator(CircularArray array) { 47 | _items = array.items; 48 | } 49 | 50 | @Override 51 | public boolean hasNext() { 52 | return _current < items.length - 1; 53 | } 54 | 55 | @Override 56 | public TI next() { 57 | _current++; 58 | TI item = (TI) _items[convert(_current)]; 59 | return item; 60 | } 61 | 62 | @Override 63 | public void remove() { 64 | throw new UnsupportedOperationException("..."); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | */ 6 | 7 | public class Solution { 8 | public int climbStairs(int n) { 9 | // Note: The Solution object is instantiated only once and is reused by each test case. 10 | // if (n < 0) { 11 | // return 0; 12 | // } 13 | // else if (n == 0) { 14 | // return 1; 15 | // } 16 | // else { 17 | // return climbStairs(n - 1) + climbStairs(n - 2); 18 | // } 19 | int[] c = new int[n + 1]; 20 | return climbStairsHelper(n, c); 21 | } 22 | 23 | public static int climbStairsHelper(int n, int[] count) { 24 | if (n < 0) { 25 | return 0; 26 | } else if (n == 0) { 27 | return 1; 28 | } else if (count[n] != 0) { 29 | return count[n]; 30 | } else { 31 | count[n] = climbStairsHelper(n - 1, count) + climbStairsHelper(n - 2, count); 32 | return count[n]; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Clone Graph.java: -------------------------------------------------------------------------------- 1 | /* 2 | Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. 3 | 4 | 5 | OJ's undirected graph serialization: 6 | Nodes are labeled uniquely. 7 | 8 | We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. 9 | As an example, consider the serialized graph {0,1,2#1,2#2,2}. 10 | 11 | The graph has a total of three nodes, and therefore contains three parts as separated by #. 12 | 13 | First node is labeled as 0. Connect node 0 to both nodes 1 and 2. 14 | Second node is labeled as 1. Connect node 1 to node 2. 15 | Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. 16 | Visually, the graph looks like the following: 17 | 18 | 1 19 | / \ 20 | / \ 21 | 0 --- 2 22 | / \ 23 | \_/ 24 | */ 25 | 26 | /** 27 | * Definition for undirected graph. 28 | * class UndirectedGraphNode { 29 | * int label; 30 | * ArrayList neighbors; 31 | * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } 32 | * }; 33 | */ 34 | public class Solution { 35 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 36 | // IMPORTANT: Please reset any member data you declared, as 37 | // the same Solution instance will be reused for each test case. 38 | if (node == null) { 39 | return null; 40 | } 41 | HashMap map = new HashMap(); 42 | 43 | UndirectedGraphNode head = new UndirectedGraphNode(node.label); 44 | Queue queue = new LinkedList(); 45 | queue.add(node); 46 | map.put(node, head); 47 | 48 | while(!queue.isEmpty()) { 49 | UndirectedGraphNode cur = queue.poll(); 50 | for (UndirectedGraphNode n : cur.neighbors) { 51 | 52 | if (!map.containsKey(n)) { 53 | UndirectedGraphNode nb = new UndirectedGraphNode(n.label); 54 | queue.add(n); 55 | map.put(n, nb); 56 | map.get(cur).neighbors.add(nb); 57 | } else { 58 | map.get(cur).neighbors.add(map.get(n)); 59 | } 60 | 61 | } 62 | } 63 | return head; 64 | 65 | } 66 | } -------------------------------------------------------------------------------- /Combination Sum ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 3 | 4 | Each number in C may only be used once in the combination. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 9 | The solution set must not contain duplicate combinations. 10 | For example, given candidate set 10,1,2,7,6,1,5 and target 8, 11 | A solution set is: 12 | [1, 7] 13 | [1, 2, 5] 14 | [2, 6] 15 | [1, 1, 6] 16 | */ 17 | 18 | public class Solution { 19 | public ArrayList> combinationSum2(int[] candidates, int target) { 20 | // IMPORTANT: Please reset any member data you declared, as 21 | // the same Solution instance will be reused for each test case. 22 | ArrayList> result = new ArrayList>(); 23 | if (candidates.length == 0) return result; 24 | Arrays.sort(candidates); 25 | helper(candidates, new ArrayList(), -1, 0, target, result); 26 | return result; 27 | } 28 | 29 | public void helper(int[] candidates, ArrayList cur, int curIndex, int curSum, int target, ArrayList> result) { 30 | if (curSum == target) { 31 | result.add(cur); 32 | } else if (curSum < target) { 33 | for (int i = curIndex + 1; i < candidates.length; i++) { 34 | if (i > curIndex + 1 && candidates[i] == candidates[i - 1]) continue; 35 | ArrayList temp = new ArrayList(cur); 36 | temp.add(candidates[i]); 37 | helper(candidates, temp, i, curSum + candidates[i], target, result); 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Combination Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 3 | 4 | The same repeated number may be chosen from C unlimited number of times. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 9 | The solution set must not contain duplicate combinations. 10 | For example, given candidate set 2,3,6,7 and target 7, 11 | A solution set is: 12 | [7] 13 | [2, 2, 3] 14 | */ 15 | 16 | public class Solution { 17 | public ArrayList> combinationSum(int[] candidates, int target) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | ArrayList> result = new ArrayList>(); 21 | if (candidates.length == 0) return result; 22 | Arrays.sort(candidates); 23 | helper(candidates, new ArrayList(), 0, 0, target, result); 24 | return result; 25 | } 26 | 27 | public void helper(int[] candidates, ArrayList cur, int curIndex, int curSum, int target, ArrayList> result) { 28 | if (curSum == target) { 29 | result.add(cur); 30 | } else if (curSum < target) { 31 | for (int i = curIndex; i < candidates.length; i++) { 32 | ArrayList temp = new ArrayList(cur); 33 | temp.add(candidates[i]); 34 | helper(candidates, temp, i, curSum + candidates[i], target, result); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Combinations.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | For example, 5 | If n = 4 and k = 2, a solution is: 6 | 7 | [ 8 | [2,4], 9 | [3,4], 10 | [2,3], 11 | [1,2], 12 | [1,3], 13 | [1,4], 14 | ] 15 | */ 16 | 17 | public class Solution { 18 | public ArrayList> combine(int n, int k) { 19 | // IMPORTANT: Please reset any member data you declared, as 20 | // the same Solution instance will be reused for each test case. 21 | ArrayList> result = new ArrayList>(); 22 | if (n <= 0 || k <= 0 || n < k) return result; 23 | 24 | for (int i = 1; i <= n; i++) { 25 | ArrayList init = new ArrayList(); 26 | init.add(i); 27 | helper(init, n, k, result); 28 | } 29 | 30 | return result; 31 | } 32 | 33 | public void helper(ArrayList cur, int n, int k, ArrayList> result) { 34 | 35 | if (cur.size() == k) { 36 | result.add(cur); 37 | return; 38 | } 39 | int curMax = cur.get(cur.size() - 1); 40 | while (curMax < n) { 41 | ArrayList res = new ArrayList(cur); 42 | res.add(++curMax); 43 | helper(res, n, k, result); 44 | } 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Construct Binary Tree from Inorder and Postorder Traversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given inorder and postorder traversal of a tree, construct the binary tree. 3 | 4 | Note: 5 | You may assume that duplicates do not exist in the tree. 6 | */ 7 | 8 | /** 9 | * Definition for binary tree 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public TreeNode buildTree(int[] inorder, int[] postorder) { 19 | // IMPORTANT: Please reset any member data you declared, as 20 | // the same Solution instance will be reused for each test case. 21 | int length = inorder.length; 22 | return buildTreeHelper(inorder, postorder, 0, length - 1, 0, length - 1); 23 | } 24 | 25 | public TreeNode buildTreeHelper(int[] inorderTree, int[] postorderTree, int inStart, int inEnd, int postStart, int postEnd) { 26 | if (inEnd < inStart || postEnd < postStart) { 27 | return null; 28 | } 29 | 30 | TreeNode root = new TreeNode(postorderTree[postEnd]); 31 | for (int i = inStart; i <= inEnd; i++) { 32 | if (inorderTree[i] == root.val) { 33 | //inEnd - inStart == postEnd - postStart 34 | root.left = buildTreeHelper(inorderTree, postorderTree, inStart, i - 1, postStart, postStart - inStart + i - 1); 35 | root.right = buildTreeHelper(inorderTree, postorderTree, i + 1, inEnd, postEnd - inEnd + i, postEnd - 1); 36 | } 37 | } 38 | return root; 39 | } 40 | } -------------------------------------------------------------------------------- /Construct Binary Tree from Preorder and Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given preorder and inorder traversal of a tree, construct the binary tree. 3 | 4 | Note: 5 | You may assume that duplicates do not exist in the tree. 6 | */ 7 | 8 | /** 9 | * Definition for binary tree 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public TreeNode buildTree(int[] preorder, int[] inorder) { 19 | // Note: The Solution object is instantiated only once and is reused by each test case. 20 | int preLength = preorder.length; 21 | int inLength = inorder.length; 22 | 23 | if (preLength != inLength) { 24 | return null; 25 | } 26 | 27 | return buildTreeHelper(preorder, inorder, 0, preLength - 1, 0, inLength - 1); 28 | } 29 | 30 | public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) { 31 | if (preEnd < preStart || inEnd < inStart) { 32 | return null; 33 | } 34 | 35 | TreeNode root = new TreeNode(preorder[preStart]); 36 | 37 | for(int i = inStart; i <= inEnd; i++) { 38 | if (inorder[i] == root.val) { 39 | root.left = buildTreeHelper(preorder, inorder, preStart + 1, preStart - inStart + i, inStart, i - 1); 40 | root.right = buildTreeHelper(preorder, inorder, preEnd - inEnd + i + 1, preEnd, i + 1, inEnd); 41 | } 42 | } 43 | 44 | return root; 45 | } 46 | } -------------------------------------------------------------------------------- /Container with Most Water.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 3 | 4 | Note: You may not slant the container. 5 | */ 6 | public class Solution { 7 | public int maxArea(int[] height) { 8 | // IMPORTANT: Please reset any member data you declared, as 9 | // the same Solution instance will be reused for each test case. 10 | int max = 0; 11 | int length = height.length; 12 | 13 | //O(N2) exceeds time limit 14 | // for(int i = 0; i < length - 1; i++) { 15 | // int leftHeight = height[i]; 16 | // for (int j = i + 1; j < length; j++) { 17 | // int rightHeight = height[j]; 18 | // int width = j - i; 19 | // int area = width * Math.min(rightHeight, leftHeight); 20 | // max = Math.max(max, area); 21 | // } 22 | // } 23 | // return max; 24 | 25 | 26 | //O(N) 27 | int left = 0; 28 | int right = length - 1; 29 | while (left < right) { 30 | int leftHeight = height[left]; 31 | int rightHeight = height[right]; 32 | max = Math.max(max, Math.min(rightHeight, leftHeight) * (right - left)); 33 | if (leftHeight < rightHeight) { 34 | left++; 35 | } else { 36 | right--; 37 | } 38 | } 39 | return max; 40 | } 41 | } -------------------------------------------------------------------------------- /Convert Sorted Array to Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | */ 4 | 5 | /** 6 | * Definition for binary tree 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class Solution { 15 | public TreeNode sortedArrayToBST(int[] num) { 16 | // IMPORTANT: Please reset any member data you declared, as 17 | // the same Solution instance will be reused for each test case. 18 | int length = num.length; 19 | 20 | if (length == 0) { 21 | return null; 22 | } 23 | return getNode(0, length - 1, num); 24 | } 25 | 26 | public TreeNode getNode (int start, int end, int[] num) { 27 | if (start > end) { 28 | return null; 29 | } 30 | int mid = (start + end) / 2; 31 | TreeNode root = new TreeNode(num[mid]); 32 | root.left = getNode(start, mid - 1, num); 33 | root.right = getNode(mid + 1, end, num); 34 | return root; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; next = null; } 11 | * } 12 | */ 13 | /** 14 | * Definition for binary tree 15 | * public class TreeNode { 16 | * int val; 17 | * TreeNode left; 18 | * TreeNode right; 19 | * TreeNode(int x) { val = x; } 20 | * } 21 | */ 22 | 23 | /* 24 | O(N) solution: 25 | 26 | BinaryTree* sortedListToBST(ListNode *& list, int start, int end) { 27 | if (start > end) return NULL; 28 | // same as (start+end)/2, avoids overflow 29 | int mid = start + (end - start) / 2; 30 | BinaryTree *leftChild = sortedListToBST(list, start, mid-1); 31 | BinaryTree *parent = new BinaryTree(list->data); 32 | parent->left = leftChild; 33 | list = list->next; 34 | parent->right = sortedListToBST(list, mid+1, end); 35 | return parent; 36 | } 37 | 38 | BinaryTree* sortedListToBST(ListNode *head, int n) { 39 | return sortedListToBST(head, 0, n-1); 40 | } 41 | 42 | */ 43 | public class Solution { 44 | public TreeNode sortedListToBST(ListNode head) { 45 | // IMPORTANT: Please reset any member data you declared, as 46 | // the same Solution instance will be reused for each test case. 47 | if (head == null) { 48 | return null; 49 | } 50 | ListNode end = head; 51 | while (end != null) { 52 | end = end.next; 53 | } 54 | return getNode(head, end); 55 | } 56 | 57 | public TreeNode getNode(ListNode start, ListNode end) { 58 | ListNode fast = start; 59 | ListNode slow = start; 60 | if (start == end) { 61 | return null; 62 | } 63 | while (fast != end && fast.next != end) { 64 | slow = slow.next; 65 | fast = fast.next.next; 66 | } 67 | TreeNode root = new TreeNode(slow.val); 68 | root.left = getNode(start, slow); 69 | root.right = getNode(slow.next, end); 70 | return root; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Copy List with Random Pointer.java: -------------------------------------------------------------------------------- 1 | /* 2 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | 4 | Return a deep copy of the list. 5 | */ 6 | 7 | /** 8 | * Definition for singly-linked list with a random pointer. 9 | * class RandomListNode { 10 | * int label; 11 | * RandomListNode next, random; 12 | * RandomListNode(int x) { this.label = x; } 13 | * }; 14 | */ 15 | 16 | /* 17 | 1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N afte the Nth node 18 | 2) Now copy the arbitrary link in this fashion 19 | 20 | original->next->arbitrary = original->arbitrary->next; /*TRAVERSE 21 | TWO NODES 22 | This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy of arbitrary. 23 | 3) Now restore the original and copy linked lists in this fashion in a single loop. 24 | 25 | original->next = original->next->next; 26 | copy->next = copy->next->next; 27 | */ 28 | 29 | public class Solution { 30 | public RandomListNode copyRandomList(RandomListNode head) { 31 | // IMPORTANT: Please reset any member data you declared, as 32 | // the same Solution instance will be reused for each test case. 33 | if (head == null) { 34 | return null; 35 | } 36 | 37 | RandomListNode node = head; 38 | while (node != null) { 39 | RandomListNode copy = new RandomListNode(node.label); 40 | copy.next = node.next; 41 | node.next = copy; 42 | node = copy.next; 43 | } 44 | 45 | node = head; 46 | while (node != null) { 47 | if (node.random != null) { 48 | node.next.random = node.random.next; 49 | } else { 50 | node.next.random = null; 51 | } 52 | 53 | node = node.next.next; 54 | } 55 | 56 | RandomListNode newHead = head; 57 | newHead = newHead.next; 58 | node = newHead.next; 59 | RandomListNode copy = newHead; 60 | 61 | head.next = node; 62 | 63 | while (node != null) { 64 | copy.next = node.next; 65 | copy = copy.next; 66 | node.next = node.next.next; 67 | node = node.next; 68 | } 69 | 70 | return newHead; 71 | 72 | } 73 | } -------------------------------------------------------------------------------- /Count and Say.java: -------------------------------------------------------------------------------- 1 | /* 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 5 | 1 is read off as "one 1" or 11. 6 | 11 is read off as "two 1s" or 21. 7 | 21 is read off as "one 2, then one 1" or 1211. 8 | 9 | Given an integer n, generate the nth sequence. 10 | 11 | Note: The sequence of integers will be represented as a string. 12 | */ 13 | 14 | public class Solution { 15 | public String countAndSay(int n) { 16 | // IMPORTANT: Please reset any member data you declared, as 17 | // the same Solution instance will be reused for each test case. 18 | if (n == 0) return ""; 19 | String s = "1"; 20 | if (n == 1) return s; 21 | 22 | int count = 1; 23 | int k = 1; 24 | while (k < n) { 25 | StringBuilder cur = new StringBuilder(); 26 | 27 | for (int i = 0; i < s.length(); i++) { 28 | if(i == s.length() - 1 || s.charAt(i + 1) != s.charAt(i)) { 29 | cur.append(count); 30 | cur.append(s.charAt(i)); 31 | count = 1; 32 | } else { 33 | count++; 34 | } 35 | } 36 | s = cur.toString(); 37 | k++; 38 | } 39 | 40 | return s; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Decode Ways.java: -------------------------------------------------------------------------------- 1 | /* 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 'A' -> 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | For example, 11 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | The number of ways decoding "12" is 2. 14 | */ 15 | 16 | /* 17 | Count[i] = Count[i-1] if S[i-1] is a valid char 18 | or = Count[i-1]+ Count[i-2] if S[i-1] and S[i-2] together is still a valid char. 19 | 20 | */ 21 | public class Solution { 22 | public int numDecodings(String s) { 23 | // IMPORTANT: Please reset any member data you declared, as 24 | // the same Solution instance will be reused for each test case. 25 | if (s == null || s.length() == 0) return 0; 26 | int length = s.length(); 27 | int[] count = new int[length + 1]; 28 | count[0] = 1; 29 | if (s.charAt(0) != '0') count[1] = 1; 30 | else return 0; 31 | 32 | 33 | for (int i = 2; i <= length; i++) { 34 | if (s.charAt(i - 1) != '0') { 35 | int value = Integer.parseInt(s.substring(i - 2, i)); 36 | if (value > 10 && value <= 26) { 37 | count[i] = count[i - 2] + count[i - 1]; 38 | } else { 39 | count[i] = count[i - 1]; 40 | } 41 | } else { 42 | if (s.charAt(i - 2) == '1' || s.charAt(i - 2) == '2') { 43 | count[i] = count[i - 2]; 44 | } else { 45 | return 0; 46 | } 47 | } 48 | } 49 | return count[length]; 50 | 51 | } 52 | } -------------------------------------------------------------------------------- /Distinct Subsequences.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S and a string T, count the number of distinct subsequences of T in S. 3 | 4 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 5 | 6 | Here is an example: 7 | S = "rabbbit", T = "rabbit" 8 | 9 | Return 3. 10 | */ 11 | 12 | /* 13 | f(i, j) = f(i - 1, j) + S[i] == T[j]? f(i - 1, j - 1) : 0 14 | Where f(i, j) is the number of distinct sub-sequence for T[0:j] in S[0:i]. 15 | */ 16 | 17 | public class Solution { 18 | public int numDistinct(String S, String T) { 19 | // IMPORTANT: Please reset any member data you declared, as 20 | // the same Solution instance will be reused for each test case. 21 | if (S == null || T == null || S.length() == 0 || S.length() < T.length()) { 22 | return 0; 23 | } 24 | if (S.length() == T.length()) { 25 | return S.equals(T)? 1 : 0; 26 | } 27 | 28 | int[][] distinct = new int[S.length() + 1][T.length() + 1]; 29 | for (int i = 0; i <= S.length(); i++) { 30 | distinct[i][0] = 1; 31 | } 32 | 33 | for (int i = 1; i <= S.length(); i++) { 34 | for (int j = 1; j <= T.length(); j++) { 35 | if (S.charAt(i - 1) == T.charAt(j - 1)) { 36 | distinct[i][j] = distinct[i - 1][j - 1] + distinct[i - 1][j]; 37 | } else { 38 | distinct[i][j] = distinct[i - 1][j]; 39 | } 40 | } 41 | 42 | } 43 | return distinct[S.length()][T.length()]; 44 | } 45 | } -------------------------------------------------------------------------------- /Divide Two Integer.java: -------------------------------------------------------------------------------- 1 | /* 2 | Divide two integers without using multiplication, division and mod operator. 3 | */ 4 | 5 | public class Solution { 6 | public int divide(int dividend, int divisor) { 7 | // IMPORTANT: Please reset any member data you declared, as 8 | // the same Solution instance will be reused for each test case. 9 | 10 | boolean negative = false; 11 | //check if negative 12 | if (dividend == 0) { 13 | return 0; 14 | } 15 | if ((dividend < 0 && divisor > 0) ||(dividend > 0 && divisor < 0)) { 16 | negative = true; 17 | } 18 | 19 | if (divisor == 1 || divisor == -1) { 20 | return negative? (0 - Math.abs(dividend)) : Math.abs(dividend); 21 | } 22 | 23 | long dividend1 = Math.abs((long)dividend); 24 | long divisor1 = Math.abs((long)divisor); 25 | 26 | long remainder = dividend1; 27 | int result = 0; 28 | 29 | while (remainder >= divisor1) { 30 | for (int i = 1; i * divisor1 <= remainder; i = i*2) { 31 | remainder = remainder - i * divisor1; 32 | result += i; 33 | } 34 | 35 | } 36 | 37 | return negative? (0 - result) : result; 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Edit Distance.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 3 | 4 | You have the following 3 operations permitted on a word: 5 | 6 | a) Insert a character 7 | b) Delete a character 8 | c) Replace a character 9 | */ 10 | 11 | /* 12 | At the first glance, we might think this is a DFS problem, but if we see it is hard to find a quick DFS thought and the problem requires some optimal result (here is the minimum), DP is a good direction to consider. 13 | Actually this is a classic DP problem: 14 | The state is: table[i][j]=minimum number steps convert word1[1:i] to word2[1:j] (here assume string starts from 1). 15 | 16 | The optimal function is: table[i+1][j+1] = min [table[i-1][j-1]+1 or 0 (+1 if word1[i+1]==word2[j+1], else +0), table[i][j+1]+1, table[i+1][j]+1 ]. 17 | 18 | Initialization: 19 | table[0][i] = i i=1:|word1| here 0 means "", any string convert to "" needs the length of string 20 | table[j][0] = j i=1:|word2| 21 | table[0][0]=0 "" convert to "" need 0 steps. 22 | */ 23 | 24 | public class Solution { 25 | public int minDistance(String word1, String word2) { 26 | // IMPORTANT: Please reset any member data you declared, as 27 | // the same Solution instance will be reused for each test case. 28 | 29 | int length1 = word1.length(); 30 | int length2 = word2.length(); 31 | 32 | if (length1 == 0 || length2 == 0) { 33 | return length1 > length2? length1 : length2; 34 | } 35 | 36 | int[][] dis = new int[length1 + 1][length2 + 1]; 37 | 38 | for (int i = 1; i <= length1; i++) { 39 | dis[i][0] = i; 40 | } 41 | for (int j = 1; j <= length2; j++) { 42 | dis[0][j] = j; 43 | } 44 | 45 | for (int i = 1; i <= length1; i++) { 46 | for (int j = 1; j <= length2; j++) { 47 | if (word1.charAt(i - 1) == word2.charAt(j - 1)) { 48 | dis[i][j] = min(dis[i - 1][j - 1], dis[i - 1][j] + 1, dis[i][j - 1] + 1); 49 | } else { 50 | dis[i][j] = min(dis[i - 1][j - 1] + 1, dis[i - 1][j] + 1, dis[i][j - 1] + 1); 51 | } 52 | } 53 | } 54 | return dis[length1][length2]; 55 | } 56 | 57 | public int min(int a, int b, int c) { 58 | int temp = Math.min(a, b); 59 | return Math.min(temp, c); 60 | } 61 | } -------------------------------------------------------------------------------- /Evaluate Reverse Polish Notation.java: -------------------------------------------------------------------------------- 1 | /* 2 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | 4 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 5 | 6 | Some examples: 7 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 8 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 9 | */ 10 | 11 | public class Solution { 12 | public int evalRPN(String[] exp) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | Stack stack = new Stack(); 16 | 17 | for (int i = 0; i < exp.length; i++) { 18 | if (exp[i].matches("-?[\\d]+")) { 19 | stack.push(Integer.parseInt(exp[i])); 20 | } else { 21 | int op2 = stack.pop(); 22 | int op1 = stack.pop(); 23 | int result = 0; 24 | String operator = exp[i]; 25 | if (operator.equals("+")) result = op1 + op2; 26 | else if (operator.equals("-")) result = op1 - op2; 27 | else if (operator.equals("*")) result = op1 * op2; 28 | else if (operator.equals("/")) result = op1 / op2; 29 | stack.push(result); 30 | } 31 | } 32 | return stack.pop(); 33 | } 34 | } -------------------------------------------------------------------------------- /First Missing Positive.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted integer array, find the first missing positive integer. 3 | 4 | For example, 5 | Given [1,2,0] return 3, 6 | and [3,4,-1,1] return 2. 7 | 8 | Your algorithm should run in O(n) time and uses constant space. 9 | */ 10 | 11 | public class Solution { 12 | public int firstMissingPositive(int[] A) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | if (A.length == 0) return 1; 16 | 17 | int n = A.length; 18 | //find negative and set it to value impossible 19 | for (int i = 0; i < n; i++) { 20 | if (A[i] <= 0) A[i] = n + 2; 21 | } 22 | 23 | //if k is present, set A[k - 1] -> negative 24 | for (int i = 0; i < n; i++) { 25 | int k = A[i]; 26 | k = Math.abs(k); 27 | if (k <= n && k > 0) { 28 | A[k - 1] = -Math.abs(A[k - 1]); 29 | } 30 | } 31 | 32 | //find the positive value and return 33 | for (int i = 0; i < n; i++) { 34 | if (A[i] > 0) return i + 1; 35 | } 36 | 37 | return n + 1; 38 | } 39 | } -------------------------------------------------------------------------------- /Flatten Binary Tree To Linked List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, flatten it to a linked list in-place. 3 | 4 | For example, 5 | Given 6 | 7 | 1 8 | / \ 9 | 2 5 10 | / \ \ 11 | 3 4 6 12 | The flattened tree should look like: 13 | 1 14 | \ 15 | 2 16 | \ 17 | 3 18 | \ 19 | 4 20 | \ 21 | 5 22 | \ 23 | 6 24 | click to show hints. 25 | 26 | Hints: 27 | If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. 28 | */ 29 | public class Solution { 30 | public void flatten(TreeNode root) { 31 | // IMPORTANT: Please reset any member data you declared, as 32 | // the same Solution instance will be reused for each test case. 33 | if (root == null) { 34 | return; 35 | } 36 | 37 | Stack rightStack = new Stack(); 38 | 39 | root = nextNode(root, rightStack); 40 | } 41 | 42 | public TreeNode nextNode (TreeNode node, Stack rightStack) { 43 | Stack stack = new Stack(); 44 | stack = (Stack) rightStack.clone(); 45 | if (node.right != null) { 46 | stack.push(node.right); 47 | } 48 | 49 | if (node.left == null) { 50 | if (!stack.isEmpty()) { 51 | TreeNode temp = stack.pop(); 52 | node.right = nextNode(temp, stack); 53 | } 54 | } else { 55 | node.right = nextNode(node.left, stack); 56 | } 57 | node.left = null; 58 | //System.out.println(node.val); 59 | return node; 60 | } 61 | } -------------------------------------------------------------------------------- /Gas Station.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | // Note: The Solution object is instantiated only once and is reused by each test case. 4 | 5 | int N = gas.length; 6 | 7 | int startIndex = 0; 8 | while (startIndex < N) { 9 | 10 | int filled = 0; 11 | int required = 0; 12 | boolean found = true; 13 | 14 | for (int i = 0; i < N; i++) { 15 | int k = i + startIndex; 16 | if (k >= N) { 17 | k -= N; 18 | } 19 | filled += gas[k]; 20 | required += cost[k]; 21 | if (required > filled) { 22 | found = false; 23 | break; 24 | } 25 | } 26 | 27 | if (found) { 28 | return startIndex; 29 | } else { 30 | filled = 0; 31 | required = 0; 32 | startIndex++; 33 | } 34 | } 35 | 36 | return -1; 37 | } 38 | } -------------------------------------------------------------------------------- /Generate Parentheses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | "((()))", "(()())", "(())()", "()(())", "()()()" 7 | */ 8 | 9 | public class Solution { 10 | public ArrayList generateParenthesis(int n) { 11 | // IMPORTANT: Please reset any member data you declared, as 12 | // the same Solution instance will be reused for each test case. 13 | if (n == 0) { 14 | return new ArrayList(); 15 | } 16 | return helper(n, 0, 0, new StringBuilder()); 17 | } 18 | 19 | public ArrayList helper(int n, int l, int r, StringBuilder s) { 20 | ArrayList result = new ArrayList(); 21 | 22 | if (l > n || r > n) { 23 | return result; 24 | } 25 | 26 | if (r == n) { 27 | result.add(s.toString()); 28 | } 29 | 30 | if (l < n) { 31 | StringBuilder ss = new StringBuilder(s); 32 | ss.append("("); 33 | result.addAll(helper(n, l + 1, r, ss)); 34 | } 35 | 36 | if (r < l) { 37 | StringBuilder ss = new StringBuilder(s); 38 | ss.append(")"); 39 | result.addAll(helper(n, l, r + 1, ss)); 40 | } 41 | 42 | return result; 43 | } 44 | } 45 | 46 | / 47 | public class Solution2 { 48 | public ArrayList generateParenthesis(int n) { 49 | // IMPORTANT: Please reset any member data you declared, as 50 | // the same Solution instance will be reused for each test case. 51 | ArrayList result = new ArrayList(); 52 | if (n == 0) { 53 | return result; 54 | } 55 | 56 | helper(n, 0, 0, "", result); 57 | return result; 58 | } 59 | 60 | public void helper(int n, int l, int r, String s, ArrayList result) { 61 | if (l == n) { 62 | while (r < n) { 63 | s += ")"; 64 | r++; 65 | } 66 | result.add(s); 67 | return; 68 | } 69 | 70 | if (l < n) { 71 | helper(n, l + 1, r, s+"(", result); 72 | } 73 | if (r < l) { 74 | helper(n, l, r + 1, s+")", result); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /Gray Code.java: -------------------------------------------------------------------------------- 1 | /* 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 8 | 00 - 0 9 | 01 - 1 10 | 11 - 3 11 | 10 - 2 12 | Note: 13 | For a given n, a gray code sequence is not uniquely defined. 14 | 15 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 16 | 17 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 18 | */ 19 | 20 | public class Solution { 21 | public ArrayList grayCode(int n) { 22 | // IMPORTANT: Please reset any member data you declared, as 23 | // the same Solution instance will be reused for each test case. 24 | ArrayList result = new ArrayList(); 25 | result.add(0); 26 | 27 | if (n == 0) return result; 28 | 29 | result.add(1); 30 | 31 | for (int i = 1; i < n; i++) { 32 | ArrayList temp = result; 33 | int m = 1 << i; 34 | for (int j = result.size() - 1; j >= 0; j--) { 35 | temp.add(m + result.get(j)); 36 | } 37 | result = temp; 38 | } 39 | 40 | return result; 41 | } 42 | } -------------------------------------------------------------------------------- /Implement strStr().java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement strStr(). 3 | 4 | Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 5 | */ 6 | 7 | public class Solution { 8 | public String strStr(String haystack, String needle) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | int length1 = haystack.length(); 12 | int length2 = needle.length(); 13 | if (length2 == 0) { 14 | return haystack; 15 | } 16 | if (length2 > length1) { 17 | return null; 18 | } 19 | 20 | for (int i = 0; i + length2 <= length1; i++) { 21 | if (haystack.charAt(i) != needle.charAt(0)) { 22 | continue; 23 | } 24 | int k = i + 1; 25 | for (int j = 1; j < length2 && k < length1; j++) { 26 | if (needle.charAt(j) == haystack.charAt(k)) { 27 | k++; 28 | } else { 29 | break; 30 | } 31 | } 32 | if (k == i + length2) { 33 | return haystack.substring(i); 34 | } 35 | } 36 | return null; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Insert Interval.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 3 | 4 | You may assume that the intervals were initially sorted according to their start times. 5 | 6 | Example 1: 7 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 8 | 9 | Example 2: 10 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 11 | 12 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 13 | */ 14 | 15 | /** 16 | * Definition for an interval. 17 | * public class Interval { 18 | * int start; 19 | * int end; 20 | * Interval() { start = 0; end = 0; } 21 | * Interval(int s, int e) { start = s; end = e; } 22 | * } 23 | */ 24 | public class Solution { 25 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 26 | // IMPORTANT: Please reset any member data you declared, as 27 | // the same Solution instance will be reused for each test case. 28 | ArrayList result = new ArrayList(intervals); 29 | if (intervals == null || intervals.isEmpty()) { 30 | result.add(newInterval); 31 | return result; 32 | } 33 | int m = 0; 34 | for (int i = 0; i < intervals.size(); i++) { 35 | Interval cur = intervals.get(i); 36 | if (cur.end < newInterval.start) continue; 37 | if (cur.start > newInterval.end) { 38 | result.add(i - m, newInterval); 39 | return result; 40 | } 41 | if (cur.start <= newInterval.start && cur.end >= newInterval.end) return result; 42 | 43 | //newInterval contain current interval 44 | if (cur.start > newInterval.start && cur.end < newInterval.end) { 45 | result.remove(cur); 46 | m++; 47 | continue; 48 | } 49 | //merge 50 | if (cur.end >= newInterval.start) { 51 | newInterval.start = Math.min(cur.start, newInterval.start); 52 | result.remove(cur); 53 | m++; 54 | } 55 | if (cur.start <= newInterval.end) { 56 | newInterval.end = Math.max(newInterval.end, cur.end); 57 | if (result.contains(cur)) { 58 | result.remove(cur); 59 | m++; 60 | } 61 | } 62 | 63 | } 64 | result.add(newInterval); 65 | return result; 66 | } 67 | } -------------------------------------------------------------------------------- /Insertion Sort List.jaa: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paopao2/Algorithm-Practice/ff438b7f6c68013d2608f92659d8449d79dc5ba8/Insertion Sort List.jaa -------------------------------------------------------------------------------- /Insertion Sort List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Sort a linked list using insertion sort. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | public class Solution { 17 | public ListNode insertionSortList(ListNode head) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | if (head == null) return null; 21 | 22 | ListNode newHead = null; 23 | ListNode newTail = null; 24 | int min = head.val; 25 | while (head != null) { 26 | ListNode next = head.next; 27 | ListNode node = head; 28 | ListNode curMin = null; 29 | while (node != null) { 30 | if (curMin == null) curMin = node; 31 | if (node.val < curMin.val) curMin = node; 32 | node = node.next; 33 | } 34 | 35 | if (newHead == null) { 36 | newHead = curMin; 37 | newTail = curMin; 38 | } else { 39 | newTail.next = curMin; 40 | newTail = curMin; 41 | } 42 | 43 | //remove curMin from original list 44 | node = head; 45 | if (curMin == head) { 46 | head = next; 47 | } else { 48 | while (node.next != null) { 49 | if (node.next == curMin) { 50 | node.next = node.next.next; 51 | break; 52 | } 53 | node = node.next; 54 | } 55 | } 56 | 57 | } 58 | return newHead; 59 | } 60 | } -------------------------------------------------------------------------------- /Interleaving String.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 3 | 4 | For example, 5 | Given: 6 | s1 = "aabcc", 7 | s2 = "dbbca", 8 | 9 | When s3 = "aadbbcbcac", return true. 10 | When s3 = "aadbbbaccc", return false. 11 | */ 12 | 13 | public class Solution { 14 | public boolean isInterleave(String s1, String s2, String s3) { 15 | // Note: The Solution object is instantiated only once and is reused by each test case. 16 | int length1 = s1.length(); 17 | int length2 = s2.length(); 18 | int length3 = s3.length(); 19 | if (length1 + length2 != length3) { 20 | return false; 21 | } 22 | boolean[][] isInter = new boolean[length1 + 1][length2 + 1]; 23 | isInter[0][0] = true; 24 | for (int i = 1; i <= length1; i++) { 25 | isInter[i][0] = s1.charAt(i - 1) == s3.charAt(i - 1); 26 | if (!isInter[i][0]) break; 27 | } 28 | for (int j = 1; j <= length2; j++) { 29 | isInter[0][j] = s2.charAt(j - 1) == s3.charAt(j - 1); 30 | if (!isInter[0][j]) break; 31 | } 32 | int k = 0; 33 | for (int i = 1; i <= length1; i++) { 34 | for (int j = 1; j <= length2; j++) { 35 | k = i + j - 1; 36 | isInter[i][j] = (isInter[i][j - 1] && s3.charAt(k) == s2.charAt(j - 1)) || (isInter[i - 1][j] && s3.charAt(k) == s1.charAt(i - 1)); 37 | } 38 | } 39 | return isInter[length1][length2]; 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /Jump Game ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Your goal is to reach the last index in the minimum number of jumps. 7 | 8 | For example: 9 | Given array A = [2,3,1,1,4] 10 | 11 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 12 | */ 13 | 14 | 15 | /* 16 | * We use "last" to keep track of the maximum distance that has been reached 17 | * by using the minimum steps "steps", whereas "curr" is the maximum distance 18 | * that can be reached by using "ret+1" steps. Thus, 19 | * curr = max(i+A[i]) where 0 <= i <= last. 20 | */ 21 | 22 | public class Solution { 23 | public int jump(int[] A) { 24 | // Note: The Solution object is instantiated only once and is reused by each test case. 25 | int last = 0; 26 | int curr = 0; 27 | int steps = 0; 28 | 29 | for (int i = 0; i < A.length; i++) { 30 | 31 | if (i > last) { 32 | last = curr; 33 | steps++; 34 | } 35 | if (last >= A.length - 1) { 36 | break; 37 | } 38 | curr = Math.max(curr, A[i] + i); 39 | } 40 | return steps; 41 | } 42 | } -------------------------------------------------------------------------------- /Jump Game.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | For example: 9 | A = [2,3,1,1,4], return true. 10 | 11 | A = [3,2,1,0,4], return false. 12 | */ 13 | 14 | 15 | //BFS, can't pass large set, time limit exceeds 16 | public class Solution { 17 | 18 | public boolean canJump(int[] A) { 19 | // IMPORTANT: Please reset any member data you declared, as 20 | // the same Solution instance will be reused for each test case. 21 | 22 | Stack stack = new Stack(); 23 | HashSet visited = new HashSet(); 24 | 25 | stack.push(0); 26 | visited.add(0); 27 | 28 | while (!stack.isEmpty()) { 29 | int index = stack.pop(); 30 | int maxJump = A[index]; 31 | if (index + maxJump >= A.length - 1) { 32 | return true; 33 | } 34 | for (int i = 1; i <= maxJump; i++) { 35 | if (!visited.contains(index + i)) { 36 | visited.add(index + i); 37 | stack.push(index + i); 38 | } 39 | } 40 | } 41 | 42 | return false; 43 | } 44 | } 45 | 46 | //brilliant solution 47 | //use coverage to track how far you can try 48 | public class Solution { 49 | 50 | public boolean canJump(int[] A) { 51 | 52 | int coverage = 0; 53 | for(int i = 0; i < A.length && i <= coverage; i++) 54 | coverage = Math.max(coverage, A[i] + i); 55 | return coverage >= A.length - 1; 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /Largest Rectangle in Histogram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 3 | 4 | 5 | Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. 6 | 7 | 8 | The largest rectangle is shown in the shaded area, which has area = 10 unit. 9 | 10 | For example, 11 | Given height = [2,1,5,6,2,3], 12 | return 10. 13 | */ 14 | 15 | //维护一个递增的栈,每次比较栈顶与当前元素。如果当前元素小于栈顶元素, 则入栈,否则合并现有栈,直至栈顶元素小于当前元素。结尾时入栈元素 0,重复合并一次。 16 | public class Solution { 17 | public int largestRectangleArea(int[] height) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | Stack stack = new Stack(); 21 | int result = 0; 22 | int[] heights = new int[height.length + 1]; 23 | for (int i = 0; i <= height.length; i++) { 24 | if (i == height.length) heights[i] = 0; 25 | else { 26 | heights[i] = height[i]; 27 | } 28 | } 29 | for (int i = 0; i < heights.length;) { 30 | if (stack.isEmpty() || heights[i] > heights[stack.peek()]) { 31 | stack.push(i++); 32 | } else { 33 | int index = stack.pop(); 34 | result = Math.max(result, heights[index] * (stack.isEmpty() ? i : (i - stack.peek() - 1))); 35 | } 36 | } 37 | return result; 38 | } 39 | } -------------------------------------------------------------------------------- /Length of Last Word.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | For example, 9 | Given s = "Hello World", 10 | return 5. 11 | */ 12 | 13 | public class Solution { 14 | public int lengthOfLastWord(String s) { 15 | // Note: The Solution object is instantiated only once and is reused by each test case. 16 | // if(s == null || s.equals("")) { 17 | // return 0; 18 | // } 19 | 20 | // String[] words = s.split(" "); 21 | // int lastWordIndex = words.length - 1; 22 | // return words[lastWordIndex].length(); 23 | int p = s.length()-1; 24 | int len=0; 25 | boolean trailing=true; 26 | while (p >= 0) { 27 | if (s.charAt(p) != ' ') { 28 | len ++; 29 | trailing=false; 30 | p --; 31 | } else if (trailing) { 32 | p--; 33 | } else { 34 | break; 35 | } 36 | } 37 | return len; 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Letter Combinations of a Phone Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a digit string, return all possible letter combinations that the number could represent. 3 | 4 | A mapping of digit to letters (just like on the telephone buttons) is given below. 5 | 6 | 7 | 8 | Input:Digit string "23" 9 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 10 | */ 11 | 12 | public class Solution { 13 | public ArrayList letterCombinations(String digits) { 14 | // Note: The Solution object is instantiated only once and is reused by each test case. 15 | char[] digitChars = digits.toCharArray(); 16 | ArrayList result = new ArrayList(); 17 | StringBuilder s = new StringBuilder(); 18 | letterCombinationHelper(0, digitChars, s, result); 19 | return result; 20 | } 21 | 22 | private char[][] map = {{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'}, {'m', 'n', 'o'}, {'p', 'q', 'r', 's'}, {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}}; 23 | 24 | private void letterCombinationHelper(int index, char[] digits, StringBuilder s, ArrayList result) { 25 | if (index >= digits.length) { 26 | result.add(s.toString()); 27 | } 28 | else { 29 | int curNum = digits[index] - '1' - 1; 30 | char[] digitString = map[curNum]; 31 | for (int i = 0; i < digitString.length; i++) { 32 | s.append(digitString[i]); 33 | letterCombinationHelper(index + 1, digits, s, result); 34 | //important 35 | s.deleteCharAt(s.length() - 1); 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Linked List Cycle II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | 4 | Follow up: 5 | Can you solve it without using extra space? 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode(int x) { 14 | * val = x; 15 | * next = null; 16 | * } 17 | * } 18 | */ 19 | public class Solution { 20 | public ListNode detectCycle(ListNode head) { 21 | // IMPORTANT: Please reset any member data you declared, as 22 | // the same Solution instance will be reused for each test case. 23 | ListNode fast = head; 24 | ListNode slow = head; 25 | boolean loop = false; 26 | 27 | while (fast != null && fast.next != null) { 28 | fast = fast.next.next; 29 | slow = slow.next; 30 | if (fast == slow) { 31 | loop = true; 32 | break; 33 | } 34 | } 35 | 36 | if (loop) { 37 | fast = head; 38 | while (fast != slow) { 39 | fast = fast.next; 40 | slow = slow.next; 41 | } 42 | return fast; 43 | } else { 44 | return null; 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, determine if it has a cycle in it. 3 | 4 | Follow up: 5 | Can you solve it without using extra space? 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode(int x) { 14 | * val = x; 15 | * next = null; 16 | * } 17 | * } 18 | */ 19 | public class Solution { 20 | public boolean hasCycle(ListNode head) { 21 | // IMPORTANT: Please reset any member data you declared, as 22 | // the same Solution instance will be reused for each test case. 23 | ListNode fast = head; 24 | ListNode slow = head; 25 | 26 | while (fast != null && fast.next != null) { 27 | fast = fast.next.next; 28 | slow = slow.next; 29 | if (fast == slow) { 30 | return true; 31 | } 32 | } 33 | 34 | return false; 35 | } 36 | } -------------------------------------------------------------------------------- /Longest Common Prefix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | */ 4 | 5 | public class Solution { 6 | public String longestCommonPrefix(String[] strs) { 7 | // IMPORTANT: Please reset any member data you declared, as 8 | // the same Solution instance will be reused for each test case. 9 | if (strs.length == 0) return ""; 10 | StringBuilder result = new StringBuilder(); 11 | int i = 0; 12 | while (i < strs[0].length()) { 13 | char c = strs[0].charAt(i); 14 | for (String s : strs) { 15 | if (i >= s.length() || s.charAt(i) != c) return result.toString(); 16 | } 17 | result.append(c); 18 | i++; 19 | } 20 | return result.toString(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Longest Consecutive Sequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | For example, 5 | Given [100, 4, 200, 1, 3, 2], 6 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 7 | 8 | Your algorithm should run in O(n) complexity. 9 | 10 | */ 11 | 12 | public class Solution { 13 | public int longestConsecutive(int[] num) { 14 | // IMPORTANT: Please reset any member data you declared, as 15 | // the same Solution instance will be reused for each test case. 16 | int length = num.length; 17 | 18 | //Key: value, Value: index 19 | HashMap numMap = new HashMap(); 20 | boolean[] visited = new boolean[length]; 21 | 22 | for (int i = 0; i < length; i++) { 23 | numMap.put(num[i], i); 24 | } 25 | 26 | int maxLength = 0; 27 | for (int cur : numMap.keySet()) { 28 | int index = numMap.get(cur); 29 | if (visited[index]) { 30 | continue; 31 | } 32 | int curLength = 1; 33 | int left = cur - 1; 34 | int right = cur + 1; 35 | while (numMap.containsKey(left)) { 36 | int leftIndex = numMap.get(left); 37 | visited[leftIndex] = true; 38 | left --; 39 | curLength++; 40 | } 41 | while (numMap.containsKey(right)) { 42 | int rightIndex = numMap.get(right); 43 | visited[rightIndex] = true; 44 | right++; 45 | curLength++; 46 | } 47 | 48 | if (curLength > maxLength) { 49 | maxLength = curLength; 50 | } 51 | } 52 | 53 | return maxLength; 54 | } 55 | } -------------------------------------------------------------------------------- /Longest Palindromic Substring.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 3 | */ 4 | 5 | public class Solution { 6 | public String longestPalindrome(String s) { 7 | // IMPORTANT: Please reset any member data you declared, as 8 | // the same Solution instance will be reused for each test case. 9 | 10 | int length = s.length(); 11 | if (length == 0 || length == 1) { 12 | return s; 13 | } 14 | if (length == 2 && s.charAt(0) == s.charAt(1)) { 15 | return s; 16 | } 17 | int max = 0; 18 | int start = 0; 19 | int end = 1; 20 | boolean[][] isPal = new boolean[length][length]; 21 | for (int i = 0; i < length; i++) { 22 | isPal[i][i] = true; 23 | } 24 | for (int i = 0; i < length - 1; i++) { 25 | isPal[i][i + 1] = s.charAt(i) == s.charAt(i + 1); 26 | if (max < 2 && isPal[i][i + 1]) { 27 | max = 2; 28 | start = i; 29 | end = i + 2; 30 | } 31 | } 32 | 33 | for (int i = length - 3; i >= 0; i--) { 34 | for (int j = i + 2; j < length; j++) { 35 | isPal[i][j] = isPal[i + 1][j - 1] && (s.charAt(i) == s.charAt(j)); 36 | if (isPal[i][j] && (j - i >= max)) { 37 | max = j - i; 38 | start = i; 39 | end = j + 1; 40 | } 41 | } 42 | } 43 | return s.substring(start, end); 44 | 45 | } 46 | } -------------------------------------------------------------------------------- /Longest Substring Without Repeating Characters.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 3 | */ 4 | 5 | public class Solution { 6 | public int lengthOfLongestSubstring(String s) { 7 | // Note: The Solution object is instantiated only once and is reused by each test case. 8 | int maxLength = 0; 9 | 10 | for(int i = 0; i < s.length(); i++) { 11 | HashSet chars = new HashSet(); 12 | chars.add(s.charAt(i)); 13 | int j = i + 1; 14 | while(j < s.length()) { 15 | if(chars.contains(s.charAt(j))) { 16 | break; 17 | } 18 | else { 19 | chars.add(s.charAt(j)); 20 | j++; 21 | } 22 | } 23 | if(chars.size() > maxLength) { 24 | maxLength = chars.size(); 25 | } 26 | } 27 | 28 | return maxLength; 29 | } 30 | } -------------------------------------------------------------------------------- /Longest Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 3 | 4 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 5 | 6 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 7 | 8 | */ 9 | 10 | 11 | public class Solution { 12 | public int longestValidParentheses(String s) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | 16 | int maxLen = 0; 17 | 18 | //the position of the last ')' 19 | //so when left stack is empty(all matched), use this to calculate the length 20 | int last = -1; 21 | 22 | Stack left = new Stack(); 23 | 24 | for (int i = 0; i < s.length(); i++) { 25 | if (s.charAt(i) == '(') { 26 | left.push(i); 27 | } else { 28 | if (left.isEmpty()) { 29 | last = i; 30 | } else { 31 | left.pop(); 32 | if (left.isEmpty()) { 33 | //all matched by now 34 | maxLen = Math.max(maxLen, i - last); 35 | } else { 36 | maxLen = Math.max(maxLen, i - left.peek()); 37 | } 38 | } 39 | 40 | } 41 | } 42 | 43 | return maxLen; 44 | 45 | } 46 | } 47 | Submit Solution 48 | -------------------------------------------------------------------------------- /Maximal Rectangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 3 | 4 | */ 5 | 6 | 7 | /* 8 | Case 1 -- matrix(i, j) = 1 9 | H(i, j) = H(i-1, j) + 1 10 | L(i, j) = max( L(i-1, j), the position of the left nearest 0 in this row ) 11 | R(i, j) = min( R(i-1, j), the position of the right nearest 0 in this row ) 12 | 13 | Case 2 -- matrix(i, j) = 0 14 | H(i, j) = 0 15 | L(i, j) = 0 16 | R(i, j) = n 17 | */ 18 | 19 | public class Solution { 20 | public int maximalRectangle(char[][] matrix) { 21 | // IMPORTANT: Please reset any member data you declared, as 22 | // the same Solution instance will be reused for each test case. 23 | 24 | if (matrix.length == 0) { 25 | return 0; 26 | } 27 | 28 | int rowLength = matrix.length; 29 | int colLength = matrix[0].length; 30 | int[] L = new int[colLength]; 31 | int[] R = new int[colLength]; 32 | int[] H = new int[colLength]; 33 | 34 | for (int j = 0; j < colLength; j++) { 35 | R[j] = colLength; 36 | } 37 | 38 | int area = 0; 39 | 40 | for (int i = 0; i < rowLength; i++) { 41 | int left = 0; 42 | int right = colLength; 43 | 44 | //from left to right 45 | for (int j = 0; j < colLength; j++) { 46 | if (matrix[i][j] == '1') { 47 | H[j]++; 48 | L[j] = Math.max(L[j], left); 49 | } else { 50 | H[j] = 0; 51 | L[j] = 0; 52 | R[j] = colLength; 53 | left = j + 1; 54 | } 55 | } 56 | 57 | for (int j = colLength - 1; j >= 0; j--) { 58 | if (matrix[i][j] == '1') { 59 | R[j] = Math.min(R[j], right); 60 | area = Math.max(area, H[j]*(R[j] - L[j])); 61 | } else { 62 | right = j; 63 | } 64 | } 65 | 66 | } 67 | return area; 68 | } 69 | } -------------------------------------------------------------------------------- /Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | /*Given a binary tree, find its maximum depth.*/ 2 | 3 | /** 4 | * Definition for binary tree 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public int maxDepth(TreeNode root) { 14 | // Note: The Solution object is instantiated only once and is reused by each test case. 15 | 16 | if(root == null) 17 | return 0; 18 | else { 19 | int leftDepth = 1 + maxDepth(root.left); 20 | int rightDepth = 1 + maxDepth(root.right); 21 | 22 | return (leftDepth > rightDepth)? leftDepth : rightDepth; 23 | 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Maximum Subarray Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum sub array sum 3 | 4 | use dynamic programming 5 | */ 6 | 7 | public int getMaximumSubarraySum(int[] arrays) { 8 | int maxSoFar = arrays[0]; 9 | int maxAtCurrentPosition = arrays[1]; 10 | 11 | for (int i = 1; i < arrays.length; i++) { 12 | if (maxAtCurrentPosition < 0) { 13 | maxAtCurrentPosition = arrays[i]; 14 | } else { 15 | maxAtCurrentPosition += arrays[i]; 16 | } 17 | 18 | if (maxAtCurrentPosition > maxSoFar) { 19 | maxSoFar = maxAtCurrentPosition; 20 | } 21 | } 22 | 23 | return maxSoFar; 24 | } -------------------------------------------------------------------------------- /Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | For example, given the array [−2,1,−3,4,−1,2,1,−5,4], 5 | the contiguous subarray [4,−1,2,1] has the largest sum = 6. 6 | 7 | click to show more practice. 8 | 9 | More practice: 10 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 11 | */ 12 | 13 | public class Solution { 14 | public int maxSubArray(int[] A) { 15 | // IMPORTANT: Please reset any member data you declared, as 16 | // the same Solution instance will be reused for each test case. 17 | int length = A.length; 18 | int[] maxSoFar = new int[length]; 19 | 20 | int max = A[0]; 21 | maxSoFar[0] = A[0]; 22 | 23 | for (int i = 1; i < length; i++) { 24 | 25 | if (maxSoFar[i - 1] > 0) { 26 | maxSoFar[i] = maxSoFar[i - 1] + A[i]; 27 | } else { 28 | maxSoFar[i] = A[i]; 29 | } 30 | 31 | if (maxSoFar[i] > max) { 32 | max = maxSoFar[i]; 33 | } 34 | 35 | } 36 | 37 | return max; 38 | } 39 | } 40 | 41 | public class Solution { 42 | public int maxSubArray(int[] A) { 43 | // IMPORTANT: Please reset any member data you declared, as 44 | // the same Solution instance will be reused for each test case. 45 | 46 | return maxSubArrayHelper(0, A.length - 1, A); 47 | } 48 | 49 | public int maxSubArrayHelper(int start, int end, int[]A) { 50 | if (start > end) { 51 | return Integer.MIN_VALUE; 52 | } 53 | if (start == end) { 54 | return A[start]; 55 | } 56 | 57 | int mid = (start + end)/2; 58 | int leftMax = Integer.MIN_VALUE; 59 | int rightMax = Integer.MIN_VALUE; 60 | 61 | //count contiguously 62 | for(int i = mid - 1, curSum = 0; i >= 0; i--) { 63 | curSum += A[i]; 64 | leftMax = Math.max(leftMax, curSum); 65 | } 66 | 67 | for (int i = mid + 1, curSum = 0; i <= end; i++) { 68 | curSum += A[i]; 69 | rightMax = Math.max(rightMax, curSum); 70 | } 71 | 72 | int midMax = A[mid] + Math.max(leftMax, 0) + Math.max(rightMax, 0); 73 | 74 | return Math.max(Math.max(maxSubArrayHelper(start, mid - 1, A), maxSubArrayHelper(mid + 1, end, A)), midMax); 75 | } 76 | } -------------------------------------------------------------------------------- /Merge Intervals.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | For example, 5 | Given [1,3],[2,6],[8,10],[15,18], 6 | return [1,6],[8,10],[15,18]. 7 | */ 8 | 9 | /** 10 | * Definition for an interval. 11 | * public class Interval { 12 | * int start; 13 | * int end; 14 | * Interval() { start = 0; end = 0; } 15 | * Interval(int s, int e) { start = s; end = e; } 16 | * } 17 | */ 18 | public class Solution { 19 | public ArrayList merge(ArrayList intervals) { 20 | // IMPORTANT: Please reset any member data you declared, as 21 | // the same Solution instance will be reused for each test case. 22 | ArrayList result = new ArrayList(); 23 | if (intervals == null || intervals.size() == 0) return result; 24 | Comparator comparator = new Comparator() { 25 | public int compare(Interval i1, Interval i2) { 26 | if (i1.start < i2.start) { 27 | return -1; 28 | } else if (i1.start > i2.start) { 29 | return 1; 30 | } else { 31 | if (i1.end < i2.end) return -1; 32 | else if (i1.end > i2.end) return 1; 33 | else return 0; 34 | } 35 | } 36 | }; 37 | 38 | Collections.sort(intervals, comparator); 39 | 40 | for (int i = 0; i < intervals.size(); i++) { 41 | Interval cur = intervals.get(i); 42 | if (result.isEmpty()) result.add(cur); 43 | else { 44 | Interval last = result.get(result.size() - 1); 45 | if (last.end >= cur.start) { 46 | last.end = Math.max(last.end, cur.end); 47 | } else { 48 | result.add(cur); 49 | } 50 | } 51 | } 52 | return result; 53 | } 54 | } -------------------------------------------------------------------------------- /Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 3 | 4 | Note: 5 | You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. 6 | */ 7 | 8 | public class Solution { 9 | public void merge(int A[], int m, int B[], int n) { 10 | // IMPORTANT: Please reset any member data you declared, as 11 | // the same Solution instance will be reused for each test case. 12 | while (m > 0 && n > 0) { 13 | if (A[m - 1] > B[n - 1]) { 14 | A[m + n - 1] = A[m - 1]; 15 | m--; 16 | } else { 17 | A[m + n - 1] = B[n - 1]; 18 | n--; 19 | } 20 | } 21 | 22 | if (n > 0) { 23 | while (n > 0) { 24 | A[n - 1] = B[n - 1]; 25 | n--; 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | public class Solution { 17 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 18 | // Note: The Solution object is instantiated only once and is reused by each test case. 19 | if (l1 == null) { 20 | return l2; 21 | } 22 | if (l2 == null) { 23 | return l1; 24 | } 25 | 26 | if(l1.val < l2.val) { 27 | l1.next = mergeTwoLists(l1.next, l2); 28 | return l1; 29 | } else { 30 | l2.next = mergeTwoLists(l2.next, l1); 31 | return l2; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Minimum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | */ 6 | 7 | /** 8 | * Definition for binary tree 9 | * public class TreeNode { 10 | * int val; 11 | * TreeNode left; 12 | * TreeNode right; 13 | * TreeNode(int x) { val = x; } 14 | * } 15 | */ 16 | public class Solution { 17 | public int minDepth(TreeNode root) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | if (root == null) { 21 | return 0; 22 | } 23 | return getDepth(root); 24 | } 25 | 26 | public int getDepth(TreeNode node) { 27 | if (node.left == null && node.right == null) { 28 | return 1; 29 | } else if (node.left == null) { 30 | return getDepth(node.right) + 1; 31 | } else if (node.right == null) { 32 | return getDepth(node.left) + 1; 33 | } else { 34 | return Math.min(getDepth(node.left), getDepth(node.right)) + 1; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Minimum Path Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | */ 6 | 7 | public class Solution { 8 | public int minPathSum(int[][] grid) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | 12 | int rowLength = grid.length; 13 | if (rowLength == 0) { 14 | return 0; 15 | } 16 | int colLength = grid[0].length; 17 | int[][] sum = new int[rowLength][colLength]; 18 | sum = grid.clone(); 19 | 20 | //initialize the first row and first column 21 | for (int i = 1; i < colLength; i++) { 22 | sum[0][i] += sum[0][i - 1]; 23 | } 24 | for (int i = 1; i < rowLength; i++) { 25 | sum[i][0] += sum[i - 1][0]; 26 | } 27 | 28 | //build the rest using the base columns and rows 29 | for (int i = 1; i < rowLength; i++) { 30 | for (int j = 1; j < colLength; j++) { 31 | int left = sum[i][j - 1]; 32 | int up = sum[i - 1][j]; 33 | 34 | int preSum = left < up ? left : up; 35 | sum[i][j] += preSum; 36 | } 37 | } 38 | return sum[rowLength - 1][colLength - 1]; 39 | } 40 | } -------------------------------------------------------------------------------- /Multiply Strings.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two numbers represented as strings, return multiplication of the numbers as a string. 3 | 4 | Note: The numbers can be arbitrarily large and are non-negative. 5 | */ 6 | 7 | public class Solution { 8 | public String multiply(String num1, String num2) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | if (num1 == null || num2 == null) return null; 12 | int length1 = num1.length(); 13 | int length2 = num2.length(); 14 | 15 | int[] result = new int[length1 + length2]; 16 | for (int i = 0; i < length1; i++) { 17 | int a = num1.charAt(length1 - i - 1) - '0'; 18 | int carry = 0; 19 | for (int j = 0; j < length2; j++) { 20 | int b = num2.charAt(length2 - j - 1) - '0'; 21 | result[i + j] += a * b + carry; 22 | carry = result[i + j] / 10; 23 | result[i + j] %= 10; 24 | } 25 | result[i + length2] += carry; 26 | } 27 | 28 | StringBuilder s = new StringBuilder(); 29 | for (int i = length1 + length2 - 1; i >= 0; i--) { 30 | if (i != 0 && result[i] == 0 && s.length() == 0) continue; 31 | s.append(result[i]); 32 | } 33 | return s.toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /N queens ii.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | int count; 3 | public int totalNQueens(int n) { 4 | // Note: The Solution object is instantiated only once and is reused by each test case. 5 | count = 0; 6 | helper(0, new int[n]); 7 | return count; 8 | } 9 | 10 | public void helper(int cur, int[] row) { 11 | if (cur == row.length) { 12 | count++; 13 | return; 14 | } 15 | 16 | for (int i = 0; i < row.length; i++) { 17 | boolean ok = true; 18 | row[cur] = i; 19 | for (int j = 0; j < cur; j++) { 20 | if (row[cur] == row[j] || row[cur] - row[j] == cur - j || row[cur] - row[j] == j - cur) { 21 | ok = false; 22 | break; 23 | } 24 | } 25 | if (ok) helper(cur + 1, row); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /N queens.java: -------------------------------------------------------------------------------- 1 | /* 2 | The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. 3 | 4 | Given an integer n, return all distinct solutions to the n-queens puzzle. 5 | 6 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 7 | 8 | For example, 9 | There exist two distinct solutions to the 4-queens puzzle: 10 | 11 | [ 12 | [".Q..", // Solution 1 13 | "...Q", 14 | "Q...", 15 | "..Q."], 16 | 17 | ["..Q.", // Solution 2 18 | "Q...", 19 | "...Q", 20 | ".Q.."] 21 | ] 22 | */ 23 | 24 | public class Solution { 25 | public ArrayList solveNQueens(int n) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | ArrayList res = new ArrayList(); 29 | solveNQueens(0,new int[n],res); 30 | return res; 31 | } 32 | 33 | public void solveNQueens(int cur, int[] row, ArrayList res) { 34 | int n = row.length; 35 | if(cur == n) 36 | res.add(generateSol(row)); 37 | else 38 | for(int i=0;i= 10) { 30 | divide *= 10; 31 | } 32 | 33 | while (x > 9) { 34 | int firstDigit = x / divide; 35 | int lastDigit = x % 10; 36 | 37 | if (firstDigit != lastDigit) { 38 | return false; 39 | } 40 | 41 | x = x % divide / 10; 42 | divide /= 100; 43 | } 44 | 45 | return true; 46 | } 47 | } -------------------------------------------------------------------------------- /Palindrome Partitioning II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return the minimum cuts needed for a palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 8 | */ 9 | 10 | public class Solution { 11 | public int minCut(String s) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | int length = s.length(); 15 | boolean[][] isPal = new boolean[length][length]; 16 | //dp[i] --> how many cuts from s.charAt(i) to the end of s. 17 | int[] dp = new int[length + 1]; 18 | 19 | for (int i = 0; i < length - 1; i++) { 20 | //initial value of dp[i]: each char is palindrome 21 | dp[i] = length - i - 1; 22 | isPal[i][i] = true; 23 | isPal[i][i + 1] = (s.charAt(i) == s.charAt(i + 1)); 24 | } 25 | isPal[length - 1][length - 1] = true; 26 | dp[length - 1] = 0; 27 | dp[length] = -1; 28 | 29 | for (int i = length - 2; i >= 0; i--) { 30 | for (int j = i + 2; j < length; j++) { 31 | isPal[i][j] = isPal[i + 1][j - 1] && (s.charAt(i) == s.charAt(j)); 32 | } 33 | } 34 | 35 | for (int i = length - 2; i >= 0; i--) { 36 | for (int j = i; j < length; j++) { 37 | if (isPal[i][j]) { 38 | dp[i] = Math.min(dp[i], dp[j + 1] + 1); 39 | } 40 | } 41 | } 42 | return dp[0]; 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Palindrome Partitioning.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return all possible palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 8 | 9 | [ 10 | ["aa","b"], 11 | ["a","a","b"] 12 | ] 13 | */ 14 | 15 | public class Solution { 16 | public ArrayList> partition(String s) { 17 | // IMPORTANT: Please reset any member data you declared, as 18 | // the same Solution instance will be reused for each test case. 19 | if (s == null || s.length() == 0) { 20 | return new ArrayList>(); 21 | } 22 | 23 | int length = s.length(); 24 | 25 | boolean[][] isPal = new boolean[length][length]; 26 | 27 | for (int i = 0; i < length; i++) { 28 | isPal[i][i] = true; 29 | } 30 | 31 | for (int i = length - 2; i >= 0; i--) { 32 | if (s.charAt(i) == s.charAt(i + 1)) { 33 | isPal[i][i + 1] = true; 34 | } 35 | for (int j = i + 2; j < length; j++) { 36 | isPal[i][j] = isPal[i + 1][j - 1] && (s.charAt(i) == s.charAt(j)); 37 | } 38 | 39 | } 40 | 41 | return partitionHelper(s, 0, isPal); 42 | } 43 | 44 | //recursively backtrack the palindrome list from startindex to the end 45 | public ArrayList> partitionHelper(String s, int index, boolean[][] isPal) { 46 | 47 | ArrayList> result = new ArrayList>(); 48 | if (index == s.length()) { 49 | result.add(new ArrayList()); 50 | return result; 51 | } 52 | 53 | for (int i = index; i < s.length(); i++) { 54 | if (isPal[index][i]) { 55 | for (ArrayList temp : partitionHelper(s, i + 1, isPal)) { 56 | temp.add(0, s.substring(index, i + 1)); 57 | result.add(temp); 58 | } 59 | } 60 | } 61 | 62 | return result; 63 | 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /Partition List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 3 | 4 | You should preserve the original relative order of the nodes in each of the two partitions. 5 | 6 | For example, 7 | Given 1->4->3->2->5->2 and x = 3, 8 | return 1->2->2->4->3->5. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { 17 | * val = x; 18 | * next = null; 19 | * } 20 | * } 21 | */ 22 | public class Solution { 23 | public ListNode partition(ListNode head, int x) { 24 | // IMPORTANT: Please reset any member data you declared, as 25 | // the same Solution instance will be reused for each test case. 26 | ListNode beforeStart = null; 27 | ListNode beforeEnd = null; 28 | ListNode afterStart = null; 29 | ListNode afterEnd = null; 30 | 31 | if (head == null) return null; 32 | ListNode node = head; 33 | while (node != null) { 34 | ListNode next = node.next; 35 | node.next = null; 36 | if (node.val < x) { 37 | if (beforeStart == null) { 38 | beforeStart = node; 39 | beforeEnd = node; 40 | } else { 41 | beforeEnd.next = node; 42 | beforeEnd = node; 43 | } 44 | } else { 45 | if (afterStart == null) { 46 | afterStart = node; 47 | afterEnd = node; 48 | } else { 49 | afterEnd.next = node; 50 | afterEnd = node; 51 | } 52 | } 53 | node = next; 54 | } 55 | if (beforeEnd == null) { 56 | return afterStart; 57 | } else { 58 | beforeEnd.next = afterStart; 59 | return beforeStart; 60 | } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Pascal's Triangle ii.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList getRow(int rowIndex) { 3 | ArrayList list = new ArrayList(); 4 | if (rowIndex < 0) return list; 5 | list.add(1); 6 | if (rowIndex == 0) return list; 7 | 8 | list.add(1); 9 | for (int i = 2; i <= rowIndex; i++) { 10 | list.add(1, list.get(0) + list.get(1)); 11 | for (int j = 2; j < list.size() - 1; j++) { 12 | list.set(j, list.get(j) + list.get(j + 1)); 13 | } 14 | } 15 | 16 | return list; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given numRows, generate the first numRows of Pascal's triangle. 3 | 4 | For example, given numRows = 5, 5 | Return 6 | 7 | [ 8 | [1], 9 | [1,1], 10 | [1,2,1], 11 | [1,3,3,1], 12 | [1,4,6,4,1] 13 | ] 14 | 15 | */ 16 | 17 | public class Solution { 18 | public ArrayList> generate(int numRows) { 19 | // IMPORTANT: Please reset any member data you declared, as 20 | // the same Solution instance will be reused for each test case. 21 | ArrayList> result = new ArrayList>(); 22 | if (numRows == 0) { 23 | return result; 24 | } 25 | if (numRows == 1) { 26 | ArrayList list = new ArrayList(); 27 | list.add(1); 28 | result.add(list); 29 | return result; 30 | } 31 | ArrayList> parentResult = generate(numRows - 1); 32 | ArrayList parentList = parentResult.get(numRows - 2); 33 | ArrayList curList = new ArrayList(); 34 | curList.add(1); 35 | for (int i = 1; i < numRows - 1; i++) { 36 | curList.add(parentList.get(i - 1) + parentList.get(i)); 37 | } 38 | curList.add(1); 39 | // result = parentResult; 40 | // result.add(curList); 41 | parentResult.add(curList); 42 | return parentResult; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Path Sum II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ / \ 12 | 7 2 5 1 13 | return 14 | [ 15 | [5,4,11,2], 16 | [5,8,4,5] 17 | ] 18 | */ 19 | 20 | /** 21 | * Definition for binary tree 22 | * public class TreeNode { 23 | * int val; 24 | * TreeNode left; 25 | * TreeNode right; 26 | * TreeNode(int x) { val = x; } 27 | * } 28 | */ 29 | public class Solution { 30 | ArrayList> result; 31 | public ArrayList> pathSum(TreeNode root, int sum) { 32 | // IMPORTANT: Please reset any member data you declared, as 33 | // the same Solution instance will be reused for each test case. 34 | result = new ArrayList>(); 35 | if (root == null) { 36 | return result; 37 | } 38 | helper(root, 0, sum, new ArrayList()); 39 | return result; 40 | } 41 | 42 | public void helper(TreeNode root, int curSum, int target, ArrayList list) { 43 | ArrayList curList = new ArrayList(list); 44 | if (root == null) { 45 | return; 46 | } 47 | curList.add(root.val); 48 | if (root.left == null && root.right == null) { 49 | if (curSum + root.val == target) { 50 | result.add(curList); 51 | } 52 | } 53 | 54 | helper(root.left, curSum + root.val, target, curList); 55 | helper(root.right, curSum + root.val, target, curList); 56 | 57 | } 58 | } -------------------------------------------------------------------------------- /Path Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ \ 12 | 7 2 1 13 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 14 | */ 15 | 16 | /** 17 | * Definition for binary tree 18 | * public class TreeNode { 19 | * int val; 20 | * TreeNode left; 21 | * TreeNode right; 22 | * TreeNode(int x) { val = x; } 23 | * } 24 | */ 25 | public class Solution { 26 | public boolean hasPathSum(TreeNode root, int sum) { 27 | // IMPORTANT: Please reset any member data you declared, as 28 | // the same Solution instance will be reused for each test case. 29 | if (root == null) { 30 | return false; 31 | } 32 | return helper(root, 0, sum); 33 | } 34 | 35 | public boolean helper(TreeNode root, int curSum, int target) { 36 | if (root == null) { 37 | return curSum == target; 38 | } 39 | if (root.left == null && root.right == null) { 40 | return helper(root.left, curSum + root.val, target) && helper(root.right, curSum + root.val, target); 41 | } else if (root.left == null) { 42 | return helper(root.right, curSum + root.val, target); 43 | } else if (root.right == null) { 44 | return helper(root.left, curSum + root.val, target); 45 | } else { 46 | return helper(root.left, curSum + root.val, target) || helper(root.right, curSum + root.val, target); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /Permutation Sequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | The set [1,2,3,…,n] contains a total of n! unique permutations. 3 | 4 | By listing and labeling all of the permutations in order, 5 | We get the following sequence (ie, for n = 3): 6 | 7 | "123" 8 | "132" 9 | "213" 10 | "231" 11 | "312" 12 | "321" 13 | Given n and k, return the kth permutation sequence. 14 | 15 | Note: Given n will be between 1 and 9 inclusive. 16 | */ 17 | 18 | public class Solution { 19 | public String getPermutation(int n, int k) { 20 | // IMPORTANT: Please reset any member data you declared, as 21 | // the same Solution instance will be reused for each test case. 22 | ArrayList nums = new ArrayList(); 23 | for (int i = 1; i <= n; i++) { 24 | nums.add(i); 25 | } 26 | 27 | int[] index = new int[n]; 28 | int i = 0; 29 | //IMPORTANT: there are k - 1 permutations before 30 | k = k - 1; 31 | while (k > 0) { 32 | index[i] = k / getFact(n - 1); 33 | k = k % getFact(n - 1); 34 | n--; 35 | i++; 36 | } 37 | 38 | String result = ""; 39 | for (int j = 0; j < index.length; j++) { 40 | result += nums.get(index[j]); 41 | nums.remove(index[j]); 42 | } 43 | return result; 44 | } 45 | 46 | public int getFact(int x) { 47 | int result = 1; 48 | for (int i = x; i > 1; i--) { 49 | result *= i; 50 | } 51 | return result; 52 | } 53 | } -------------------------------------------------------------------------------- /Permutation ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | For example, 5 | [1,1,2] have the following unique permutations: 6 | [1,1,2], [1,2,1], and [2,1,1]. 7 | */ 8 | public class Solution { 9 | public ArrayList> permuteUnique(int[] num) { 10 | // IMPORTANT: Please reset any member data you declared, as 11 | // the same Solution instance will be reused for each test case. 12 | ArrayList> result = new ArrayList>(); 13 | permuteUnique(num, 0, result); 14 | return result; 15 | } 16 | 17 | public void permuteUnique(int[] num, int begin, ArrayList> result) { 18 | if (begin == num.length) { 19 | ArrayList list = new ArrayList(); 20 | for (int h = 0; h < num.length; h++) { 21 | list.add(num[h]); 22 | } 23 | result.add(list); 24 | } 25 | for (int end = begin; end < num.length; end++) { 26 | if (isSwap(num, begin, end)) { 27 | int temp = num[end]; 28 | num[end] = num[begin]; 29 | num[begin] = temp; 30 | 31 | permuteUnique(num, begin + 1, result); 32 | 33 | temp = num[end]; 34 | num[end] = num[begin]; 35 | num[begin] = temp; 36 | } 37 | } 38 | } 39 | 40 | public boolean isSwap(int[] arr, int i, int j) { 41 | for (int k = i; k < j; k++) { 42 | if (arr[k] == arr[j]) { 43 | return false; 44 | } 45 | } 46 | return true; 47 | } 48 | } -------------------------------------------------------------------------------- /Permutations.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of numbers, return all possible permutations. 3 | 4 | For example, 5 | [1,2,3] have the following permutations: 6 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 7 | */ 8 | 9 | public class Solution { 10 | public ArrayList> permute(int[] num) { 11 | // Note: The Solution object is instantiated only once and is reused by each test case. 12 | return helper(num, num.length - 1); 13 | } 14 | 15 | public ArrayList> helper(int[] num, int index) { 16 | ArrayList> s = new ArrayList>(); 17 | if (index == 0) { 18 | ArrayList init = new ArrayList(); 19 | init.add(num[0]); 20 | s.add(init); 21 | return s; 22 | } 23 | 24 | for (ArrayList cur : helper(num, index - 1)) { 25 | for (int i = 0; i <= cur.size(); i++) { 26 | ArrayList temp = new ArrayList(cur); 27 | temp.add(i, num[index]); 28 | s.add(temp); 29 | } 30 | } 31 | return s; 32 | } 33 | } -------------------------------------------------------------------------------- /Plus One.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number represented as an array of digits, plus one to the number. 3 | */ 4 | 5 | public class Solution { 6 | public int[] plusOne(int[] digits) { 7 | // IMPORTANT: Please reset any member data you declared, as 8 | // the same Solution instance will be reused for each test case. 9 | int length = digits.length; 10 | int carry = 0; 11 | digits[length - 1] += 1; 12 | for (int i = length - 1; i >= 0; i--) { 13 | digits[i] += carry; 14 | carry = 0; 15 | if (digits[i] >= 10) { 16 | digits[i] -= 10; 17 | carry = 1; 18 | } 19 | } 20 | if (carry == 1) { 21 | int[] result = new int[length + 1]; 22 | result[0] = 1; 23 | for (int i = 1; i < length + 1; i++) { 24 | result[i] = digits[i - 1]; 25 | } 26 | return result; 27 | } 28 | return digits; 29 | } 30 | } -------------------------------------------------------------------------------- /Populating Next Right Pointers in Each Node II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for problem "Populating Next Right Pointers in Each Node". 3 | 4 | What if the given tree could be any binary tree? Would your previous solution still work? 5 | 6 | Note: 7 | 8 | You may only use constant extra space. 9 | For example, 10 | Given the following binary tree, 11 | 1 12 | / \ 13 | 2 3 14 | / \ \ 15 | 4 5 7 16 | After calling your function, the tree should look like: 17 | 1 -> NULL 18 | / \ 19 | 2 -> 3 -> NULL 20 | / \ \ 21 | 4-> 5 -> 7 -> NULL 22 | */ 23 | 24 | /** 25 | * Definition for binary tree with next pointer. 26 | * public class TreeLinkNode { 27 | * int val; 28 | * TreeLinkNode left, right, next; 29 | * TreeLinkNode(int x) { val = x; } 30 | * } 31 | */ 32 | public class Solution { 33 | public void connect(TreeLinkNode root) { 34 | // IMPORTANT: Please reset any member data you declared, as 35 | // the same Solution instance will be reused for each test case. 36 | while (root != null) { 37 | TreeLinkNode next = null; //first node of next level 38 | TreeLinkNode prev = null; //previous node on the same level 39 | while (root != null) { 40 | if (next == null) next = root.left == null? root.right : root.left; 41 | if (root.left != null) { 42 | if (prev != null) prev.next = root.left; 43 | prev = root.left; 44 | } 45 | if (root.right != null) { 46 | if (prev != null) prev.next = root.right; 47 | prev = root.right; 48 | } 49 | root = root.next; 50 | } 51 | root = next; 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Populating Next Right Pointers in Each Node.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree 3 | 4 | struct TreeLinkNode { 5 | TreeLinkNode *left; 6 | TreeLinkNode *right; 7 | TreeLinkNode *next; 8 | } 9 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 10 | 11 | Initially, all next pointers are set to NULL. 12 | 13 | Note: 14 | 15 | You may only use constant extra space. 16 | You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). 17 | For example, 18 | Given the following perfect binary tree, 19 | 1 20 | / \ 21 | 2 3 22 | / \ / \ 23 | 4 5 6 7 24 | After calling your function, the tree should look like: 25 | 1 -> NULL 26 | / \ 27 | 2 -> 3 -> NULL 28 | / \ / \ 29 | 4->5->6->7 -> NULL 30 | */ 31 | 32 | /** 33 | * Definition for binary tree with next pointer. 34 | * public class TreeLinkNode { 35 | * int val; 36 | * TreeLinkNode left, right, next; 37 | * TreeLinkNode(int x) { val = x; } 38 | * } 39 | */ 40 | public class Solution { 41 | public void connect(TreeLinkNode root) { 42 | // IMPORTANT: Please reset any member data you declared, as 43 | // the same Solution instance will be reused for each test case. 44 | if (root == null) { 45 | return; 46 | } 47 | ArrayList levelList = new ArrayList(); 48 | levelList.add(root); 49 | 50 | while (!levelList.isEmpty()) { 51 | ArrayList nextLevel = new ArrayList(); 52 | for (int i = 0; i < levelList.size(); i++) { 53 | levelList.get(i).next = (i + 1 == levelList.size()) ? null : levelList.get(i + 1); 54 | if (levelList.get(i).left != null) { 55 | nextLevel.add(levelList.get(i).left); 56 | } 57 | if (levelList.get(i).right != null) { 58 | nextLevel.add(levelList.get(i).right); 59 | } 60 | } 61 | levelList = nextLevel; 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /Pow(x, n).java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement pow(x, n). 3 | */ 4 | 5 | public class Solution { 6 | public double pow(double x, int n) { 7 | // IMPORTANT: Please reset any member data you declared, as 8 | // the same Solution instance will be reused for each test case. 9 | if (n == 0) return 1; 10 | if (n == 1) return x; 11 | if (n == -1) return 1/x; 12 | 13 | if (n % 2 == 0) { 14 | double temp = pow(x, n/2); 15 | return temp * temp; 16 | } else { 17 | double temp = pow(x, (n - 1)/2); 18 | return temp * temp * x; 19 | } 20 | } 21 | } 22 | 23 | //exceeds time limit 24 | public class Solution { 25 | public double pow(double x, int n) { 26 | // IMPORTANT: Please reset any member data you declared, as 27 | // the same Solution instance will be reused for each test case. 28 | boolean neg = false; 29 | if (n == 0) return 1; 30 | if (n < 0) neg = true; 31 | 32 | n = Math.abs(n); 33 | double result = 1; 34 | int i = 1, k = 0; 35 | while (k < n) { 36 | double temp = x; 37 | for (i = 1; i * 2 <= n - k; i = i * 2) { 38 | temp *= temp; 39 | } 40 | k += i; 41 | result *= temp; 42 | } 43 | 44 | if (neg) return 1.0/result; 45 | else return result; 46 | } 47 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Algorithm-Practice 2 | ================== 3 | 4 | For practicing data structures and algorithms. 5 | 6 | Language: Java. 7 | -------------------------------------------------------------------------------- /Recover Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | /* 11 | Straight forward approach: 12 | Inorder traverse the tree, put the nodes in a treenode list and the values in an integer list. 13 | Sort the value list and update the treenode list's values one by one. 14 | */ 15 | /* 16 | Inorder traverse, keep the previous tree node, 17 | Find first misplaced node by 18 | if ( current.val < prev.val ) 19 | Node first = prev; 20 | 21 | Find second by 22 | if ( current.val < prev.val ) 23 | Node second = current; 24 | 25 | After traversal, swap the values of first and second node. Only need two pointers, prev and current node. O(1) space. 26 | */ 27 | public class Solution { 28 | ArrayList track; 29 | TreeNode previous; 30 | public void recoverTree(TreeNode root) { 31 | // IMPORTANT: Please reset any member data you declared, as 32 | // the same Solution instance will be reused for each test case. 33 | track = new ArrayList(); 34 | previous = null; 35 | inorderTraverse(root); 36 | 37 | int size = track.size(); 38 | int temp = track.get(0).val; 39 | track.get(0).val = track.get(size - 1).val; 40 | track.get(size - 1).val = temp; 41 | } 42 | 43 | public void inorderTraverse(TreeNode root) { 44 | if (root == null) { 45 | return; 46 | } 47 | inorderTraverse(root.left); 48 | if (previous != null && previous.val > root.val) { 49 | if (!track.contains(previous)) { 50 | track.add(previous); 51 | } 52 | if (!track.contains(root)) { 53 | track.add(root); 54 | } 55 | } 56 | previous = root; 57 | inorderTraverse(root.right); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Regular Expression Matching.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement regular expression matching with support for '.' and '*'. 3 | 4 | '.' Matches any single character. 5 | '*' Matches zero or more of the preceding element. 6 | 7 | The matching should cover the entire input string (not partial). 8 | 9 | The function prototype should be: 10 | bool isMatch(const char *s, const char *p) 11 | 12 | Some examples: 13 | isMatch("aa","a") → false 14 | isMatch("aa","aa") → true 15 | isMatch("aaa","aa") → false 16 | isMatch("aa", "a*") → true 17 | isMatch("aa", ".*") → true 18 | isMatch("ab", ".*") → true 19 | isMatch("aab", "c*a*b") → true 20 | */ 21 | 22 | public class Solution { 23 | public boolean isMatch(String s, String p) { 24 | // IMPORTANT: Please reset any member data you declared, as 25 | // the same Solution instance will be reused for each test case. 26 | if (s == null) return p == null; 27 | return helper(s, p, 0, 0); 28 | } 29 | 30 | public boolean helper(String s, String p, int i, int j) { 31 | if (j == p.length()) return i == s.length(); 32 | 33 | if (j == p.length() - 1 || p.charAt(j + 1) != '*') { 34 | if (i == s.length()) return false; 35 | return (p.charAt(j) == '.' || s.charAt(i) == p.charAt(j)) && helper(s, p, ++i, ++j); 36 | } 37 | 38 | while (i < s.length() && (p.charAt(j) == '.' || p.charAt(j) == s.charAt(i))) { 39 | if (helper(s, p, i++, j + 2)) return true; 40 | } 41 | return helper(s, p, i, j + 2); 42 | } 43 | } -------------------------------------------------------------------------------- /Remove Duplicates From Sorted Array ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for "Remove Duplicates": 3 | What if duplicates are allowed at most twice? 4 | 5 | For example, 6 | Given sorted array A = [1,1,1,2,2,3], 7 | 8 | Your function should return length = 5, and A is now [1,1,2,2,3]. 9 | */ 10 | 11 | public class Solution { 12 | public int removeDuplicates(int[] A) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | if (A.length == 0) return 0; 16 | if (A.length == 1) return 1; 17 | int pre = Integer.MAX_VALUE; 18 | int writeSeq = 1; 19 | for (int readSeq = 1; readSeq < A.length; readSeq++) { 20 | if (A[readSeq] != A[readSeq - 1]) { 21 | A[writeSeq++] = A[readSeq]; 22 | } else { 23 | if (pre != A[readSeq]) { 24 | pre = A[readSeq]; 25 | A[writeSeq++] = A[readSeq]; 26 | } 27 | } 28 | } 29 | return writeSeq; 30 | } 31 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this in place with constant memory. 5 | 6 | For example, 7 | Given input array A = [1,1,2], 8 | 9 | Your function should return length = 2, and A is now [1,2]. 10 | */ 11 | 12 | public class Solution { 13 | public int removeDuplicates(int[] A) { 14 | // Note: The Solution object is instantiated only once and is reused by each test case. 15 | 16 | if(A.length == 0) 17 | return 0; 18 | else if(A.length == 1) 19 | return 1; 20 | else { 21 | int writeSeq = 0; 22 | for(int readSeq = 1; readSeq < A.length; readSeq++) { 23 | if(A[readSeq - 1] != A[readSeq]) { 24 | A[++writeSeq] = A[readSeq]; 25 | } 26 | } 27 | return writeSeq + 1; 28 | } 29 | 30 | } 31 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | 4 | For example, 5 | Given 1->2->3->3->4->4->5, return 1->2->5. 6 | Given 1->1->1->2->3, return 2->3. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | public class Solution { 21 | public ListNode deleteDuplicates(ListNode head) { 22 | // IMPORTANT: Please reset any member data you declared, as 23 | // the same Solution instance will be reused for each test case. 24 | ListNode node = head; 25 | HashSet duplicates = new HashSet(); 26 | 27 | while (node != null && node.next != null) { 28 | if (node.val == node.next.val) { 29 | node.next = node.next.next; 30 | duplicates.add(node); 31 | } else { 32 | node = node.next; 33 | } 34 | } 35 | 36 | node = head; 37 | 38 | while (node != null) { 39 | if (duplicates.contains(node.next)) { 40 | duplicates.remove(node.next); 41 | node.next = node.next.next; 42 | } else { 43 | node = node.next; 44 | } 45 | } 46 | if (duplicates.contains(head)) { 47 | head = head.next; 48 | } 49 | return head; 50 | } 51 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | 4 | For example, 5 | Given 1->1->2, return 1->2. 6 | Given 1->1->2->3->3, return 1->2->3. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | public class Solution { 21 | public ListNode deleteDuplicates(ListNode head) { 22 | // IMPORTANT: Please reset any member data you declared, as 23 | // the same Solution instance will be reused for each test case. 24 | ListNode node = head; 25 | while (node != null && node.next != null) { 26 | if (node.val == node.next.val) { 27 | node.next = node.next.next; 28 | } else { 29 | node = node.next; 30 | } 31 | } 32 | 33 | return head; 34 | } 35 | } -------------------------------------------------------------------------------- /Remove Element.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array and a value, remove all instances of that value in place and return the new length. 3 | 4 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | */ 6 | 7 | public class Solution { 8 | public int removeElement(int[] A, int elem) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | if (A.length == 0) { 12 | return 0; 13 | } 14 | int readSeq; 15 | int writeSeq = 0; 16 | for (readSeq = 0; readSeq < A.length; readSeq++) { 17 | if (A[readSeq] != elem) { 18 | A[writeSeq] = A[readSeq]; 19 | writeSeq++; 20 | } 21 | } 22 | return writeSeq; 23 | } 24 | } -------------------------------------------------------------------------------- /Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, remove the nth node from the end of list and return its head. 3 | 4 | For example, 5 | 6 | Given linked list: 1->2->3->4->5, and n = 2. 7 | 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | Note: 10 | Given n will always be valid. 11 | Try to do this in one pass. 12 | */ 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * public class ListNode { 17 | * int val; 18 | * ListNode next; 19 | * ListNode(int x) { 20 | * val = x; 21 | * next = null; 22 | * } 23 | * } 24 | */ 25 | public class Solution { 26 | public ListNode removeNthFromEnd(ListNode head, int n) { 27 | // IMPORTANT: Please reset any member data you declared, as 28 | // the same Solution instance will be reused for each test case. 29 | if (head == null) return null; 30 | 31 | ListNode p1 = head; 32 | ListNode p2 = head; 33 | ListNode pre = head; 34 | for (int i = 0; i < n; i++) { 35 | p1 = p1.next; 36 | } 37 | while (p1 != null) { 38 | p1 = p1.next; 39 | pre = p2; 40 | p2 = p2.next; 41 | } 42 | if (p2 == head) return head.next; 43 | else pre.next = p2.next; 44 | 45 | return head; 46 | } 47 | } -------------------------------------------------------------------------------- /Restore IP Address.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 3 | 4 | For example: 5 | Given "25525511135", 6 | 7 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 8 | */ 9 | 10 | public class Solution { 11 | public ArrayList restoreIpAddresses(String s) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | ArrayList result = new ArrayList(); 15 | if (s == null || s.equals("")) return result; 16 | helper(s, 0, 0, new StringBuilder(), result); 17 | return result; 18 | } 19 | public void helper(String s, int index, int k, StringBuilder sb, ArrayList result) { 20 | if (index == s.length() && k == 4) { 21 | result.add(sb.toString()); 22 | return; 23 | } 24 | 25 | if (s.length() - index > (4 - k) * 3) return; 26 | if (s.length() - index < 4 - k) return; 27 | 28 | int num = 0; 29 | for (int i = index; i < index + 3 && i < s.length(); i++) { 30 | num = num * 10 + s.charAt(i) - '0'; 31 | if (num <= 255) { 32 | StringBuilder cur = new StringBuilder(sb); 33 | if (cur.length() == 0) cur.append(num); 34 | else { 35 | cur.append("."); 36 | cur.append(num); 37 | } 38 | 39 | helper(s, i + 1, k + 1, cur, result); 40 | } 41 | if (num == 0) break; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Reverse Integer.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse digits of an integer. 3 | 4 | Example1: x = 123, return 321 5 | Example2: x = -123, return -321 6 | */ 7 | 8 | public class Solution { 9 | public int reverse(int x) { 10 | // Note: The Solution object is instantiated only once and is reused by each test case. 11 | boolean neg = false; 12 | if(x < 0) { 13 | neg = true; 14 | } 15 | 16 | String[] numbers = Integer.toString(Math.abs(x)).split(""); 17 | 18 | StringBuffer bf = new StringBuffer(); 19 | for (int i = numbers.length - 1; i >= 0 ; i--) { 20 | bf.append(numbers[i]); 21 | } 22 | 23 | String temp = bf.toString(); 24 | int result = Integer.parseInt(temp); 25 | 26 | if(result >= 1073741824) 27 | return -1; 28 | else { 29 | return neg? (0 - result) : result; 30 | } 31 | } 32 | 33 | public int reverse2(int x) { 34 | int result = 0 35 | while (x != 0) { 36 | result = result * 10 + x % 10; 37 | x /= 10; 38 | } 39 | 40 | return result; 41 | } 42 | } -------------------------------------------------------------------------------- /Reverse Linked List ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 6 | 7 | return 1->4->3->2->5->NULL. 8 | 9 | Note: 10 | Given m, n satisfy the following condition: 11 | 1 ≤ m ≤ n ≤ length of list. 12 | */ 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * public class ListNode { 17 | * int val; 18 | * ListNode next; 19 | * ListNode(int x) { 20 | * val = x; 21 | * next = null; 22 | * } 23 | * } 24 | */ 25 | public class Solution { 26 | public ListNode reverseBetween(ListNode head, int m, int n) { 27 | // IMPORTANT: Please reset any member data you declared, as 28 | // the same Solution instance will be reused for each test case. 29 | ListNode beforeTail, afterHead; 30 | //initialize beforeTail 31 | if (m == 1) beforeTail = null; 32 | else { 33 | beforeTail = head; 34 | while (m > 2) { 35 | beforeTail = beforeTail.next; 36 | m--; 37 | } 38 | } 39 | //initialize afterHead 40 | afterHead = head; 41 | while (n > 0) { 42 | afterHead = afterHead.next; 43 | n--; 44 | } 45 | 46 | ListNode node = beforeTail == null? head : beforeTail.next; 47 | ListNode tail = afterHead; 48 | while (node != afterHead) { 49 | ListNode next = node.next; 50 | node.next = tail; 51 | tail = node; 52 | node = next; 53 | } 54 | if (beforeTail == null) return tail; 55 | else { 56 | beforeTail.next = tail; 57 | return head; 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | //interative 2 | public ListNode reverseLinkedList(ListNode head) { 3 | if (head == null) return null; 4 | ListNode pre = null; 5 | ListNode cur = head; 6 | while (cur != null) { 7 | ListNode next = cur.next; 8 | cur.next = pre; 9 | pre = cur; 10 | cur = next; 11 | } 12 | head = prev; 13 | return head; 14 | } 15 | 16 | //recursive 17 | public ListNode reverseLinkedList(ListNode head) { 18 | if (head == null) return null; 19 | if (head.next == null) return head; 20 | 21 | ListNode newHead = reverseLinkedList(head.next); 22 | head.next.next = head; 23 | head.next = null; 24 | 25 | return newHead; 26 | } -------------------------------------------------------------------------------- /Reverse Nodes in k-Group.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 3 | If the number of nodes is not a multiple of k then le-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nodes itself may be changed. 4 | Only constant memory is allowed. 5 | For example, Given this linked list: 1->2->3->4->5 6 | For k = 2, you should return: 2->1->4->3->5 7 | For k = 3, you should return: 3->2->1->4->5 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * public class ListNode { 13 | * int val; 14 | * ListNode next; 15 | * ListNode(int x) { 16 | * val = x; 17 | * next = null; 18 | * } 19 | * } 20 | */ 21 | public class Solution { 22 | public ListNode reverseKGroup(ListNode head, int k) { 23 | // IMPORTANT: Please reset any member data you declared, as 24 | // the same Solution instance will be reused for each test case. 25 | if (head == null) return null; 26 | ListNode newHead = head; 27 | for (int i = 0; i < k; i++) { 28 | if (newHead == null) return head; 29 | newHead = newHead.next; 30 | } 31 | 32 | ListNode newGroupHead = reverseKGroup(newHead, k); 33 | ListNode pre = newGroupHead; ListNode cur = head; 34 | for (int i = 0; i < k; i++) { 35 | ListNode next = cur.next; 36 | cur.next = pre; 37 | pre = cur; 38 | cur = next; 39 | } 40 | return pre; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Rotate Image.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | Follow up: 7 | Could you do this in-place? 8 | */ 9 | 10 | public class Solution { 11 | public void rotate(int[][] matrix) { 12 | // Note: The Solution object is instantiated only once and is reused by each test case. 13 | 14 | int length = matrix.length; 15 | if (length == 0) { 16 | return; 17 | } 18 | 19 | for (int layer = 0; layer < length/2; layer++) { 20 | 21 | for (int offset = layer; offset < length - layer - 1; offset++) { 22 | //Store the top 23 | int temp = matrix[layer][offset]; 24 | 25 | //left -> top 26 | matrix[layer][offset] = matrix[length - offset - 1][layer]; 27 | 28 | //down -> left 29 | matrix[length - offset - 1][layer] = matrix[length - layer - 1][length - 1 - offset]; 30 | 31 | //right -> down 32 | matrix[length - layer - 1][length - 1 - offset] = matrix[offset][length - layer - 1]; 33 | 34 | //top -> right 35 | matrix[offset][length - layer - 1] = temp; 36 | 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Rotate List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list, rotate the list to the right by k places, where k is non-negative. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL and k = 2, 6 | return 4->5->1->2->3->NULL. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | public class Solution { 21 | public ListNode rotateRight(ListNode head, int n) { 22 | // Note: The Solution object is instantiated only once and is reused by each test case. 23 | 24 | if (head == null) { 25 | return head; 26 | } 27 | 28 | ListNode node1 = head; 29 | ListNode node2 = head; 30 | int length = 0; 31 | while (node1 != null) { 32 | node1 = node1.next; 33 | length++; 34 | } 35 | n = n % length; 36 | 37 | if (n == 0 || length == 1) { 38 | return head; 39 | } 40 | node1 = head; 41 | while (n > 0 && node1 != null) { 42 | node1 = node1.next; 43 | n--; 44 | } 45 | 46 | while (node1 != null && node1.next != null) { 47 | node1 = node1.next; 48 | node2 = node2.next; 49 | } 50 | 51 | ListNode newHead = node2.next; 52 | node2.next = null; 53 | node1.next = head; 54 | return newHead; 55 | } 56 | } -------------------------------------------------------------------------------- /Same Tree.java: -------------------------------------------------------------------------------- 1 | /*Given two binary trees, write a function to check if they are equal or not.*/ 2 | 3 | /** 4 | * Definition for binary tree 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean isSameTree(TreeNode p, TreeNode q) { 14 | // Note: The Solution object is instantiated only once and is reused by each test case. 15 | if(p == null && q == null) 16 | return true; 17 | 18 | if(p == null || q == null) 19 | return false; 20 | 21 | if(p.val != q.val) { 22 | return false; 23 | } 24 | else { 25 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 26 | } 27 | 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Search Insert Position.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Here are few examples. 7 | [1,3,5,6], 5 → 2 8 | [1,3,5,6], 2 → 1 9 | [1,3,5,6], 7 → 4 10 | [1,3,5,6], 0 → 0 11 | */ 12 | 13 | public class Solution { 14 | public int searchInsert(int[] A, int target) { 15 | // IMPORTANT: Please reset any member data you declared, as 16 | // the same Solution instance will be reused for each test case. 17 | int low = 0; 18 | int high = A.length - 1; 19 | 20 | while (low <= high) { 21 | int mid = (low + high)/2; 22 | int cur = A[mid]; 23 | if (cur == target) { 24 | return mid; 25 | } else if (cur < target) { 26 | low = mid + 1; 27 | } else { 28 | high = mid - 1; 29 | } 30 | } 31 | 32 | return low; 33 | } 34 | } -------------------------------------------------------------------------------- /Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | For example, 7 | 8 | Consider the following matrix: 9 | 10 | [ 11 | [1, 3, 5, 7], 12 | [10, 11, 16, 20], 13 | [23, 30, 34, 50] 14 | ] 15 | Given target = 3, return true. 16 | */ 17 | 18 | public class Solution { 19 | public boolean searchMatrix(int[][] matrix, int target) { 20 | // Note: The Solution object is instantiated only once and is reused by each test case. 21 | int rowLength = matrix.length; 22 | int columnLength = matrix[0].length; 23 | 24 | boolean found = false; 25 | 26 | int low = 0, high = rowLength * columnLength; 27 | 28 | 29 | while(low <= high) { 30 | int cur = (low + high)/2; 31 | int row = cur / columnLength; 32 | int column = cur % columnLength; 33 | if(row > rowLength - 1 || column > columnLength - 1) { 34 | break; 35 | } 36 | if(matrix[row][column] == target) { 37 | found = true; 38 | break; 39 | } 40 | else if(matrix[row][column] > target) { 41 | high = cur - 1; 42 | } 43 | else { 44 | low = cur + 1; 45 | } 46 | } 47 | 48 | return found; 49 | } 50 | } -------------------------------------------------------------------------------- /Search for A Range.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array of integers, find the starting and ending position of a given target value. 3 | 4 | Your algorithm's runtime complexity must be in the order of O(log n). 5 | 6 | If the target is not found in the array, return [-1, -1]. 7 | 8 | For example, 9 | Given [5, 7, 7, 8, 8, 10] and target value 8, 10 | return [3, 4]. 11 | */ 12 | 13 | public class Solution { 14 | public int[] searchRange(int[] A, int target) { 15 | // IMPORTANT: Please reset any member data you declared, as 16 | // the same Solution instance will be reused for each test case. 17 | int[] result = new int[2]; 18 | result[0] = findStartIndex(A, 0, A.length - 1, target); 19 | result[1] = findEndIndex(A, 0, A.length - 1, target); 20 | return result; 21 | } 22 | 23 | public int findStartIndex(int[] A, int start, int end, int target) { 24 | if (start > end || start < 0 || end > A.length - 1) return -1; 25 | if (A[end] < target) { 26 | if (end == A.length - 1 || A[end + 1] != target) return -1; 27 | else return end + 1; 28 | } 29 | 30 | int mid = (start + end) / 2; 31 | if (A[mid] < target) { 32 | return findStartIndex(A, mid + 1, end, target); 33 | } else { 34 | if (A[mid] == target && mid == start) return mid; 35 | return findStartIndex(A, start, mid - 1, target); 36 | } 37 | } 38 | 39 | public int findEndIndex(int[] A, int start, int end, int target) { 40 | if (start > end || start < 0 || end > A.length - 1) return -1; 41 | if (A[start] > target) { 42 | if (start == 0 || A[start - 1] != target) return -1; 43 | else return start - 1; 44 | } 45 | 46 | int mid = (start + end) / 2; 47 | if (A[mid] <= target) { 48 | if (A[mid] == target && mid == end) return mid; 49 | return findEndIndex(A, mid + 1, end, target); 50 | } else { 51 | return findEndIndex(A, start, mid - 1, target); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Search in Rotated Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int search(int[] A, int target) { 3 | // IMPORTANT: Please reset any member data you declared, as 4 | // the same Solution instance will be reused for each test case. 5 | return searchHelper(A, 0, A.length - 1, target); 6 | } 7 | 8 | public int searchHelper(int[] A, int start, int end, int target) { 9 | int mid = (start + end) / 2; 10 | if (A[mid] == target) { 11 | return mid; 12 | } 13 | if (start > end) { 14 | return -1; 15 | } 16 | 17 | //compare target with A[start],A[end], use <=, >= 18 | 19 | //left part is sorted 20 | if (A[mid] >= A[start]) { 21 | if (A[start] <= target && A[mid] > target) { 22 | return searchHelper(A, start, mid - 1, target); 23 | } else { 24 | return searchHelper(A, mid + 1, end, target); 25 | } 26 | } 27 | //right part is sorted 28 | if (A[mid] <= A[end]) { 29 | if (A[mid] < target && A[end] >= target) { 30 | return searchHelper(A, mid + 1, end, target); 31 | } else { 32 | return searchHelper(A, start, mid - 1, target); 33 | } 34 | } 35 | return -1; 36 | } 37 | } -------------------------------------------------------------------------------- /Simplify Path.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an absolute path for a file (Unix-style), simplify it. 3 | 4 | For example, 5 | path = "/home/", => "/home" 6 | path = "/a/./b/../../c/", => "/c" 7 | click to show corner cases. 8 | 9 | Corner Cases: 10 | Did you consider the case where path = "/../"? 11 | In this case, you should return "/". 12 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 13 | In this case, you should ignore redundant slashes and return "/home/foo". 14 | */ 15 | 16 | public class Solution { 17 | public String simplifyPath(String path) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | StringBuilder s = new StringBuilder(path); 21 | 22 | String cleanPath = s.toString(); 23 | String[] paths = cleanPath.split("/"); 24 | 25 | ArrayList result = new ArrayList(); 26 | for (int i = 0; i < paths.length; i++) { 27 | if (paths[i].equals(".") || paths[i].length() == 0) { 28 | 29 | } else if (paths[i].equals("..")) { 30 | //remove previous path location 31 | if (result.isEmpty()) { 32 | continue; 33 | } 34 | //System.out.println("REMOVE: " + result.get(result.size() - 1)); 35 | result.remove(result.size() - 1); 36 | 37 | } else { 38 | //System.out.println("ADD: " + paths[i]); 39 | result.add(paths[i]); 40 | } 41 | } 42 | 43 | if (result.isEmpty()) { 44 | return "/"; 45 | } 46 | 47 | StringBuilder finalPath = new StringBuilder(); 48 | for (int i = 0; i < result.size(); i++) { 49 | if (result.get(i).length() != 0) { 50 | finalPath.append("/"); 51 | finalPath.append(result.get(i)); 52 | } 53 | } 54 | if (finalPath.length() > 0) { 55 | return finalPath.toString(); 56 | } else { 57 | return "/"; 58 | } 59 | 60 | 61 | 62 | } 63 | } -------------------------------------------------------------------------------- /Single Number II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears three times except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | 8 | public class Solution { 9 | public int singleNumber(int[] A) { 10 | // Note: The Solution object is instantiated only once and is reused by each test case. 11 | int ones = 0, twos = 0, threes = 0; 12 | for(int i = 0; i < A.length; i++) { 13 | 14 | twos |= (ones & A[i]); 15 | ones ^= A[i]; 16 | threes = ~(twos & ones); 17 | 18 | twos = twos & threes; 19 | ones = ones & threes; 20 | } 21 | 22 | return ones; 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Single Number III.java: -------------------------------------------------------------------------------- 1 | /* 2 | case of four 3 | 4 | Given an array of integers, every element appears four times except for one. Find that single one. 5 | */ 6 | import java.util.*; 7 | public class Solution { 8 | 9 | 10 | public int singleNumber(int A[]) { 11 | // Note: The Solution object is instantiated only once and is reused by each test case. 12 | int ones=0, twos=0, threes=0, fours=0; 13 | for(int i=0; i> a){ 36 | int len=a.size(); 37 | for (int i=0; i 0 && m[row][col - 1] == 0) { 44 | m[row][col--] = number++; 45 | } 46 | 47 | //up 48 | while (row > 0 && m[row - 1][col] == 0) { 49 | m[row--][col] = number++; 50 | } 51 | } 52 | m[row][col] = number; 53 | return m; 54 | 55 | } 56 | } -------------------------------------------------------------------------------- /Spiral Matrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 3 | 4 | For example, 5 | Given the following matrix: 6 | 7 | [ 8 | [ 1, 2, 3 ], 9 | [ 4, 5, 6 ], 10 | [ 7, 8, 9 ] 11 | ] 12 | You should return [1,2,3,6,9,8,7,4,5]. 13 | */ 14 | 15 | public class Solution { 16 | public ArrayList spiralOrder(int[][] matrix) { 17 | // Note: The Solution object is instantiated only once and is reused by each test case. 18 | int rowLength = matrix.length; 19 | ArrayList results = new ArrayList(); 20 | if (rowLength == 0) { 21 | return results; 22 | } 23 | int columnLength = matrix[0].length; 24 | 25 | spiralOrderHelper(0, rowLength, columnLength, matrix, results); 26 | return results; 27 | } 28 | 29 | public void spiralOrderHelper(int layer, int row, int col, int[][] matrix, ArrayList res) { 30 | if (row == 0 || col == 0) { 31 | return; 32 | } else if (row == 1) { 33 | for (int i = 0; i < col; i++) { 34 | res.add(matrix[layer][i + layer]); 35 | } 36 | return; 37 | } else if (col == 1) { 38 | for (int i = 0; i < row; i++) { 39 | res.add(matrix[i + layer][layer]); 40 | } 41 | return; 42 | } else { 43 | //add top to result 44 | for (int i = 0; i < col - 1; i++) { 45 | res.add(matrix[layer][i + layer]); 46 | } 47 | //add right to result 48 | for (int i = 0; i < row - 1; i++) { 49 | res.add(matrix[i + layer][col + layer - 1]); 50 | } 51 | //add botton to result 52 | for (int i = col - 1; i > 0; i--) { 53 | res.add(matrix[row + layer - 1][i + layer]); 54 | } 55 | //add left to result 56 | for (int i = row - 1; i > 0; i--) { 57 | res.add(matrix[i + layer][layer]); 58 | } 59 | 60 | spiralOrderHelper(layer + 1, row - 2, col - 2, matrix, res); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /Sqrt.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | */ 6 | 7 | public class Solution { 8 | public int sqrt(int x) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | if (x <= 1) { 12 | return x; 13 | } 14 | int start = 0; 15 | int end = x; 16 | int mid; 17 | while (end >= start) { 18 | mid = (start + end) / 2; 19 | int div = x / mid; 20 | if (div < mid) { 21 | end = mid - 1; 22 | } else if (div == mid) { 23 | return mid; 24 | } else { 25 | start = mid + 1; 26 | } 27 | 28 | } 29 | return (start + end) / 2; 30 | } 31 | } -------------------------------------------------------------------------------- /String to Integer atoi.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement atoi to convert a string to an integer. 3 | 4 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 5 | 6 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 7 | 8 | spoilers alert... click to show requirements for atoi. 9 | 10 | Requirements for atoi: 11 | The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. 12 | 13 | The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. 14 | 15 | If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. 16 | 17 | If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 18 | */ 19 | 20 | public class Solution { 21 | public int atoi(String str) { 22 | // IMPORTANT: Please reset any member data you declared, as 23 | // the same Solution instance will be reused for each test case. 24 | if (str == null || str.equals("")) return 0; 25 | 26 | int num = 0; 27 | int sign = 1; 28 | int length = str.length(); 29 | int i = 0; 30 | 31 | while (str.charAt(i) == ' ' && i < length) i++; 32 | 33 | if (str.charAt(i) == '+') i++; 34 | if (str.charAt(i) == '-') { 35 | sign = -1; 36 | i++; 37 | } 38 | for (; i < length; i++) { 39 | if (str.charAt(i) < '0' || str.charAt(i) > '9') break; 40 | if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > Integer.MAX_VALUE % 10)) return sign == -1? Integer.MIN_VALUE : Integer.MAX_VALUE; 41 | num = num * 10 + str.charAt(i) - '0'; 42 | } 43 | return num * sign; 44 | } 45 | } -------------------------------------------------------------------------------- /SubSet ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If S = [1,2,2], a solution is: 9 | 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | */ 19 | public class Solution { 20 | public ArrayList> subsetsWithDup(int[] num) { 21 | // IMPORTANT: Please reset any member data you declared, as 22 | // the same Solution instance will be reused for each test case. 23 | Arrays.sort(num); 24 | ArrayList> results = new ArrayList>(); 25 | results.add(new ArrayList()); 26 | int index = 0; 27 | while (index < num.length) { 28 | int cur = num[index]; 29 | //copy to current to get rid of concurrentModification exception 30 | ArrayList> current = new ArrayList>(results); 31 | for(ArrayList arr : current) { 32 | ArrayList newList = new ArrayList(arr); 33 | newList.add(cur); 34 | if (!results.contains(newList)) { 35 | results.add(newList); 36 | } 37 | 38 | } 39 | index ++; 40 | } 41 | return results; 42 | } 43 | } -------------------------------------------------------------------------------- /Subsets.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of distinct integers, S, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If S = [1,2,3], a solution is: 9 | 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | */ 21 | 22 | public class Solution { 23 | public ArrayList> subsets(int[] S) { 24 | // IMPORTANT: Please reset any member data you declared, as 25 | // the same Solution instance will be reused for each test case. 26 | Arrays.sort(S); 27 | ArrayList> results = new ArrayList>(); 28 | results.add(new ArrayList()); 29 | int index = 0; 30 | while (index < S.length) { 31 | int cur = S[index]; 32 | //copy to current to get rid of concurrentModification exception 33 | ArrayList> current = new ArrayList>(results); 34 | for(ArrayList arr : current) { 35 | ArrayList newList = new ArrayList(arr); 36 | newList.add(cur); 37 | results.add(newList); 38 | } 39 | index ++; 40 | } 41 | return results; 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /Substring with Concatenantion of All Words.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. 3 | 4 | For example, given: 5 | S: "barfoothefoobarman" 6 | L: ["foo", "bar"] 7 | 8 | You should return the indices: [0,9]. 9 | (order does not matter). 10 | */ 11 | 12 | public class Solution { 13 | public ArrayList findSubstring(String S, String[] L) { 14 | // Note: The Solution object is instantiated only once and is reused by each test case. 15 | HashMap mapL = new HashMap(); 16 | 17 | int singleWordSize = L[0].length(); 18 | int LSize = L.length; 19 | 20 | int concatLength = LSize * singleWordSize; 21 | 22 | ArrayList result = new ArrayList(); 23 | 24 | for(String s : L) { 25 | mapL.put(s, mapL.get(s) == null? 1 : (mapL.get(s) + 1)); 26 | } 27 | 28 | for(int i = 0; i <= S.length() - concatLength; i++) { 29 | String s = S.substring(i, i + concatLength); 30 | HashMap temp = new HashMap(mapL); 31 | 32 | for(int j = 0; j < concatLength; j += singleWordSize) { 33 | String cur = s.substring(j, j + singleWordSize); 34 | if(temp.containsKey(cur)) { 35 | if(temp.get(cur) == 1) { 36 | temp.remove(cur); 37 | } 38 | else{ 39 | temp.put(cur, temp.get(cur) - 1); 40 | } 41 | 42 | } 43 | else { 44 | break; 45 | } 46 | 47 | } 48 | if(temp.isEmpty()) { 49 | result.add(i); 50 | } 51 | 52 | } 53 | return result; 54 | } 55 | } -------------------------------------------------------------------------------- /Sudoku Solver.java: -------------------------------------------------------------------------------- 1 | /* 2 | http://oj.leetcode.com/problems/sudoku-solver/ 3 | Write a program to solve a Sudoku puzzle by filling the empty cells. 4 | 5 | Empty cells are indicated by the character '.'. 6 | 7 | You may assume that there will be only one unique solution. 8 | 9 | 10 | A sudoku puzzle... 11 | 12 | 13 | ...and its solution numbers marked in red. 14 | */ 15 | 16 | public class Solution { 17 | public void solveSudoku(char[][] board) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | solveSudokuHelper(board); 21 | } 22 | 23 | public boolean solveSudokuHelper(char[][] board) { 24 | for (int i = 0; i < 9; i++) { 25 | for (int j = 0; j < 9; j++) { 26 | if (board[i][j] == '.') { 27 | for (int k = 0; k < 9; k++) { 28 | board[i][j] = (char) ('1' + k); 29 | if (isValid(board, i, j) && solveSudokuHelper(board)) return true; 30 | board[i][j] = '.'; 31 | } 32 | return false; 33 | } 34 | } 35 | } 36 | return true; 37 | } 38 | 39 | public boolean isValid(char[][] board, int row, int col) { 40 | char c = board[row][col]; 41 | 42 | //check row 43 | for (int j = 0; j < 9; j++) { 44 | if (j == col) continue; 45 | if (board[row][j] == c) return false; 46 | } 47 | 48 | //check column 49 | for (int i = 0; i < 9; i++) { 50 | if (i == row) continue; 51 | if (board[i][col] == c) return false; 52 | } 53 | 54 | //check square 55 | int baseRow = row / 3; 56 | int baseCol = col / 3; 57 | for (int i = baseRow * 3; i < baseRow * 3 + 3; i++) { 58 | for (int j = baseCol * 3; j < baseCol * 3 + 3; j++) { 59 | if (i == row && j == col) continue; 60 | if (board[i][j] == c) return false; 61 | } 62 | } 63 | return true; 64 | } 65 | } -------------------------------------------------------------------------------- /Sum Root to Leaf Numbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 | 4 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 5 | 6 | Find the total sum of all root-to-leaf numbers. 7 | 8 | For example, 9 | 10 | 1 11 | / \ 12 | 2 3 13 | The root-to-leaf path 1->2 represents the number 12. 14 | The root-to-leaf path 1->3 represents the number 13. 15 | 16 | Return the sum = 12 + 13 = 25. 17 | */ 18 | 19 | /** 20 | * Definition for binary tree 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | int sum; 30 | public int sumNumbers(TreeNode root) { 31 | // IMPORTANT: Please reset any member data you declared, as 32 | // the same Solution instance will be reused for each test case. 33 | sum = 0; 34 | if (root == null) { 35 | return sum; 36 | } 37 | helper(root, 0); 38 | return sum; 39 | } 40 | 41 | public void helper(TreeNode root, int curSum) { 42 | curSum = curSum * 10 + root.val; 43 | if (root.left == null && root.right == null) { 44 | sum = sum + curSum; 45 | } 46 | if (root.left != null) { 47 | helper(root.left, curSum); 48 | } 49 | if (root.right != null) { 50 | helper(root.right, curSum); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Surrounded Regions.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. 3 | 4 | A region is captured by flipping all 'O's into 'X's in that surrounded region . 5 | 6 | For example, 7 | X X X X 8 | X O O X 9 | X X O X 10 | X O X X 11 | After running your function, the board should be: 12 | 13 | X X X X 14 | X X X X 15 | X X X X 16 | X O X X 17 | */ 18 | 19 | public class Solution { 20 | public void solve(char[][] board) { 21 | // Note: The Solution object is instantiated only once and is reused by each test case. 22 | if(board == null || board.length == 0) 23 | return; 24 | 25 | int rowLength = board.length; 26 | int columnLength = board[0].length; 27 | 28 | for (int i = 0; i < rowLength; i++) { 29 | bfs(i, 0, board); 30 | bfs(i, columnLength - 1, board); 31 | } 32 | 33 | for (int j = 1; j < columnLength; j++) { 34 | bfs(0, j, board); 35 | bfs(rowLength - 1, j, board); 36 | } 37 | 38 | for(int i = 0; i < rowLength; i++) { 39 | for(int j = 0; j < columnLength; j++) { 40 | if(board[i][j] == '+') { 41 | board[i][j] = 'O'; 42 | } 43 | else if(board[i][j] == 'O') { 44 | board[i][j] = 'X'; 45 | } 46 | } 47 | } 48 | } 49 | 50 | public void bfs(int i, int j, char[][] board) { 51 | Queue q = new LinkedList(); 52 | visit(i, j, q, board); 53 | 54 | int rowLength = board.length; 55 | int columnLength = board[0].length; 56 | 57 | while(!q.isEmpty()) { 58 | int r = q.poll(); 59 | int col = r % columnLength; 60 | int row = r / columnLength; 61 | 62 | visit(row, col - 1, q, board); 63 | visit(row, col + 1, q, board); 64 | visit(row - 1, col, q, board); 65 | visit(row + 1, col, q, board); 66 | } 67 | 68 | } 69 | 70 | public void visit(int i, int j, Queue q, char[][] board) { 71 | int rowLength = board.length; 72 | int columnLength = board[0].length; 73 | if(i < 0 || i >= rowLength || j < 0 || j >= columnLength || board[i][j] == 'X') 74 | return; 75 | if(board[i][j] == 'O') { 76 | board[i][j] = '+'; 77 | q.offer(i*columnLength + j); 78 | return; 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /Swap Nodes in Pairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | For example, 5 | Given 1->2->3->4, you should return the list as 2->1->4->3. 6 | 7 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 8 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { 17 | * val = x; 18 | * next = null; 19 | * } 20 | * } 21 | */ 22 | public class ListNode { 23 | int val; 24 | ListNode next; 25 | ListNode(int x) { 26 | val = x; 27 | next = null; 28 | } 29 | } 30 | public class Solution { 31 | public ListNode swapPairs(ListNode head) { 32 | // IMPORTANT: Please reset any member data you declared, as 33 | // the same Solution instance will be reused for each test case. 34 | if (head == null || head.next == null) return head; 35 | ListNode a = head; 36 | ListNode b = head.next; 37 | ListNode nex = head.next.next; 38 | a.next = b.next; 39 | b.next = a; 40 | 41 | ListNode newHead = b; 42 | while (nex != null && nex.next != null) { 43 | a.next = nex.next; 44 | ListNode t = nex.next.next; 45 | a = nex; 46 | b = nex.next; 47 | a.next = b.next; 48 | b.next = a; 49 | nex = t; 50 | } 51 | 52 | return newHead; 53 | } 54 | } -------------------------------------------------------------------------------- /Symmetric Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | 4 | For example, this binary tree is symmetric: 5 | 6 | 1 7 | / \ 8 | 2 2 9 | / \ / \ 10 | 3 4 4 3 11 | But the following is not: 12 | 1 13 | / \ 14 | 2 2 15 | \ \ 16 | 3 3 17 | Note: 18 | Bonus points if you could solve it both recursively and iteratively. 19 | 20 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 21 | 22 | 23 | OJ's Binary Tree Serialization: 24 | The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 25 | 26 | Here's an example: 27 | 1 28 | / \ 29 | 2 3 30 | / 31 | 4 32 | \ 33 | 5 34 | The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 35 | */ 36 | 37 | /** 38 | * Definition for binary tree 39 | * public class TreeNode { 40 | * int val; 41 | * TreeNode left; 42 | * TreeNode right; 43 | * TreeNode(int x) { val = x; } 44 | * } 45 | */ 46 | public class Solution { 47 | public boolean isSymmetric(TreeNode root) { 48 | // IMPORTANT: Please reset any member data you declared, as 49 | // the same Solution instance will be reused for each test case. 50 | if (root == null) { 51 | return true; 52 | } 53 | 54 | return isSymmetricHelper(root.left, root.right); 55 | } 56 | 57 | public boolean isSymmetricHelper(TreeNode n1, TreeNode n2) { 58 | if (n1 == null && n2 == null) { 59 | return true; 60 | } else if (n1 == null || n2 == null || n1.val != n2.val) { 61 | return false; 62 | } else { 63 | return isSymmetricHelper(n1.left, n2.right) && isSymmetricHelper(n1.right, n2.left); 64 | 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /Text Justification.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList fullJustify(String[] words, int L) { 3 | // IMPORTANT: Please reset any member data you declared, as 4 | // the same Solution instance will be reused for each test case. 5 | 6 | ArrayList result = new ArrayList(); 7 | if (L == 0) { 8 | result.add(""); 9 | return result; 10 | } 11 | for (int i = 0; i < words.length;) { 12 | String curLine = ""; 13 | int curLength = 0; 14 | int wordCount = 0; 15 | while (i < words.length && curLength + words[i].length() <= L) { 16 | //each word padded with a space 17 | curLength += words[i].length() + 1; 18 | //each word get a space 19 | curLine = curLine + words[i] + " "; 20 | wordCount++; 21 | i++; 22 | } 23 | 24 | //get rid of the last padding space 25 | curLine = curLine.substring(0, curLine.length() - 1); 26 | curLength--; 27 | 28 | if (wordCount == 1 || i == words.length) { 29 | while (curLength < L) { 30 | curLine += " "; 31 | curLength++; 32 | } 33 | result.add(curLine); 34 | } else { 35 | int extraSpace = L - curLength; 36 | if (extraSpace == 0) { 37 | result.add(curLine); 38 | } else { 39 | int extraSpacePerWord = extraSpace / (wordCount - 1); 40 | int spacesLeft = extraSpace % (wordCount - 1); 41 | String spacePerWord = " "; 42 | while (extraSpacePerWord > 0) { 43 | spacePerWord += " "; 44 | extraSpacePerWord--; 45 | } 46 | 47 | String[] w = curLine.split(" "); 48 | String s = w[0]; 49 | for(int j = 1; j < w.length; j++) { 50 | if(spacesLeft > 0) { 51 | s = s + spacePerWord + " " + w[j]; 52 | spacesLeft--; 53 | } else { 54 | s = s + spacePerWord + w[j]; 55 | } 56 | } 57 | result.add(s); 58 | } 59 | } 60 | } 61 | return result; 62 | } 63 | } -------------------------------------------------------------------------------- /Trapping Rain Water.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | //for each bar, find the max height bars on its left and right, 3 | //then it can hold min(leftMax, rightMax) - own height 4 | public int trap(int[] A) { 5 | // IMPORTANT: Please reset any member data you declared, as 6 | // the same Solution instance will be reused for each test case 7 | 8 | int water = 0; 9 | int length = A.length; 10 | 11 | if (length == 0) { 12 | return 0; 13 | } 14 | 15 | int[] leftMax = new int[length]; 16 | int[] rightMax = new int[length]; 17 | 18 | leftMax[0] = 0; 19 | rightMax[length - 1] = 0; 20 | 21 | for (int i = 1; i < length; i++) { 22 | leftMax[i] = Math.max(leftMax[i - 1], A[i - 1]); 23 | } 24 | 25 | for (int i = length - 2; i >= 0; i--) { 26 | rightMax[i] = Math.max(rightMax[i + 1], A[i + 1]); 27 | } 28 | 29 | for (int i = 1; i < length - 1; i++) { 30 | int max = Math.min(rightMax[i], leftMax[i]); 31 | int temp = max - A[i]; 32 | if (temp > 0) { 33 | water += temp; 34 | } 35 | } 36 | 37 | return water; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Triangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minimumTotal(ArrayList> triangle) { 3 | // IMPORTANT: Please reset any member data you declared, as 4 | // the same Solution instance will be reused for each test case. 5 | for (int i = triangle.size() - 2; i >= 0; i--) { 6 | ArrayList preList = triangle.get(i + 1); 7 | ArrayList curList = triangle.get(i); 8 | 9 | for (int j = 0; j < curList.size(); j++) { 10 | int sum1 = curList.get(j) + preList.get(j); 11 | int sum2 = curList.get(j) + preList.get(j + 1); 12 | 13 | curList.set(j, Math.min(sum1, sum2)); 14 | } 15 | } 16 | return triangle.get(0).get(0); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Two Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, find two numbers such that they add up to a specific target number. 3 | 4 | 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 zero-based. 5 | 6 | You may assume that each input would have exactly one solution. 7 | 8 | Input: numbers={2, 7, 11, 15}, target=9 9 | Output: index1=1, index2=2 10 | */ 11 | 12 | public class Solution { 13 | public int[] twoSum(int[] numbers, int target) { 14 | // IMPORTANT: Please reset any member data you declared, as 15 | // the same Solution instance will be reused for each test case. 16 | int[] result = new int[2]; 17 | 18 | int length = numbers.length; 19 | for (int i = 0; i < length; i++) { 20 | int cur = numbers[i]; 21 | int remainder = target - cur; 22 | for (int j = i + 1; j < length; j++) { 23 | if (remainder == numbers[j]) { 24 | result[0] = i + 1; 25 | result[1] = j + 1; 26 | return result; 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /Unique Binary Search Trees II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 3 | 4 | For example, 5 | Given n = 3, your program should return all 5 unique BST's shown below. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 13 | 14 | 15 | OJ's Binary Tree Serialization: 16 | The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 17 | 18 | Here's an example: 19 | 1 20 | / \ 21 | 2 3 22 | / 23 | 4 24 | \ 25 | 5 26 | The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 27 | */ 28 | 29 | /** 30 | * Definition for binary tree 31 | * public class TreeNode { 32 | * int val; 33 | * TreeNode left; 34 | * TreeNode right; 35 | * TreeNode(int x) { val = x; left = null; right = null; } 36 | * } 37 | */ 38 | public class Solution { 39 | public ArrayList generateTrees(int n) { 40 | // IMPORTANT: Please reset any member data you declared, as 41 | // the same Solution instance will be reused for each test case. 42 | return helper(1, n); 43 | } 44 | 45 | public ArrayList helper(int start, int end) { 46 | ArrayList result = new ArrayList(); 47 | if (start > end) { 48 | result.add(null); 49 | return result; 50 | } 51 | 52 | for (int i = start; i <= end; i++) { 53 | for (TreeNode left : helper(start, i - 1)) { 54 | for (TreeNode right : helper(i + 1, end)) { 55 | TreeNode root = new TreeNode(i); 56 | root.left = left; 57 | root.right = right; 58 | result.add(root); 59 | } 60 | } 61 | } 62 | return result; 63 | } 64 | } -------------------------------------------------------------------------------- /Unique Binary Search Trees.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | 4 | For example, 5 | Given n = 3, there are a total of 5 unique BST's. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | 13 | */ 14 | 15 | //f(n) += f(i-1)*f(n-i). 16 | public class Solution { 17 | public int numTrees(int n) { 18 | // IMPORTANT: Please reset any member data you declared, as 19 | // the same Solution instance will be reused for each test case. 20 | if (n <= 1) { 21 | return 1; 22 | } 23 | 24 | int[] dp = new int[n + 1]; 25 | 26 | dp[0] = 1; 27 | dp[1] = 1; 28 | 29 | for (int i = 2; i <= n; i++) { 30 | //start from 0, since one child could be null 31 | for (int j = 0; j < i; j++) { 32 | dp[i] += dp[j] * dp[i - j - 1]; 33 | } 34 | } 35 | 36 | return dp[n]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Unique Paths ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for "Unique Paths": 3 | 4 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 5 | 6 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 7 | 8 | For example, 9 | There is one obstacle in the middle of a 3x3 grid as illustrated below. 10 | 11 | [ 12 | [0,0,0], 13 | [0,1,0], 14 | [0,0,0] 15 | ] 16 | The total number of unique paths is 2. 17 | 18 | Note: m and n will be at most 100. 19 | */ 20 | 21 | public class Solution { 22 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 23 | // IMPORTANT: Please reset any member data you declared, as 24 | // the same Solution instance will be reused for each test case. 25 | int row = obstacleGrid.length; 26 | int col = obstacleGrid[0].length; 27 | 28 | int[][] path = new int[row][col]; 29 | 30 | //initialize 31 | for (int i = 0; i < row; i++) { 32 | if (obstacleGrid[i][0] == 1) { 33 | break; 34 | } 35 | path[i][0] = 1; 36 | } 37 | 38 | for (int j = 0; j < col; j++) { 39 | if (obstacleGrid[0][j] == 1) { 40 | break; 41 | } 42 | path[0][j] = 1; 43 | } 44 | 45 | for (int i = 1; i < row; i++) { 46 | for (int j = 1; j < col; j++) { 47 | if (obstacleGrid[i][j] == 1) { 48 | path[i][j] = 0; 49 | } else { 50 | path[i][j] = path[i - 1][j] + path[i][j - 1]; 51 | } 52 | 53 | } 54 | } 55 | return path[row - 1][col - 1]; 56 | } 57 | } -------------------------------------------------------------------------------- /Unique Paths.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePaths(int m, int n) { 3 | // IMPORTANT: Please reset any member data you declared, as 4 | // the same Solution instance will be reused for each test case. 5 | 6 | //recursive, exceeds time limit 7 | // if (m < 0 || n < 0) { 8 | // return 0; 9 | // } else if (m == 0 && n == 0) { 10 | // return 1; 11 | // } else { 12 | // return uniquePaths(m - 1, n) + uniquePaths(m, n - 1); 13 | // } 14 | 15 | //math approach 16 | //in total m + n steps, choose m out of m + n 17 | double result = 1; 18 | int bigger = Math.max(m - 1, n - 1); 19 | for (int i = m + n - 2; i > bigger; i--) { 20 | result = result * i / (i - bigger); 21 | } 22 | return (int) (result + 0.5); 23 | } 24 | } 25 | 26 | //DP 27 | public class Solution { 28 | public int uniquePaths(int m, int n) { 29 | 30 | int[][] path = new int[m][n]; 31 | //initialize 32 | for (int i = 0; i < m; i++) { 33 | path[i][0] = 1; 34 | } 35 | for (int i = 0; i < n; i++) { 36 | path[0][i] = 1; 37 | } 38 | 39 | for (int i = 1; i < m; i++) { 40 | for (int j = 1; j < n; j++) { 41 | path[i][j] = path[i - 1][j] + path[i][j - 1]; 42 | } 43 | } 44 | 45 | return path[m - 1][n - 1]; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Valid Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | Validate if a given string is numeric. 3 | 4 | Some examples: 5 | "0" => true 6 | " 0.1 " => true 7 | "abc" => false 8 | "1 a" => false 9 | "2e10" => true 10 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. 11 | */ 12 | 13 | public class Solution { 14 | public boolean isNumber(String s) { 15 | // IMPORTANT: Please reset any member data you declared, as 16 | // the same Solution instance will be reused for each test case. 17 | if (s == null || s.equals("")) return false; 18 | boolean canSign = true; 19 | boolean canE = false; 20 | boolean haveE = false; 21 | boolean canDot = true; 22 | boolean onlySpace = false; 23 | boolean haveNum = false; 24 | boolean numBegin = false; 25 | for (int i = 0; i < s.length(); i++) { 26 | char c = s.charAt(i); 27 | if (c == ' ') { 28 | //space is allowed in the beginning when num doesn't begin 29 | if (numBegin) onlySpace = true; 30 | continue; 31 | } else if (onlySpace) { 32 | //space is allowed at the end of the string. if space is not followed by space, return false 33 | return false; 34 | } 35 | 36 | if (c == '+' || c == '-') { 37 | if (!canSign) return false; 38 | canSign = false; 39 | numBegin = true; 40 | } else if (c == 'e') { 41 | if (!canE) return false; 42 | canE = false; 43 | haveNum = false; 44 | numBegin = true; 45 | canSign = true; 46 | haveE = true; 47 | canDot = false; 48 | } else if (c == '.') { 49 | if (!canDot) return false; 50 | canDot = false; 51 | numBegin = true; 52 | canSign = false; 53 | } else if (c >= '0' && c <= '9') { 54 | haveNum = true; 55 | numBegin = true; 56 | canSign = false; 57 | if (!haveE) canE = true; 58 | } else { 59 | return false; 60 | } 61 | } 62 | return haveNum; 63 | } 64 | } -------------------------------------------------------------------------------- /Valid Palindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | For example, 5 | "A man, a plan, a canal: Panama" is a palindrome. 6 | "race a car" is not a palindrome. 7 | 8 | Note: 9 | Have you consider that the string might be empty? This is a good question to ask during an interview. 10 | 11 | For the purpose of this problem, we define empty string as valid palindrome. 12 | */ 13 | 14 | public class Solution { 15 | public boolean isPalindrome(String s) { 16 | // IMPORTANT: Please reset any member data you declared, as 17 | // the same Solution instance will be reused for each test case. 18 | if (s == null || s.length() == 0) { 19 | return true; 20 | } 21 | 22 | StringBuilder sanitizedString = new StringBuilder(); 23 | for (int i = 0; i < s.length(); i++) { 24 | 25 | char cur = s.charAt(i); 26 | 27 | if ((cur >= 'a' && cur <= 'z') || (cur >= '0' && cur <= '9')) { 28 | sanitizedString.append(cur); 29 | } 30 | 31 | if (cur >= 'A' && cur <= 'Z') { 32 | cur = Character.toLowerCase(cur); 33 | sanitizedString.append(cur); 34 | } 35 | 36 | } 37 | 38 | int size = sanitizedString.length(); 39 | for (int i = 0; i < size/2; i++) { 40 | if (sanitizedString.charAt(i) != sanitizedString.charAt(size - i - 1)) { 41 | return false; 42 | } 43 | } 44 | 45 | return true; 46 | } 47 | } -------------------------------------------------------------------------------- /Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 5 | */ 6 | 7 | public class Solution { 8 | public boolean isValid(String s) { 9 | // IMPORTANT: Please reset any member data you declared, as 10 | // the same Solution instance will be reused for each test case. 11 | HashMap parenthese = new HashMap(); 12 | parenthese.put(')', '('); 13 | parenthese.put('}', '{'); 14 | parenthese.put(']', '['); 15 | 16 | ArrayList toBeClosed = new ArrayList(); 17 | for (int i = 0; i < s.length(); i++) { 18 | char cur = s.charAt(i); 19 | if (!parenthese.containsKey(cur)) { 20 | toBeClosed.add(cur); 21 | } else { 22 | if (toBeClosed.isEmpty()) { 23 | return false; 24 | } else { 25 | int length = toBeClosed.size(); 26 | if (toBeClosed.get(length - 1) == parenthese.get(cur)) { 27 | toBeClosed.remove(length - 1); 28 | } else { 29 | return false; 30 | } 31 | } 32 | } 33 | } 34 | 35 | if (toBeClosed.isEmpty()) { 36 | return true; 37 | } else { 38 | return false; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Validate Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | Assume a BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 10 | 11 | 12 | OJ's Binary Tree Serialization: 13 | The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 14 | 15 | Here's an example: 16 | 1 17 | / \ 18 | 2 3 19 | / 20 | 4 21 | \ 22 | 5 23 | The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 24 | */ 25 | 26 | /** 27 | * Definition for binary tree 28 | * public class TreeNode { 29 | * int val; 30 | * TreeNode left; 31 | * TreeNode right; 32 | * TreeNode(int x) { val = x; } 33 | * } 34 | */ 35 | public class Solution { 36 | TreeNode previous; 37 | boolean valid; 38 | public boolean isValidBST(TreeNode root) { 39 | // IMPORTANT: Please reset any member data you declared, as 40 | // the same Solution instance will be reused for each test case. 41 | previous = null; 42 | valid = true; 43 | isValid(root); 44 | return valid; 45 | } 46 | 47 | public void isValid(TreeNode root) { 48 | if (root == null) { 49 | return; 50 | } 51 | isValid(root.left); 52 | if (previous != null && previous.val >= root.val) { 53 | valid = false; 54 | return; 55 | } 56 | previous = root; 57 | isValid(root.right); 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /Word Break.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | For example, given 5 | s = "leetcode", 6 | dict = ["leet", "code"]. 7 | 8 | Return true because "leetcode" can be segmented as "leet code". 9 | */ 10 | 11 | public class Solution { 12 | public boolean wordBreak(String s, Set dict) { 13 | if (s == null || dict.isEmpty()) { 14 | return false; 15 | } 16 | boolean[] chars = new boolean[s.length() + 1]; 17 | chars[0] = true; 18 | 19 | for (int i = 1; i <= s.length(); i++) { 20 | for (int j = 0; j < i; j++) { 21 | if (chars[j] && dict.contains(s.substring(j, i))) { 22 | chars[i] = true; 23 | } 24 | } 25 | } 26 | return chars[s.length()]; 27 | } 28 | } 29 | 30 | public class Solution { 31 | public boolean wordBreak(String s, Set dict) { 32 | // Note: The Solution object is instantiated only once and is reused by each test case. 33 | //TODO: CANNOT PASS THE LAST TEST CASE 34 | if (s.length() == 0) { 35 | return true; 36 | } 37 | else { 38 | int i; 39 | HashSet currentWords = new HashSet(); 40 | for (i = 1; i <= s.length(); i++) { 41 | String current = s.substring(0, i); 42 | if (dict.contains(current)) { 43 | currentWords.add(current); 44 | } 45 | } 46 | for (String temp : currentWords) { 47 | String left = s.substring(temp.length()); 48 | if (dict.contains(left)) { 49 | return true; 50 | } else { 51 | return wordBreak(left, dict); 52 | } 53 | } 54 | return false; 55 | } 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Word Ladder.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: 3 | 4 | Only one letter can be changed at a time 5 | Each intermediate word must exist in the dictionary 6 | For example, 7 | 8 | Given: 9 | start = "hit" 10 | end = "cog" 11 | dict = ["hot","dot","dog","lot","log"] 12 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", 13 | return its length 5. 14 | 15 | Note: 16 | Return 0 if there is no such transformation sequence. 17 | All words have the same length. 18 | All words contain only lowercase alphabetic characters. 19 | */ 20 | 21 | public class Solution { 22 | public int ladderLength(String start, String end, HashSet dict) { 23 | // IMPORTANT: Please reset any member data you declared, as 24 | // the same Solution instance will be reused for each test case. 25 | Map visited = new HashMap(); 26 | LinkedList queue = new LinkedList(); 27 | queue.add(new Count(start, 1)); 28 | visited.put(start, true); 29 | 30 | while (!queue.isEmpty()) { 31 | Count c = queue.poll(); 32 | // for each character in the string, start new branches 33 | for (int i = 0; i < start.length(); i++) { 34 | StringBuilder sb = new StringBuilder(c.string); 35 | char sc = c.string.charAt(i); 36 | // for each different character as new node 37 | for (char cc = 'a'; cc <= 'z'; cc++) { 38 | if (cc == sc) continue; 39 | sb.setCharAt(i, cc); 40 | String tmp = sb.toString(); 41 | // if we haven't visited this node and is in our dictionary 42 | // we visit this node 43 | if (visited.get(tmp) == null && dict.contains(tmp)) { 44 | if (tmp.equals(end)) return c.count+1; 45 | visited.put(tmp, true); 46 | queue.add(new Count(tmp, c.count+1)); 47 | } 48 | } 49 | } 50 | } 51 | return 0; 52 | 53 | } 54 | 55 | class Count { 56 | //string 57 | String string; 58 | //the counts from start string to current string 59 | int count; 60 | 61 | public Count(String string, int count) { 62 | this.string = string; 63 | this.count = count; 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /Zigzag Conversion.java: -------------------------------------------------------------------------------- 1 | /* 2 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 3 | 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: "PAHNAPLSIIGYIR" 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | 10 | string convert(string text, int nRows); 11 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 12 | */ 13 | 14 | public class Solution { 15 | public String convert(String s, int nRows) { 16 | // IMPORTANT: Please reset any member data you declared, as 17 | // the same Solution instance will be reused for each test case. 18 | int size = 2 * nRows - 2; 19 | if (nRows >= s.length() || nRows == 1) { 20 | return s; 21 | } 22 | String result = ""; 23 | 24 | for (int i = 0; i < nRows; i++) { 25 | for (int j = i; j < s.length(); j += size) { 26 | result += s.charAt(j); 27 | if (i != 0 && i != nRows - 1) { 28 | int mid = j + (size - i) - i; 29 | if (mid < s.length()) { 30 | result += s.charAt(mid); 31 | } 32 | 33 | } 34 | } 35 | } 36 | return result; 37 | } 38 | } --------------------------------------------------------------------------------