├── .gitignore ├── AddBinary.java ├── AddTwoNumbersInLinkedList.java ├── Anagram.java ├── BalancedBianryTree.java ├── BestTimeToBuyAndSellStock.java ├── BestTimeToBuyAndSellStockII.java ├── BestTimeToBuyAndSellStockIII.java ├── BinaryTreeInorderTraversal.java ├── BinaryTreeLevelOrderBottom.java ├── BinaryTreeLevelOrderTraversal.java ├── BinaryTreeMaximumSum.java ├── BinaryTreePostOrderTraversal.java ├── BinaryTreePreorderTraversal.java ├── BinaryTreeZigzagLevelOrderTraversal.java ├── CheckNumOfDuplicateWords.java ├── ClimbingStairs.java ├── CombinationSum.java ├── CombinationSum2.java ├── Combinations.java ├── ConstructBinaryTreeFromInorderPreorderTraversal.java ├── ContainerWithMostWater.java ├── ConvertSortedArrayToBST.java ├── CountAndSay.java ├── CovertSortedListToBST.java ├── DecodeWays.java ├── DistinctSubsequences.java ├── DivideTwoIntegers.java ├── EditDistance.java ├── FindMissingPositive.java ├── FlattenBinaryTreeToLinkedList.java ├── FourSum.java ├── GenerateParentheses.java ├── GreyCode.java ├── ImplementstrStr.java ├── InsertInterval.java ├── IntegerToRoman.java ├── InterleavingString.java ├── JumpGame.java ├── JumpGameII.java ├── LargestRectangleInHistogram.java ├── LengthOfLastWord.java ├── LetterCombinationsOfAPhoneNum.java ├── LongestCommonPrefix.java ├── LongestCommonSubsequence.java ├── LongestCommonSubstring.java ├── LongestPalindromicSubstring.java ├── LongestSubstringWithoutRepeatingCharacters.java ├── LongestValidParentheses.java ├── MaximumDepthOfBinaryTree.java ├── MaximumRectangle.java ├── MaximumSubarray.java ├── MedianOfTwoSortedArrays.java ├── MergeKSortedArrays.java ├── MergeKSortedLists.java ├── MergeSortedArray.java ├── MergeTwoSortedLists.java ├── MinimumDepthOfBinaryTree.java ├── MinimumPathSum.java ├── MinimumSumPath.java ├── MinimumWindowSubstring.java ├── MultiplyStrings.java ├── NQueens.java ├── NQueensII.java ├── NextPermutation.java ├── OddOccurenceStringFinding.java ├── PalindromeNumber.java ├── PalindromePartitioning.java ├── PartitionList.java ├── PascalTriangle.java ├── PascalTriangleII.java ├── PathSum.java ├── PathSumII.java ├── PermutationSequence.java ├── Permutations.java ├── PermutationsII.java ├── PlusOne.java ├── PopulatingNextRightPointersInEachNode.java ├── PopulatingNextRightPointersInEachNodeII.java ├── Power.java ├── README.md ├── RecoverBinarySearchTree.java ├── RegularExpressionMatching.java ├── RemoveDuplicatesFromSortedArray.java ├── RemoveDuplicatesFromSortedList.java ├── RemoveDuplicatesFromSortedListII.java ├── RemoveElement.java ├── RemoveNthNodeFromEndOfList.java ├── RestoreIPAddresses.java ├── ReverseALinkedList.java ├── ReverseInteger.java ├── ReverseLinkedListII.java ├── ReverseNodesInKGroup.java ├── RomanToInteger.java ├── RotateImage.java ├── RotateList.java ├── SameTree.java ├── ScrambleString.java ├── SearchA2DMatrix.java ├── SearchForARange.java ├── SearchInRotatedSortedArray.java ├── SearchInRotatedSortedArrayII.java ├── SearchInsertPosition.java ├── SetMatrixZeros.java ├── Shift.java ├── SimplifyPath.java ├── Solution.java ├── SortColors.java ├── SortRotatedArray.java ├── SpiralMatrix.java ├── SpiralMatrixII.java ├── Sqrtx.java ├── StringToIntegerATOI.java ├── Subsets.java ├── SubsetsII.java ├── SubstringWithConcatenationOfAllWords.java ├── SudokuSolver.java ├── SumRootToLeafNumbers.java ├── SurroundedRegions.java ├── SwapNodesInPairs.java ├── SymmetricTree.java ├── TextJustification.java ├── ThreeNumSumClosest.java ├── TrappingRainWater.java ├── Triangle.java ├── TwoSum.java ├── UniqueBinarySearchTree.java ├── UniqueBinarySearchTreeII.java ├── UniquePaths.java ├── UniquePathsII.java ├── ValidNumber.java ├── ValidParentheses.java ├── WordLadderII.java ├── WordSearch.java ├── ZigZagConversion.java └── threeSum.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Package Files # 4 | *.jar 5 | *.war 6 | *.ear 7 | -------------------------------------------------------------------------------- /AddBinary.java: -------------------------------------------------------------------------------- 1 | public class AddBinary { 2 | public String addBinary(String a, String b) { 3 | String l = a.length() > b.length() ? a : b;// long string 4 | String s = l == a ? b : a;// short string 5 | int carry = 0; 6 | StringBuilder sb = new StringBuilder(); 7 | for (int i = l.length() - 1, j = s.length() - 1; j >= 0; i--, j--) { 8 | Character cl = l.charAt(i); 9 | Character cs = s.charAt(j); 10 | if (cl == cs && cl == '0') { 11 | sb.append(0 + carry); 12 | carry = 0; 13 | } else if (cl == cs && cl == '1') { 14 | sb.append(0 + carry); 15 | carry = 1; 16 | } else if (cl != cs && carry == 0) { 17 | sb.append(1); 18 | } else if (cl != cs && carry == 1) { 19 | sb.append(0); 20 | carry = 1; 21 | } 22 | } 23 | 24 | for (int i = l.length() - s.length() - 1; i >= 0; i--) { 25 | Character cl = l.charAt(i); 26 | if (cl == '0' && carry == 1) { 27 | sb.append(1); 28 | carry = 0; 29 | } else if (cl == '1' && carry == 1) { 30 | sb.append(0); 31 | carry = 1; 32 | } else { 33 | sb.append(cl); 34 | } 35 | } 36 | if(carry==1){ 37 | sb.append(1); 38 | } 39 | return sb.reverse().toString(); 40 | } 41 | 42 | 43 | public static void main(String[] args){ 44 | String c = "111"; 45 | String d = "10"; 46 | AddBinary o = new AddBinary(); 47 | String result = o.addBinary(c, d); 48 | System.out.println("result "+result); 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /AddTwoNumbersInLinkedList.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | ListNode(int v) { 6 | val = v; 7 | next = null; 8 | } 9 | } 10 | 11 | public class AddTwoNumbersInLinkedList { 12 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 | int carry = 0; 14 | int value = 0; 15 | ListNode head; 16 | ListNode temp; 17 | ListNode node; 18 | if (l1 == null || l2 == null) { 19 | return null; 20 | } 21 | value = l1.val + l2.val; 22 | head = new ListNode(value % 10); 23 | node = head; 24 | carry = value / 10; 25 | l1 = l1.next; 26 | l2 = l2.next; 27 | 28 | while (l1 != null || l2 != null) { 29 | value = 0; 30 | if (l1 != null) { 31 | value += l1.val; 32 | l1 = l1.next; 33 | } 34 | if (l2 != null) { 35 | value += l2.val; 36 | l2 = l2.next; 37 | } 38 | value += carry; 39 | carry = value / 10; 40 | temp = new ListNode(value % 10); 41 | node.next = temp; 42 | node = node.next; 43 | } 44 | if(carry != 0){ 45 | temp = new ListNode(carry); 46 | node.next = temp; 47 | } 48 | 49 | return head; 50 | } 51 | public void printListNode(ListNode head){ 52 | while(head!=null){ 53 | System.out.print(head.val+"=>"); 54 | head = head.next; 55 | } 56 | } 57 | 58 | public static void main(String[] args){ 59 | AddTwoNumbersInLinkedList o = new AddTwoNumbersInLinkedList(); 60 | ListNode l1 = new ListNode(1); 61 | ListNode head = l1; 62 | for(int i = 2;i<5;i++){ 63 | ListNode l = new ListNode(i); 64 | l1.next = l; 65 | l1=l1.next; 66 | } 67 | o.printListNode(head); 68 | System.out.println(); 69 | ListNode l2 = new ListNode(1); 70 | ListNode head2 = l2; 71 | for(int i = 2;i<4;i++){ 72 | ListNode l22 = new ListNode(i); 73 | l2.next = l22; 74 | l2=l2.next; 75 | } 76 | o.printListNode(head2); 77 | System.out.println(); 78 | 79 | ListNode result = o.addTwoNumbers(head, head2); 80 | o.printListNode(result); 81 | 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /Anagram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Anagram { 4 | public ArrayList anagrams(String[] strs) { 5 | ArrayList result = new ArrayList(); 6 | HashMap> map = new HashMap>(); 7 | LinkedList l = new LinkedList(); 8 | for (String s : strs) { 9 | String si = inorderString(s); 10 | if (!map.containsKey(si)) { 11 | l = new LinkedList(); 12 | 13 | } else { 14 | l = map.get(si); 15 | } 16 | l.push(s); 17 | map.put(si, l); 18 | System.out.println("si"+si+" l "+l); 19 | } 20 | 21 | System.out.println("key:"+map.keySet()); 22 | for (String si : map.keySet()) { 23 | System.out.println("si "+si); 24 | l = map.get(si); 25 | if (l.size() > 1) { 26 | for (String s : l) { 27 | result.add(s); 28 | } 29 | } 30 | } 31 | return result; 32 | 33 | } 34 | 35 | public String inorderString(String str) { 36 | char[] ch = str.toCharArray();//string => char array 37 | Arrays.sort(ch); 38 | System.out.println("ch:"+ch.toString()); 39 | return new String(ch);//char array => string 40 | } 41 | 42 | public static void main(String[] args) { 43 | ArrayList result; 44 | String[] st = { "abc", "bca", "a", "bb", "ac", "ca", "" }; 45 | Anagram a = new Anagram(); 46 | result = a.anagrams(st); 47 | System.out.println(result); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /BalancedBianryTree.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | public class BalancedBianryTree { 7 | public boolean isBalanced(TreeNode root) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if(root==null){ 11 | return true; 12 | } 13 | int diff = Math.abs(getHeight(root.left)-getHeight(root.right)); 14 | if(diff>1){ 15 | return false; 16 | } 17 | return isBalanced(root.left)||isBalanced(root.right); 18 | 19 | } 20 | public int getHeight(TreeNode root){ 21 | if(root==null){ 22 | return 0; 23 | } 24 | int leftHeight = getHeight(root.left); 25 | int rightHeight = getHeight(root.right); 26 | return Math.max(leftHeight,rightHeight)+1; 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStock.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 | public class BestTimeToBuyAndSellStock { 7 | public int maxProfit(int[] prices) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if (prices.length == 0 || prices.length == 1) { 11 | return 0; 12 | } 13 | int max = 0; 14 | for (int i = 1; i < prices.length; i++) { 15 | for (int j = 0; j < i; j++) { 16 | if (prices[i] > prices[j]) { 17 | int value = prices[i] - prices[j]; 18 | max = Math.max(max, value); 19 | } 20 | } 21 | } 22 | 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStockII.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 | //the problem is actually to find all non-decreasing continuous subsequence 8 | 9 | public class BestTimeToBuyAndSellStockII { 10 | public int maxProfit(int[] prices) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | if (prices.length == 0 || prices.length == 1) { 14 | return 0; 15 | } 16 | int value = 0; 17 | for (int i = 0; i < prices.length - 1; i++) { 18 | if (prices[i] <= prices[i + 1]) { 19 | value += prices[i + 1] - prices[i]; 20 | } 21 | } 22 | return value; 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStockIII.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 | //idea comes from peking2 of Mitbbs 10 | // use two array dp1 and dp2 to traversal from both end 11 | 12 | public class BestTimeToBuyAndSellStockIII { 13 | public int maxProfit(int[] prices) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if (prices.length == 0 || prices.length == 1) { 17 | return 0; 18 | } 19 | int len = prices.length; 20 | int[] dp1 = new int[prices.length]; 21 | int[] dp2 = new int[prices.length]; 22 | int min = prices[0]; 23 | int max = prices[len - 1]; 24 | 25 | // for dp1: travel from left to right 26 | System.out.print(" " + dp1[0]); 27 | 28 | for (int i = 1; i < len; i++) { 29 | min = Math.min(min, prices[i]); 30 | dp1[i] = Math.max(dp1[i - 1], prices[i] - min); 31 | System.out.print(" " + dp1[i]); 32 | } 33 | System.out.println(); 34 | // for dp2: travel from right to left 35 | System.out.print(" " + dp2[len - 1]); 36 | for (int j = len - 2; j >= 0; j--) { 37 | max = Math.max(max, prices[j]); 38 | dp2[j] = Math.max(dp2[j + 1], max - prices[j]); 39 | System.out.print(" " + dp2[j]); 40 | } 41 | System.out.println(); 42 | int ans = 0; 43 | for (int k = 0; k < len; k++) { 44 | ans = Math.max(ans, dp1[k] + dp2[k]);// You may not engage in 45 | // multiple transactions at 46 | // the same time 47 | } 48 | return ans; 49 | 50 | } 51 | 52 | public static void main(String[] args) { 53 | BestTimeToBuyAndSellStockIII o = new BestTimeToBuyAndSellStockIII(); 54 | int[] prices = { 2, 1, 2, 1, 0, 1, 2 }; 55 | System.out.println(o.maxProfit(prices)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /BinaryTreeInorderTraversal.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c0090555/Leetcode/dc54c865aadffbffc6c4de1c3248d2874c23a87e/BinaryTreeInorderTraversal.java -------------------------------------------------------------------------------- /BinaryTreeLevelOrderBottom.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class TreeNode { 4 | public int val; 5 | public TreeNode left; 6 | public TreeNode right; 7 | 8 | TreeNode(int v) { 9 | val = v; 10 | left = null; 11 | right = null; 12 | } 13 | } 14 | 15 | public class BinaryTreeLevelOrderBottom { 16 | public ArrayList> levelOrderBottom(TreeNode root) { 17 | ArrayList> result = new ArrayList>(); 18 | ArrayList currentLevel = new ArrayList(); 19 | LinkedList current = new LinkedList(); 20 | LinkedList next = new LinkedList(); 21 | if (root == null) { 22 | return result; 23 | } 24 | current.add(root); 25 | while (current.size() != 0 || next.size() != 0) { 26 | currentLevel = new ArrayList(); 27 | while (current.size() != 0) { 28 | TreeNode current_element = current.remove(); 29 | if (current_element.left != null) { 30 | next.add(current_element.left); 31 | } 32 | if (current_element.right != null) { 33 | next.add(current_element.right); 34 | } 35 | currentLevel.add(current_element.val); 36 | } 37 | result.add(0, currentLevel); 38 | current = next; 39 | next = new LinkedList(); 40 | 41 | } 42 | return result; 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /BinaryTreeLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | //class TreeNode implements Cloneable { 4 | // int val; 5 | // TreeNode left; 6 | // TreeNode right; 7 | // 8 | // TreeNode(int v) { 9 | // val = v; 10 | // } 11 | // public Object clone() { 12 | // try { 13 | // return super.clone(); 14 | // } catch (Exception e) { 15 | // return null; 16 | // } 17 | // } 18 | //} 19 | 20 | public class BinaryTreeLevelOrderTraversal { 21 | public ArrayList> levelOrder(TreeNode root) { 22 | ArrayList> result = new ArrayList>(); 23 | ArrayList currentLevel = new ArrayList(); 24 | LinkedList current = new LinkedList(); 25 | LinkedList next = new LinkedList(); 26 | if (root == null) { 27 | return result; 28 | } 29 | current.add(root); 30 | while (current.size() != 0 || next.size() != 0) { 31 | currentLevel = new ArrayList(); 32 | while (current.size() != 0) { 33 | TreeNode current_element = current.remove(); 34 | if (current_element.left != null) { 35 | next.add(current_element.left); 36 | } 37 | if (current_element.right != null) { 38 | next.add(current_element.right); 39 | } 40 | currentLevel.add(current_element.val); 41 | } 42 | result.add(currentLevel); 43 | current = next; 44 | next = new LinkedList(); 45 | 46 | } 47 | return result; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /BinaryTreeMaximumSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Key idea: use recursion and a global static variable maxSoFar to record the current maximum value 3 | For each node: we will get the leftMax and rightMax for its left subtree and right subtree, if any of them >0, 4 | add it to current node value, then update maxSoFar 5 | 6 | Go to upper level with the selection of correct path(left or right or nothing) 7 | 8 | 9 | 10 | */ 11 | public class BinaryTreeMaximumSum { 12 | public static int maxSoFar = 0; 13 | 14 | public static int maxPathSum(TreeNode root) { 15 | // Start typing your Java solution below 16 | // DO NOT write main() function 17 | if (root == null) { 18 | return 0; 19 | } 20 | maxSoFar = root.val; 21 | maxPathSumHelper(root); 22 | return maxSoFar; 23 | } 24 | 25 | public static int maxPathSumHelper(TreeNode root) { 26 | if (root == null) { 27 | return 0; 28 | } 29 | 30 | int leftMax = maxPathSumHelper(root.left); 31 | int rightMax = maxPathSumHelper(root.right); 32 | int maxPath = root.val; 33 | if (leftMax > 0) { 34 | maxPath += leftMax; 35 | } 36 | if (rightMax > 0) { 37 | maxPath += rightMax; 38 | } 39 | if (maxPath > maxSoFar) { 40 | maxSoFar = maxPath; 41 | } 42 | int result = root.val; 43 | 44 | return Math.max(result, result + Math.max(leftMax, rightMax)); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /BinaryTreePostOrderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BinaryTreePostOrderTraversal { 4 | // recursive approach 5 | public ArrayList postorderTraversalRecursive(TreeNode root) { 6 | ArrayList list = new ArrayList(); 7 | if (root == null) { 8 | return list; 9 | } 10 | postorderTraversalHelper(root, list); 11 | return list; 12 | 13 | } 14 | 15 | public void postorderTraversalHelper(TreeNode root, ArrayList list) { 16 | if (root == null) { 17 | return; 18 | } 19 | postorderTraversalHelper(root.left, list); 20 | postorderTraversalHelper(root.right, list); 21 | list.add(root.val); 22 | return; 23 | } 24 | 25 | // iterative approach 26 | // idea comes from: 27 | // http://www.leetcode.com/2010/10/binary-tree-post-order-traversal.html 28 | public ArrayList postorderTraversalIterative(TreeNode root) { 29 | ArrayList list = new ArrayList(); 30 | if (root == null) { 31 | return list; 32 | } 33 | Stack s = new Stack(); 34 | TreeNode prev = null;// previous visited Node 35 | s.push(root); 36 | while (!s.isEmpty()) { 37 | TreeNode top = s.peek(); 38 | // traversing down the tree 39 | if (prev == null || prev.left == top || prev.right == top) { 40 | if (top.left != null) {// traverse left to the bottom 41 | s.push(top.left); 42 | } else if (top.right != null) { 43 | s.push(top.right); 44 | } else { 45 | s.pop(); 46 | list.add(top.val); 47 | } 48 | } 49 | // traversing up the tree from the left side 50 | else if (top.left == prev) { 51 | if (top.right != null) { 52 | s.push(top.right); 53 | } else { 54 | s.pop(); 55 | list.add(top.val); 56 | } 57 | } 58 | // traversing up from the right side 59 | else if (top.right == prev) { 60 | s.pop(); 61 | list.add(top.val); 62 | } 63 | prev = top; //update prev 64 | } 65 | return list; 66 | 67 | } 68 | } -------------------------------------------------------------------------------- /BinaryTreePreorderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BinaryTreePreorderTraversal { 4 | // recursive approach 5 | public ArrayList preorderTraversalRecursive(TreeNode root) { 6 | ArrayList result = new ArrayList(); 7 | if (root == null) { 8 | return result; 9 | } 10 | preorderTraversalHelper(root, result); 11 | return result; 12 | 13 | } 14 | 15 | public void preorderTraversalHelper(TreeNode root, ArrayList list) { 16 | if (root == null) { 17 | return; 18 | } 19 | list.add(root.val); 20 | preorderTraversalHelper(root.left, list); 21 | preorderTraversalHelper(root.right, list); 22 | return; 23 | } 24 | 25 | // iterative approach - use a stack, push right child first, then left child 26 | public ArrayList preorderTraversalIterative(TreeNode root) { 27 | ArrayList list = new ArrayList(); 28 | if (root == null) { 29 | return list; 30 | } 31 | Stack s = new Stack(); 32 | s.push(root); 33 | while (!s.isEmpty()) { 34 | TreeNode top = s.pop(); 35 | list.add(top.val); 36 | 37 | if (top.right != null) { 38 | s.push(top.right); 39 | } 40 | if (top.left != null) { 41 | s.push(top.left); 42 | } 43 | } 44 | return list; 45 | 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /BinaryTreeZigzagLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BinaryTreeZigzagLevelOrderTraversal { 4 | public ArrayList> zigzagLevelOrder(TreeNode root) { 5 | ArrayList> result = new ArrayList>(); 6 | ArrayList currentLevelValue = new ArrayList(); 7 | Stack currentLevelTree = new Stack(); 8 | Stack nextLevelTree = new Stack(); 9 | int level = 0; 10 | if (root == null) 11 | return result; 12 | currentLevelTree.push(root); 13 | while (!currentLevelTree.isEmpty() || !nextLevelTree.isEmpty()) { 14 | level++; 15 | currentLevelValue = new ArrayList(); 16 | while (!currentLevelTree.isEmpty()) { 17 | TreeNode currentNode = currentLevelTree.pop(); 18 | currentLevelValue.add(currentNode.val); 19 | if (level % 2 != 0) { 20 | if (currentNode.left != null) { 21 | nextLevelTree.push(currentNode.left); 22 | } 23 | if (currentNode.right != null) { 24 | nextLevelTree.push(currentNode.right); 25 | } 26 | } else { 27 | if (currentNode.right != null) { 28 | nextLevelTree.push(currentNode.right); 29 | } 30 | if (currentNode.left != null) { 31 | nextLevelTree.push(currentNode.left); 32 | } 33 | } 34 | } 35 | result.add(currentLevelValue); 36 | currentLevelTree = nextLevelTree; 37 | nextLevelTree = new Stack(); 38 | 39 | } 40 | return result; 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /CheckNumOfDuplicateWords.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list of words (string), let compound word be the 3 | combination of any two words in the array, check the numbers of duplicated 4 | words (to check if there are duplicated compound words, and if the compound 5 | word is the same as some word in the original list, 6 | it is also considered as duplicated) 7 | {"am", "eat", "a", "meat"} "am"+"eat"="a"+"meat" outout =1 8 | 9 | 10 | use a Hashtable 11 | */ 12 | import java.util.*; 13 | 14 | public class CheckNumOfDuplicateWords { 15 | public int numOfDups(String[] words) { 16 | if (words.length == 0) { 17 | return 0; 18 | } 19 | Hashtable hash = new Hashtable(); 20 | int counter = 0; 21 | for (int i = 0; i < words.length; i++) { 22 | if (!hash.containsKey(words[i])) { 23 | hash.put(words[i], 1); 24 | } else { 25 | int c = hash.get(words[i]); 26 | c++; 27 | hash.put(words[i], c); 28 | } 29 | } 30 | 31 | for (int j = 0; j < words.length; j++) { 32 | for (int k = 0; k < words.length; k++) { 33 | if (j != k) { 34 | String s = words[j] + words[k]; 35 | if (!hash.containsKey(s)) { 36 | hash.put(s, 1); 37 | } else { 38 | int c = hash.get(s); 39 | c++; 40 | hash.put(s, c); 41 | } 42 | } 43 | } 44 | } 45 | 46 | for (String s : hash.keySet()) { 47 | int c = hash.get(s); 48 | if (c >= 2) { 49 | System.out.println("s " +s); 50 | counter++; 51 | } 52 | } 53 | return counter; 54 | 55 | } 56 | public static void main(String[] args){ 57 | CheckNumOfDuplicateWords o = new CheckNumOfDuplicateWords(); 58 | String[] words = {"am", "eat", "a", "meat","meat"}; 59 | System.out.println(o.numOfDups(words)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ClimbingStairs { 4 | Hashtable hash = new Hashtable();//this hashtable is used to cache the results and has to be defined outside of the method 5 | 6 | public int climbStairs(int n) { 7 | 8 | int sum = 0; 9 | if (hash.containsKey(n)) { 10 | return hash.get(n); 11 | } 12 | // using DP 13 | if (n == 1) { 14 | if (!hash.containsKey(n)) { 15 | hash.put(1, 1); 16 | } 17 | return 1; 18 | } else if (n == 2) { 19 | if (!hash.containsKey(n)) { 20 | hash.put(2, 2); 21 | } 22 | return 2; 23 | } 24 | if (n <= 0) { 25 | if (!hash.containsKey(n)) { 26 | hash.put(n, 0); 27 | } 28 | return 0; 29 | } 30 | sum = climbStairs(n - 1) + climbStairs(n - 2); 31 | if (!hash.containsKey(n)) { 32 | hash.put(n, sum); 33 | } 34 | return sum; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /CombinationSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class CombinationSum { 4 | public ArrayList> combinationSum(int[] candidates, 5 | int target) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | ArrayList> result = new ArrayList>(); 9 | int[] index = new int[10000]; 10 | index[0] = 0; 11 | Arrays.sort(candidates); 12 | int sum = 0; 13 | solve(result, sum, candidates, index, target, 0); 14 | return result; 15 | } 16 | 17 | public void solve(ArrayList> result, int sum, 18 | int[] candidates, int[] index, int target, int n) { 19 | if (sum == target) { 20 | addSum(result, candidates, index, n); 21 | } else if (sum > target) { 22 | return; 23 | } else { 24 | for (int i = index[n]; i < candidates.length; i++) { 25 | index[n + 1] = i; 26 | solve(result, sum + candidates[i], candidates, index, target, 27 | n + 1); 28 | } 29 | } 30 | 31 | } 32 | 33 | public void addSum(ArrayList> result, int[] candidates, 34 | int[] index, int n) { 35 | ArrayList comb = new ArrayList(); 36 | for (int i = 1; i <= n; i++) { 37 | comb.add(candidates[index[i]]); 38 | } 39 | result.add(comb); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /CombinationSum2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class CombinationSum2 { 4 | public ArrayList> combinationSum2(int[] num, int target) { 5 | ArrayList> result = new ArrayList>(); 6 | ArrayList comb = new ArrayList(); 7 | Arrays.sort(num); 8 | solve(result, comb, num, 0, target); 9 | return result; 10 | } 11 | 12 | public void solve(ArrayList> result, 13 | ArrayList comb, int[] num, int start, int target) { 14 | if (target == 0) { 15 | result.add((ArrayList)comb.clone());//Need to use clone method here 16 | return; 17 | } 18 | if (start == num.length || target < 0) { 19 | return; 20 | } 21 | 22 | int prev = -1; 23 | for (int i = start; i < num.length; i++) { 24 | if (num[i] != prev) { 25 | comb.add(num[i]); 26 | solve(result, comb, num, i + 1, target - num[i]); 27 | comb.remove(comb.size() - 1); 28 | prev = num[i]; 29 | } 30 | } 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Combinations.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Combinations { 4 | public ArrayList> combine(int n, int k) { 5 | ArrayList> result = new ArrayList>(); 6 | ArrayList comb = new ArrayList(); 7 | //base case: k==1 8 | if (k == 1) { 9 | for (int i = 1; i <= n; i++) { 10 | comb = new ArrayList(); 11 | comb.add(i); 12 | result.add(comb); 13 | } 14 | return result; 15 | } else if (k == n) { 16 | comb = new ArrayList(); 17 | for (int i = 1; i <= n; i++) { 18 | comb.add(i); 19 | } 20 | result.add(comb); 21 | return result; 22 | } 23 | else if(k>n){ 24 | return new ArrayList>(); 25 | } 26 | 27 | else { 28 | ArrayList> f1 = combine(n - 1, k - 1);// choose n 29 | ArrayList> f2 = combine(n - 1, k);// not choose n 30 | 31 | // add n back to f1 32 | for (int i = 0; i < f1.size(); i++) { 33 | f1.get(i).add(n); 34 | } 35 | // merge f1 and f2 36 | f1.addAll(f2); 37 | return f1; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ConstructBinaryTreeFromInorderPreorderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ConstructBinaryTreeFromInorderPreorderTraversal { 4 | public TreeNode buildTree(int[] preorder, int[] inorder) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (inorder.length != preorder.length) { 8 | return null; 9 | } 10 | if (inorder.length == 0 || preorder.length == 0) { 11 | return null; 12 | } 13 | Hashtable indexHash = new Hashtable(); 14 | for (int i = 0; i < inorder.length; i++) { 15 | indexHash.put(inorder[i], i); 16 | } 17 | 18 | TreeNode root = buildTree(inorder, preorder, 0, inorder.length - 1, 0, 19 | preorder.length - 1, 0, indexHash); 20 | return root; 21 | } 22 | 23 | public TreeNode buildTree(int[] inorder, int[] preorder, int inStart, 24 | int inEnd, int preStart, int preEnd, int offset, 25 | Hashtable indexHash) { 26 | if (inStart > inEnd || inStart < 0 || inEnd >= inorder.length 27 | || preStart > preEnd || preStart < 0 28 | || preEnd >= preorder.length) { 29 | return null; 30 | } 31 | if (inStart == inEnd) { 32 | return new TreeNode(inorder[inStart]); 33 | } 34 | if (preStart == preEnd) { 35 | return new TreeNode(preorder[preStart]); 36 | } 37 | 38 | TreeNode root = new TreeNode(preorder[preStart]); 39 | int rootInorderIndex = indexHash.get(preorder[preStart]); 40 | int leftNum = rootInorderIndex - offset; 41 | int rightNum = inEnd - inStart - leftNum; 42 | root.left = buildTree(inorder, preorder, inStart, 43 | inStart + leftNum - 1, preStart + 1, preStart + leftNum, 44 | offset, indexHash); 45 | root.right = buildTree(inorder, preorder, rootInorderIndex + 1, 46 | rootInorderIndex + rightNum, preStart + leftNum + 1, preStart 47 | + leftNum + 1 + rightNum - 1, offset + leftNum + 1, 48 | indexHash); 49 | return root; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ContainerWithMostWater { 4 | public int maxArea(int[] height) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | Hashtable areaHash = new Hashtable(); 8 | int max = Integer.MIN_VALUE; 9 | for (int i = 0; i < height.length; i++) { 10 | for (int j = i + 1; j < height.length; j++) { 11 | int w = Math.abs(i - j); 12 | int h = Math.min(height[i], height[j]); 13 | Wrapper temp = new Wrapper(h, w); 14 | if (areaHash.containsKey(temp)) { 15 | return areaHash.get(temp); 16 | } 17 | int result = w * h; 18 | if (result > max) { 19 | max = result; 20 | } 21 | 22 | areaHash.put(temp, max); 23 | } 24 | 25 | } 26 | 27 | return max; 28 | } 29 | 30 | public double calculateArea(int m, int am, int n, int an) { 31 | if (am == 0 || an == 0) { 32 | return 0; 33 | } 34 | double area = Math.min(m, n) * Math.abs(m - n); 35 | return area; 36 | } 37 | 38 | class Wrapper { 39 | int width; 40 | int height; 41 | 42 | public Wrapper(int h, int w) { 43 | height = h; 44 | width = w; 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /ConvertSortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | //Convert a sorted array(ascending order) to a height balanced BST 4 | 5 | public class ConvertSortedArrayToBST { 6 | public TreeNode sortedArrayToBST(int[] num) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | if (num.length == 0) { 10 | return null; 11 | } 12 | if (num.length == 1) { 13 | return new TreeNode(num[0]); 14 | } 15 | int mid = (num.length - 1) / 2; 16 | TreeNode root = new TreeNode(num[mid]); 17 | if (mid >= 1) { 18 | root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid)); 19 | } else { 20 | root.left = null; 21 | } 22 | if (num.length - 1 - mid - 1 >= 0) { 23 | root.right = sortedArrayToBST(Arrays.copyOfRange(num, mid + 1, 24 | num.length)); 25 | } else { 26 | root.right = null; 27 | } 28 | 29 | return root; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CountAndSay.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class CountAndSay { 4 | Hashtable sequenceHash = new Hashtable(); 5 | 6 | public String countAndSay(int n) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | if (n == 1) 10 | return "1"; 11 | if (n == 2) 12 | return "11"; 13 | if (n == 3) 14 | return "21"; 15 | if (n == 4) 16 | return "1211"; 17 | if (sequenceHash.containsKey(n)) { 18 | return sequenceHash.get(n); 19 | } 20 | sequenceHash.put(n, rotate(countAndSay(n - 1), 2 * (n - 4)) 21 | + countAndSay(n - 2)); 22 | return rotate(countAndSay(n - 1), 2 * (n - 4)) + countAndSay(n - 2); 23 | 24 | } 25 | 26 | public String rotate(String str, int d) { 27 | if (d < 0) { 28 | return null; 29 | } 30 | return str.substring(str.length() - d % str.length()) 31 | + str.substring(0, str.length() - d % str.length()); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /CovertSortedListToBST.java: -------------------------------------------------------------------------------- 1 | public class CovertSortedListToBST { 2 | public TreeNode sortedListToBST(ListNode head) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | TreeNode root = constructBST(head, length(head)); 6 | return root; 7 | 8 | } 9 | 10 | public TreeNode constructBST(ListNode head, int length) { 11 | if (length <= 0 || head == null) { 12 | return null; 13 | } 14 | if (length == 1) { 15 | return new TreeNode(head.val); 16 | } 17 | ListNode mid = head; 18 | for (int i = 1; i <= length / 2; i++) { 19 | mid = mid.next; 20 | } 21 | TreeNode root = new TreeNode(mid.val); 22 | if (length % 2 == 0) { 23 | root.left = constructBST(head, length / 2); 24 | root.right = constructBST(mid.next, length / 2 - 1); 25 | } else { 26 | root.left = constructBST(head, length / 2); 27 | root.right = constructBST(mid.next, length / 2); 28 | } 29 | 30 | return root; 31 | 32 | } 33 | 34 | public int length(ListNode head) { 35 | int counter = 0; 36 | while (head != null) { 37 | counter++; 38 | head = head.next; 39 | } 40 | return counter; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /DecodeWays.java: -------------------------------------------------------------------------------- 1 | public class DecodeWays { 2 | public int numDecodings(String s) { 3 | if(s==null||s.length()==0){ 4 | return 0; 5 | } 6 | int[] dp = new int[s.length() + 1]; 7 | dp[s.length()] = 1; 8 | 9 | for (int i = s.length() - 1; i >= 0; i++) { 10 | if (s.charAt(i) != '0') { 11 | dp[i] = dp[i + 1]; 12 | if (i < s.length() 13 | && Integer.parseInt(s.substring(i, i + 2)) <= 26) { 14 | dp[i] += dp[i + 2]; 15 | } 16 | 17 | } 18 | } 19 | return dp[0]; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DistinctSubsequences.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S and a string T, count the number of distinct subsequences of T in S. 3 | 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). 4 | 5 | Here is an example: 6 | S = "rabbbit", T = "rabbit" 7 | Return 3. 8 | Let the three b's in "rabbbit" be labeled as b1, b2, and b3. Then there can be 3 distinct subsequences of "rabbit", that is: rab1b2it, rab1b3it, and rab2b3it. 9 | */ 10 | public class DistinctSubsequences { 11 | public int numDistinct(String S, String T) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if (S.length() == 0 || S.length() < T.length()) { 15 | return 0; 16 | } 17 | if (T.length() == 0) { 18 | return 1; 19 | } 20 | int[][] dp = new int[S.length() + 1][T.length() + 1]; 21 | for (int j = 0; j <= T.length(); j++) { 22 | dp[0][j] = 0; 23 | } 24 | for (int i = 0; i <= S.length(); i++) {// dp[0][0]==1 25 | dp[i][0] = 1; 26 | } 27 | 28 | for (int j = 1; j <= T.length(); j++) { 29 | for (int i = 1; i <= S.length(); i++) { 30 | if (S.charAt(i - 1) == T.charAt(j - 1)) { 31 | dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; 32 | } else { 33 | dp[i][j] = dp[i - 1][j]; 34 | } 35 | } 36 | } 37 | 38 | return dp[S.length()][T.length()]; 39 | 40 | } 41 | 42 | public static void main(String[] args) { 43 | DistinctSubsequences o = new DistinctSubsequences(); 44 | String S = "rabbbbit"; 45 | String T = "rabbit"; 46 | System.out.println(o.numDistinct(S, T)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /DivideTwoIntegers.java: -------------------------------------------------------------------------------- 1 | public class DivideTwoIntegers { 2 | public int divide(int dividend, int divisor) { 3 | if (divisor == 0) { 4 | throw new ArithmeticException(); 5 | } 6 | if (dividend == 0) { 7 | return 0; 8 | } 9 | long a = dividend; 10 | long b = divisor; 11 | boolean neg = false; // used to indicate whether the result is positive 12 | // or negative 13 | int result = 0; 14 | neg = dividend < 0 ? !neg : neg; 15 | neg = divisor < 0 ? !neg : neg; 16 | 17 | a = Math.abs(a); 18 | b = Math.abs(b); 19 | 20 | int c = 0;// c is the number of digits moved 21 | while (b << c <= a) { 22 | c++; 23 | } 24 | 25 | while (c >= 0) { 26 | if (b << c <= a) { 27 | a -= b << c; 28 | result |= 1 << c; 29 | } 30 | c--; 31 | } 32 | if(neg){ 33 | result = -result; 34 | } 35 | return result; 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /EditDistance.java: -------------------------------------------------------------------------------- 1 | 2 | //typical DP question 3 | //d[i,j] = minimum distance from s1,s2...si to t1,t2..tj 4 | //d[i,j]=d[i-1,j-1] if si == tj 5 | // =min(d[i-1,j]+1,d[i,j-1]+1,d[i-1,j-1]+1 if si != tj 6 | 7 | public class EditDistance { 8 | public int minDistance(String word1, String word2) { 9 | int d[][] = new int[word1.length()+1][word2.length()+1]; 10 | for(int i=0;i<=word1.length();i++){ 11 | d[i][0] = i; 12 | } 13 | for(int j=0;j<=word2.length();j++){ 14 | d[0][j] = j; 15 | } 16 | 17 | for(int i=1;i<=word1.length();i++){ 18 | for(int j=1;j<=word2.length();j++){ 19 | if(word1.charAt(i-1)==word2.charAt(j-1)){ 20 | d[i][j]=d[i-1][j-1]; 21 | } 22 | else d[i][j]=minInThree(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+1); 23 | } 24 | } 25 | 26 | return d[word1.length()][word2.length()]; 27 | } 28 | public int minInThree(int a, int b, int c){ 29 | if(a 0 && (A[i] - 1 < A.length) && A[A[i] - 1] != A[i]) { 23 | int temp = A[A[i] - 1]; 24 | A[A[i] - 1] = A[i]; 25 | A[i] = temp; 26 | i--;//continue doing A[i] 27 | } 28 | } 29 | 30 | int j = 1; 31 | 32 | while (j <= A.length && A[j - 1] == j) { 33 | j++; 34 | } 35 | return j; 36 | 37 | } 38 | 39 | public static void main(String[] args) { 40 | FindMissingPositive o = new FindMissingPositive(); 41 | int[] A = { 1 }; 42 | System.out.println(o.firstMissingPositive(A)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /FlattenBinaryTreeToLinkedList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FlattenBinaryTreeToLinkedList { 4 | public void flatten(TreeNode root) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (root == null) { 8 | return; 9 | } 10 | LinkedList l = new LinkedList(); 11 | flattenToLinkedList(root, l); 12 | l.remove(0);// get rid of the first element in the LinkedList(i.e. root) 13 | 14 | if (!l.isEmpty()) { 15 | TreeNode temp = new TreeNode(l.remove(0)); 16 | root.left = null; 17 | root.right = temp; 18 | 19 | while (!l.isEmpty()) { 20 | temp.left = null; 21 | temp.right = new TreeNode(l.remove(0)); 22 | temp = temp.right; 23 | } 24 | } 25 | 26 | // System.out.print(root.val +"_"); 27 | // System.out.print(root.right.left +"_"); 28 | // System.out.print(root.right.right.val +"_"); 29 | // 30 | // 31 | return; 32 | } 33 | 34 | public void flattenToLinkedList(TreeNode root, LinkedList n) { 35 | if (root == null) { 36 | return; 37 | } 38 | n.add(root.val); 39 | // System.out.println(root.val); 40 | if (root.left != null) { 41 | flattenToLinkedList(root.left, n); 42 | } 43 | if (root.right != null) { 44 | flattenToLinkedList(root.right, n); 45 | } 46 | return; 47 | } 48 | 49 | public static void main(String[] args) { 50 | TreeNode root = new TreeNode(1); 51 | root.left = new TreeNode(2); 52 | root.right = new TreeNode(3); 53 | 54 | FlattenBinaryTreeToLinkedList o = new FlattenBinaryTreeToLinkedList(); 55 | o.flatten(root); 56 | System.out.print(root.val + "_"); 57 | System.out.print(root.left + "_"); 58 | System.out.print(root.right + "_"); 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /FourSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FourSum { 4 | public static ArrayList> fourSum(int[] num, int target) { 5 | ArrayList fourSum = new ArrayList(); 6 | ArrayList> result = new ArrayList>(); 7 | Hashtable, Boolean> occur = new Hashtable, Boolean>(); 8 | Arrays.sort(num); 9 | 10 | for (int i = 0; i < num.length; i++) { 11 | for (int j = i + 1; j < num.length; j++) { 12 | for (int k = j + 1, l = num.length - 1; k < l;) { 13 | if (num[i] + num[j] + num[k] + num[l] == target) { 14 | fourSum = new ArrayList(); 15 | fourSum.add(num[i]); 16 | fourSum.add(num[j]); 17 | fourSum.add(num[k]); 18 | fourSum.add(num[l]); 19 | Collections.sort(fourSum); 20 | System.out.println("fourSum: "+fourSum); 21 | if (!occur.containsKey(fourSum)) { 22 | occur.put(fourSum, true); 23 | result.add(fourSum); 24 | } 25 | l--; 26 | k++; 27 | } else if (num[i] + num[j] + num[k] + num[l] > target) { 28 | l--; 29 | } else { 30 | k++; 31 | } 32 | } 33 | 34 | } 35 | } 36 | return result; 37 | } 38 | 39 | public static void main(String[] args){ 40 | int num[] = {0,-2,1,3,5,2,3,5,6,2,-3,0,0,0,-6}; 41 | ArrayList> result = fourSum(num,0); 42 | System.out.println(result); 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | //use recursion 3 | //use +1 & -1 to simulate stack operation 4 | //sum+1 means inserting a left parenthese 5 | //sum-1 means inserting a right parenthese 6 | //sum should be always >=0 7 | 8 | public class GenerateParentheses { 9 | 10 | public ArrayList generateParenthesis(int n) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | ArrayList result = new ArrayList(); 14 | generateParenthesis(n, n, 0, "", result); 15 | return result; 16 | 17 | } 18 | 19 | public void generateParenthesis(int left, int right, int sum, String s, 20 | ArrayList result) { 21 | if (left == 0 && right == 0 && sum == 0) { 22 | result.add(s); 23 | return; 24 | } 25 | if (left < 0 || right < 0 || sum < 0) { 26 | return; 27 | } 28 | generateParenthesis(left - 1, right, sum + 1, s + "(", result); 29 | if (sum > 0) { 30 | generateParenthesis(left, right - 1, sum - 1, s + ")", result); 31 | 32 | } 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /GreyCode.java: -------------------------------------------------------------------------------- 1 | //google grey code 2 | // 1.construction of grey code: (num>>1)^num 3 | // 2.use a dp idea, assume sequence[n] is the gray code sequence in n digits 4 | //if we reverse sequence[n] and add a '1' to the left side of each numbers, then we get the new reverse 5 | //sequence newReverse[n] 6 | //combine sequence[n] and newReverse[n] to get sequence[n+1] 7 | import java.util.*; 8 | 9 | public class GreyCode { 10 | public ArrayList grayCodeUsingFormula(int n) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | ArrayList res = new ArrayList(); 14 | for (int i = 0; i < Math.pow(2.0, n); i++) { 15 | res.add((i >> 1) ^ i); 16 | } 17 | return res; 18 | } 19 | 20 | public ArrayList grayCode(int n) { 21 | ArrayList res = new ArrayList(); 22 | res.add(0);// append the first element of gray code sequence - 0 23 | for (int i = 1; i <= n; i++) { 24 | int addedOne = 1 << (i - 1); 25 | for (int j = res.size() - 1; j >= 0; j--) { 26 | res.add(res.get(j) | addedOne); 27 | 28 | } 29 | } 30 | return res; 31 | } 32 | public static void main(String[] args){ 33 | GreyCode o = new GreyCode(); 34 | int n=2; 35 | ArrayList res = o.grayCode(n); 36 | for(int i=0;i insert(ArrayList intervals, 20 | Interval newInterval) { 21 | // Start typing your Java solution below 22 | // DO NOT write main() function 23 | // figure out whether it is necessary to merge 24 | if (intervals.size() == 0) { 25 | intervals.add(newInterval); 26 | return intervals; 27 | } 28 | if (newInterval == null) { 29 | return intervals; 30 | } 31 | boolean merge = false;//indicate whether merge happened 32 | int mergeStart = -1; 33 | int mergeEnd = intervals.get((intervals.size() - 1)).end; 34 | boolean nonOverlap = false;//indicate whether merge happened before 35 | ArrayList result = new ArrayList(); 36 | boolean newInserted = false;//indicate whether newInterval inserted 37 | // ArrayList mergePosition = new ArrayList(); 38 | for (int i = 0; i < intervals.size(); i++) { 39 | if (overlap(intervals.get(i), newInterval)) { 40 | if (merge == false) { 41 | mergeStart = Math.min(newInterval.start, 42 | intervals.get(i).start); 43 | } 44 | if (i == intervals.size() - 1) { 45 | mergeEnd = Math.max(newInterval.end, intervals.get(i).end); 46 | result.add(new Interval(mergeStart, mergeEnd)); 47 | 48 | } 49 | merge = true; 50 | } else { 51 | if (merge == true) { 52 | if (nonOverlap == false) { 53 | mergeEnd = Math.max(newInterval.end, 54 | intervals.get(i - 1).end); 55 | result.add(new Interval(mergeStart, mergeEnd)); 56 | merge = false; 57 | nonOverlap = true; 58 | result.add(intervals.get(i)); 59 | 60 | } 61 | } else { 62 | if (nonOverlap == true) {// merge happened 63 | result.add(intervals.get(i)); 64 | 65 | } else {// merge never happen 66 | if (newInserted == true) { 67 | result.add(intervals.get(i)); 68 | } else { 69 | if (i == intervals.size() - 1) { 70 | if (newInterval.end < intervals.get(i).start) { 71 | result.add(newInterval); 72 | result.add(intervals.get(i)); 73 | newInserted = true; 74 | } else { 75 | result.add(intervals.get(i)); 76 | result.add(newInterval); 77 | newInserted = true; 78 | 79 | } 80 | } else { 81 | if (newInterval.end < intervals.get(i).start) { 82 | result.add(newInterval); 83 | result.add(intervals.get(i)); 84 | newInserted = true; 85 | } else { 86 | result.add(intervals.get(i)); 87 | 88 | } 89 | } 90 | } 91 | } 92 | } 93 | } 94 | } 95 | // System.out.print("start :" + start + "end: " + end); 96 | // System.out.print("start :" + mergeStart + "end: " + mergeEnd); 97 | 98 | return result; 99 | 100 | } 101 | 102 | public boolean overlap(Interval a, Interval b) { 103 | if ((b.start >= a.start && b.start <= a.end) 104 | || (b.end >= a.start && b.end <= a.end) 105 | || (a.start >= b.start && a.start <= b.end) 106 | || (a.end >= b.start && a.end <= b.end)) { 107 | return true; 108 | } else { 109 | return false; 110 | } 111 | } 112 | 113 | public static void main(String[] args) { 114 | InsertInterval o = new InsertInterval(); 115 | ArrayList original = new ArrayList(); 116 | original.add(new Interval(2, 4)); 117 | original.add(new Interval(5, 7)); 118 | original.add(new Interval(8, 10)); 119 | 120 | original.add(new Interval(11, 13)); 121 | 122 | Interval newInterval = new Interval(3, 6); 123 | 124 | ArrayList result = o.insert(original, newInterval); 125 | 126 | } 127 | } 128 | 129 | 130 | -------------------------------------------------------------------------------- /IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | public class IntegerToRoman { 2 | public String intToRoman(int num) { 3 | StringBuilder roman = new StringBuilder(); 4 | String[] ones = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", 5 | "IX" }; 6 | String[] tens = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", 7 | "XC" }; 8 | String[] hundreds = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", 9 | "DCCC", "CM" }; 10 | String[] thousands = { "", "M", "MM", "MMM" }; 11 | if (num >= 4000 || num <= 0) { 12 | return null; 13 | } 14 | 15 | roman.append(thousands[num / 1000]); 16 | num = num % 1000; 17 | roman.append(hundreds[num / 100]); 18 | num = num % 100; 19 | roman.append(tens[num / 10]); 20 | num = num % 10; 21 | roman.append(ones[num]); 22 | return roman.toString(); 23 | } 24 | } -------------------------------------------------------------------------------- /InterleavingString.java: -------------------------------------------------------------------------------- 1 | //2 Dimensional DP 2 | public class InterleavingString { 3 | public boolean isInterleave(String s1, String s2, String s3) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (s3.length() != s1.length() + s2.length()) { 7 | return false; 8 | } 9 | if (s1.length() == 0) { 10 | return s2.equals(s3); 11 | } 12 | if (s2.length() == 0) { 13 | return s1.equals(s3); 14 | } 15 | boolean matrix[][] = new boolean[s1.length()][s2.length()]; 16 | return isInterleave(s1, s1.length(), s2, s2.length(), s3, s3.length(), 17 | matrix); 18 | 19 | } 20 | 21 | public boolean isInterleave(String s1, int len1, String s2, int len2, 22 | String s3, int len3, boolean[][] matrix) { 23 | if (len1 == 0 && len2 == 0 && len3 == 0) { 24 | return true; 25 | } 26 | if (len1 < 0 || len2 < 0 || len3 < 0) { 27 | return false; 28 | } 29 | if (len1 + len2 != len3) { 30 | return false; 31 | } 32 | if (len1 >= 1 && len2 >= 1) { 33 | matrix[len1 - 1][len2 - 1] = ((s1.charAt(len1 - 1) == s3 34 | .charAt(len3 - 1)) && isInterleave(s1, len1 - 1, s2, len2, 35 | s3, len3 - 1, matrix)) 36 | || ((s2.charAt(len2 - 1) == s3.charAt(len3 - 1)) && isInterleave( 37 | s1, len1, s2, len2 - 1, s3, len3 - 1, matrix)); 38 | } else { 39 | if (len1 >= 1) { 40 | matrix[len1 - 1][0] = (s1.charAt(len1 - 1) == s3 41 | .charAt(len3 - 1)) 42 | && isInterleave(s1, len1 - 1, s2, 0, s3, len3 - 1, 43 | matrix); 44 | } 45 | if (len2 >= 1) { 46 | matrix[0][len2 - 1] = (s2.charAt(len2 - 1) == s3 47 | .charAt(len3 - 1)) 48 | && isInterleave(s1, 0, s2, len2 - 1, s3, len3 - 1, 49 | matrix); 50 | 51 | } 52 | } 53 | return matrix[0][0]; 54 | 55 | } 56 | 57 | public static void main(String[] args) { 58 | String s1 = "a"; 59 | String s2 = "b"; 60 | String s3 = "ab"; 61 | InterleavingString o = new InterleavingString(); 62 | System.out.println(o.isInterleave(s1, s2, s3)); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /JumpGame.java: -------------------------------------------------------------------------------- 1 | //typical DP 2 | public class JumpGame { 3 | public boolean canJump(int[] A) { 4 | int range = 0; 5 | int i = 0; 6 | while (i <= range) { 7 | if (range >= A.length - 1) { 8 | return true; 9 | } 10 | range = Math.max(i + A[i], range); 11 | i++; 12 | } 13 | return false; 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /JumpGameII.java: -------------------------------------------------------------------------------- 1 | //DP 2 | public class JumpGameII { 3 | public int jump(int[] A) { 4 | int[] steps = new int[A.length]; 5 | int limit = 0;// reachable range * 6 | steps[0] = 0; 7 | 8 | for (int i = 0; i < A.length - 1; i++) { 9 | if (A[i] + i > limit) { 10 | if (A[i] + i >= A.length - 1) { 11 | System.out.println("i " + i); 12 | System.out.println("stepsi" + steps[i]); 13 | 14 | return steps[i] + 1; 15 | } 16 | for (int j = limit + 1; j <= i + A[i] && j <= A.length - 1; j++) { 17 | steps[j] = steps[i] + 1; 18 | } 19 | limit = A[i] + i; 20 | 21 | } 22 | 23 | } 24 | 25 | return steps[A.length - 1]; 26 | 27 | } 28 | 29 | public static void main(String[] args) { 30 | JumpGameII o = new JumpGameII(); 31 | int[] a = { 7, 0, 9, 6, 9, 6, 1, 7, 9, 0, 1, 2, 9, 0, 3 }; 32 | System.out.print(o.jump(a)); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /LargestRectangleInHistogram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | //maintain a stack where higher element is always greater or equal to the lower element 3 | //LARGER element: we just need to push them to stack 4 | //SMALLER element: (1).pop the stack until we can maintain the non-decreasing order. 5 | //push the smaller element for m times,where m = number of popped elements 6 | //(2).keep track of the maximum area that cause by those pop 7 | 8 | public class LargestRectangleInHistogram { 9 | public int largestRectangleArea(int[] height) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | 13 | Stack s = new Stack(); 14 | int i = 0; 15 | int max = 0; 16 | int counter = 0; 17 | while (i <= height.length - 1) { 18 | if (s.isEmpty() || height[i] >= s.peek()) { 19 | s.push(height[i]); 20 | } else { 21 | counter = 0; 22 | while (!s.isEmpty() && height[i] < s.peek()) { 23 | counter++; 24 | max = Math.max(s.pop() * counter, max);// track the maximum 25 | // area that cause 26 | // by those pop 27 | 28 | } 29 | for (int j = 1; j <= counter + 1; j++) { 30 | s.push(height[i]);// push back the smaller element for m 31 | // times 32 | } 33 | } 34 | i++; 35 | 36 | } 37 | 38 | counter = 0; 39 | for (i = 0; i <= height.length - 1; i++) { 40 | counter++; 41 | max = Math.max(s.pop() * counter, max); 42 | } 43 | return max; 44 | 45 | } 46 | // brute force approach - O(n) 47 | public int largestRectangleArea1(int[] height) { 48 | int n = height.length; 49 | int[] area = new int[n]; 50 | for (int i = 0; i < n; i++) { 51 | int j = i; 52 | while (j >= 0 && height[j] >= height[i]) {// search left until we 53 | // find the first bar 54 | // lower than current 55 | // bar 56 | j--; 57 | } 58 | 59 | area[i] += i - j - 1; 60 | 61 | j = i; 62 | while (j < n && height[j] >= height[i]) {// search right until we 63 | // find the first bar 64 | // lower than current 65 | // bar 66 | j++; 67 | } 68 | area[i] = j - i - 1; 69 | 70 | } 71 | int max = 0; 72 | for (int k = 0; k < n; k++) { 73 | max = Math.max(max, height[k] * (area[k] + 1)); 74 | } 75 | return max; 76 | } 77 | 78 | // stack approach - O(n) 79 | public int largestRectangleArea2(int[] height) { 80 | Stack s = new Stack(); 81 | int n = height.length; 82 | int[] area = new int[n]; 83 | for (int i = 0; i < n; i++) { 84 | while (!s.isEmpty() && height[i] <= height[s.peek()]) {//search left until we find the first bar lower than current bar 85 | s.pop(); 86 | } 87 | int j = s.isEmpty() ? -1 : s.peek(); 88 | area[i] += i - j - 1; 89 | s.push(i); 90 | } 91 | 92 | s=new Stack(); //clean stack 93 | 94 | for(int i=n-1;i>=0;i--){ 95 | while(!s.isEmpty()&&height[i]<=height[s.peek()]){//search right until we find the first bar lower than current bar 96 | s.pop(); 97 | } 98 | int j=s.isEmpty()?n:s.peek(); 99 | area[i]+=j-i-1; 100 | s.push(i); 101 | } 102 | 103 | int max=0; 104 | for(int i=0;i= 0) { 10 | if (s.charAt(i) != ' ' && wordStart == false) { 11 | length++; 12 | wordStart = true; 13 | } else if (wordStart == true && s.charAt(i) != ' ') { 14 | length++; 15 | } 16 | 17 | else if (wordStart == true && s.charAt(i) == ' ') { 18 | break; 19 | } 20 | i--; 21 | } 22 | return length; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LetterCombinationsOfAPhoneNum.java: -------------------------------------------------------------------------------- 1 | //recursion 2 | import java.util.*; 3 | 4 | public class LetterCombinationsOfAPhoneNum { 5 | private ArrayList result = new ArrayList(); 6 | private String[] letters = new String[10]; 7 | 8 | public ArrayList letterCombinations(String digits) { 9 | result = new ArrayList(); 10 | letters[0] = " "; 11 | letters[1] = ""; 12 | letters[2] = "abc"; 13 | letters[3] = "def"; 14 | letters[4] = "ghi"; 15 | letters[5] = "jkl"; 16 | letters[6] = "mno"; 17 | letters[7] = "pqrs"; 18 | letters[8] = "tuv"; 19 | letters[9] = "wxyz"; 20 | String st = ""; 21 | letterCombinationsRecursion(digits, 0, st); 22 | return result; 23 | } 24 | 25 | public void letterCombinationsRecursion(String digits, int n, String st) { 26 | if (n >= digits.length()) { 27 | result.add(st); 28 | return; 29 | } 30 | for (int i = 0; i < letters[digits.charAt(n) - '0'].length(); i++) { 31 | letterCombinationsRecursion(digits, n + 1, 32 | st + letters[digits.charAt(n) - '0'].charAt(i)); 33 | } 34 | 35 | } 36 | 37 | public static void main(String[] args) { 38 | LetterCombinationsOfAPhoneNum o = new LetterCombinationsOfAPhoneNum(); 39 | String s = "23"; 40 | System.out.println(o.letterCombinations(s)); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | //using binary tree idea to speed up the process 2 | 3 | public class LongestCommonPrefix { 4 | public String longestCommonPrefix(String[] strs) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (strs.length == 0) { 8 | return new String(); 9 | } 10 | return binary(0, strs.length - 1, strs); 11 | } 12 | 13 | public String commonPrefix(String st1, String st2) { 14 | if (st1.length() == 0 || st2.length() == 0) { 15 | return new String(); 16 | } 17 | int length = Math.min(st1.length(), st2.length()); 18 | int i = 0; 19 | for (i = 0; i < length; i++) { 20 | if (st1.charAt(i) != st2.charAt(i)) { 21 | break; 22 | } 23 | } 24 | return st1.substring(0, i); 25 | 26 | } 27 | 28 | public String binary(int s, int t, String[] strs) { 29 | if (s > t) { 30 | return null; 31 | } 32 | if (s == t) { 33 | return strs[s]; 34 | } 35 | return commonPrefix(binary(s, (s + t) / 2, strs), 36 | binary((s + t) / 2 + 1, t, strs)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | //LCS problem 2 | //DP:use a 2 dimensional array to represent the length of the longest subsequence ending at index i of string s and index j of string t 3 | //Situations: 4 | //matrix[i][j]= 1) 0 if i<0 || j<0 5 | // = 2) matrix[i-1][j-1] if x[i]=y[j] 6 | // = 3) Math.max(matrix[i-1][j],matrix[i][j-1]) 7 | // 8 | // 9 | 10 | public class LongestCommonSubsequence { 11 | public String longestCommonSubsequence(String s, String t) { 12 | if (s.length() == 0) { 13 | return new String(); 14 | } 15 | if (t.length() == 0) { 16 | return new String(); 17 | } 18 | int[][] matrix = new int[s.length()][t.length()]; 19 | calculateLongestLength(s,t,matrix); 20 | return constructLCS(s,t,matrix,s.length()-1,t.length()-1); 21 | 22 | } 23 | 24 | public void calculateLongestLength(String s, String t, int[][] matrix) { 25 | for (int i = 0; i < s.length(); i++) { 26 | for (int j = 0; j < t.length(); j++) { 27 | if (s.charAt(i) == t.charAt(j)) {// if match, try to find the 28 | // previous one(diagonal 29 | // direction) 30 | if (i == 0 || j == 0) { 31 | matrix[i][j] = 1; 32 | } else { 33 | matrix[i][j] = matrix[i - 1][j - 1] + 1; 34 | } 35 | } else {// if not match, try to search the top and left 36 | // directions 37 | if (i == 0 || j == 0) { 38 | matrix[i][j] = 0; 39 | } else { 40 | matrix[i][j] = Math.max(matrix[i - 1][j], 41 | matrix[i][j - 1]); 42 | } 43 | } 44 | 45 | } 46 | } 47 | } 48 | 49 | public String constructLCS(String s, String t, int[][] matrix, int i, int j) { 50 | StringBuilder sb = new StringBuilder(); 51 | if (i < 0 || j < 0) { 52 | return ""; 53 | } 54 | 55 | if (s.charAt(i) == t.charAt(j)) { 56 | constructLCS(s, t, matrix, i - 1, j - 1); 57 | sb.append(s.charAt(i)); 58 | } else { 59 | if (i == 0 || j == 0) { 60 | return sb.toString(); 61 | } 62 | if (matrix[i - 1][j] > matrix[i][j - 1]) { 63 | constructLCS(s, t, matrix, i - 1, j); 64 | } else if (matrix[i - 1][j] < matrix[i][j - 1]) { 65 | constructLCS(s, t, matrix, i, j - 1); 66 | } else { 67 | constructLCS(s, t, matrix, i - 1, j); 68 | constructLCS(s, t, matrix, i, j - 1); 69 | } 70 | 71 | } 72 | return sb.toString(); 73 | 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | //For two string s and t and length(s)=m length(t)=n: 2 | //there are two solutions for this problems 3 | //1).building the suffix tree O(n+m) 4 | //2).DP(use a two dimensional array to represent length of the longest substring ending at index i of s and index j of t 5 | //time complexity of this solution is O(n*m) 6 | //the following is the DP solution 7 | 8 | public class LongestCommonSubstring { 9 | public String longestCommonSubstring(String s, String t) { 10 | int[][] matrix = new int[s.length()][t.length()]; 11 | int maxLen = 0; 12 | int lastSubStart = 0; 13 | int currentSubStart = 0; 14 | StringBuilder sb = new StringBuilder(); 15 | for (int i = 0; i < s.length(); i++) { 16 | for (int j = 0; j < t.length(); j++) { 17 | if (s.charAt(i) == t.charAt(j)) {// character matching 18 | if (i == 0 || j == 0) {// initialize the first row and 19 | // column to 1 20 | matrix[i][j] = 1; 21 | } else { 22 | matrix[i][j] = matrix[i - 1][j - 1] + 1; 23 | } 24 | if (matrix[i][j] > maxLen) { 25 | maxLen = matrix[i][j];// update maxLen 26 | currentSubStart = i - matrix[i][j] + 1; 27 | if (currentSubStart == lastSubStart) {// if we are in 28 | // the same 29 | // substring 30 | sb.append(s.charAt(i)); 31 | } else {// we are creating a new substring, so we need 32 | // to clear sb first 33 | sb = new StringBuilder();// clear sb 34 | lastSubStart = currentSubStart; 35 | sb.append(s.subSequence(currentSubStart, i + 1));// append 36 | // current 37 | // longest 38 | // substring 39 | } 40 | 41 | } 42 | 43 | } 44 | } 45 | } 46 | return sb.toString(); 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | //basic idea: reverse the string and find the longest common substring between the original and reversed strings 2 | public class LongestPalindromicSubstring { 3 | public String longestPalindrome(String s) { 4 | if (s.length() == 0) { 5 | return new String(); 6 | } 7 | String t = reverseString(s); 8 | return longestCommonSubstring(s, t); 9 | } 10 | 11 | public String reverseString(String s) { 12 | if (s.length() == 0) { 13 | return new String(); 14 | } 15 | char[] charArray = s.toCharArray(); 16 | StringBuilder sb = new StringBuilder(); 17 | for (int i = charArray.length - 1; i >= 0; i--) { 18 | sb.append(charArray[i]); 19 | } 20 | return sb.toString(); 21 | } 22 | 23 | public String longestCommonSubstring(String s, String t) { 24 | int[][] matrix = new int[s.length()][t.length()]; 25 | int maxLen = 0; 26 | int lastSubStart = 0; 27 | int currentSubStart = 0; 28 | StringBuilder sb = new StringBuilder(); 29 | for (int i = 0; i < s.length(); i++) { 30 | for (int j = 0; j < t.length(); j++) { 31 | if (s.charAt(i) == t.charAt(j)) {// character matching 32 | if (i == 0 || j == 0) {// initialize the first row and 33 | // column to 1 34 | matrix[i][j] = 1; 35 | } else { 36 | matrix[i][j] = matrix[i - 1][j - 1] + 1; 37 | } 38 | if (matrix[i][j] > maxLen) { 39 | maxLen = matrix[i][j];// update maxLen 40 | currentSubStart = i - matrix[i][j] + 1; 41 | if (currentSubStart == lastSubStart) {// if we are in 42 | // the same 43 | // substring 44 | sb.append(s.charAt(i)); 45 | } else {// we are creating a new substring, so we need 46 | // to clear sb first 47 | sb = new StringBuilder();// clear sb 48 | lastSubStart = currentSubStart; 49 | sb.append(s.subSequence(currentSubStart, i + 1));// append 50 | // current 51 | // longest 52 | // substring 53 | } 54 | 55 | } 56 | 57 | } 58 | } 59 | } 60 | return sb.toString(); 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /LongestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | //assume this string only contains letters 2 | //maintain a stack of characters to represent current substring 3 | //use a boolean array map to indicate whether current character is in the array or not (like using a hashtable) 4 | 5 | import java.util.*; 6 | 7 | public class LongestSubstringWithoutRepeatingCharacters { 8 | public int lengthOfLongestSubstring(String s) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | if (s.length() == 0) { 12 | return 0; 13 | } 14 | boolean[] map = new boolean[26]; 15 | LinkedList currentSub = new LinkedList(); 16 | int maxLen = 0; 17 | for (int i = 0; i < s.length(); i++) { 18 | // System.out.println("char " + s.charAt(i)); 19 | if (map[s.charAt(i) - 'a']) { 20 | while (currentSub.peek() != s.charAt(i)) { 21 | map[currentSub.peek()-'a']=false; 22 | currentSub.poll(); 23 | } 24 | currentSub.poll(); 25 | currentSub.add(s.charAt(i)); 26 | } else { 27 | currentSub.add(s.charAt(i)); 28 | map[s.charAt(i) - 'a'] = true; 29 | } 30 | maxLen = currentSub.size() > maxLen ? currentSub.size() : maxLen; 31 | 32 | } 33 | return maxLen; 34 | 35 | } 36 | 37 | public static void main(String[] args) { 38 | LongestSubstringWithoutRepeatingCharacters o = new LongestSubstringWithoutRepeatingCharacters(); 39 | System.out.println(o.lengthOfLongestSubstring("facbadebbbbbbbb")); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /LongestValidParentheses.java: -------------------------------------------------------------------------------- 1 | //sum + 1 for left parenthese 2 | //sum - 1 for right parenthese 3 | //sum should be always >= 0 4 | 5 | public class LongestValidParentheses { 6 | public int longestValidParentheses(String s) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | int sum = 0; 10 | int maxLen = 0; 11 | int currentLen = 0; 12 | for(int i=0;i= 0; j--) { 27 | if (matrix[i][j] == '1') { 28 | newMatrix[i][j] = j < n - 1 ? newMatrix[i][j + 1] + 1 : 1; 29 | } else { 30 | newMatrix[i][j] = 0; 31 | } 32 | } 33 | } 34 | 35 | for (int i = 0; i < m; i++) { 36 | for (int j = 0; j < n; j++) { 37 | max = Math.max(max, maxArea(newMatrix, i, j)); 38 | // System.out.println("max: "+max); 39 | // System.out.println("i: "+i+"j: "+j+"max: "+max); 40 | } 41 | } 42 | return max; 43 | 44 | } 45 | 46 | public int maxArea(int[][] newMatrix, int lx, int ly) { 47 | if (lx < 0 || lx > newMatrix.length || ly < 0 48 | || ly > newMatrix[0].length) { 49 | return -1; 50 | } 51 | int m = newMatrix.length;// length 52 | int area = 0; 53 | int rx = lx; 54 | int ry = ly + newMatrix[rx][ly] - 1; 55 | while (rx < m - 1 && newMatrix[rx][ly] >= 1) {// go down until we reach 56 | // the second last one 57 | // or we meet a '0' 58 | area = Math.max(area, (ry - ly + 1) * (rx - lx + 1)); 59 | rx++;// update rx 60 | ry = Math.min(ry, ly + newMatrix[rx][ly] - 1);//update ry 61 | } 62 | if (newMatrix[rx][ly] >= 1)// update the last one if necessary 63 | area = Math.max(area, (ry - ly + 1) * (rx - lx + 1)); 64 | 65 | return area; 66 | } 67 | 68 | public static void main(String[] args) { 69 | MaximumRectangle o = new MaximumRectangle(); 70 | char[][] x = { { '1', '0', '0' }, { '1', '1', '1' } }; 71 | System.out.println(o.maximalRectangle(x)); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | //If the array has consecutive positive numbers, the maximum subarray cannot only have part of them, because adding the rest of them will make the subarray bigger 2 | //Similarly, if the array has consecutive negative numbers because the only reason why we need to put the negative numbers in the maximum subarray is it could connect two bigger positive numbers 3 | //Hence, we can merge the consecutive positive and negative numbers first 4 | //Then scan from left, we main a tempSum, if temSum<0,reset it 5 | import java.util.*; 6 | 7 | public class MaximumSubarray { 8 | public int maxSubArray(int[] A) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | ArrayList merge = new ArrayList(); 12 | merge = mergeConsecutive(A); 13 | for(int i=0;i mergeConsecutive(int[] A) { 36 | ArrayList merge = new ArrayList(); 37 | int sum = 0; 38 | boolean positive = false; 39 | if (A.length == 0) { 40 | return new ArrayList(); 41 | } 42 | if (A.length == 1) { 43 | merge.add(A[0]); 44 | return merge; 45 | } 46 | if (A[0] >= 0) { 47 | positive = true; 48 | } 49 | 50 | 51 | sum += A[0]; 52 | for (int i = 1; i < A.length - 1; i++) { 53 | if (A[i] >= 0) { 54 | if (positive) { 55 | sum += A[i]; 56 | } else { 57 | merge.add(sum); 58 | positive = true; 59 | sum = 0; 60 | sum += A[i]; 61 | 62 | } 63 | } else { 64 | if (!positive) { 65 | sum += A[i]; 66 | } else { 67 | System.out.println("sum"+sum); 68 | merge.add(sum); 69 | positive = false; 70 | sum = 0; 71 | sum += A[i]; 72 | 73 | } 74 | 75 | } 76 | } 77 | if (A[A.length - 1] >= 0) { 78 | if (positive) { 79 | sum += A[A.length - 1]; 80 | merge.add(sum); 81 | } else { 82 | merge.add(sum); 83 | merge.add(A[A.length - 1]); 84 | } 85 | } else { 86 | if (!positive) { 87 | sum += A[A.length - 1]; 88 | merge.add(sum); 89 | } else { 90 | merge.add(sum); 91 | merge.add(A[A.length - 1]); 92 | } 93 | } 94 | 95 | return merge; 96 | } 97 | 98 | public static void main(String[] args) { 99 | MaximumSubarray o = new MaximumSubarray(); 100 | int[] x = {31,-41,59,26,-53,58,97,-93,-23,84}; 101 | System.out.println(o.maxSubArray(x)); 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /MedianOfTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | public class MedianOfTwoSortedArrays { 2 | public double findMedianSortedArrays(int A[], int B[]) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int m = A.length; 6 | int n = B.length; 7 | if (m == 0 && n == 0) { 8 | return 0; 9 | } 10 | int i = 0; 11 | int j = 0; 12 | int s = (m + n) / 2; 13 | System.out.println(s); 14 | int m1 = -1; 15 | int m2 = -1; 16 | while (s >= 0) { 17 | int a = (i < m) ? A[i] : Integer.MAX_VALUE; 18 | int b = (j < n) ? B[j] : Integer.MAX_VALUE; 19 | m1 = m2; 20 | if (a < b) { 21 | m2 = a; 22 | i++; 23 | } else { 24 | m2 = b; 25 | j++; 26 | } 27 | s--; 28 | 29 | } 30 | if ((m + n) % 2 == 0) { 31 | return (m1 + m2) / 2.0; 32 | } 33 | return m2; 34 | } 35 | 36 | public static void main(String[] args) { 37 | MedianOfTwoSortedArrays o = new MedianOfTwoSortedArrays(); 38 | int[] A = {}; 39 | int[] B = {}; 40 | System.out.println(o.findMedianSortedArrays(A, B)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /MergeKSortedArrays.java: -------------------------------------------------------------------------------- 1 | //Given k sorted arrays of size n, merge them into one array 2 | /* 3 | Two ideas for this problem: 4 | 1. first, divide these k arrays to (k/2) groups, each group has 2n elements, do merge in each group, then we got 5 | k/2 arrays, similarly merge then (k/4) groups 6 | 2. use a min-heap 7 | */ 8 | import java.util.*; 9 | 10 | public class MergeKSortedArrays { 11 | // solution 1 12 | // public ArrayList mergeKSortedArrays( 13 | // ArrayList> lists) { 14 | // ArrayList result = new ArrayList(); 15 | // int k = lists.size(); 16 | // if (k == 0) { 17 | // return result; 18 | // } 19 | // int n = lists.get(0).size(); 20 | // if (n == 0) { 21 | // return result; 22 | // } 23 | // ArrayList> temp = new ArrayList>(); 24 | // while(k>1){ 25 | // temp = new ArrayList>(); 26 | // int x=k/2; 27 | // int y=k%2; 28 | // for(int i=0;i pair = 30 | // } 31 | // 32 | // } 33 | 34 | 35 | // } 36 | 37 | public ArrayList mergeTwoArrays(ArrayList a, 38 | ArrayList b) { 39 | if (a.size() != b.size()) { 40 | return null; 41 | } 42 | if (a.size() == 0) { 43 | return new ArrayList(); 44 | } 45 | ArrayList result = new ArrayList(); 46 | int len = a.size(); 47 | int ai = 0; 48 | int bi = 0; 49 | while (ai <= len - 1 && bi <= len - 1) { 50 | if (a.get(ai) <= b.get(bi)) { 51 | result.add(a.get(ai)); 52 | ai++; 53 | } else { 54 | result.add(b.get(bi)); 55 | bi++; 56 | } 57 | } 58 | boolean aEnd = (ai <= len - 1) ? true : false; 59 | if (aEnd) { 60 | for (int i = ai; i <= len - 1; i++) { 61 | result.add(a.get(i)); 62 | } 63 | } else { 64 | for (int j = bi; j <= len - 1; j++) { 65 | result.add(b.get(j)); 66 | } 67 | } 68 | return result; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /MergeKSortedLists.java: -------------------------------------------------------------------------------- 1 | //we use the number of null ListNodes in the ArrayList lists to indicate whether we have finished the merge 2 | import java.util.*; 3 | 4 | //class ListNode { 5 | // int val; 6 | // ListNode next; 7 | // 8 | // ListNode(int x) { 9 | // val = x; 10 | // next = null; 11 | // } 12 | //} 13 | 14 | public class MergeKSortedLists { 15 | public ListNode mergeKLists(ArrayList lists) { 16 | // Start typing your Java solution below 17 | // DO NOT{ write main() function 18 | int countNull = getNullListNumber(lists); 19 | // System.out.println("countNull" + countNull); 20 | System.out.println("size" + lists.size()); 21 | 22 | if (countNull == lists.size()) { 23 | return null; 24 | } 25 | if (lists.size() == 0) { 26 | return null; 27 | } 28 | int min = Integer.MAX_VALUE; 29 | int minLocation = 0; 30 | for (int i = 0; i < lists.size(); i++) { 31 | ListNode n = lists.get(i); 32 | if (n != null) { 33 | if (n.val < min) { 34 | min = n.val; 35 | minLocation = i; 36 | } 37 | } else { 38 | countNull++; 39 | } 40 | } 41 | ListNode minNode = lists.get(minLocation); 42 | // System.out.println("minLocation" + minLocation); 43 | minNode = minNode.next; 44 | if (minNode == null) { 45 | countNull++; 46 | } 47 | lists.set(minLocation, minNode); 48 | // System.out.println("minLoca" + minLocation); 49 | // 50 | // System.out.println("countNull2" + countNull); 51 | 52 | ListNode start = new ListNode(min); 53 | ListNode current = start; 54 | 55 | while (countNull < lists.size()) { 56 | // System.out.println("countNull3" + countNull); 57 | 58 | min = Integer.MAX_VALUE; 59 | minLocation = 0; 60 | for (int i = 0; i < lists.size(); i++) { 61 | ListNode n = lists.get(i); 62 | if (n != null) { 63 | if (n.val < min) { 64 | min = n.val; 65 | minLocation = i; 66 | } 67 | } else { 68 | countNull++; 69 | } 70 | } 71 | minNode = lists.get(minLocation); 72 | minNode = minNode.next; 73 | if (minNode == null) { 74 | countNull++; 75 | } 76 | lists.set(minLocation, minNode); 77 | ListNode newNode = new ListNode(min); 78 | current.next = newNode; 79 | current = newNode; 80 | 81 | } 82 | // System.out.println("min" + min); 83 | 84 | return start; 85 | 86 | } 87 | 88 | public int getNullListNumber(ArrayList lists) { 89 | int count = 0; 90 | for (int i = 0; i < lists.size(); i++) { 91 | if (lists.get(i) == null) { 92 | count++; 93 | } 94 | } 95 | return count; 96 | 97 | } 98 | 99 | public static void main(String[] args) { 100 | MergeKSortedLists o = new MergeKSortedLists(); 101 | ListNode a = new ListNode(1); 102 | ListNode b = new ListNode(2); 103 | ArrayList result = new ArrayList(); 104 | result.add(a); 105 | result.add(b); 106 | System.out.println(o.mergeKLists(result).next.next); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | //Given two sorted integer arrays A and B, merge B into A as one sorted array. 2 | //Note: 3 | //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. 4 | //merge B to the end of A, if all elements in B have been merged, then done 5 | 6 | public class MergeSortedArray { 7 | public void merge(int A[], int m, int B[], int n) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if (m == 0 && n > 0) { 11 | for (int i = 0; i < n; i++) { 12 | A[i] = B[i]; 13 | } 14 | return; 15 | } 16 | if (n == 0 && m > 0) { 17 | return; 18 | } 19 | int indexA = m - 1; 20 | int indexB = n - 1; 21 | int mergeIndex = m + n - 1; 22 | while (indexB >= 0) { 23 | if (indexA < 0) { 24 | break; 25 | } 26 | if (B[indexB] >= A[indexA]) { 27 | A[mergeIndex] = B[indexB]; 28 | indexB--; 29 | } else { 30 | A[mergeIndex] = A[indexA]; 31 | indexA--; 32 | } 33 | mergeIndex--; 34 | } 35 | if (indexA < 0) { 36 | for (int i = mergeIndex; i >= 0; i--) { 37 | A[i] = B[indexB]; 38 | indexB--; 39 | } 40 | } 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | //very similar with merge k sorted lists 2 | public class MergeTwoSortedLists { 3 | // public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 4 | // // Start typing your Java solution below 5 | // // DO NOT write main() function 6 | // 7 | // } 8 | } 9 | -------------------------------------------------------------------------------- /MinimumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | //The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 2 | //for tree like this: 3 | // 1 4 | // / 5 | // 2 6 | //we can think the right height of node 1 is Integer.MAX_VALUE 7 | 8 | public class MinimumDepthOfBinaryTree { 9 | public int minDepth(TreeNode root) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | if (root == null) { 13 | return 0; 14 | } 15 | if (root.left == null && root.right == null) {// reach the leaf 16 | return 1; 17 | } 18 | int leftHeight = Integer.MAX_VALUE; 19 | int rightHeight = Integer.MAX_VALUE; 20 | int height = 0; 21 | if (root.left != null) { 22 | leftHeight = minDepth(root.left) + 1; 23 | } 24 | if (root.right != null) { 25 | rightHeight = minDepth(root.right) + 1; 26 | } 27 | height = Math.min(leftHeight, rightHeight); 28 | return height; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | //DP 2 | public class MinimumPathSum { 3 | public int minPathSum(int[][] grid) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (grid.length == 0 || grid[0].length == 0) { 7 | return 0; 8 | } 9 | int[][] matrix = new int[grid.length][grid[0].length]; 10 | minPathSum(grid, 0, 0, matrix); 11 | return matrix[grid.length - 1][grid[0].length - 1]; 12 | } 13 | 14 | public void minPathSum(int[][] grid, int m, int n, int matrix[][]) { 15 | if (m > grid.length - 1 || n > grid[0].length - 1) { 16 | return; 17 | } 18 | if (m == 0 && n == 0) { 19 | matrix[m][n] = grid[m][n]; 20 | } else if (m == 0 && n > 0) { 21 | matrix[m][n] = matrix[m][n - 1] + grid[m][n]; 22 | } else if (n == 0 && m > 0) { 23 | matrix[m][n] = matrix[m - 1][n] + grid[m][n]; 24 | } else { 25 | matrix[m][n] = Math.min(matrix[m][n - 1], matrix[m - 1][n]) 26 | + grid[m][n]; 27 | } 28 | if (m < grid.length - 1) { 29 | minPathSum(grid, m + 1, n, matrix); 30 | } 31 | if (n < grid[0].length - 1) { 32 | minPathSum(grid, m, n + 1, matrix); 33 | 34 | } 35 | return; 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MinimumSumPath.java: -------------------------------------------------------------------------------- 1 | 2 | public class MinimumSumPath { 3 | public static int minPathSum(int[][] matrix){ 4 | int i;//for column 5 | int j;//for row 6 | 7 | for(i=1;i needToFind[(int) S 49 | .charAt(begin)]) { 50 | if (hasFound[(int) S.charAt(begin)] > needToFind[(int) S 51 | .charAt(begin)]) { 52 | hasFound[(int) S.charAt(begin)]--; 53 | } 54 | begin++; 55 | } 56 | int currentLen = end - begin + 1; 57 | if (currentLen < minLen) { 58 | minLen = currentLen; 59 | minBegin = begin; 60 | minEnd = end; 61 | } 62 | 63 | } 64 | 65 | } 66 | if (minBegin == -1) {// window not found 67 | return ""; 68 | } else { 69 | return S.substring(minBegin, minEnd + 1); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /MultiplyStrings.java: -------------------------------------------------------------------------------- 1 | //Given two numbers represented as strings, return multiplication of the numbers as a string. 2 | //Note: The numbers can be arbitrarily large and are non-negative. 3 | //We create another two help methods reverse and add 4 | 5 | public class MultiplyStrings { 6 | public String multiply(String num1, String num2) { 7 | if (num1.equals("0") || num2.equals("0")) { 8 | return "0"; 9 | } 10 | num1 = reverse(num1); 11 | num2 = reverse(num2); 12 | StringBuilder[] cum = new StringBuilder[10];// cum saves the multiple 13 | // times of num1 14 | cum[0] = new StringBuilder("0"); 15 | StringBuilder factor = new StringBuilder(); 16 | StringBuilder result = new StringBuilder(); 17 | StringBuilder num1Sb = new StringBuilder(num1); 18 | // System.out.println("size" + num1Sb.length()); 19 | for (int i = 1; i < 10; i++) {// initializaiton of cum 20 | cum[i] = add(cum[i - 1], num1Sb); 21 | } 22 | 23 | for (int i = 0; i < num2.length(); i++) { 24 | factor = new StringBuilder(); 25 | if (num2.charAt(i) == '0') {// if this digit of num2 is '0', just 26 | // skip it 27 | continue; 28 | } else { 29 | 30 | for (int j = 0; j < i; j++) { 31 | factor.append("0"); 32 | } 33 | factor.append(cum[num2.charAt(i) - '0']); 34 | 35 | } 36 | result = add(result, factor); 37 | } 38 | return reverse(result.toString()); 39 | } 40 | 41 | public String reverse(String s) { 42 | StringBuilder sb = new StringBuilder(); 43 | for (int i = s.length() - 1; i >= 0; i--) { 44 | sb.append(s.charAt(i)); 45 | } 46 | return sb.toString(); 47 | } 48 | 49 | public StringBuilder add(StringBuilder num1, StringBuilder num2) { 50 | if (num1.length() == 0 && num2.length() > 0) { 51 | return num2; 52 | } 53 | if (num2.length() == 0 && num1.length() > 0) { 54 | return num1; 55 | } 56 | int sum = 0; 57 | int carry = 0; 58 | StringBuilder sb = new StringBuilder(); 59 | int i = 0; 60 | for (i = 0; i < num1.length() && i < num2.length(); i++) { 61 | sum = (num1.charAt(i) - '0') + (num2.charAt(i) - '0') + carry; 62 | carry = sum / 10; 63 | sum = sum % 10; 64 | sb.append(String.valueOf(sum)); 65 | } 66 | if (i < num2.length()) {// if num2 is longer than num1 67 | num1 = num2; 68 | } 69 | for (; i < num1.length(); i++) { 70 | sum = num1.charAt(i) - '0' + carry; 71 | carry = sum / 10; 72 | sum = sum % 10; 73 | sb.append(String.valueOf(sum)); 74 | } 75 | if (carry > 0) { 76 | sb.append(String.valueOf(carry)); 77 | } 78 | return sb; 79 | 80 | } 81 | 82 | public static void main(String[] args) { 83 | MultiplyStrings o = new MultiplyStrings(); 84 | System.out.println(o.multiply("5", "1")); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /NQueens.java: -------------------------------------------------------------------------------- 1 | //DFS 2 | //use sol[] to indicate the column numbers of the solution(row by row) 3 | 4 | import java.util.*; 5 | //DFS 6 | public class NQueens { 7 | public ArrayList solveNQueens(int n) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if (n <= 0) { 11 | return new ArrayList(); 12 | } 13 | ArrayList result = new ArrayList(); 14 | int[] sol = new int[n];// indicate the column numbers of possible 15 | // solutions(row by row) 16 | placeQueen(sol, 0, result); 17 | return result; 18 | } 19 | 20 | public void placeQueen(int[] sol, int row, ArrayList result) { 21 | int n = sol.length; 22 | if (row == n) {// finish placing all n queens, so print the result 23 | String[] valid = transform(sol); 24 | result.add(valid); 25 | return; 26 | 27 | } 28 | 29 | for (int i = 0; i < n; i++) {// try to find a valid column for row 30 | if (feasible(sol, row, i)) { 31 | sol[row] = i; 32 | placeQueen(sol, row + 1, result); 33 | } 34 | } 35 | } 36 | 37 | public boolean feasible(int[] sol, int row, int col) { 38 | for (int i = 0; i < row; i++) { 39 | if (sol[i] == col) {// check column 40 | return false; 41 | } 42 | if (row - i == Math.abs(col - sol[i])) {// check diagonal 43 | return false; 44 | } 45 | } 46 | return true; 47 | 48 | } 49 | 50 | public String[] transform(int[] sol) { 51 | String[] validResult = new String[sol.length]; 52 | StringBuilder sb = new StringBuilder(); 53 | for (int i = 0; i < sol.length; i++) { 54 | sb = new StringBuilder(); 55 | for (int j = 0; j < sol.length; j++) { 56 | if (j == sol[i]) { 57 | sb.append("Q"); 58 | 59 | } else { 60 | sb.append("."); 61 | } 62 | } 63 | validResult[i] = sb.toString(); 64 | 65 | } 66 | return validResult; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /NQueensII.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class NQueensII { 4 | 5 | public int totalNQueens(int n) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (n <= 0) { 9 | return 0; 10 | } 11 | ArrayList result = new ArrayList(); 12 | int[] sol = new int[n];// indicate the column numbers of possible 13 | // solutions(row by row) 14 | placeQueen(sol, 0, result); 15 | return result.size(); 16 | } 17 | 18 | public void placeQueen(int[] sol, int row, ArrayList result) { 19 | int n = sol.length; 20 | if (row == n) {// finish placing all n queens, so print the result 21 | result.add(1); 22 | return; 23 | 24 | } 25 | 26 | for (int i = 0; i < n; i++) {// try to find a valid column for row 27 | if (feasible(sol, row, i)) { 28 | sol[row] = i; 29 | placeQueen(sol, row + 1, result); 30 | } 31 | } 32 | } 33 | 34 | public boolean feasible(int[] sol, int row, int col) { 35 | for (int i = 0; i < row; i++) { 36 | if (sol[i] == col) {// check column 37 | return false; 38 | } 39 | if (row - i == Math.abs(col - sol[i])) {// check diagonal 40 | return false; 41 | } 42 | } 43 | return true; 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /NextPermutation.java: -------------------------------------------------------------------------------- 1 | // http://en.wikipedia.org/wiki/Permutation 2 | //Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. 3 | //Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l. 4 | //Swap a[k] with a[l]. 5 | //Reverse the sequence from a[k + 1] up to and including the final element a[n]. 6 | // 7 | 8 | public class NextPermutation { 9 | public void nextPermutation(int[] num) { 10 | boolean found = false; 11 | int k = 0; 12 | int l = 0; 13 | 14 | if (num.length == 0 || num.length == 1) { 15 | return; 16 | } 17 | for (int i = num.length - 2; i >= 0; i--) { 18 | if (num[i] < num[i + 1]) { 19 | found = true; 20 | k = i; 21 | break; 22 | } 23 | } 24 | 25 | if (found == false) {// not found, the permutation is the last one,so 26 | // the next permutation is the reverse of it 27 | for (int i = 0; i < num.length / 2; i++) { 28 | swap(num, i, num.length - 1 - i); 29 | } 30 | return; 31 | } 32 | 33 | for (int i = num.length - 1; i > k; i--) { 34 | if (num[i] > num[k]) { 35 | l = i; 36 | break; 37 | } 38 | } 39 | 40 | swap(num, k, l); 41 | System.out.println(num[0]); 42 | reverse(num, k + 1, num.length - 1); 43 | return; 44 | 45 | } 46 | 47 | public void swap(int[] num, int m, int n) { 48 | int temp = num[m]; 49 | num[m] = num[n]; 50 | num[n] = temp; 51 | } 52 | 53 | public void reverse(int[] num, int m, int n) { 54 | 55 | int len = n - m + 1; 56 | for (int i = 1; i <= len / 2; i++) { 57 | swap(num, m + i - 1, n - i + 1); 58 | } 59 | 60 | } 61 | 62 | public static void main(String[] args) { 63 | NextPermutation o = new NextPermutation(); 64 | int[] a = { 2, 2, 7, 5, 4, 3, 2, 2, 1 }; 65 | o.nextPermutation(a); 66 | for (int i = 0; i < a.length; i++) 67 | System.out.print(a[i]); 68 | 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /OddOccurenceStringFinding.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string array, there is only one string occurring odd times, and all the others occur even times 3 | find this string which occurs odd times 4 | 5 | Number them based on their serial number, then XOR all this numbers 6 | */ 7 | import java.util.*; 8 | 9 | public class OddOccurenceStringFinding { 10 | public String oddOccur(String[] words) { 11 | if (words.length == 0) { 12 | return null; 13 | } 14 | if (words.length == 1) { 15 | return words[0]; 16 | } 17 | Hashtable hash = new Hashtable(); 18 | ArrayList nums = new ArrayList(); 19 | int serial = 0; 20 | int target = 0; 21 | for (int i = 0; i < words.length; i++) { 22 | if (!hash.containsKey(words[i])) { 23 | hash.put(words[i], serial); 24 | nums.add(serial); 25 | serial++; 26 | } else { 27 | nums.add(hash.get(words[i])); 28 | } 29 | } 30 | 31 | for (int j = 0; j < nums.size(); j++) { 32 | target = target ^ nums.get(j); 33 | } 34 | 35 | for (String k : hash.keySet()) { 36 | if (hash.get(k) == target) { 37 | return k; 38 | } 39 | } 40 | return null; 41 | } 42 | 43 | public static void main(String[] args){ 44 | OddOccurenceStringFinding o = new OddOccurenceStringFinding(); 45 | String[] words ={"a","a","b","b","d",}; 46 | System.out.println(o.oddOccur(words)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | public class PalindromeNumber { 2 | public boolean isPalindrome(int x) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if (x < 0) { 6 | return false; 7 | } 8 | if (x < 10) { 9 | return true; 10 | } 11 | 12 | int len = 0; 13 | while ((int) (x / Math.pow(10.0, len)) != 0) { 14 | len++; 15 | } 16 | for (int i = 0; i < len / 2; i++) { 17 | if ((int) (x / Math.pow(10.0, i)) % 10 != (int) (x / Math.pow(10.0, 18 | len - 1 - i)) % 10) { 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | 25 | } 26 | 27 | public static void main(String[] args) { 28 | PalindromeNumber o = new PalindromeNumber(); 29 | System.out.println(o.isPalindrome(11)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /PalindromePartitioning.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 | DFS 15 | 16 | */ 17 | import java.util.*; 18 | public class PalindromePartitioning { 19 | public ArrayList> res = new ArrayList>(); 20 | public ArrayList> partition(String s) { 21 | // Start typing your Java solution below 22 | // DO NOT write main() function 23 | res = new ArrayList>(); 24 | if(s.length()==0){ 25 | return res; 26 | } 27 | ArrayList sol = new ArrayList(); 28 | dfs(s,0,sol); 29 | return res; 30 | } 31 | public void dfs(String s, int b, ArrayList sol){ 32 | if(b>=s.length()){ 33 | res.add(new ArrayList(sol)); 34 | } 35 | for(int i=b;i<=s.length()-1;i++){ 36 | if(isPalindrome(s,b,i)){ 37 | sol.add(s.substring(b,i+1)); 38 | dfs(s,i+1,sol); 39 | sol.remove(sol.size()-1); 40 | } 41 | } 42 | } 43 | public boolean isPalindrome(String s, int b, int e){ 44 | if(b>e){ 45 | return false; 46 | } 47 | while(b> generate(int numRows) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | ArrayList> result = new ArrayList>(); 16 | generate(numRows, result); 17 | return result; 18 | } 19 | 20 | public void generate(int numRows, ArrayList> result) { 21 | ArrayList level = new ArrayList(); 22 | ArrayList prevLevel; 23 | if (numRows <= 0) { 24 | return; 25 | } 26 | if (numRows == 1) { 27 | // level 1 28 | level.add(1); 29 | result.add(level); 30 | } else if (numRows == 2) { 31 | // level 1 32 | level.add(1); 33 | result.add(level); 34 | // level 2 35 | level = new ArrayList(); 36 | level.add(1); 37 | level.add(1); 38 | result.add(level); 39 | } 40 | // for level>=3 41 | else { 42 | // level 1 43 | level.add(1); 44 | result.add(level); 45 | // level 2 46 | level = new ArrayList(); 47 | level.add(1); 48 | level.add(1); 49 | result.add(level); 50 | for (int i = 2; i <= numRows - 1; i++) { 51 | level = new ArrayList(); 52 | prevLevel = result.get(i - 1); 53 | level.add(1); 54 | for (int j = 1; j <= i - 1; j++) { 55 | int currentElement = prevLevel.get(j - 1) 56 | + prevLevel.get(j); 57 | level.add(currentElement); 58 | } 59 | level.add(1); 60 | result.add(level); 61 | } 62 | } 63 | return; 64 | 65 | } 66 | 67 | public static void main(String[] args) { 68 | PascalTriangle o = new PascalTriangle(); 69 | System.out.println(o.generate(10)); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /PascalTriangleII.java: -------------------------------------------------------------------------------- 1 | //only the previous line will affect the value of current line 2 | 3 | import java.util.*; 4 | 5 | public class PascalTriangleII { 6 | public ArrayList getRow(int rowIndex) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | ArrayList currentLine = new ArrayList(); 10 | ArrayList prevLine = new ArrayList(); 11 | 12 | if (rowIndex < 0) { 13 | return new ArrayList(); 14 | } else if (rowIndex == 0) { 15 | currentLine.add(1); 16 | return currentLine; 17 | } else { 18 | prevLine.add(1);// line 1 19 | for (int i = 1; i <= rowIndex; i++) { 20 | currentLine = new ArrayList(); 21 | currentLine.add(1); 22 | for (int j = 1; j <= i - 1; j++) { 23 | int currentElement = prevLine.get(j - 1) + prevLine.get(j); 24 | currentLine.add(currentElement); 25 | } 26 | currentLine.add(1); 27 | prevLine = currentLine; 28 | } 29 | return currentLine; 30 | } 31 | 32 | } 33 | 34 | public static void main(String[] args) { 35 | PascalTriangleII o = new PascalTriangleII(); 36 | System.out.println(o.getRow(1)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /PathSum.java: -------------------------------------------------------------------------------- 1 | public class PathSum { 2 | public boolean hasPathSum(TreeNode root, int sum) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | PartialSum ps = new PartialSum(0); 6 | return hasPathSum(root, ps, sum); 7 | 8 | } 9 | 10 | public boolean hasPathSum(TreeNode root, PartialSum ps, int sum) { 11 | if (root == null) { 12 | return false; 13 | } 14 | ps = new PartialSum(ps.val + root.val); 15 | if (root.left == null && root.right == null) { 16 | 17 | if (ps.val == sum) { 18 | return true; 19 | } else { 20 | return false; 21 | } 22 | } 23 | return hasPathSum(root.left, ps, sum) 24 | || hasPathSum(root.right, ps, sum); 25 | 26 | } 27 | 28 | class PartialSum { 29 | int val; 30 | 31 | PartialSum(int v) { 32 | val = v; 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | TreeNode root = new TreeNode(1); 38 | root.left = new TreeNode(-2); 39 | root.right = new TreeNode(-3); 40 | root.left.left = new TreeNode(1); 41 | root.left.right = new TreeNode(3); 42 | root.right.left = new TreeNode(-2); 43 | root.left.left.left = new TreeNode(-1); 44 | PathSum o = new PathSum(); 45 | System.out.println(o.hasPathSum(root, -3)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /PathSumII.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PathSumII { 4 | public ArrayList> pathSum(TreeNode root, int sum) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | ArrayList level = new ArrayList(); 8 | ArrayList> result = new ArrayList>(); 9 | PartialSum ps = new PartialSum(0); 10 | pathSum(root, ps, result, level, sum); 11 | return result; 12 | } 13 | 14 | @SuppressWarnings("unchecked") 15 | public void pathSum(TreeNode root, PartialSum ps, 16 | ArrayList> result, ArrayList level, 17 | int sum) { 18 | if (root == null){ 19 | return; 20 | } 21 | ArrayList newLevel = (ArrayList) level.clone(); 22 | newLevel.add(root.val); 23 | ps = new PartialSum(ps.val + root.val); 24 | if (root.left == null && root.right == null) { 25 | if (ps.val == sum) { 26 | result.add(newLevel); 27 | } 28 | return; 29 | } 30 | pathSum(root.left, ps, result, newLevel, sum); 31 | pathSum(root.right, ps, result, newLevel, sum); 32 | 33 | return; 34 | 35 | } 36 | 37 | class PartialSum { 38 | int val; 39 | 40 | PartialSum(int v) { 41 | val = v; 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | TreeNode root = new TreeNode(1); 47 | root.left = new TreeNode(-2); 48 | root.right = new TreeNode(3); 49 | 50 | PathSumII o = new PathSumII(); 51 | System.out.println(o.pathSum(root, -1).get(0)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /PermutationSequence.java: -------------------------------------------------------------------------------- 1 | //idea comes from:https://github.com/zwxxx/LeetCode/blob/825fe4c23fd108675f4e7d41d0130cb3a556ff3b/Permutation_Sequence.cpp 2 | //For set [1,2,3,...,n], there are a total of n! unique permutations. 3 | //Then we know there are n!/n=(n-1)! permutations start with 1, n!/n=(n-1)! 4 | //permutations start with 2, etc. 5 | //To get the kth permutation, We start by locating the digit from left 6 | //to right. 7 | //For n = 9, there are 362880 unique permutations. 8 | //1 - 40320 starts with 1 9 | //40321 - 80640 starts with 2 10 | //80641 - 120960 starts with 3 11 | 12 | //another idea is to do "find the next permutation" operation k-1 times 13 | import java.util.*; 14 | 15 | public class PermutationSequence { 16 | public String getPermutation(int n, int k) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | if (k > factorial(n) || k <= 0 || n <= 0) { 20 | return new String(); 21 | } 22 | StringBuilder sb = new StringBuilder(); 23 | ArrayList num = new ArrayList(); 24 | for (int i = 1; i <= n; i++) { 25 | num.add(i); 26 | } 27 | System.out.println("size" + num.size()); 28 | 29 | int[] factor = new int[n];// store factorial result to speed up 30 | for (int i = 0; i <= n - 1; i++) { 31 | factor[i] = factorial(i); 32 | } 33 | 34 | // determine the permutation digit by digit 35 | for (int i = 0; i < n; i++) { 36 | int f = factor[n - i - 1]; 37 | int j = 0; 38 | while (j * f < k) { 39 | j++; 40 | } 41 | j--; 42 | k -= j * f; 43 | sb.append(String.valueOf(num.get(j))); 44 | num.remove(j); 45 | 46 | } 47 | return sb.toString(); 48 | 49 | } 50 | 51 | public int factorial(int n) { 52 | if (n < 0) { 53 | return -1; 54 | } 55 | int result = 1; 56 | if (n == 0) { 57 | return 1; 58 | } else { 59 | for (int i = 1; i <= n; i++) { 60 | result = result * i; 61 | } 62 | return result; 63 | } 64 | 65 | } 66 | 67 | public static void main(String[] args) { 68 | PermutationSequence o = new PermutationSequence(); 69 | System.out.println(o.getPermutation(9, 214267)); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /Permutations.java: -------------------------------------------------------------------------------- 1 | //idea comes from: https://github.com/anson627/leetcode/blob/master/Permutations/src/Permutations.cpp 2 | //All permutations can be generated by swapping 3 | import java.util.*; 4 | 5 | public class Permutations { 6 | public ArrayList> permute(int[] num) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | ArrayList> result = new ArrayList>(); 10 | permuteHelper(result, num, 0); 11 | return result; 12 | } 13 | 14 | public void permuteHelper(ArrayList> result, int[] num, 15 | int i) { 16 | if (i < 0) { 17 | return; 18 | } 19 | if (i == num.length) { 20 | ArrayList permutation = arrayToArrayList(num); 21 | result.add(permutation); 22 | } else { 23 | for (int j = i; j < num.length; j++) {// use swap to generate 24 | // permutations 25 | swap(num, i, j); 26 | permuteHelper(result, num, i + 1); 27 | swap(num, i, j); 28 | } 29 | 30 | } 31 | return; 32 | } 33 | 34 | public void swap(int[] num, int i, int j) { 35 | int temp = num[i]; 36 | num[i] = num[j]; 37 | num[j] = temp; 38 | } 39 | 40 | public ArrayList arrayToArrayList(int[] num) { 41 | ArrayList result = new ArrayList(); 42 | for (int i = 0; i < num.length; i++) { 43 | result.add(num[i]); 44 | } 45 | return result; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /PermutationsII.java: -------------------------------------------------------------------------------- 1 | //similar with the problem Permutations, the only difference is we use a hashtable to indicate whether this permutation is unique or not 2 | import java.util.*; 3 | 4 | public class PermutationsII { 5 | public ArrayList> permuteUnique(int[] num) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | 9 | ArrayList> result = new ArrayList>(); 10 | Hashtable occur = new Hashtable(); 11 | permuteHelper(result, num, 0, occur); 12 | return result; 13 | } 14 | 15 | public void permuteHelper(ArrayList> result, int[] num, 16 | int i, Hashtable occur) { 17 | if (i < 0) { 18 | return; 19 | } 20 | if (i == num.length) { 21 | ArrayList permutation = arrayToArrayList(num); 22 | String perm = arrayToString(num); 23 | if (!occur.containsKey(perm)) { 24 | result.add(permutation); 25 | occur.put(perm, true); 26 | } 27 | 28 | } else { 29 | for (int j = i; j < num.length; j++) {// use swap to generate 30 | // permutations 31 | swap(num, i, j); 32 | permuteHelper(result, num, i + 1, occur); 33 | swap(num, i, j); 34 | } 35 | 36 | } 37 | return; 38 | } 39 | 40 | public void swap(int[] num, int i, int j) { 41 | int temp = num[i]; 42 | num[i] = num[j]; 43 | num[j] = temp; 44 | } 45 | 46 | public ArrayList arrayToArrayList(int[] num) { 47 | ArrayList result = new ArrayList(); 48 | for (int i = 0; i < num.length; i++) { 49 | result.add(num[i]); 50 | } 51 | return result; 52 | } 53 | 54 | public String arrayToString(int[] num) { 55 | StringBuilder sb = new StringBuilder(); 56 | for (int i = 0; i < num.length; i++) { 57 | sb.append(String.valueOf(num[i])); 58 | } 59 | return sb.toString(); 60 | } 61 | 62 | public static void main(String[] args) { 63 | PermutationsII o = new PermutationsII(); 64 | int[] num = { 1, 2 }; 65 | System.out.println(o.permuteUnique(num)); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /PlusOne.java: -------------------------------------------------------------------------------- 1 | 2 | public class PlusOne { 3 | public int[] plusOne(int[] digits) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | int carry = 1; 7 | int temp; 8 | boolean needMoreDigit = true; 9 | for (int i = digits.length - 1; i >= 0; i--) { 10 | temp = (digits[i] + carry) % 10; 11 | // System.out.println("i "+i+"temp "+temp); 12 | carry = (digits[i] + carry) / 10; 13 | digits[i] = temp; 14 | if (carry == 0) { 15 | needMoreDigit = false; 16 | break; 17 | } 18 | } 19 | // System.out.println("nn"+needMoreDigit); 20 | if (!needMoreDigit) { 21 | return digits; 22 | } else { 23 | int[] newDigits = new int[digits.length + 1]; 24 | newDigits[0] = carry; 25 | for (int i = 1; i <= digits.length; i++) { 26 | newDigits[i] = digits[i - 1]; 27 | } 28 | return newDigits; 29 | } 30 | 31 | } 32 | public static void main(String[] args){ 33 | PlusOne o = new PlusOne(); 34 | int[]digits = {9,8,7,6,5,4,3,2,1,0}; 35 | int[] result = o.plusOne(digits); 36 | for(int i=0;i 0) { 20 | if (n % 2 == 0) { 21 | double t = pow(x, n / 2);// for even number, do it as binary 22 | return t * t; 23 | } else { 24 | return pow(x, n - 1) * x;// for odd number, just minus one to 25 | // have a even number 26 | } 27 | } else { 28 | if (n % 2 == 0) { 29 | double t = pow(x, n / 2); 30 | return t * t; 31 | } else { 32 | if (n == Integer.MIN_VALUE) { 33 | return 1 / (pow(x, Integer.MAX_VALUE) * x); 34 | } else { 35 | return 1 / (pow(x, -n - 1) * x); 36 | } 37 | } 38 | } 39 | 40 | } 41 | 42 | public static void main(String[] args) { 43 | Power o = new Power(); 44 | double x = 2.0; 45 | int n = -2; 46 | System.out.println(o.pow(x, n)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Leetcode 2 | ======== 3 | Author:Yisong Wang 4 | 5 | -------------------------------------------------------------------------------- /RecoverBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /*if swap two neighbor nodes,then there are two nodes which don't meet the BST requirement, 2 | * otherwise, there are three nodes which don't meet the BST requirement 3 | * We use an ArrayList to save these nodes and swap the first and last element in the ArrayList 4 | */ 5 | 6 | import java.util.*; 7 | 8 | public class RecoverBinarySearchTree { 9 | public void recoverTree(TreeNode root) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | if (root == null) { 13 | return; 14 | } 15 | ArrayList unsort = new ArrayList(); 16 | recoverTreeHelper(root, unsort); 17 | swap(unsort.get(0), unsort.get(unsort.size() - 1)); 18 | } 19 | 20 | public void recoverTreeHelper(TreeNode root, ArrayList unsort) { 21 | if (root == null) { 22 | return; 23 | } 24 | if (!isBSTNode(root)) { 25 | unsort.add(root); 26 | System.out.println("unsort " + root.val); 27 | if (unsort.size() == 3) { 28 | return; 29 | } 30 | } 31 | recoverTreeHelper(root.left, unsort); 32 | recoverTreeHelper(root.right, unsort); 33 | return; 34 | } 35 | 36 | public boolean isBSTNode(TreeNode root) { 37 | if (root == null) { 38 | return true; 39 | } 40 | int leftVal = Integer.MIN_VALUE; 41 | int rightVal = Integer.MAX_VALUE; 42 | if (root.left != null) { 43 | leftVal = root.left.val; 44 | } 45 | if (root.right != null) { 46 | rightVal = root.right.val; 47 | } 48 | return (root.val <= rightVal) && (root.val >= leftVal); 49 | 50 | } 51 | 52 | public void swap(TreeNode a, TreeNode b) { 53 | int temp = a.val; 54 | a.val = b.val; 55 | b.val = temp; 56 | } 57 | 58 | public static void main(String[] args) { 59 | TreeNode root = new TreeNode(5); 60 | root.left = new TreeNode(8); 61 | root.right = new TreeNode(10); 62 | root.left.left = new TreeNode(3); 63 | root.left.right = new TreeNode(6); 64 | root.right.left = new TreeNode(9); 65 | root.right.right = new TreeNode(11); 66 | root.left.left.left = new TreeNode(1); 67 | root.left.left.right = new TreeNode(4); 68 | root.left.right.right = new TreeNode(7); 69 | RecoverBinarySearchTree o = new RecoverBinarySearchTree(); 70 | o.recoverTree(root); 71 | System.out.println(root.val); 72 | System.out.println(root.left.val); 73 | System.out.println(root.right.val); 74 | System.out.println(root.left.left.val); 75 | System.out.println(root.left.right.val); 76 | System.out.println(root.right.left.val); 77 | System.out.println(root.right.right.val); 78 | System.out.println(root.left.left.left.val); 79 | System.out.println(root.left.left.right.val); 80 | System.out.println(root.left.right.right.val); 81 | 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /RegularExpressionMatching.java: -------------------------------------------------------------------------------- 1 | /*it's meaningless to have such regular expression: *. 2 | '.' Matches any single character. 3 | '*' Matches zero or more of the preceding element 4 | '*' cannont be the first element 5 | 6 | idea come from:http://blog.csdn.net/hopeztm/article/details/7992253 7 | use dp[i][j] to indicate s[1..len(s)] could match p[1..len(p)] 8 | dp[i][j]= 9 | 1).when p[j+1] != '*': if s[i] == p[i], dp[i][j]=dp[i+1][j+1],else dp[i][j]=false 10 | 2).when p[j+1] == '*': expand '*' 11 | 12 | Use recursion 13 | 14 | */ 15 | 16 | public class RegularExpressionMatching { 17 | public boolean isMatch(String s, String p) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | return isMatch(s, 0, p, 0); 21 | } 22 | 23 | public boolean isMatch(String s, int indexS, String p, int indexP) { 24 | if (indexP >= p.length() - 1) { 25 | return indexS == s.length() - 1; 26 | } 27 | System.out.println("indexSaa " + indexS); 28 | System.out.println("indexPaa " + indexP); 29 | System.out.println(p.charAt(indexP + 1)); 30 | if (p.charAt(indexP + 1) != '*') { 31 | System.out.println("begin"); 32 | if (indexS <= s.length() - 1 && indexP <= p.length() - 1 33 | && p.charAt(indexP) == s.charAt(indexS) 34 | || (p.charAt(indexP) == '.' && indexS <= s.length() - 1)) { 35 | return isMatch(s, indexS + 1, p, indexP + 1); 36 | } 37 | return false; 38 | } else { 39 | // expand * 40 | System.out.println("indexS " + indexS); 41 | System.out.println("indexP " + indexP); 42 | while (indexS <= s.length() - 1 && indexP <= p.length() - 1 43 | && p.charAt(indexP) == s.charAt(indexS) 44 | || (p.charAt(indexP) == '.' && indexS <= s.length() - 1)) { 45 | if (isMatch(s, indexS, p, indexP + 2)) { 46 | return true; 47 | } 48 | 49 | indexS++; 50 | } 51 | return isMatch(s, indexS, p, indexP + 2); 52 | } 53 | 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | //pay attention to the ending part 2 | import java.util.*; 3 | 4 | public class RemoveDuplicatesFromSortedArray { 5 | public int removeDuplicates(int[] A) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (A.length == 0) { 9 | return 0; 10 | } 11 | if (A.length == 1) { 12 | return 1; 13 | } 14 | int counter = 0; 15 | for (int i = 1; i <= A.length - 1; i++) { 16 | if (A[i] != A[i - 1]) { 17 | A[counter] = A[i - 1]; 18 | counter++; 19 | } 20 | } 21 | A[counter] = A[A.length - 1]; 22 | counter++; 23 | A = Arrays.copyOf(A, counter); 24 | return counter; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /RemoveDuplicatesFromSortedList.java: -------------------------------------------------------------------------------- 1 | //pay attention to special case: it contains only one repeating number, e.g. {1,1};{1,1,1} 2 | public class RemoveDuplicatesFromSortedList { 3 | public ListNode deleteDuplicates(ListNode head) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (head == null) { 7 | return null; 8 | } 9 | if (head.next == null) { 10 | return head; 11 | } 12 | ListNode saveHead = head; 13 | ListNode runner = head; 14 | 15 | while (runner.next != null) { 16 | if (runner.val != runner.next.val && runner.val != saveHead.val) { 17 | head.next = new ListNode(runner.val); 18 | head = head.next; 19 | } 20 | runner = runner.next; 21 | } 22 | if (runner.val != saveHead.val) { 23 | head.next = new ListNode(runner.val); 24 | head = head.next; 25 | head.next = null; 26 | } else { 27 | head.next = null; 28 | } 29 | return saveHead; 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /RemoveDuplicatesFromSortedListII.java: -------------------------------------------------------------------------------- 1 | //The key is to try to find the first unique node and pay attention to the ending part 2 | public class RemoveDuplicatesFromSortedListII { 3 | public ListNode deleteDuplicates(ListNode head) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (head == null) { 7 | return null; 8 | } 9 | if (head.next == null) { 10 | return head; 11 | } 12 | ListNode saveHead; 13 | ListNode runner; 14 | boolean duplicate = false; 15 | 16 | // try to find the first unique node 17 | while (head.next != null) { 18 | if (head.val == head.next.val) { 19 | duplicate = true; 20 | } else { 21 | if (!duplicate) { 22 | break; 23 | } else { 24 | duplicate = false; 25 | } 26 | 27 | } 28 | head = head.next; 29 | 30 | } 31 | if (head.next == null) { 32 | if (!duplicate) { 33 | return head; 34 | } else { 35 | return null;// all nodes are duplicate nodes 36 | } 37 | } else { 38 | saveHead = head; 39 | runner = head; 40 | } 41 | 42 | while (runner.next != null) { 43 | if (runner.val == runner.next.val) { 44 | duplicate = true; 45 | } else { 46 | if (!duplicate && runner.val != saveHead.val) { 47 | head.next = new ListNode(runner.val); 48 | head = head.next; 49 | } 50 | duplicate = false; 51 | } 52 | runner = runner.next; 53 | } 54 | 55 | if (!duplicate) { 56 | head.next = new ListNode(runner.val); 57 | head = head.next; 58 | head.next = null; 59 | } else { 60 | head.next = null; 61 | } 62 | return saveHead; 63 | } 64 | 65 | public static void main(String[] args) { 66 | RemoveDuplicatesFromSortedListII o = new RemoveDuplicatesFromSortedListII(); 67 | ListNode head = new ListNode(1); 68 | head.next = new ListNode(1); 69 | head.next.next = new ListNode(2); 70 | head.next.next.next = null; 71 | // System.out.println("head" + head.val); 72 | System.out.println(o.deleteDuplicates(head).val); 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /RemoveElement.java: -------------------------------------------------------------------------------- 1 | //easy 2 | 3 | public class RemoveElement { 4 | public int removeElement(int[] A, int elem) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (A.length == 0) { 8 | return 0; 9 | } 10 | int counter = 0; 11 | for (int i = 0; i < A.length; i++) { 12 | if (A[i] != elem) { 13 | A[counter] = A[i]; 14 | counter++; 15 | } 16 | } 17 | return counter; 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RemoveNthNodeFromEndOfList.java: -------------------------------------------------------------------------------- 1 | //assume n is always valid 2 | //use fast-slow runner strategy 3 | //pay attention to delete the first node 4 | 5 | public class RemoveNthNodeFromEndOfList { 6 | public ListNode removeNthFromEnd(ListNode head, int n) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | ListNode saveHead = head; 10 | ListNode fast = head; 11 | for (int i = 1; i <= n; i++) { 12 | fast = fast.next; 13 | } 14 | if (fast == null) { 15 | saveHead = saveHead.next; 16 | return saveHead; 17 | } 18 | while (fast.next != null) { 19 | head = head.next; 20 | fast = fast.next; 21 | } 22 | if (head.next != null) { 23 | head.next = head.next.next; 24 | } else { 25 | head.next = null; 26 | } 27 | 28 | return saveHead; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /RestoreIPAddresses.java: -------------------------------------------------------------------------------- 1 | //DP 2 | import java.util.*; 3 | 4 | public class RestoreIPAddresses { 5 | // solution 1 6 | public ArrayList restoreIpAddresses(String s) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | if (s.length() == 0) { 10 | return new ArrayList(); 11 | } 12 | ArrayList result = new ArrayList(); 13 | StringBuilder sb = new StringBuilder(); 14 | restoreIpAddressesHelper(s, 0, sb, result, 0); 15 | return result; 16 | } 17 | 18 | public void restoreIpAddressesHelper(String s, int index, StringBuilder sb, 19 | ArrayList result, int counter) { 20 | // StringBuilder sbLocal = new StringBuilder(); 21 | if (counter > 4) {// to speed up 22 | return; 23 | } 24 | if (index >= s.length()) { 25 | if (counter == 4) { 26 | sb.deleteCharAt(sb.length() - 1);// delete '.' 27 | result.add(sb.toString()); 28 | } 29 | return; 30 | } 31 | if (index <= s.length() - 1) { 32 | if (isValidIPAddress(s.substring(index, index + 1))) { 33 | 34 | StringBuilder sbLocal = copySB(sb); 35 | 36 | sbLocal.append(s.substring(index, index + 1) + "."); 37 | restoreIpAddressesHelper(s, index + 1, sbLocal, result, 38 | counter + 1); 39 | } else { 40 | return; 41 | } 42 | } 43 | if (index <= s.length() - 2) { 44 | if (isValidIPAddress(s.substring(index, index + 2))) { 45 | 46 | StringBuilder sbLocal = copySB(sb); 47 | 48 | sbLocal.append(s.substring(index, index + 2) + "."); 49 | restoreIpAddressesHelper(s, index + 2, sbLocal, result, 50 | counter + 1); 51 | } else { 52 | return; 53 | } 54 | } 55 | if (index <= s.length() - 3) { 56 | if (isValidIPAddress(s.substring(index, index + 3))) { 57 | StringBuilder sbLocal = copySB(sb); 58 | sbLocal.append(s.substring(index, index + 3) + "."); 59 | restoreIpAddressesHelper(s, index + 3, sbLocal, result, 60 | counter + 1); 61 | } else { 62 | return; 63 | } 64 | } 65 | return; 66 | 67 | } 68 | 69 | public boolean isValidIPAddress(String s) { 70 | if (s.length() == 0 || s.length() > 3 71 | || (s.charAt(0) == '0' && s.length() != 1)) { 72 | return false; 73 | } 74 | int value = Integer.parseInt(s); 75 | return value >= 0 && value <= 255; 76 | } 77 | 78 | public StringBuilder copySB(StringBuilder sb) { 79 | StringBuilder newsb = new StringBuilder(); 80 | for (int i = 0; i < sb.length(); i++) { 81 | newsb.append(sb.charAt(i)); 82 | } 83 | return newsb; 84 | } 85 | 86 | // solution2 87 | public ArrayList restoreIpAddresses2(String s) { 88 | // Start typing your Java solution below 89 | // DO NOT write main() function 90 | ArrayList result = new ArrayList(); 91 | if (s.length() < 4 || s.length() > 16) { 92 | return result; 93 | } 94 | for (int i = 1; i <= s.length(); i++) { 95 | if (!isValid(s, 0, i)) { 96 | break; 97 | } 98 | 99 | for (int j = i + 1; j <= s.length(); j++) { 100 | if (!isValid(s, i, j)) { 101 | break; 102 | } 103 | 104 | for (int k = j + 1; k <= s.length(); k++) { 105 | 106 | if ((!isValid(s, j, k)) || (!isValid(s, k, s.length()))) { 107 | continue; 108 | } 109 | result.add(s.substring(0, i) + "." + s.substring(i, j) 110 | + "." + s.substring(j, k) + "." + s.substring(k)); 111 | 112 | } 113 | 114 | } 115 | } 116 | return result; 117 | 118 | } 119 | 120 | public boolean isValid(String st, int start, int end) { 121 | if (start >= end || start < 0 || end > st.length() || st.length() < 4 122 | || st.length() > 12) { 123 | return false; 124 | } 125 | if (end - start > 3 || (end - start >= 2 && st.charAt(start) == '0')) { 126 | return false; 127 | } 128 | int num = Integer.parseInt(st.substring(start, end)); 129 | if (num < 0 || num > 255) { 130 | return false; 131 | } 132 | return true; 133 | } 134 | 135 | public static void main(String[] args) { 136 | RestoreIPAddresses o = new RestoreIPAddresses(); 137 | System.out.println(o.restoreIpAddresses("19216811")); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /ReverseALinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse a LinkedList without any extra space 3 | Solution: 4 | http://analgorithmaday.blogspot.com/2011/03/reverse-linked-listusing-recursion.html 5 | 6 | Use recursion and consider the last two ListNodes 7 | 8 | */ 9 | 10 | public class ReverseALinkedList { 11 | // recursive version - start fro the second last ListNode 12 | public ListNode reverse(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return head; 15 | } 16 | ListNode result = reverse(head.next); 17 | head.next.next = head;// start from the second last ListNode 18 | head.next = null; 19 | return result; 20 | 21 | } 22 | 23 | // iterative version - record previous node 24 | public ListNode reverseIter(ListNode head) { 25 | if (head == null) { 26 | return null; 27 | } 28 | ListNode curr = head; 29 | ListNode prev = null; 30 | while (curr != null) { 31 | ListNode temp = curr; 32 | curr = curr.next; 33 | temp.next = prev; 34 | prev = temp; 35 | } 36 | return prev; 37 | 38 | 39 | } 40 | 41 | public static void main(String[] args) { 42 | ListNode head = new ListNode(1); 43 | head.next = new ListNode(2); 44 | head.next.next = new ListNode(3); 45 | ReverseALinkedList o = new ReverseALinkedList(); 46 | 47 | ListNode newHead = o.reverseIter(head); 48 | System.out.println("start"); 49 | while (newHead != null) { 50 | System.out.println(newHead.val); 51 | newHead = newHead.next; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ReverseInteger.java: -------------------------------------------------------------------------------- 1 | /*Special cases: 2 | 1).the integer's last digit is 0 3 | 2).overflow, for example: Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. 4 | 5 | 6 | idea comes from: https://github.com/zwxxx/LeetCode/blob/825fe4c23fd108675f4e7d41d0130cb3a556ff3b/Reverse_Integer.cpp 7 | do it from the least important digit and digit by digit 8 | */ 9 | public class ReverseInteger { 10 | public int reverse(int x) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | int y = 0; 14 | while (x > 0) { 15 | y *= 10; 16 | y += x % 10; 17 | x /= 10; 18 | System.out.println(x + " " + y); 19 | 20 | } 21 | return y; 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.print(Integer.MAX_VALUE); 26 | System.out.println(Integer.MIN_VALUE); 27 | ReverseInteger o = new ReverseInteger(); 28 | System.out.println(o.reverse(2147483647)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ReverseLinkedListII.java: -------------------------------------------------------------------------------- 1 | /*create a new LinkedList, for the ListNode in [m,n] range, insert them before its tail, just like stack 2 | else, insert them after the tail 3 | Assume m,n are valid (1<=m n || m <= 0 | n <= 0) { 13 | return null; 14 | } 15 | if (m == n) { 16 | return head; 17 | } 18 | ListNode copy; 19 | ListNode saveHead = head; 20 | ListNode rtail = null;// tail of reverse part 21 | ListNode saveRtail = rtail; 22 | ListNode saveEnd; 23 | int i; 24 | if (m > 1) { 25 | for (i = 1; i <= m - 2; i++) { 26 | head = head.next; 27 | } 28 | // save the end of the first (m-1) nodes 29 | saveEnd = head; 30 | System.out.println("saveHead" + saveHead.val); 31 | System.out.println("head" + head.val); 32 | 33 | for (i = m; i <= n; i++) { 34 | head = head.next; 35 | copy = new ListNode(head.val); 36 | if (i == m) { 37 | saveRtail = copy; 38 | } 39 | copy.next = rtail; 40 | rtail = copy; 41 | } 42 | System.out.println("rtail" + rtail.val); 43 | // connect the first part with the reverse part 44 | 45 | head = head.next; 46 | saveRtail.next = head; 47 | saveEnd.next = rtail; 48 | return saveHead; 49 | } else { 50 | for (i = 1; i <= n; i++) { 51 | copy = new ListNode(head.val); 52 | if (i == 1) { 53 | saveRtail = copy; 54 | } 55 | copy.next = rtail; 56 | rtail = copy; 57 | head = head.next; 58 | } 59 | saveRtail.next = head; 60 | return rtail; 61 | 62 | } 63 | 64 | } 65 | 66 | public static void main(String[] args) { 67 | ReverseLinkedListII o = new ReverseLinkedListII(); 68 | ListNode head = new ListNode(1); 69 | head.next = new ListNode(2); 70 | head.next.next = new ListNode(3); 71 | head.next.next.next = new ListNode(4); 72 | head.next.next.next.next = new ListNode(5); 73 | 74 | ListNode result = o.reverseBetween(head, 4, 5); 75 | System.out.println(result.val); 76 | System.out.println(result.next.val); 77 | System.out.println(result.next.next.val); 78 | System.out.println(result.next.next.next.val); 79 | System.out.println(result.next.next.next.next.val); 80 | 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /ReverseNodesInKGroup.java: -------------------------------------------------------------------------------- 1 | //calculate the length first, then do it part by part 2 | 3 | public class ReverseNodesInKGroup { 4 | public ListNode reverseKGroup(ListNode head, int k) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (head == null || k < 0) { 8 | return null; 9 | } 10 | if (k == 0 || k == 1) { 11 | return head; 12 | } 13 | int l = calculateLength(head); 14 | int repeat = l / k; 15 | if (repeat == 0) { 16 | return head; 17 | } 18 | ListNode currNode = head; 19 | ListNode partTail = null; 20 | ListNode partHead = null; 21 | ListNode copy; 22 | ListNode saveHead = head; 23 | ListNode prevTail = head; 24 | 25 | for (int i = 0; i < repeat; i++) { 26 | for (int j = 0; j < k; j++) { 27 | if (j == 0) { 28 | partTail = new ListNode(currNode.val); 29 | partHead = partTail; 30 | } else { 31 | copy = new ListNode(currNode.val); 32 | copy.next = partHead; 33 | partHead = copy; 34 | } 35 | if (j != k - 1) { 36 | currNode = currNode.next; 37 | } 38 | } 39 | if (i == 0) { 40 | saveHead = partHead; 41 | 42 | } else { 43 | prevTail.next = partHead; 44 | } 45 | prevTail = partTail; 46 | currNode = currNode.next; 47 | } 48 | prevTail.next = currNode; 49 | 50 | return saveHead; 51 | 52 | } 53 | 54 | public int calculateLength(ListNode head) { 55 | int counter = 0; 56 | while (head != null) { 57 | counter++; 58 | head = head.next; 59 | } 60 | return counter; 61 | } 62 | 63 | public static void main(String[] args) { 64 | ReverseNodesInKGroup o = new ReverseNodesInKGroup(); 65 | ListNode head = new ListNode(1); 66 | head.next = new ListNode(2); 67 | head.next.next = new ListNode(3); 68 | head.next.next.next = new ListNode(4); 69 | head.next.next.next.next = new ListNode(5); 70 | 71 | ListNode result = o.reverseKGroup(head, 5); 72 | System.out.println(result.val); 73 | System.out.println(result.next.val); 74 | System.out.println(result.next.next.val); 75 | System.out.println(result.next.next.next.val); 76 | System.out.println(result.next.next.next.next.val); 77 | 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /RomanToInteger.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class RomanToInteger { 5 | public int romanToInt(String s) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (s.length() == 0) { 9 | return 0; 10 | } 11 | Hashtable hash = new Hashtable(); 12 | hash.put('I', 1); 13 | hash.put('V', 5); 14 | hash.put('X', 10); 15 | hash.put('L', 50); 16 | hash.put('C', 100); 17 | hash.put('D', 500); 18 | hash.put('M', 1000); 19 | if (s.length() == 1) { 20 | return hash.get(s.charAt(0)); 21 | } 22 | int sum = 0; 23 | int i = 0; 24 | while (i < s.length() - 1) { 25 | if (hash.get(s.charAt(i)) < hash.get(s.charAt(i + 1))) { 26 | sum += hash.get(s.charAt(i + 1)) - hash.get(s.charAt(i)); 27 | i += 2; 28 | } else { 29 | sum += hash.get(s.charAt(i)); 30 | i++; 31 | } 32 | } 33 | if (hash.get(s.charAt(s.length() - 2)) >= hash 34 | .get(s.charAt(s.length() - 1))) { 35 | sum += hash.get(s.charAt(s.length() - 1)); 36 | } 37 | 38 | return sum; 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /RotateImage.java: -------------------------------------------------------------------------------- 1 | public class RotateImage { 2 | public void rotate(int[][] matrix) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int length = matrix[0].length; 6 | for (int i = 0; i < length / 2; i++) { 7 | int first = i; 8 | int last = length - 1 - i; 9 | for (int j = first; j < last; j++) {/* 10 | * Here j!=last, otherwise the 11 | * image will be rotated by 180' 12 | */ 13 | int offset = j - first; 14 | int top = matrix[first][j]; 15 | 16 | // left->top 17 | matrix[first][j] = matrix[last - offset][first]; 18 | // bottom->left 19 | matrix[last - offset][first] = matrix[last][last - offset]; 20 | // right->bottom 21 | matrix[last][last - offset] = matrix[j][last]; 22 | // top->right 23 | matrix[j][last] = top; 24 | 25 | } 26 | 27 | } 28 | return; 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /RotateList.java: -------------------------------------------------------------------------------- 1 | //use slow-fast runner strategy 2 | 3 | //Internal Error when run leetcode OJ 4 | 5 | 6 | public class RotateList { 7 | public ListNode rotateRight(ListNode head, int n) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if (head == null) { 11 | return null; 12 | } 13 | int l = calculateLength(head); 14 | if (n % l == 0) { 15 | return head; 16 | } 17 | if (n > l) { 18 | n = n % l; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head; 23 | ListNode saveHead = head; 24 | for (int i = 0; i < n; i++) { 25 | if (fast == null) { 26 | return null; 27 | } 28 | fast = fast.next; 29 | } 30 | 31 | while (fast.next != null) { 32 | slow = slow.next; 33 | fast = fast.next; 34 | } 35 | 36 | head = slow.next; 37 | fast.next = saveHead; 38 | slow.next = null; 39 | System.out.println("head " + head.val); 40 | 41 | return head; 42 | 43 | } 44 | 45 | public int calculateLength(ListNode head) { 46 | if (head == null) { 47 | return 0; 48 | } 49 | int counter = 0; 50 | while (head != null) { 51 | counter++; 52 | head = head.next; 53 | } 54 | return counter; 55 | } 56 | 57 | public static void main(String[] args) { 58 | RotateList o = new RotateList(); 59 | ListNode head = new ListNode(1); 60 | head.next = new ListNode(2); 61 | 62 | head = o.rotateRight(head, 1); 63 | 64 | System.out.println(head.next.next); 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /SameTree.java: -------------------------------------------------------------------------------- 1 | //preorder traversal 2 | //easy 3 | 4 | public class SameTree { 5 | public boolean isSameTree(TreeNode p, TreeNode q) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (p == null) { 9 | return q == null; 10 | } 11 | if (q == null) { 12 | return p == null; 13 | } 14 | if (p.val == q.val) { 15 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 16 | } else { 17 | return false; 18 | } 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /ScrambleString.java: -------------------------------------------------------------------------------- 1 | /*idea comes from: https://github.com/zwxxx/LeetCode/blob/825fe4c23fd108675f4e7d41d0130cb3a556ff3b/Scramble_String.cpp 2 | Assume we have a string s1=[0..n], and we scramble at position p, then s1 is split into [0..p] and [p+1..n]. 3 | The children of [0..p] must be within[0..p] and the children of [p+1..n] must be within [p+1..n]. 4 | Hence if s2 is a scramble of s1, then it must have a point that the half before is within[0..p](or [p+1..n), and the half after 5 | it is within [p+1..n](or [0..p]) 6 | 7 | Attention: the string doesn't have to be partitioned evenly 8 | Recursion 9 | 10 | */ 11 | 12 | public class ScrambleString { 13 | public boolean isScramble(String s1, String s2) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if (s1.length() != s2.length()) { 17 | return false; 18 | } 19 | if (s1.length() == 0) { 20 | return true; 21 | } 22 | 23 | if (s1.length() <= 2) { 24 | return haveSameContent(s1, s2); 25 | } 26 | int l = s1.length(); 27 | for (int i = 1; i < l; i++) { 28 | // System.out.println("a "+haveSameContent(s1.substring(0, i), 29 | // s2.substring(l-i, l))); 30 | // System.out.println("b "+haveSameContent(s1.substring(i, 31 | // l),s2.substring(0, l-i))); 32 | if (haveSameContent(s1.substring(0, i), s1.substring(0, i)) 33 | && haveSameContent(s1.substring(i, l), s2.substring(i, l))) { 34 | // System.out.println("i "+i); 35 | boolean left = isScramble(s1.substring(0, i), 36 | s2.substring(0, i)); 37 | boolean right = isScramble(s1.substring(i, l), 38 | s2.substring(i, l)); 39 | // System.out.println(left+""+right); 40 | if (left && right) { 41 | return true; 42 | } 43 | } else if (haveSameContent(s1.substring(0, i), 44 | s2.substring(l - i, l)) 45 | && haveSameContent(s1.substring(i, l), 46 | s2.substring(0, l - i))) {// have to make sure two 47 | // substrings have the 48 | // same length 49 | 50 | // System.out.println("2i "+i); 51 | 52 | boolean left = isScramble(s1.substring(0, i), 53 | s2.substring(l - i, l)); 54 | boolean right = isScramble(s1.substring(i, l), 55 | s2.substring(0, l - i)); 56 | if (left && right) { 57 | return true; 58 | } 59 | } 60 | 61 | } 62 | return false; 63 | 64 | } 65 | 66 | public boolean haveSameContent(String s1, String s2) { 67 | if (s1.length() != s2.length()) { 68 | return false; 69 | } 70 | if (s1.length() == 0) { 71 | return true; 72 | } 73 | int[] content = new int[26]; 74 | for (int i = 0; i < s1.length(); i++) { 75 | content[s1.charAt(i) - 'a']++; 76 | } 77 | for (int j = 0; j < s2.length(); j++) { 78 | content[s2.charAt(j) - 'a']--; 79 | if (content[s2.charAt(j) - 'a'] < 0) { 80 | return false; 81 | } 82 | } 83 | return true; 84 | 85 | } 86 | 87 | public static void main(String[] args) { 88 | ScrambleString o = new ScrambleString(); 89 | boolean r = o.isScramble("abab", "aabb"); 90 | System.out.println(r); 91 | 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /SearchA2DMatrix.java: -------------------------------------------------------------------------------- 1 | //idea: find the first row whose first element is bigger than target 2 | //Attention: matrix may have only one row 3 | 4 | public class SearchA2DMatrix { 5 | public boolean searchMatrix(int[][] matrix, int target) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (matrix.length == 0 || matrix[0].length == 0) { 9 | return false; 10 | } 11 | if (matrix.length == 1) { 12 | return searchRow(matrix[0], target); 13 | } 14 | int row = 0; 15 | for (row = 0; row < matrix.length; row++) { 16 | if (matrix[row][0] == target) { 17 | return true; 18 | } else if (matrix[row][0] > target) { 19 | break; 20 | } 21 | } 22 | if (row == 0) { 23 | return false; 24 | } else { 25 | row--; 26 | return searchRow(matrix[row], target); 27 | } 28 | 29 | } 30 | 31 | public boolean searchRow(int[] row, int target) { 32 | if (row.length == 0) { 33 | return false; 34 | } 35 | int start = 0; 36 | int end = row.length - 1; 37 | while (start <= end) { 38 | int mid = (start + end) / 2; 39 | 40 | if (row[mid] == target) { 41 | return true; 42 | } else if (row[mid] > target) { 43 | end = mid - 1; 44 | } else { 45 | start = mid + 1; 46 | } 47 | } 48 | return false; 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /SearchForARange.java: -------------------------------------------------------------------------------- 1 | //similar with BS, the only difference is when we find the target, we don't return the position immediately 2 | //we try to expand the range based on the center of this position 3 | 4 | //Internal Error 5 | 6 | public class SearchForARange { 7 | public int[] searchRange(int[] A, int target) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if (A.length == 0) { 11 | return new int[] { -1, -1 }; 12 | } 13 | 14 | int[] range = new int[2]; 15 | int start = 0; 16 | int end = A.length - 1; 17 | int mid; 18 | int left = -1; 19 | int right = -1; 20 | 21 | while (start <= end) { 22 | System.out.println("start " + start); 23 | System.out.println("end " + end); 24 | mid = (start + end) / 2; 25 | if (A[mid] == target) { 26 | left = mid; 27 | right = mid; 28 | for (int j = mid - 1; j >= 0; j--) { 29 | if (A[j] != target) { 30 | left = j + 1; 31 | break; 32 | } 33 | } 34 | for (int k = mid + 1; k < A.length; k++) { 35 | if (A[k] != target) { 36 | right = k - 1; 37 | break; 38 | } 39 | } 40 | break; 41 | } else if (target > A[mid]) { 42 | start = mid + 1; 43 | } else { 44 | end = mid - 1; 45 | } 46 | 47 | } 48 | range[0] = left; 49 | range[1] = right; 50 | return range; 51 | 52 | } 53 | 54 | public static void main(String[] args) { 55 | SearchForARange o = new SearchForARange(); 56 | int[] a = { 1, 2, 2, 3, 4, 4, 4, 5 }; 57 | System.out.println(o.searchRange(a, 4)[0] + ", " 58 | + o.searchRange(a, 4)[1]); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /SearchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | //no duplicates allowed 2 | //key idea: after rotated, half of the new array is sorted 3 | //don't use recursion cause it's too slow 4 | //use iterative approach 5 | //Attention: compare mid value with high value to indicate which half is sorted (to avoid the special case when there are only two elements left) 6 | //otherwise, if we compare mid value with low value, when there are only two elements left, if A[mid]>A[low] is false,that doesn't mean right half is sorted 7 | 8 | public class SearchInRotatedSortedArray { 9 | public int search(int[] A, int target) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | if (A.length == 0) { 13 | return -1; 14 | } 15 | int start = 0; 16 | int end = A.length - 1; 17 | int mid; 18 | while (start <= end) { 19 | mid = (start + end) / 2; 20 | if (A[mid] == target) { 21 | return mid; 22 | } 23 | if (A[mid] >= A[end]) {// left part sorted 24 | if (target >= A[start] && target < A[mid]) { 25 | end = mid - 1; 26 | } else { 27 | start = mid + 1; 28 | } 29 | 30 | } else {// right part sorted 31 | if (target > A[mid] && target <= A[end]) { 32 | start = mid + 1; 33 | } else { 34 | end = mid - 1; 35 | } 36 | } 37 | System.out.println("Start " + start); 38 | System.out.println("End " + end); 39 | 40 | } 41 | return -1; 42 | 43 | } 44 | 45 | public static void main(String[] args) { 46 | SearchInRotatedSortedArray o = new SearchInRotatedSortedArray(); 47 | int[] A = { 5, 1, 2, 3, 4 }; 48 | System.out.println(o.search(A, 1)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /SearchInRotatedSortedArrayII.java: -------------------------------------------------------------------------------- 1 | //if duplicates allowed, then binary search may not work 2 | //worst case time complexity: O(n) 3 | public class SearchInRotatedSortedArrayII { 4 | public boolean search(int[] A, int target) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (A.length == 0) { 8 | return false; 9 | } 10 | 11 | int start = 0; 12 | int end = A.length - 1; 13 | int mid; 14 | while (start <= end) { 15 | mid = (start + end) / 2; 16 | if (target == A[mid]) { 17 | return true; 18 | } 19 | if (A[mid] == A[end]) { 20 | for (int i = start; i <= end; i++) { 21 | if (A[i] == target) { 22 | return true; 23 | } 24 | } 25 | return false; 26 | 27 | } else if (A[mid] > A[end]) {// left part sorted 28 | if (target >= A[start] && target < A[mid]) { 29 | end = mid - 1; 30 | } else { 31 | start = mid + 1; 32 | } 33 | 34 | } else { 35 | if (target > A[mid] && target <= A[end]) { 36 | start = mid + 1; 37 | } else { 38 | end = mid - 1; 39 | } 40 | } 41 | System.out.println("start " + start); 42 | System.out.println("end " + end); 43 | 44 | } 45 | return false; 46 | 47 | } 48 | 49 | public boolean search2(int[] A, int target) { 50 | int start = 0; 51 | int end = A.length - 1; 52 | int mid; 53 | while (start <= end) { 54 | mid = start + (end - start) / 2; 55 | if (A[mid] == target) { 56 | return true; 57 | } 58 | if (A[start] == A[mid]) { 59 | if (A[mid] == A[end]) { 60 | for (int i = start + 1; i <= end - 1; i++) { 61 | if (A[i] == target) { 62 | return true; 63 | } 64 | } 65 | return false; 66 | 67 | } else if (A[mid] < A[end]) {// right part sorted 68 | if (target > A[mid] && target <= A[end]) { 69 | start = mid + 1; 70 | } else { 71 | return false; 72 | } 73 | } else {// left part all duplicate 74 | start = mid + 1; 75 | } 76 | } else if (A[start] < A[mid]) {// left part sorted 77 | if (target >= A[start] && target < A[mid]) { 78 | end = mid - 1; 79 | } else { 80 | start = mid + 1; 81 | } 82 | 83 | } else {// right part sorted 84 | if (target > A[mid] && target <= A[end]) { 85 | start = mid + 1; 86 | } else { 87 | end = mid - 1; 88 | } 89 | } 90 | 91 | } 92 | return false; 93 | } 94 | 95 | public static void main(String[] args) { 96 | SearchInRotatedSortedArrayII o = new SearchInRotatedSortedArrayII(); 97 | int[] A = { 1, 1, 3, 1 }; 98 | int target = 3; 99 | System.out.println(o.search2(A, target)); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | //easy 2 | public class SearchInsertPosition { 3 | public int searchInsert(int[] A, int target) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (A.length == 0) { 7 | return -1; 8 | } 9 | int pos = 0; 10 | 11 | for (pos = 0; pos < A.length; pos++) { 12 | if (A[pos] == target) { 13 | return pos; 14 | } 15 | if (A[pos] > target) { 16 | break; 17 | } 18 | } 19 | 20 | return pos; 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SetMatrixZeros.java: -------------------------------------------------------------------------------- 1 | //idea comes from: https://github.com/anson627/leetcode/blob/master/SetMatrixZeroes.cpp 2 | //spread zeros to the first row and the first column 3 | //Attention: after setting fristRow and firstCol, start scanning from the second row and the second column 4 | 5 | public class SetMatrixZeros { 6 | public void setZeroes(int[][] matrix) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | int m = matrix.length; 10 | int n = matrix[0].length; 11 | if (m == 0 || n == 0) { 12 | return; 13 | } 14 | boolean firstRow = false;/* indicate whether the first row is all zeros */ 15 | boolean firstCol = false;/* 16 | * indicate whether the first column is all 17 | * zeros 18 | */ 19 | for (int i = 0; i < n; i++) { 20 | if (matrix[0][i] == 0) { 21 | firstRow = true; 22 | break; 23 | } 24 | } 25 | for (int j = 0; j < m; j++) { 26 | if (matrix[j][0] == 0) { 27 | firstCol = true; 28 | break; 29 | } 30 | } 31 | 32 | for (int j = 0; j < m; j++) { 33 | for (int i = 0; i < n; i++) { 34 | if (matrix[j][i] == 0) {// spread zeros to the first row and the 35 | // first column 36 | matrix[0][i] = 0; 37 | matrix[j][0] = 0; 38 | } 39 | } 40 | } 41 | 42 | for (int j = 1; j < m; j++) { 43 | for (int i = 1; i < n; i++) { 44 | if (matrix[j][0] == 0 || matrix[0][i] == 0) { 45 | matrix[j][i] = 0; 46 | } 47 | } 48 | } 49 | 50 | if (firstRow) { 51 | for (int i = 1; i < n; i++) { 52 | matrix[0][i] = 0; 53 | } 54 | } 55 | if (firstCol) { 56 | for (int j = 1; j < m; j++) { 57 | matrix[j][0] = 0; 58 | } 59 | } 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Shift.java: -------------------------------------------------------------------------------- 1 | public class Shift { 2 | public static boolean shift(int[] arr){ 3 | //Verify the input array doesn't have any zero 4 | for(int i = 0; i < arr.length -1; i++){ 5 | if(arr[i] == 0){ 6 | System.out.println("Invaild input(0) scanned"); 7 | return false; 8 | } 9 | } 10 | int start = 0; 11 | int end = arr.length - 1; 12 | while(start <= end){ 13 | if(arr[start]<0){ 14 | start ++; 15 | } 16 | if(arr[end]>0){ 17 | end--; 18 | } 19 | if(start<=end){ 20 | swap(arr,start,end); 21 | } 22 | } 23 | return true; 24 | 25 | } 26 | 27 | public static void swap(int[] arr, int i, int j){ 28 | int temp; 29 | temp = arr[i]; 30 | arr[i] = arr[j]; 31 | arr[j] = temp; 32 | return; 33 | } 34 | //Test Case 35 | 36 | public static void main(String arg[]){ 37 | boolean result; 38 | int[] a = {1,2,3,5,-1,1}; 39 | result = shift(a); 40 | if(result){ 41 | for(int i = 0; i < a.length; i++) 42 | System.out.print(a[i]+"\t"); 43 | System.out.println(); 44 | } 45 | 46 | int[] b = {2,4,4,1,3,-1,-3}; 47 | result = shift(b); 48 | if(result){ 49 | for(int i = 0; i < b.length; i++) 50 | System.out.print(b[i]+"\t"); 51 | System.out.println(); 52 | } 53 | 54 | int[] c = {-2,-3,123,5,-1,1}; 55 | result = shift(c); 56 | if(result){ 57 | for(int i = 0; i < c.length; i++) 58 | System.out.print(c[i]+"\t"); 59 | System.out.println(); 60 | } 61 | 62 | int[] d = {-1,-2,1,2,3,4,5}; 63 | result = shift(d); 64 | if(result){ 65 | for(int i = 0; i < d.length; i++) 66 | System.out.print(d[i]+"\t"); 67 | System.out.println(); 68 | } 69 | 70 | int[] e = {3,0,-2,-3,123,5,-1,1}; 71 | result = shift(e); 72 | if(result){ 73 | for(int i = 0; i < c.length; i++) 74 | System.out.print(e[i]+"\t"); 75 | System.out.println(); 76 | } 77 | 78 | 79 | 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /SimplifyPath.java: -------------------------------------------------------------------------------- 1 | // '.' means the same level 2 | // '..'means the higher level 3 | //key idea: use a stack 4 | 5 | //Internal Error 6 | 7 | import java.util.*; 8 | 9 | public class SimplifyPath { 10 | public String simplifyPath(String path) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | if (path.length() == 0) { 14 | return new String(); 15 | } 16 | Stack s = new Stack(); 17 | StringBuilder sb = new StringBuilder(); 18 | ArrayList slash = new ArrayList(); 19 | 20 | for (int i = 0; i < path.length(); i++) {// store the location of 21 | // slashes 22 | if (path.charAt(i) == '/') { 23 | slash.add(i); 24 | } 25 | } 26 | 27 | for (int j = 1; j < slash.size(); j++) { 28 | if (slash.get(j - 1) + 1 != slash.get(j)) {// there are characters 29 | // between two slashes 30 | String name = path 31 | .substring(slash.get(j - 1) + 1, slash.get(j)); 32 | System.out.println("name " + name); 33 | if (!name.equals(".")) {// for '.', jut skip it 34 | if (name.equals("..")) { 35 | if (!s.isEmpty()) { 36 | s.pop(); 37 | } 38 | } else { 39 | s.add(name); 40 | } 41 | 42 | } 43 | 44 | } 45 | 46 | } 47 | if (s.size() == 0) { 48 | return "/"; 49 | } 50 | 51 | for (int k = 0; k < s.size(); k++) { 52 | sb.append("/" + s.get(k)); 53 | } 54 | return sb.toString(); 55 | 56 | } 57 | 58 | public static void main(String[] args) { 59 | SimplifyPath o = new SimplifyPath(); 60 | System.out.println(o 61 | .simplifyPath("/home/of/foo/../../bar/../../is/./here/.")); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.io.*; 3 | 4 | public class Solution { 5 | public int solver(int[] pos, int k) { 6 | if (k < 0) { 7 | return 0; 8 | } 9 | ArrayList result = new ArrayList(); 10 | placeKing(pos, k, result); 11 | int res = result.size()%1000000007; 12 | return res; 13 | 14 | } 15 | 16 | public void placeKing(int[] pos, int row, ArrayList result) { 17 | int n = pos.length; 18 | if (row == n) {// finish placing all n queens, so print the result 19 | result.add(1); 20 | return; 21 | 22 | } 23 | 24 | for (int i = 0; i < n; i++) {// try to find a valid column for row 25 | if (feasible(pos, row, i)) { 26 | pos[row] = i; 27 | placeKing(pos, row + 1, result); 28 | } 29 | } 30 | 31 | } 32 | 33 | public boolean feasible(int[] pos, int row, int col) { 34 | if (row == 0) { 35 | return true; 36 | } 37 | for (int i = 0; i < row; i++) { 38 | if (pos[i] == col) { 39 | return false; 40 | } 41 | } 42 | // System.out.println("prev" + pos[row - 1]); 43 | if (Math.abs(col - pos[row - 1]) <= 1) {// check diagonal 44 | return false; 45 | } 46 | return true; 47 | 48 | } 49 | 50 | public static void main(String[] args) { 51 | InputStreamReader ir = new InputStreamReader(System.in); 52 | BufferedReader in = new BufferedReader(ir); 53 | Solution o = new Solution(); 54 | int t; 55 | int n = 0; 56 | int k = 0; 57 | String line = new String(); 58 | 59 | try { 60 | line = in.readLine(); 61 | t = Integer.parseInt(line); 62 | for (int i = 0; i < t; i++) { 63 | line = in.readLine(); 64 | String[] arr = line.trim().split("\\s+"); 65 | n = Integer.parseInt(arr[0]); 66 | k = Integer.parseInt(arr[1]); 67 | 68 | line = in.readLine(); 69 | if (k == 0) { 70 | int[] pos = new int[n]; 71 | System.out.println(o.solver(pos, k)); 72 | continue; 73 | } 74 | arr = line.trim().split("\\s+"); 75 | int[] pos = new int[n]; 76 | for (int j = 0; j < k; j++) { 77 | pos[j] = Integer.parseInt(arr[j]); 78 | } 79 | System.out.println(o.solver(pos, k)); 80 | 81 | } 82 | in.close(); 83 | } catch (IOException e) { 84 | e.printStackTrace(); 85 | } 86 | 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /SortColors.java: -------------------------------------------------------------------------------- 1 | //design a one-pass algorithm using only constant space 2 | //use three pointers low,mid,high, which are pointing to '0', '1' and '2' separately 3 | 4 | public class SortColors { 5 | public void sortColors(int[] A) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (A.length == 0) { 9 | return; 10 | } 11 | int low = 0; 12 | int mid = 0; 13 | int high = A.length - 1; 14 | 15 | while (mid <= high) { 16 | if (A[mid] == 0) { 17 | A[mid] = A[low]; 18 | A[low] = 0; 19 | low++; 20 | mid++; 21 | } else if (A[mid] == 1) { 22 | mid++; 23 | } else if (A[mid] == 2) {// Attention: we don't need to increment 24 | // mid here since A[mid] may be zero 25 | // after swapping A[mid] and A[high] 26 | A[mid] = A[high]; 27 | A[high] = 2; 28 | high--; 29 | } 30 | 31 | } 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /SortRotatedArray.java: -------------------------------------------------------------------------------- 1 | 2 | public class SortRotatedArray { 3 | 4 | } 5 | -------------------------------------------------------------------------------- /SpiralMatrix.java: -------------------------------------------------------------------------------- 1 | //user recursion, pay attention to the boundary cases 2 | import java.util.*; 3 | 4 | public class SpiralMatrix { 5 | public ArrayList spiralOrder(int[][] matrix) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (matrix.length == 0 || matrix[0].length == 0) { 9 | return new ArrayList(); 10 | } 11 | ArrayList result = new ArrayList(); 12 | spiralOrderRecursion(matrix, 0, matrix.length - 1, 0, 13 | matrix[0].length - 1, result); 14 | return result; 15 | } 16 | 17 | public void spiralOrderRecursion(int[][] matrix, int startRow, int endRow, 18 | int startCol, int endCol, ArrayList result) { 19 | if (startRow > endRow || startCol > endCol) { 20 | return; 21 | } 22 | 23 | if (startRow == endRow && startCol == endCol) {// only one element 24 | result.add(matrix[startRow][startCol]); 25 | return; 26 | } else if (startRow == endRow) {// only one row 27 | 28 | for (int i = startCol; i <= endCol; i++) { 29 | result.add(matrix[startRow][i]); 30 | } 31 | return; 32 | } else if (startCol == endCol) {// only one column 33 | for (int j = startRow; j <= endRow; j++) { 34 | result.add(matrix[j][startCol]); 35 | } 36 | return; 37 | } 38 | 39 | // add elements on startRow 40 | for (int i = startCol; i <= endCol; i++) { 41 | result.add(matrix[startRow][i]); 42 | } 43 | // add elements on endCol 44 | for (int j = startRow + 1; j <= endRow - 1; j++) { 45 | result.add(matrix[j][endCol]); 46 | } 47 | // add elements on endRow 48 | for (int k = endCol; k >= startCol; k--) { 49 | result.add(matrix[endRow][k]); 50 | } 51 | // add elements on startCol 52 | for (int l = endRow - 1; l >= startRow + 1; l--) { 53 | result.add(matrix[l][startCol]); 54 | } 55 | spiralOrderRecursion(matrix, startRow + 1, endRow - 1, startCol + 1, 56 | endCol - 1, result); 57 | 58 | } 59 | 60 | public static void main(String[] args) { 61 | SpiralMatrix o = new SpiralMatrix(); 62 | int[][] matrix = { { 2, 3 } }; 63 | ArrayList result = new ArrayList(); 64 | result = o.spiralOrder(matrix); 65 | System.out.println(result.size()); 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /SpiralMatrixII.java: -------------------------------------------------------------------------------- 1 | //Attention: the case when n is odd 2 | 3 | public class SpiralMatrixII { 4 | public int[][] generateMatrix(int n) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (n < 0) { 8 | return null; 9 | } 10 | if (n == 0) { 11 | return new int[0][0]; 12 | } 13 | int curr = 0;// current index of the left upper corner 14 | int counter = 1; 15 | int[][] result = new int[n][n]; 16 | while (curr < n / 2) { 17 | if (n == 1) { 18 | result[curr][curr] = counter; 19 | return result; 20 | } 21 | // fill the first row 22 | for (int i = curr; i < n - curr; i++) { 23 | result[curr][i] = counter; 24 | counter++; 25 | } 26 | 27 | // fill the last column 28 | for (int j = curr + 1; j < n - curr - 1; j++) { 29 | result[j][n - 1 - curr] = counter; 30 | counter++; 31 | } 32 | 33 | // fill the last row 34 | for (int k = n - 1 - curr; k >= curr; k--) { 35 | result[n - 1 - curr][k] = counter; 36 | counter++; 37 | } 38 | // fill the first column 39 | for (int l = n - 1 - curr - 1; l >= curr + 1; l--) { 40 | result[l][curr] = counter; 41 | counter++; 42 | } 43 | 44 | curr++; 45 | } 46 | 47 | if (n % 2 == 1) {// n is odd 48 | result[curr][curr] = counter; 49 | } 50 | return result; 51 | } 52 | 53 | public static void main(String[] args) { 54 | SpiralMatrixII o = new SpiralMatrixII(); 55 | int n = 5; 56 | int[][] result = new int[n][n]; 57 | result = o.generateMatrix(n); 58 | for (int i = 0; i < n; i++) { 59 | for (int j = 0; j < n; j++) { 60 | System.out.print(result[i][j]); 61 | } 62 | System.out.println(); 63 | } 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /Sqrtx.java: -------------------------------------------------------------------------------- 1 | //Attention to overflow: Integer.MAX_VALUE's square root is approximately 46340 2 | // the middle value always >= the square root when x>=4 3 | 4 | public class Sqrtx { 5 | public int sqrt(int x) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (x < 0) { 9 | return -1; 10 | } 11 | int mid ; 12 | int root = 0; 13 | int low = 0; 14 | int high = x; 15 | 16 | while (low <= high) { 17 | mid = (low + high) / 2; 18 | if (mid > 46340) {// this part is for speeding up 19 | high = mid - 1; 20 | continue; 21 | } 22 | int y = mid * mid; 23 | if (y == x) { 24 | return mid; 25 | } else if (y > x) { 26 | high = mid - 1; 27 | } else { 28 | low = mid + 1; 29 | root = mid;// use the floor value 30 | 31 | } 32 | 33 | } 34 | return root; 35 | 36 | } 37 | 38 | public static void main(String[] args) { 39 | Sqrtx o = new Sqrtx(); 40 | int n = 2147395599; 41 | System.out.println(o.sqrt(n)); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /StringToIntegerATOI.java: -------------------------------------------------------------------------------- 1 | //use a long value to save the result in order 2 | //Attention: -Integer.MIN_VALUE=-2147483648 3 | 4 | //Internal Error 5 | 6 | 7 | public class StringToIntegerATOI { 8 | public int atoi(String str) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | if (str.length() == 0) { 12 | return 0; 13 | } 14 | long sum = 0; 15 | int i = 0; 16 | boolean start = false; 17 | char c; 18 | boolean pos = true; 19 | while (i < str.length()) { 20 | if (str.charAt(i) != ' ') { 21 | start = true; 22 | break; 23 | } 24 | i++; 25 | } 26 | System.out.println("i1" + i); 27 | if (start) { 28 | c = str.charAt(i); 29 | if (c - '0' >= 0 && c - '0' <= 9) { 30 | sum += c - '0'; 31 | } else if (c == '+') { 32 | pos = true; 33 | } else if (c == '-') { 34 | pos = false; 35 | } else { 36 | return 0; 37 | } 38 | i++; 39 | 40 | } else { 41 | return 0; 42 | } 43 | for (int j = i; j < str.length(); j++) { 44 | c = str.charAt(j); 45 | 46 | if (c - '0' >= 0 && c - '0' <= 9) { 47 | sum *= 10; 48 | sum += c - '0'; 49 | 50 | } else { 51 | break; 52 | } 53 | if (sum > Integer.MAX_VALUE && pos == true) { 54 | return Integer.MAX_VALUE; 55 | } else if (sum > 2147483648.0 && pos == false) { 56 | return Integer.MIN_VALUE; 57 | } 58 | 59 | } 60 | 61 | if (pos) { 62 | return (int) sum; 63 | } else { 64 | return -(int) sum; 65 | } 66 | } 67 | 68 | public static void main(String[] args) { 69 | StringToIntegerATOI o = new StringToIntegerATOI(); 70 | System.out.println(o.atoi("-12")); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Subsets.java: -------------------------------------------------------------------------------- 1 | //idea comes from: https://github.com/anson627/leetcode/blob/master/Subsets/Subsets.cpp 2 | //use bit manipulation 3 | 4 | import java.util.*; 5 | 6 | public class Subsets { 7 | public ArrayList> subsets(int[] S) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if (S.length == 0) { 11 | return new ArrayList>(); 12 | } 13 | ArrayList> result = new ArrayList>(); 14 | ArrayList solution = new ArrayList(); 15 | Arrays.sort(S); 16 | int l = S.length; 17 | int k = 1 << l; 18 | for (int i = 0; i <= k - 1; i++) { 19 | int j = i; 20 | solution = new ArrayList(); 21 | int m = 0; 22 | while (j > 0) { 23 | if ((1 & j) == 1) { 24 | solution.add(S[m]); 25 | } 26 | j >>= 1; 27 | m++; 28 | } 29 | 30 | result.add(solution); 31 | } 32 | return result; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /SubsetsII.java: -------------------------------------------------------------------------------- 1 | //use Hashtable 2 | 3 | import java.util.*; 4 | 5 | public class SubsetsII { 6 | public ArrayList> subsetsWithDup(int[] num) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | if (num.length == 0) { 10 | return new ArrayList>(); 11 | } 12 | ArrayList> result = new ArrayList>(); 13 | ArrayList solution = new ArrayList(); 14 | Hashtable hash = new Hashtable(); 15 | int l = num.length; 16 | int k = 1 << l; 17 | Arrays.sort(num); 18 | for (int i = 0; i <= k - 1; i++) { 19 | int j = i; 20 | solution = new ArrayList(); 21 | int m = 0; 22 | while (j > 0) { 23 | if ((1 & j) == 1) { 24 | solution.add(num[m]); 25 | } 26 | j >>= 1; 27 | m++; 28 | } 29 | String s = arrayToString(solution); 30 | if (!hash.containsKey(s)) { 31 | result.add(solution); 32 | hash.put(s, true); 33 | } 34 | } 35 | return result; 36 | } 37 | 38 | public String arrayToString(ArrayList list) { 39 | if (list.size() == 0) { 40 | return new String(); 41 | } 42 | int[] num = new int[list.size()]; 43 | for (int i = 0; i < num.length; i++) { 44 | num[i] = list.get(i); 45 | } 46 | Arrays.sort(num); 47 | StringBuilder sb = new StringBuilder(); 48 | for (int i = 0; i < num.length; i++) { 49 | sb.append(num[i]); 50 | } 51 | return sb.toString(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /SubstringWithConcatenationOfAllWords.java: -------------------------------------------------------------------------------- 1 | //iterative search 2 | import java.util.*; 3 | 4 | public class SubstringWithConcatenationOfAllWords { 5 | public ArrayList findSubstring(String S, String[] L) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (S.length() == 0 || L.length == 0 9 | || L[0].length() * L.length > S.length()) { 10 | return new ArrayList(); 11 | } 12 | ArrayList result = new ArrayList(); 13 | Hashtable hash = new Hashtable(); 14 | for (int i = 0; i < L.length; i++) { 15 | if (!hash.containsKey(L[i])) { 16 | hash.put(L[i], 1); 17 | } else { 18 | int counter = hash.get(L[i]); 19 | counter++; 20 | hash.put(L[i], counter); 21 | } 22 | } 23 | System.out.println(hash); 24 | 25 | int len = L[0].length(); 26 | 27 | for (int j = 0; j <= S.length() - L[0].length() * L.length; j++) { 28 | boolean found = true; 29 | Hashtable foundHash = new Hashtable(); 30 | for (int k = 0; k < L.length; k++) { 31 | int startIndex = j + k * len; 32 | String str = S.substring(startIndex, startIndex + len); 33 | System.out.println(str); 34 | System.out.println("k" + k); 35 | if (!hash.containsKey(str)) { 36 | found = false; 37 | break; 38 | } else { 39 | if (!foundHash.containsKey(str)) { 40 | foundHash.put(str, 1); 41 | } else { 42 | int counter = foundHash.get(str); 43 | counter++; 44 | foundHash.put(str, counter); 45 | } 46 | int targetNum = hash.get(str); 47 | int foundNum = foundHash.get(str); 48 | // System.out.println("targetNum"+targetNum); 49 | // System.out.println("foundNum"+foundNum); 50 | if (foundNum > targetNum) { 51 | found = false; 52 | break; 53 | } 54 | } 55 | } 56 | if (found) { 57 | // System.out.println("j " + j); 58 | result.add(j); 59 | } 60 | 61 | } 62 | return result; 63 | 64 | } 65 | 66 | public static void main(String[] args) { 67 | SubstringWithConcatenationOfAllWords o = new SubstringWithConcatenationOfAllWords(); 68 | String s = "lingmindraboofooowingdingbarrwingmonkeypoundcake"; 69 | String[] l = { "fooo", "barr", "wing", "ding", "wing" }; 70 | System.out.println(o.findSubstring(s, l)); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /SudokuSolver.java: -------------------------------------------------------------------------------- 1 | //char[][] must be 9*9 since it's a Sudoku board 2 | //You may assume that there will be only one unique solution 3 | //similar with N Queen problem, DFS 4 | //idea comes from:https://github.com/anson627/leetcode/blob/master/SudokuSolver/SudokuSolver.cpp 5 | 6 | //basic idea is 7 | 8 | import java.util.*; 9 | 10 | public class SudokuSolver { 11 | public void solveSudoku(char[][] board) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | solveSudokuRecursion(board, 0, 0); 15 | } 16 | 17 | public boolean solveSudokuRecursion(char[][] board, int row, int col) { 18 | Pair res = getNextEmpty(board, row, col); 19 | if (res == null) {// boundary case 20 | return true; 21 | } 22 | ArrayList possible = new ArrayList(); 23 | possible = getPossibleValues(board, res.row, res.col); 24 | if (possible.size() == 0) {// no valid possible solutions available 25 | return false; 26 | } 27 | for (int i = 0; i < possible.size(); i++) {// try all possible solutions 28 | board[res.row][res.col] = possible.get(i); 29 | if (solveSudokuRecursion(board, res.row, res.col)) 30 | return true; 31 | board[res.row][res.col] = '.'; 32 | } 33 | return false; 34 | } 35 | 36 | public Pair getNextEmpty(char[][] board, int row, int col) { 37 | while (row <= 8 && col <= 8) { 38 | if (board[row][col] == '.') { 39 | return new Pair(row, col); 40 | } 41 | row = (col == 8) ? row + 1 : row; 42 | col = (col == 8) ? 0 : col + 1; 43 | } 44 | return null; 45 | } 46 | 47 | public ArrayList getPossibleValues(char[][] board, int row, 48 | int col) { 49 | boolean[] s = new boolean[10]; 50 | ArrayList possible = new ArrayList(); 51 | for (int i = 0; i < 9; i++) { 52 | if (board[i][col] != '.') {// check row 53 | s[board[i][col] - '0'] = true; 54 | } 55 | if (board[row][i] != '.') {// check column 56 | // System.out.println("row " + row); 57 | // System.out.println("col " + col); 58 | // System.out.println("i "+i); 59 | // System.out.println("value " + board[row][i]); 60 | // 61 | // System.out.println("value " + (board[row][i] - '0')); 62 | s[board[row][i] - '0'] = true; 63 | } 64 | char c = board[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3];// *check 65 | // its 66 | // own 67 | // 3*3 68 | // square 69 | if (c != '.') { 70 | s[c - '0'] = true; 71 | } 72 | 73 | } 74 | for (int j = 1; j <= 9; j++) { 75 | if (!s[j]) { 76 | possible.add((char) (j + '0')); 77 | // System.out.println((char) (j + '0')); 78 | } 79 | } 80 | return possible; 81 | 82 | } 83 | 84 | class Pair { 85 | int row, col; 86 | 87 | Pair(int r, int c) { 88 | row = r; 89 | col = c; 90 | } 91 | } 92 | 93 | public static void main(String[] args) { 94 | SudokuSolver o = new SudokuSolver(); 95 | char[][] b = { { '.', '.', '9', '7', '4', '8', '.', '.', '.' }, 96 | { '7', '.', '.', '.', '.', '.', '.', '.', '.' }, 97 | { '.', '2', '.', '1', '.', '9', '.', '.', '.' }, 98 | { '.', '.', '7', '.', '.', '.', '2', '4', '.' }, 99 | { '.', '6', '4', '.', '1', '.', '5', '9', '.' }, 100 | { '.', '9', '8', '.', '.', '.', '3', '.', '.' }, 101 | { '.', '.', '.', '8', '.', '3', '.', '2', '.' }, 102 | { '.', '.', '.', '.', '.', '.', '.', '.', '6' }, 103 | { '.', '.', '.', '2', '7', '5', '9', '.', '.' } }; 104 | o.solveSudoku(b); 105 | for (int i = 0; i < b.length; i++) { 106 | for (int j = 0; j < b[0].length; j++) { 107 | System.out.print(b[i][j]); 108 | } 109 | System.out.println(); 110 | } 111 | } 112 | } 113 | // ["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."] -------------------------------------------------------------------------------- /SumRootToLeafNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class SumRootToLeafNumbers { 4 | public static int finalSum = 0; 5 | public Hashtable hash = new Hashtable(); 6 | 7 | public int sumNumbers(TreeNode root) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | finalSum = 0; 11 | hash = new Hashtable(); 12 | PartialSum ps = new PartialSum(0); 13 | dfs(root, ps); 14 | return finalSum; 15 | 16 | } 17 | 18 | public void dfs(TreeNode n, PartialSum ps) { 19 | if (n == null) { 20 | return; 21 | } 22 | if (n.left == null && n.right == null) { 23 | int sum = ps.sum * 10 + n.val; 24 | finalSum += sum; 25 | return; 26 | } 27 | int currentSum = ps.sum * 10 + n.val; 28 | if (!hash.containsKey(n)) { 29 | hash.put(n, currentSum); 30 | } 31 | if (n.left != null) { 32 | dfs(n.left, new PartialSum(currentSum)); 33 | } 34 | if (n.right != null) { 35 | dfs(n.right, new PartialSum(currentSum)); 36 | } 37 | 38 | } 39 | 40 | } 41 | 42 | // public static void main 43 | 44 | class PartialSum { 45 | public int sum; 46 | 47 | PartialSum(int s) { 48 | sum = s; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /SurroundedRegions.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 | 8 | X X X X 9 | X O O X 10 | X X O X 11 | X O X X 12 | 13 | After running your function, the board should be: 14 | 15 | X X X X 16 | X X X X 17 | X X X X 18 | X O X X 19 | 20 | Solution: 21 | 22 | */ 23 | public class SurroundedRegions { 24 | public void solve(char[][] board) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | //swap value of nodes instead of swapping nodes 2 | public class SwapNodesInPairs { 3 | public ListNode swapPairs(ListNode head) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (head == null) { 7 | return null; 8 | } 9 | if (head.next == null) { 10 | return head; 11 | } 12 | ListNode saveHead = head; 13 | while (head != null) { 14 | if (head.next == null) {// the last node 15 | return saveHead; 16 | } 17 | int temp = head.val; 18 | head.val = head.next.val; 19 | head.next.val = temp; 20 | head = head.next.next; 21 | 22 | } 23 | return saveHead; 24 | 25 | } 26 | 27 | public static void main(String[] args) { 28 | SwapNodesInPairs o = new SwapNodesInPairs(); 29 | ListNode head = new ListNode(1); 30 | head.next = new ListNode(2); 31 | // head.next.next=new ListNode(3); 32 | 33 | head = o.swapPairs(head); 34 | System.out.println(head.val); 35 | System.out.println(head.next.val); 36 | // System.out.println(head.next.next.val); 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /SymmetricTree.java: -------------------------------------------------------------------------------- 1 | //solve it recursively 2 | public class SymmetricTree { 3 | public boolean isSymmetric(TreeNode root) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (root == null) { 7 | return true; 8 | } 9 | return isSymmetricHelper(root.left, root.right); 10 | 11 | } 12 | 13 | public boolean isSymmetricHelper(TreeNode left, TreeNode right) { 14 | if (left == null && right == null) { 15 | return true; 16 | } 17 | if ((left == null && right != null) || (right == null && left != null)) { 18 | return false; 19 | } 20 | return (left.val == right.val) 21 | && isSymmetricHelper(left.left, right.right) 22 | && isSymmetricHelper(left.right, right.left); 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /TextJustification.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class TextJustification { 4 | public ArrayList fullJustify(String[] words, int L) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (words.length == 0 || L == 0) { 8 | return new ArrayList(); 9 | } 10 | ArrayList res = new ArrayList(); 11 | String line = new String(); 12 | int size = 0; 13 | int start = 0; 14 | for (int i = 0; i < words.length; i++) { 15 | size += words[i].length(); 16 | if (size > L) {// 17 | line = padString(start, i - 1, words, L); 18 | res.add(line); 19 | size = words[i].length(); 20 | start = i; 21 | } 22 | 23 | } 24 | // ending part 25 | line = padString(start, words.length - 1, words, L); 26 | res.add(line); 27 | return res; 28 | 29 | } 30 | 31 | public String padString(int startIndex, int endIndex, String[] words, 32 | int targetLength) { 33 | if (startIndex > endIndex) { 34 | return null; 35 | } 36 | int currentLength = 0; 37 | int diff = 0; 38 | int gap = 0; 39 | int firstGap = 0; 40 | String gapStr = new String(); 41 | String firstGapStr = new String(); 42 | StringBuilder sb = new StringBuilder(); 43 | 44 | for (int i = startIndex; i <= endIndex; i++) { 45 | currentLength += words[i].length(); 46 | } 47 | 48 | diff = targetLength - currentLength; 49 | if (startIndex == endIndex) {// only one word, left justification 50 | firstGap = diff; 51 | } else { 52 | gap = diff / (endIndex - startIndex + 1); 53 | firstGap = diff % (endIndex - startIndex + 1) == 1 ? gap + 1 : gap; 54 | } 55 | firstGapStr = createPad(firstGap); 56 | // append the first word 57 | sb.append(words[startIndex]); 58 | sb.append(firstGapStr); 59 | 60 | gapStr = createPad(gap); 61 | for (int i = startIndex + 1; i <= endIndex; i++) { 62 | sb.append(words[i]); 63 | if (i != endIndex) { 64 | sb.append(gapStr); 65 | } 66 | 67 | } 68 | return sb.toString(); 69 | 70 | } 71 | 72 | public String createPad(int num) { 73 | if (num == 0) { 74 | return new String(); 75 | } 76 | StringBuilder sb = new StringBuilder(); 77 | for (int i = 1; i <= num; i++) { 78 | sb.append(" "); 79 | } 80 | return sb.toString(); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /ThreeNumSumClosest.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ThreeNumSumClosest { 4 | public static ArrayList threeNumSumClosest(int[] a, int t) { 5 | ArrayList result = new ArrayList(); 6 | Arrays.sort(a); 7 | int difference = Integer.MAX_VALUE; 8 | 9 | for (int i = 0; i < a.length; i++) { 10 | for (int j = i + 1, k = a.length - 1; j < k;) { 11 | if (a[i] + a[j] + a[k] == t) { 12 | result = new ArrayList(); 13 | result.add(a[i]); 14 | result.add(a[j]); 15 | result.add(a[k]); 16 | return result; 17 | } else if (a[i] + a[j] + a[k] < t) { 18 | int temp = t - a[i] - a[j]- a[k]; 19 | if (temp < difference) { 20 | difference=temp; 21 | result = new ArrayList(); 22 | result.add(a[i]); 23 | result.add(a[j]); 24 | result.add(a[k]); 25 | } 26 | j++; 27 | } else { 28 | int temp = a[i] + a[j] + a[k] - t; 29 | if (temp < difference) { 30 | difference=temp; 31 | result = new ArrayList(); 32 | result.add(a[i]); 33 | result.add(a[j]); 34 | result.add(a[k]); 35 | } 36 | k--; 37 | } 38 | } 39 | System.out.println("diff: "+difference); 40 | } 41 | return result; 42 | 43 | } 44 | 45 | public static void main(String[] args) { 46 | int a[] = { 1, 2, -1, 0, 3, 5 }; 47 | ArrayList result = threeNumSumClosest(a,11); 48 | System.out.println(result); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | //idea comes from:https://github.com/anson627/leetcode/blob/master/TrappingRainWater/TrappingRainWater.cpp 2 | //traverse from both ends 3 | public class TrappingRainWater { 4 | public int trap(int[] A) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | int sum = 0; 8 | int n = A.length; 9 | if (n <= 2) { 10 | return 0; 11 | } 12 | int[] lmax = new int[A.length]; 13 | int[] rmax = new int[A.length]; 14 | lmax[0] = A[0]; 15 | for (int i = 1; i < A.length; i++) { 16 | lmax[i] = Math.max(A[i], lmax[i - 1]); 17 | } 18 | 19 | rmax[n - 1] = A[n - 1]; 20 | for (int j = n - 2; j >= 0; j--) { 21 | rmax[j] = Math.max(A[j], rmax[j + 1]); 22 | } 23 | 24 | for (int k = 1; k < n-1; k++) { 25 | int low = Math.min(lmax[k-1], rmax[k+1]); 26 | sum += (low > A[k]) ? (low-A[k]) : 0; 27 | } 28 | return sum; 29 | 30 | } 31 | 32 | public static void main(String[] args){ 33 | TrappingRainWater o=new TrappingRainWater(); 34 | int[] A ={4,2,3}; 35 | System.out.println(o.trap(A)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Triangle.java: -------------------------------------------------------------------------------- 1 | //DP 2 | //idea comes from:http://blog.unieagle.net/2012/10/31/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Atriangle%EF%BC%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/ 3 | //do this using only O(n) extra space, where n is the total number of rows in the triangle. 4 | 5 | import java.util.*; 6 | 7 | public class Triangle { 8 | public int minimumTotal(ArrayList> triangle) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | int rows = triangle.size(); 12 | if (rows == 0) { 13 | return 0; 14 | } 15 | 16 | int[] minSum = new int[rows]; 17 | for (int i = 0; i < rows; i++) { 18 | int[] temp = new int[rows]; 19 | ArrayList level = triangle.get(i); 20 | if (level.size() != i + 1) { 21 | return -1;// input error 22 | } 23 | // first element 24 | temp[0] = level.get(0) + ((i > 0) ? minSum[0] : 0); 25 | // middle elements 26 | for (int j = 1; j < i; j++) { 27 | temp[j] = Math.min(minSum[j - 1], minSum[j]) + level.get(j); 28 | } 29 | // last element 30 | temp[i] = level.get(i) + ((i > 0) ? minSum[i - 1] : 0); 31 | 32 | minSum = temp;// update minSum 33 | // System.out.println("minSum "+minSum[0]+" "+minSum[1]+" "+minSum[2]); 34 | } 35 | 36 | // scan minSum and find the smallest value 37 | int min = Integer.MAX_VALUE; 38 | for (int k = 0; k < rows; k++) { 39 | min = Math.min(min, minSum[k]); 40 | } 41 | return min; 42 | 43 | } 44 | 45 | public static void main(String[] args) { 46 | Triangle o = new Triangle(); 47 | ArrayList a = new ArrayList(); 48 | ArrayList> triangle = new ArrayList>(); 49 | a.add(-1); 50 | triangle.add(a); 51 | a = new ArrayList(); 52 | a.add(2); 53 | a.add(3); 54 | triangle.add(a); 55 | a = new ArrayList(); 56 | a.add(1); 57 | a.add(-1); 58 | a.add(-3); 59 | triangle.add(a); 60 | // System.out.println(triangle); 61 | System.out.println(o.minimumTotal(triangle)); 62 | 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /TwoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class TwoSum { 4 | public int[] twoSum(int[] numbers, int target) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (numbers.length == 0) { 8 | return null; 9 | } 10 | Hashtable hash = new Hashtable(); 11 | int[] result = new int[2]; 12 | int small = 0; 13 | int big = 0; 14 | for (int i = 0; i < numbers.length; i++) { 15 | if (!hash.containsKey(numbers[i])) { 16 | hash.put(target - numbers[i], i); 17 | } else { 18 | small = i < hash.get(numbers[i]) ? i : hash.get(numbers[i]); 19 | big = small == i ? hash.get(numbers[i]) : i; 20 | 21 | } 22 | } 23 | result[0] = small + 1; 24 | result[1] = big + 1; 25 | return result; 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /UniqueBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | //idea comes from: https://github.com/anson627/leetcode/blob/master/UniqueBinarySearchTrees/UniqueBinarySearchTrees.cpp 2 | 3 | //DP, dp[n] is numbers of BSTs for n nodes 4 | //we have a list of n numbers, assuming [1..n] 5 | //if we select 1 as the root, the 0 nodes left in left BST and n-1 nodes in right BST, dp += dp[0]+dp[n-1] 6 | // 7 | 8 | public class UniqueBinarySearchTree { 9 | public int numTrees(int n) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | if (n == 0 || n == 1) { 13 | return 1; 14 | } 15 | 16 | int[] dp = new int[n + 1]; 17 | dp[0] = 1; 18 | dp[1] = 1; 19 | for (int i = 2; i <= n; i++) { 20 | for (int j = 0; j < i; j++) { 21 | dp[i] += dp[j] * dp[i - j - 1]; 22 | } 23 | } 24 | return dp[n]; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /UniqueBinarySearchTreeII.java: -------------------------------------------------------------------------------- 1 | //use recursion 2 | import java.util.*; 3 | 4 | public class UniqueBinarySearchTreeII { 5 | public ArrayList generateTrees(int n) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | if (n == 0) { 9 | ArrayList res = new ArrayList(); 10 | res.add(null); 11 | return res; 12 | } 13 | return generateTrees(1, n); 14 | } 15 | 16 | public ArrayList generateTrees(int low, int upper) { 17 | ArrayList res = new ArrayList(); 18 | if (low > upper) { 19 | res.add(null); 20 | return res; 21 | } 22 | 23 | for (int k = low; k <= upper; k++) { 24 | ArrayList leftTree = generateTrees(low, k - 1); 25 | ArrayList rightTree = generateTrees(k + 1, upper); 26 | for (int i = 0; i < leftTree.size(); i++) { 27 | for (int j = 0; j < rightTree.size(); j++) { 28 | TreeNode root = new TreeNode(k); 29 | root.left = leftTree.get(i); 30 | root.right = rightTree.get(j); 31 | res.add(root); 32 | 33 | } 34 | } 35 | 36 | } 37 | return res; 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /UniquePaths.java: -------------------------------------------------------------------------------- 1 | //idea comes from:https://github.com/anson627/leetcode/blob/master/UniquePaths/UniquePaths.cpp 2 | //DP 3 | //dp[x][y]=dp[x-1][y]+dp[x][y-1] 4 | 5 | public class UniquePaths { 6 | public int uniquePaths(int m, int n) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | if (m == 0 || n == 0) { 10 | return 0; 11 | } 12 | int[][] dp = new int[m][n]; 13 | dp[0][0] = 1; 14 | for (int i = 1; i < m; i++) {// first column 15 | dp[i][0] = dp[i - 1][0]; 16 | } 17 | for (int j = 1; j < n; j++) {// first row 18 | dp[0][j] = dp[0][j - 1]; 19 | } 20 | for (int i = 1; i < m; i++) {// middle part 21 | for (int j = 1; j < n; j++) { 22 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 23 | } 24 | } 25 | return dp[m - 1][n - 1]; 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /UniquePathsII.java: -------------------------------------------------------------------------------- 1 | //another version of unique paths problem 2 | //Attention: if obstacleGrid[0][0]==1 || obstacleGrid[m-1][n-1]==1 then just return 0 3 | public class UniquePathsII { 4 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | int m = obstacleGrid.length; 8 | int n = obstacleGrid[0].length; 9 | if (m == 0 || n == 0) { 10 | return 0; 11 | } 12 | int[][] dp = new int[m][n]; 13 | if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) { 14 | return 0; 15 | } else { 16 | dp[0][0] = 1; 17 | } 18 | for (int i = 1; i < m; i++) { 19 | if (obstacleGrid[i][0] == 0) { 20 | dp[i][0] = dp[i - 1][0]; 21 | } else { 22 | dp[i][0] = 0; 23 | } 24 | } 25 | for (int j = 1; j < n; j++) { 26 | if (obstacleGrid[0][j] == 0) { 27 | dp[0][j] = dp[0][j - 1]; 28 | } else { 29 | dp[0][j] = 0; 30 | } 31 | } 32 | for (int i = 1; i < m; i++) { 33 | for (int j = 1; j < n; j++) { 34 | if (obstacleGrid[i][j] == 0) { 35 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 36 | } else { 37 | dp[i][j] = 0; 38 | } 39 | } 40 | } 41 | return dp[m - 1][n - 1]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ValidNumber.java: -------------------------------------------------------------------------------- 1 | /*// Valid Number 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 11 | // gather all requirements up front before implementing one. 12 | * 13 | */ 14 | //idea comes from: https://github.com/anson627/leetcode/blob/master/ValidNumber/ValidNumber.cpp 15 | //trim the leading and trailing white spaces first 16 | 17 | public class ValidNumber { 18 | public boolean isNumber(String s) { 19 | if (s.length() == 0) { 20 | return false; 21 | } 22 | 23 | // trim leading and trailing white spaces 24 | int h = 0; 25 | int t = 0; 26 | char c = s.charAt(0); 27 | for (int i = 0; i < s.length(); i++) { 28 | c = s.charAt(i); 29 | if (c == ' ') { 30 | h++; 31 | } else { 32 | break; 33 | } 34 | 35 | } 36 | if (h == s.length()) { 37 | return false; 38 | } 39 | for (int j = s.length() - 1; j >= h; j--) { 40 | c = s.charAt(j); 41 | if (c == ' ') { 42 | t++; 43 | } else { 44 | break; 45 | } 46 | } 47 | 48 | // skip leading '+'/'-' 49 | if (s.charAt(h) == '+' || s.charAt(h) == '-') { 50 | h++; 51 | } 52 | boolean num = false; // is a digit 53 | boolean dot = false; // is a dot 54 | boolean e = false; // is a e 55 | 56 | for (int k = h; k <= s.length() - 1 - t; k++) { 57 | c = s.charAt(k); 58 | if (c - '0' >= 0 && c - '0' <= 9) { 59 | num = true; 60 | } else if (c == '.') { 61 | if (e || dot) { 62 | return false; 63 | } 64 | dot = true; 65 | } else if (c == 'e') { 66 | if (e || !num) { 67 | return false; 68 | } 69 | e = true; 70 | num = false; 71 | } else if (c == '+' || c == '-') { 72 | if (s.charAt(k - 1) != 'e') { 73 | return false; 74 | } 75 | } else { 76 | return false; 77 | } 78 | 79 | } 80 | return num; 81 | 82 | } 83 | 84 | public static void main(String[] args) { 85 | String s = "+"; 86 | ValidNumber o = new ValidNumber(); 87 | System.out.println(o.isNumber(s)); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /ValidParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ValidParentheses { 4 | public boolean isValid(String s) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | if (s.length() == 0 || s.length() % 2 == 1) { 8 | return false; 9 | } 10 | int sum = 0; 11 | char target; 12 | Stack k = new Stack(); 13 | for (int i = 0; i < s.length(); i++) { 14 | char c = s.charAt(i); 15 | if (c == '(' || c == '{' || c == '[') { 16 | sum++; 17 | k.push(c); 18 | } else { 19 | sum--; 20 | if (sum < 0 || k.isEmpty()) { 21 | return false; 22 | } 23 | switch (c) { 24 | case ')': 25 | target = '('; 26 | break; 27 | case '}': 28 | target = '{'; 29 | break; 30 | case ']': 31 | target = '['; 32 | break; 33 | default: 34 | return false; 35 | } 36 | if (k.peek() != target) { 37 | return false; 38 | } else { 39 | k.pop(); 40 | } 41 | 42 | } 43 | } 44 | if (sum == 0) { 45 | return true; 46 | } else { 47 | return false; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /WordLadderII.java: -------------------------------------------------------------------------------- 1 | 2 | public class WordLadderII { 3 | 4 | } 5 | -------------------------------------------------------------------------------- /WordSearch.java: -------------------------------------------------------------------------------- 1 | //DP 2 | public class WordSearch { 3 | public boolean exist(char[][] board, String word) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if (board.length == 0 || board[0].length == 0 || word.length() == 0) { 7 | return false; 8 | } 9 | boolean[][] visit = new boolean[board.length][board[0].length]; 10 | boolean result = false; 11 | for (int i = 0; i < board.length; i++) { 12 | for (int j = 0; j < board[0].length; j++) { 13 | if (board[i][j] == word.charAt(0)) { 14 | visit = new boolean[board.length][board[0].length]; 15 | result = result || existDP(board, word, visit, i, j, 0); 16 | } 17 | } 18 | } 19 | return result; 20 | 21 | } 22 | 23 | public boolean existDP(char[][] board, String word, boolean[][] visit, 24 | int row, int col, int step) { 25 | // System.out.println("row " + row); 26 | // System.out.println("col " + col); 27 | // System.out.println("step " + step); 28 | // System.out.println("length " + word.length()); 29 | if (step == word.length() - 1) { 30 | return board[row][col] == word.charAt(step);// done 31 | } 32 | if (board[row][col] != word.charAt(step)) { 33 | return false; 34 | } 35 | int rowNum = board.length; 36 | int colNum = board[0].length; 37 | boolean left = col == 0 ? false : true; 38 | boolean right = col == colNum - 1 ? false : true; 39 | boolean up = row == 0 ? false : true; 40 | boolean down = row == rowNum - 1 ? false : true; 41 | boolean move = false; 42 | 43 | boolean result = (board[row][col] == word.charAt(step)); 44 | boolean leftRes = false; 45 | boolean rightRes = false; 46 | boolean upRes = false; 47 | boolean downRes = false; 48 | 49 | visit[row][col] = true; 50 | if (left && !visit[row][col - 1]) { 51 | // System.out.println("1"); 52 | leftRes = existDP(board, word, visit, row, col - 1, step + 1); 53 | move = true; 54 | 55 | } 56 | if (right && !visit[row][col + 1]) { 57 | // System.out.println("2"); 58 | rightRes = existDP(board, word, visit, row, col + 1, step + 1); 59 | move = true; 60 | 61 | } 62 | if (up && !visit[row - 1][col]) { 63 | // System.out.println("3"); 64 | upRes = existDP(board, word, visit, row - 1, col, step + 1); 65 | move = true; 66 | 67 | } 68 | if (down && !visit[row + 1][col]) { 69 | // System.out.println("4"); 70 | downRes = existDP(board, word, visit, row + 1, col, step + 1); 71 | move = true; 72 | 73 | } 74 | // System.out.println("move " + move); 75 | if (step < word.length() - 1 && !move) { 76 | return false; 77 | } 78 | result = leftRes || rightRes || upRes || downRes; 79 | // System.out.println("lRes "+leftRes); 80 | // System.out.println("rRes "+rightRes); 81 | // System.out.println("uRes "+upRes); 82 | // System.out.println("dRes "+downRes); 83 | // 84 | // System.out.println("result " + result); 85 | 86 | return result; 87 | 88 | } 89 | 90 | public static void main(String[] args) { 91 | WordSearch o = new WordSearch(); 92 | char[][] board = { { 'a', 'b' } }; 93 | String word = "abb"; 94 | System.out.println(o.exist(board, word)); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /ZigZagConversion.java: -------------------------------------------------------------------------------- 1 | /* 2 | Examples: 3 | nRows==1: 4 | 12345 5 | nRows==2: 6 | 135 differences: 2 7 | 246 2 8 | nRows==3: 9 | 1 5 9 4 4 10 | 246810 2 4 4 2 11 | 3 7 11 4 4 12 | nRows==4: 13 | 1 7 13 6 6 14 | 2 68 1214 4 2 4 2 15 | 35 9 11 15 2 4 2 4 16 | 4 10 16 6 6 17 | nRows==5: 18 | 1 9 17 8 8 19 | 2 810 1618 6 2 6 2 20 | 3 7 11 15 19 4 4 4 4 21 | 46 12 14 20 2 6 2 6 22 | 5 13 21 8 8 23 | 24 | 25 | 26 | */ 27 | 28 | public class ZigZagConversion { 29 | public String convert(String s, int nRows) { 30 | // Start typing your Java solution below 31 | // DO NOT write main() function 32 | 33 | if (s.length() == 0 || nRows == 1 || nRows >= s.length()) { 34 | return s; 35 | } 36 | if (nRows == 0) { 37 | return null; 38 | } 39 | StringBuilder sb = new StringBuilder(); 40 | String[] result = new String[nRows]; 41 | int oddDiff = 0;// difference at odd position 42 | int evenDiff = 0; 43 | int maxDiff = (nRows - 1) * 2; 44 | for (int i = 0; i <= nRows - 1; i++) { 45 | sb = new StringBuilder(); 46 | int startPos = i; 47 | int k = 0; 48 | if (i == 0 || i == nRows - 1) { 49 | oddDiff = maxDiff; 50 | evenDiff = maxDiff; 51 | } else { 52 | oddDiff = 2 * i; 53 | evenDiff = maxDiff - oddDiff; 54 | } 55 | while (startPos <= s.length() - 1) { 56 | sb.append(s.charAt(startPos)); 57 | if (k % 2 == 0) { 58 | startPos += evenDiff; 59 | } else { 60 | startPos += oddDiff; 61 | } 62 | k++; 63 | } 64 | result[i] = sb.toString(); 65 | 66 | } 67 | sb = new StringBuilder(); 68 | for (int i = 0; i < result.length; i++) { 69 | sb.append(result[i]); 70 | } 71 | return sb.toString(); 72 | } 73 | 74 | public static void main(String[] args) { 75 | ZigZagConversion o = new ZigZagConversion(); 76 | String s = "PAYPALISHIRING"; 77 | int nRows = 2; 78 | System.out.println(o.convert(s, nRows)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /threeSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class threeSum { 4 | public ArrayList> threeSumMethod(int[] num) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | Arrays.sort(num); 8 | int[] opposite = new int[num.length]; 9 | int sum = 0; 10 | ArrayList threeNum; 11 | ArrayList> result = new ArrayList>(); 12 | Hashtable count = new Hashtable(); 13 | Hashtable, Boolean> occurrence = new Hashtable, Boolean>(); 14 | for (int i = 0; i < num.length; i++) { 15 | opposite[i] = num[i] * (-1); 16 | if (!count.containsKey(num[i])) { 17 | count.put(num[i], 1); 18 | } else { 19 | int val = count.get(num[i]); 20 | count.put(num[i], val + 1); 21 | } 22 | } 23 | System.out.println(Arrays.toString(num)); 24 | System.out.println(Arrays.toString(opposite)); 25 | 26 | System.out.println(count); 27 | 28 | // sliding window 29 | for (int i = 0; i < num.length; i++) { 30 | int start = 0; 31 | int end = num.length - 1; 32 | while (start < end) { 33 | System.out.print("i:" + i); 34 | System.out.print("opposite: " + opposite[i]); 35 | System.out.print("start:" + num[start] + " "); 36 | System.out.print("end" + num[end] + " "); 37 | sum = num[start] + num[end]; 38 | System.out.print("sum:" + sum + " "); 39 | if (sum ==opposite[i]) { 40 | if ((num[start] == opposite[i]&& count.get(opposite[i]) <= 1) || (num[end] == opposite[i]&& count.get(opposite[i]) <= 1)) { 41 | System.out.println("false!!!"); 42 | 43 | } 44 | 45 | else { 46 | threeNum = new ArrayList(); 47 | threeNum.add(opposite[i]); 48 | threeNum.add(num[start]); 49 | threeNum.add(num[end]); 50 | System.out.println("threeNum: " + threeNum); 51 | Collections.sort(threeNum); 52 | if (!occurrence.containsKey(threeNum)) { 53 | result.add(threeNum); 54 | occurrence.put(threeNum, true); 55 | } 56 | } 57 | 58 | start++; 59 | end--; 60 | } else if (sum > opposite[i]) { 61 | end--; 62 | } else { 63 | start++; 64 | } 65 | } 66 | 67 | } 68 | return result; 69 | } 70 | 71 | public static void main(String[] args) { 72 | int[] number = { -1, 2, 3, -2, 0, 4, 0, 0 }; 73 | // Start typing your code here... 74 | threeSum o = new threeSum(); 75 | ArrayList> result = new ArrayList>(); 76 | result = o.threeSumMethod(number); 77 | System.out.println(result); 78 | 79 | } 80 | 81 | } 82 | --------------------------------------------------------------------------------