├── .gitignore ├── 3Sum1.java ├── 3Sum2.java ├── 3Sum3.java ├── 3Sum4.java ├── 3SumCloset.java ├── 4Sum.java ├── AddBinary1.java ├── AddBinary2.java ├── AddBinary3.java ├── AddTwoNumbers.java ├── BestTimeToBuyAndSellStock.java ├── BestTimeToBuyAndSellStockII.java ├── Decodeways.java ├── FlattenBinaryTreeToLinkedList.java ├── N-Queens.java ├── N-QueensII.java ├── SortColors.java ├── anagrams.java ├── balancebinarytree.java ├── binaryTreeLevelOrderTraversal.java ├── binaryTreeZigzagLevelOrderTraversal.java ├── btreeInorderTraversal.java ├── climbingstairs1.java ├── climbingstairs2.java ├── climbingstairs3.java ├── combinationSumII3.java ├── combinations1.java ├── combinationsum.java ├── combinationsumII1.java ├── combinationsum||2.java ├── constructBinaryTreeFromInorderAndPostorderTraversal.java ├── constructBinaryTreeFromPreorderAndInorderTraversal.java ├── containerwithmostwater.java ├── convertSortedArrayToBinarySearchTree.java ├── convertSortedListToBinarySearchTree.java ├── countandsay.java ├── findmissingpositive.java ├── generateparentheses.java ├── graycode.java ├── insertinterval1.java ├── insertinterval2.java ├── interleavingstring.java ├── jumpgame1.java ├── jumpgame2.java ├── jumpgameII.java ├── largestrectangleinhistogram.java ├── largestrectangleinhistogram1.java ├── largestrectangleinhistogram2.java ├── largestrectangleinhistogram3.java ├── largestrectangleinhistogram4.java ├── lengthoflastword1.java ├── lengthoflastword2.java ├── lettercombinationsofphonenumber.java ├── longestcommonprefix.java ├── longestprolindromicsubstring.java ├── longestsubstringwithoutrepeatingcharaters.java ├── longestvalidparentheses1.java ├── longestvalidprentheses2.java ├── maximalrectangle1.java ├── maximumDepthofBinaryTree.java ├── maximumsubarray1.java ├── maximumsubarray2.java ├── medianoftwosortedarrays.java ├── mergeintervals.java ├── mergeksortedlists.java ├── mergesortedarray.java ├── mergetwosortedlists.java ├── minimumDepthOfBinaryTree.java ├── minimumpathsum.java ├── minimumwindowsubstring.java ├── palindromeNumber.java ├── pascal'sTriangle.java ├── pathSum.java ├── pathSumII.java ├── permutations.java ├── plusone.java ├── populatingNextRightPointersInEachNode.java ├── populatingNextRightPointersInEachNodeII.java ├── pow.java ├── readme.txt ├── recoverbinarysearchtree.java ├── removeduplicatesfromsortedarray.java ├── removeduplicatesfromsortedarrayII.java ├── removeduplicatesfromsortedlistII.java ├── removeduplicatesfromsortlist.java ├── removeelement.java ├── removenthnodefromendoflist.java ├── restoreipaddresses.java ├── reverseinteger.java ├── reverselinkedlistII.java ├── reversenodesinkgroup.java ├── rotateimage.java ├── rotatelist.java ├── sametree1.java ├── sametree2.java ├── searcha2DMatrix.java ├── searchforarange.java ├── searchinrotatedsortedarray.java ├── searchinrotatedsortedarrayII.java ├── searchinsertposition.java ├── setmatrixzeroes.java ├── sodukusolver.java ├── spiralmatrix.java ├── spiralmatrixII.java ├── sqrt(x).java ├── strStr.java ├── subset.java ├── subset||.java ├── substringwithconcatenationofallwords.java ├── swapnodesinpairs.java ├── symmetrictree.java ├── trappingrainwater.java ├── twosum.java ├── uniquebinarysearchtrees.java ├── uniquebinarysearchtreesII.java ├── uniquepath.java ├── uniquepathII.java ├── validbst.java ├── validnumber.java ├── validparentheses.java ├── validsoduku.java └── wordsearch.java /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /3Sum1.java: -------------------------------------------------------------------------------- 1 | /* judge samll:passed 2 | judge large:Time limit exceeded 3 | time complexity: O(n^3) 4 | Memo: java.util.Arrays to use Arrays.sort(); 1)It is in place; 5 | java.util.ArrayList to use ArrayList; 1)ArrayList.get(index) to get one element;2)ArrayList.contains() 6 | */ 7 | import java.util.Arrays; 8 | import java.util.ArrayList; 9 | public class Solution { 10 | public ArrayList> threeSum(int[] num) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | ArrayList> result = new ArrayList>(); 14 | 15 | if(num.length<3) 16 | return result; 17 | 18 | Arrays.sort(num); 19 | for(int i=0;i triplet = new ArrayList(3); 24 | triplet.add(num[i]); 25 | triplet.add(num[j]); 26 | triplet.add(num[p]); 27 | if(!result.contains(triplet)) 28 | result.add(triplet); 29 | } 30 | } 31 | 32 | return result; 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /3Sum2.java: -------------------------------------------------------------------------------- 1 | /* judge samll:passed 2 | judge large:Time limit exceeded 3 | time complexity: O(n^2logn) 4 | */ 5 | import java.util.Arrays; 6 | import java.util.ArrayList; 7 | public class Solution { 8 | public ArrayList> threeSum(int[] num) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | ArrayList> result = new ArrayList>(); 12 | 13 | if(num.length<3) 14 | return result; 15 | 16 | Arrays.sort(num); 17 | for(int i=0;i=0){ 20 | ArrayList triplet = new ArrayList(3); 21 | triplet.add(num[i]); 22 | triplet.add(num[j]); 23 | triplet.add(-num[i]-num[j]); 24 | if(!result.contains(triplet)) 25 | result.add(triplet); 26 | } 27 | return result; 28 | } 29 | 30 | public static int binarySearch(int[] num,int p,int r, int val){ 31 | if(num==null || num.length==0 || p>r) 32 | return -1; 33 | int m = (p+r)/2; 34 | if( val ==num[m]) 35 | return m; 36 | else if (val>num[m]) 37 | return binarySearch(num,m+1,r,val); 38 | else 39 | return binarySearch(num,p,m-1,val); 40 | } 41 | 42 | } 43 | 44 | -------------------------------------------------------------------------------- /3Sum3.java: -------------------------------------------------------------------------------- 1 | /* judge samll:passed 2 | judge large: passed mostly,around 1000-1100 ms, sometimes time limit exceeded 3 | time complexity: O(n^2) 4 | */ 5 | 6 | import java.util.*; 7 | public class Solution { 8 | public ArrayList> threeSum(int[] num) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | ArrayList> ret = new ArrayList>(); 12 | if(num.length<3) 13 | return ret; 14 | 15 | Arrays.sort(num); 16 | for(int i=0;i triplet = new ArrayList(3); 21 | triplet.add(num[i]); 22 | triplet.add(num[p]); 23 | triplet.add(num[q]); 24 | if(!ret.contains(triplet)) 25 | ret.add(triplet); 26 | p++; q--; // add "q--" here to avoid more duplicates 27 | } 28 | else if (num[p]+num[q]>-num[i]) 29 | q--; 30 | else 31 | p++; 32 | } 33 | } 34 | return ret; 35 | 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /3Sum4.java: -------------------------------------------------------------------------------- 1 | /* judge samll:passed 2 | judge large: passed mostly,around 700-800 ms 3 | time complexity: O(n^2) 4 | 5 | Based on 3Sum3.java, applied the avoid-redundency method by Chi Su. 6 | */ 7 | 8 | import java.util.*; 9 | 10 | public class Solution { 11 | public int increment(int[] num, int index) { 12 | int newindex = index + 1; 13 | while(newindex < num.length && num[newindex] == num[index]) 14 | newindex ++; 15 | return newindex; 16 | } 17 | 18 | public int decrement(int[] num, int index) { 19 | int newindex = index - 1; 20 | while(newindex >= 0 && num[newindex] == num[index]) 21 | newindex --; 22 | return newindex; 23 | } 24 | public ArrayList> threeSum(int[] num) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | ArrayList> ret = new ArrayList>(); 28 | if (num.length < 3) 29 | return ret; 30 | 31 | Arrays.sort(num); 32 | for (int i = 0; i < num.length - 2; i = increment(num, i)) { 33 | int p = i + 1, q = num.length - 1; 34 | while (p < q) { 35 | if (num[p] + num[q] == -num[i]) { 36 | ArrayList triplet = new ArrayList(3); 37 | triplet.add(num[i]); 38 | triplet.add(num[p]); 39 | triplet.add(num[q]); 40 | 41 | ret.add(triplet); 42 | p = increment(num, p); 43 | q = decrement(num, q); 44 | } else if (num[p] + num[q] > -num[i]) 45 | q = decrement(num, q); 46 | else 47 | p = increment(num, p); 48 | } 49 | } 50 | 51 | return ret; 52 | 53 | } 54 | 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /3SumCloset.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public int increment(int[] num, int index) { 5 | int newindex = index + 1; 6 | while(newindex < num.length && num[newindex] == num[index]) 7 | newindex ++; 8 | return newindex; 9 | } 10 | 11 | public int decrement(int[] num, int index) { 12 | int newindex = index - 1; 13 | while(newindex >= 0 && num[newindex] == num[index]) 14 | newindex --; 15 | return newindex; 16 | } 17 | public int threeSumClosest(int[] num,int target) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | int ret=num[0]+num[1]+num[2]; 21 | 22 | Arrays.sort(num); 23 | for (int i = 0; i < num.length - 2; i = increment(num, i)) { 24 | int p = i + 1, q = num.length - 1; 25 | while (p < q) { 26 | int sum = num[p] + num[q] + num[i]; 27 | if (sum ==target) 28 | return target; 29 | else if(Math.abs(sum-target)target) 33 | q = decrement(num, q); 34 | else 35 | p = increment(num, p); 36 | } 37 | } 38 | 39 | return ret; 40 | 41 | } 42 | 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /4Sum.java: -------------------------------------------------------------------------------- 1 | /* judge samll:passed 2 | judge large: passed mostly,around 1000-1100 ms 3 | time complexity: O(n^3) 4 | 5 | Based on 3Sum4.java 6 | */ 7 | 8 | import java.util.*; 9 | 10 | public class Solution { 11 | public int increment(int[] num, int index) { 12 | int newindex = index + 1; 13 | while(newindex < num.length && num[newindex] == num[index]) 14 | newindex ++; 15 | return newindex; 16 | } 17 | 18 | public int decrement(int[] num, int index) { 19 | int newindex = index - 1; 20 | while(newindex >= 0 && num[newindex] == num[index]) 21 | newindex --; 22 | return newindex; 23 | } 24 | public ArrayList> fourSum(int[] num, int target) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | ArrayList> ret = new ArrayList>(); 28 | if (num.length<4) 29 | return ret; 30 | 31 | Arrays.sort(num); 32 | for (int i = 0; i < num.length - 3; i = increment(num, i)) 33 | for(int j=i+1;j quadruplet = new ArrayList(3); 38 | quadruplet.add(num[i]); 39 | quadruplet.add(num[j]); 40 | quadruplet.add(num[p]); 41 | quadruplet.add(num[q]); 42 | ret.add(quadruplet); 43 | p = increment(num, p); 44 | q = decrement(num, q); 45 | } else if (num[p] + num[q] +num[i] +num[j]>target) 46 | q = decrement(num, q); 47 | else 48 | p = increment(num, p); 49 | } 50 | } 51 | 52 | return ret; 53 | 54 | } 55 | 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /AddBinary1.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small: passed 3 | judge large: wrong. In some test cases, the binary number is incredibly big so that 4 | java primitive data types can not handle. 5 | 6 | Convert binary strings to numbers, add numbers and convert the sum back to binary string 7 | */ 8 | 9 | public class Solution { 10 | public String addBinary(String a, String b) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | return decimalToBinary(binaryToDecimal(a)+binaryToDecimal(b)); 14 | } 15 | 16 | public long binaryToDecimal(String binary){ 17 | long deci =0; 18 | for(int i=binary.length()-1;i>=0;i--) 19 | if(binary.charAt(i)=='1') 20 | deci += Math.pow(2,binary.length()-1-i); 21 | return deci; 22 | } 23 | 24 | public String decimalToBinary(long deci){ 25 | long leftover = deci; 26 | String binary = ""; 27 | if(leftover==0) 28 | return "0"; 29 | while(leftover>0){ 30 | long currentbit = leftover%2; 31 | binary = currentbit+binary; 32 | leftover = leftover/2; 33 | } 34 | return binary; 35 | } 36 | } -------------------------------------------------------------------------------- /AddBinary2.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small: passed 3 | judge large: passed 4 | 5 | This solution is correct but the code is messy. 6 | */ 7 | public class Solution { 8 | public String addBinary(String a, String b) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | char[] aChars=a.toCharArray(); 12 | char[] bChars=b.toCharArray(); 13 | int ap=aChars.length-1; 14 | int bp=bChars.length-1; 15 | int step = 0; 16 | String sum =""; 17 | 18 | while(ap>=0||bp>=0||step>0){ 19 | if(ap>=0||bp>=0){ 20 | int temp =0; 21 | if(ap>=0 && bp>=0) 22 | temp = step+Integer.parseInt(aChars[ap]+"")+Integer.parseInt(bChars[bp]+""); 23 | else if(ap>=0) 24 | temp = step+Integer.parseInt(aChars[ap]+""); 25 | else 26 | temp = step+Integer.parseInt(bChars[bp]+""); 27 | switch(temp){ 28 | case 0: sum = "0"+sum;step=0;break; 29 | case 1: sum = "1"+sum;step=0;break; 30 | case 2: sum = "0"+sum;step=1;break; 31 | case 3: sum = "1"+sum;step=1;break; 32 | 33 | } 34 | } 35 | else if(step==1){ 36 | sum= "1"+sum; 37 | step=0; 38 | } 39 | 40 | ap--;bp--; 41 | } 42 | return sum; 43 | 44 | } 45 | 46 | 47 | } -------------------------------------------------------------------------------- /AddBinary3.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small: passed 3 | judge large: passed 4 | 5 | Improved version from AddBinary2.java 6 | 7 | */ 8 | public class Solution { 9 | public String addBinary(String a, String b) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | int ap=a.length()-1; 13 | int bp=b.length()-1; 14 | int count = 0; 15 | String sum =""; 16 | 17 | while(ap>=0||bp>=0||count>0){ 18 | if(ap>=0 && a.charAt(ap)=='1') 19 | count++; 20 | if(bp>=0 && b.charAt(bp)=='1') 21 | count++; 22 | sum = count%2+sum; 23 | count = count/2; 24 | ap--;bp--; 25 | } 26 | return sum; 27 | 28 | } 29 | 30 | 31 | } -------------------------------------------------------------------------------- /AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | The paradigm of this solution and that of AddBinary3.java are similar. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | public class Solution { 17 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | ListNode header = new ListNode(-1); 21 | ListNode prev = header; 22 | int sum=0; 23 | while(l1!=null || l2!=null || sum>0){ 24 | if(l1!=null) 25 | sum+=l1.val; 26 | if(l2!=null) 27 | sum+=l2.val; 28 | int val = sum%10; 29 | sum = sum/10; 30 | ListNode current = new ListNode(val); 31 | prev.next = current; 32 | prev = current; 33 | l1 = l1==null?l1:l1.next; 34 | l2 = l2==null?l2:l2.next; 35 | } 36 | return header.next; 37 | } 38 | } -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(prices==null || prices.length==0) 6 | return 0; 7 | 8 | int bot = prices[0]; 9 | int maxProfit = 0; 10 | for(int i=0;imaxProfit) 14 | maxProfit = prices[i]-bot; 15 | } 16 | 17 | return maxProfit; 18 | 19 | } 20 | } -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStockII.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(prices==null || prices.length==0) 6 | return 0; 7 | int maxProfit = 0; 8 | 9 | for(int i=1;iprices[i-1]) 11 | maxProfit += prices[i]-prices[i-1]; 12 | } 13 | 14 | return maxProfit; 15 | } 16 | } -------------------------------------------------------------------------------- /Decodeways.java: -------------------------------------------------------------------------------- 1 | /* 2 | This freaking problem seems quite easy, but I messed up for quite a long while. 3 | */ 4 | 5 | 6 | public class Solution { 7 | public int numDecodings(String s) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if(s.length()==0 || s.charAt(0)=='0') 11 | return 0; 12 | for(int i=1;i'2'||s.charAt(i-1)=='0') && s.charAt(i)=='0') 14 | return 0; 15 | 16 | 17 | int[] dp = new int[s.length()+1]; 18 | dp[0] =1; 19 | dp[1] =1; 20 | 21 | for(int i=2;i solveNQueens(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList res = new ArrayList(); 6 | solveNQueens(0,new int[n],res); 7 | return res; 8 | } 9 | 10 | public void solveNQueens(int cur, int[] row, ArrayList res) { 11 | int n = row.length; 12 | if(cur == n) 13 | res.add(generateSol(row)); 14 | else 15 | for(int i=0;ip]==0 5 | A[p->r]== unknown 6 | A[r->A.length-1]==2 7 | */ 8 | 9 | public class Solution { 10 | public void sortColors(int[] A) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | int p=-1,r=A.length; 14 | for(int q=0;q anagrams(String[] strs) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | ArrayList result = new ArrayList(); 12 | 13 | HashMap> map = new HashMap>(); 14 | 15 | for(String str : strs){ 16 | char[] tempstr= str.toCharArray(); 17 | Arrays.sort(tempstr); 18 | String sortedstr = new String(tempstr); 19 | if(map.containsKey(sortedstr)){ 20 | map.get(sortedstr).add(str); 21 | }else{ 22 | ArrayList list = new ArrayList(); 23 | list.add(str); 24 | map.put(sortedstr,list); 25 | } 26 | } 27 | 28 | for(ArrayList list:map.values()) 29 | if(list.size()>1) 30 | for(String str : list) 31 | result.add(str); 32 | 33 | return result; 34 | } 35 | } -------------------------------------------------------------------------------- /balancebinarytree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isBalanced(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | 15 | 16 | if(root == null) return true; 17 | int leftSubtreeHeight = height(root.left); 18 | int rightSubtreeHeight = height(root.right); 19 | return Math.abs(leftSubtreeHeight-rightSubtreeHeight)<=1 && 20 | isBalanced(root.left) && isBalanced(root.right); 21 | } 22 | 23 | public int height(TreeNode node){ 24 | if(node ==null) return 0; 25 | 26 | return 1+Math.max(height(node.left),height(node.right)); 27 | } 28 | 29 | 30 | } -------------------------------------------------------------------------------- /binaryTreeLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | It's not hard to come up with BFS and 2 queues. 3 | In fact, we can also do this with BFS and 1 queue. http://www.leetcode.com/2010/09/printing-binary-tree-in-level-order.html 4 | And even DFS http://www.leetcode.com/2010/09/binary-tree-level-order-traversal-using_17.html 5 | or http://www.geeksforgeeks.org/archives/2686 6 | */ 7 | 8 | /** 9 | * Definition for binary tree 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public ArrayList> levelOrder(TreeNode root) { 19 | // Start typing your Java solution below 20 | // DO NOT write main() function 21 | ArrayList> res = new ArrayList>(); 22 | Queue q = new LinkedList(); 23 | q.add(root); 24 | 25 | while(q.peek()!=null){ 26 | Queue p = new LinkedList(); 27 | ArrayList clvl = new ArrayList(); 28 | 29 | while(q.peek()!=null){ 30 | TreeNode node = q.poll(); 31 | clvl.add(node.val); 32 | if(node.left!=null) 33 | p.add(node.left); 34 | if(node.right!=null) 35 | p.add(node.right); 36 | } 37 | res.add(clvl); 38 | q = p; 39 | 40 | } 41 | 42 | return res; 43 | } 44 | } -------------------------------------------------------------------------------- /binaryTreeZigzagLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | It's similar to binaryTreeLevelOrderTraversal except we use stack and do some 3 | minor change. 4 | /* 5 | /** 6 | * Definition for binary tree 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | 15 | public class Solution { 16 | public ArrayList> zigzagLevelOrder(TreeNode root) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | ArrayList> res = new ArrayList>(); 20 | if(root==null) return res; 21 | Stack q = new Stack(); 22 | q.push(root); 23 | boolean leftToRight = true; 24 | 25 | while(!q.empty()){ 26 | Stack p = new Stack(); 27 | ArrayList clvl = new ArrayList(); 28 | 29 | while(!q.empty()){ 30 | TreeNode node = q.pop(); 31 | clvl.add(node.val); 32 | if(leftToRight){ 33 | if(node.left!=null) 34 | p.push(node.left); 35 | if(node.right!=null) 36 | p.push(node.right); } 37 | else{ 38 | if(node.right!=null) 39 | p.push(node.right); 40 | if(node.left!=null) 41 | p.push(node.left); } 42 | } 43 | leftToRight=!leftToRight; 44 | res.add(clvl); 45 | q = p; 46 | 47 | } 48 | 49 | return res; 50 | } 51 | } -------------------------------------------------------------------------------- /btreeInorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Iterative Binary Tree Inorder Traversal. 3 | For Preoder and Postoerder, please refer to http://www.brilliantsheep.com/iterative-binary-tree-traversal-in-java/ 4 | 5 | */ 6 | 7 | 8 | /* 9 | * Definition for binary tree 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | 18 | import java.util.*; 19 | public class Solution { 20 | public ArrayList inorderTraversal(TreeNode root) { 21 | // Start typing your Java solution below 22 | // DO NOT write main() function 23 | ArrayList result = new ArrayList(); 24 | Stack stack = new Stack(); 25 | TreeNode node= root; 26 | 27 | while(!stack.isEmpty() || node!=null){ 28 | if(node != null){ 29 | stack.push(node); 30 | node = node.left; 31 | }else { 32 | node = stack.pop(); 33 | result.add(node.val); 34 | node = node.right; 35 | } 36 | } 37 | return result; 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /climbingstairs1.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small : passed 3 | judge large : time limit exceeded 4 | */ 5 | 6 | 7 | public class Solution { 8 | public int climbStairs(int n) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | if(n==0) 12 | return 0; 13 | else 14 | return climbStairs(0,n); 15 | 16 | } 17 | 18 | public int climbStairs(int level,int n){ 19 | if(level> n) 20 | return 0; 21 | else if(level==n) 22 | return 1; 23 | else 24 | return climbStairs(level+1,n)+climbStairs(level+2,n); 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /climbingstairs2.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small : passed 540ms 3 | judge large : passed 520ms 4 | 5 | Added cache to the previous solution. 6 | */ 7 | 8 | import java.util.*; 9 | public class Solution { 10 | public int climbStairs(int n) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | if(n==0) 14 | return 0; 15 | else{ 16 | HashMap cache = new HashMap(); 17 | return climbStairs(0,n,cache); 18 | } 19 | } 20 | 21 | public int climbStairs(int level,int n,HashMap cache){ 22 | if(level> n) 23 | return 0; 24 | else if(level==n) 25 | return 1; 26 | else { 27 | int count1=0; 28 | int count2=0; 29 | if(cache.containsKey(level+1)) 30 | count1 = cache.get(level+1); 31 | else{ 32 | count1 = climbStairs(level+1,n,cache); 33 | cache.put(level+1,count1); 34 | } 35 | if(cache.containsKey(level+2)) 36 | count2 = cache.get(level+2); 37 | else{ 38 | count2 = climbStairs(level+2,n,cache); 39 | cache.put(level+2,count2); 40 | } 41 | 42 | return count1+count2; 43 | } 44 | 45 | } 46 | } -------------------------------------------------------------------------------- /climbingstairs3.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small : passed 470ms 3 | judge large : passed 510ms 4 | 5 | This is Chi Su's solution on his github. His solution reminds me of me reading this problem and similar answer before囧. 6 | Anyway, this solution is more elegant than climbingstairs2.java and more effecient than climbingstairs1.java. 7 | */ 8 | 9 | 10 | import java.util.*; 11 | public class Solution { 12 | public int climbStairs(int n) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | int[] level = new int[n+1]; 16 | level[0] = 1; 17 | level[1] = 1; 18 | for(int i=2;i> combinationSum2(int[] num, int target) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | // Initialization 13 | Arrays.sort(num); 14 | int size = num[num.length-1]>target?num[num.length-1]+1:target+1; 15 | Vector>> dp = new Vector>>(size); 16 | for(int i=0;i>()); 18 | 19 | HashMap count = new HashMap(); 20 | for(int i=0;i=0;j--) 31 | if(j+1 list = new ArrayList(); 35 | list.add(num[j]); 36 | dp.get(i).add(list); 37 | }else if(i-num[j]>0) 38 | for(ArrayList list:dp.get(i-num[j])) 39 | if(list.get(list.size()-1)<=num[j]){ 40 | int numOfNum=1; 41 | for(Integer in:list) 42 | if(in==num[j]) 43 | numOfNum++; 44 | if(numOfNum<=count.get(num[j])){ 45 | ArrayList combo = new ArrayList(list); 46 | combo.add(num[j]); 47 | dp.get(i).add(combo); 48 | } 49 | } 50 | 51 | 52 | return dp.get(target); 53 | 54 | 55 | } 56 | } -------------------------------------------------------------------------------- /combinations1.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small: passed 470ms 3 | judge large: passed 620ms 4 | 5 | */ 6 | 7 | public class Solution { 8 | public ArrayList> combine(int n, int k) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | 12 | return find_combine(n,k); 13 | } 14 | 15 | public ArrayList> find_combine(int n,int k){ 16 | ArrayList> res = new ArrayList>(); 17 | if(k==0 || k>n) 18 | res.add(new ArrayList()); 19 | else if (k==n){ 20 | ArrayList combo = new ArrayList(); 21 | for(int i=1;i<=n;i++) 22 | combo.add(i); 23 | res.add(combo); 24 | }else{ 25 | for(ArrayList list : find_combine(n-1,k)) 26 | res.add(list); 27 | for(ArrayList list : find_combine(n-1,k-1)){ 28 | ArrayList combo = new ArrayList (); 29 | for(Integer i : list) 30 | combo.add(i); 31 | combo.add(n); 32 | res.add(combo); 33 | } 34 | } 35 | return res; 36 | } 37 | } -------------------------------------------------------------------------------- /combinationsum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Dynamic programming. 3 | It is extended from the climbing stairs problem. 4 | 5 | judge small:476ms 6 | judge large:940ms 7 | 8 | */ 9 | 10 | 11 | import java.util.*; 12 | public class Solution { 13 | public ArrayList> combinationSum(int[] candidates, int target) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | ArrayList> result = new ArrayList>(); 17 | if(candidates.length==0) 18 | return result; 19 | 20 | Arrays.sort(candidates); 21 | 22 | int size = target>candidates[candidates.length-1]? target+1:candidates[candidates.length-1]+1; 23 | 24 | Vector>> dp = new Vector>>(size); 25 | for(int i=0;i>()); 27 | for(int i=0;i list = new ArrayList(); 29 | list.add(candidates[i]); 30 | dp.get(candidates[i]).add(list); 31 | } 32 | 33 | 34 | for(int j=candidates[0];j=0;i--) 36 | if(j-candidates[i]>=0 && dp.get(j-candidates[i])!=null) 37 | for(ArrayList list : dp.get(j-candidates[i])) 38 | if(list.get(list.size()-1)<=candidates[i]){ 39 | ArrayList combo = new ArrayList(list); 40 | combo.add(candidates[i]); 41 | dp.get(j).add(combo); 42 | } 43 | return dp.get(target); 44 | } 45 | } -------------------------------------------------------------------------------- /combinationsumII1.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small :passed 560ms 3 | judge large :time limit exceeded sometimes 950ms 4 | 5 | This is a bad solution in terms of performance. 6 | 7 | */ 8 | 9 | import java.util.*; 10 | public class Solution { 11 | public ArrayList> combinationSum2(int[] num, int target) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | ArrayList> result = new ArrayList>(); 15 | Arrays.sort(num); 16 | combinationSum2(num,target,0,new ArrayList(),result); 17 | return result; 18 | } 19 | 20 | public void combinationSum2(int[] num, int target, int pointer, ArrayList currentCombo,ArrayList> result) { 21 | if(target==0){ 22 | if(!result.contains(currentCombo)) 23 | result.add(new ArrayList(currentCombo)); 24 | return; 25 | }else if(target<0 || pointer<0) 26 | return; 27 | 28 | for(int i=pointer;i> combinationSum2(int[] num, int target) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | Arrays.sort(num); 15 | return find_combinationSum2(num,target,num.length-1); 16 | } 17 | 18 | public ArrayList> find_combinationSum2(int[] num, int target, int pointer){ 19 | ArrayList> result = new ArrayList>(); 20 | if(target==0) 21 | result.add(new ArrayList()); 22 | else if(target>0) 23 | for(int i=pointer;i>=0;i--) 24 | if(i+1<=pointer && num[i]==num[i+1]) // a better way to avoid redundancy than "if(!result.contains(combo))" 25 | continue; 26 | else 27 | for(ArrayList combo:find_combinationSum2(num,target-num[i],i-1)){ 28 | combo.add(num[i]); 29 | // if(!result.contains(combo)) 30 | result.add(combo); 31 | } 32 | return result; 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /constructBinaryTreeFromInorderAndPostorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode buildTree(int[] inorder, int[] postorder) { 12 | return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1); 13 | } 14 | 15 | 16 | public TreeNode buildTree(int[] inorder, int i, int j, int[] postorder, int p, int q){ 17 | if(i>j) 18 | return null; 19 | 20 | if(i==j && p==q) 21 | return new TreeNode(postorder[q]); 22 | 23 | TreeNode root = new TreeNode(postorder[q]); 24 | 25 | int idx =-1; 26 | for(int x=i;x<=j;x++) 27 | if(inorder[x]==postorder[q]){ 28 | idx = x; 29 | break; 30 | } 31 | 32 | TreeNode leftChild = buildTree(inorder,i,idx-1,postorder,p,p+idx-i-1); 33 | TreeNode rightChild = buildTree(inorder,idx+1,j,postorder,p+idx-i,q-1); 34 | 35 | root.left = leftChild; 36 | root.right = rightChild; 37 | return root; 38 | } 39 | } -------------------------------------------------------------------------------- /constructBinaryTreeFromPreorderAndInorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode buildTree(int[] preorder, int[] inorder) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | return buildTree(inorder,0,inorder.length-1,preorder,0,preorder.length-1); 15 | } 16 | 17 | public TreeNode buildTree(int[] inorder, int i, int j, int[] preorder, int p, int q){ 18 | if(i>j) 19 | return null; 20 | 21 | if(i==j && p==q) 22 | return new TreeNode(preorder[p]); 23 | 24 | TreeNode root = new TreeNode(preorder[p]); 25 | 26 | int idx =-1; 27 | for(int x=i;x<=j;x++) 28 | if(inorder[x]==preorder[p]){ 29 | idx = x; 30 | break; 31 | } 32 | 33 | TreeNode leftChild = buildTree(inorder,i,idx-1,preorder,p+1,p+idx-i); 34 | TreeNode rightChild = buildTree(inorder,idx+1,j,preorder,p+idx-i+1,q); 35 | 36 | root.left = leftChild; 37 | root.right = rightChild; 38 | return root; 39 | } 40 | } -------------------------------------------------------------------------------- /containerwithmostwater.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int max = 0 , left=0,right= height.length-1; 6 | while(leftmax) 10 | max = area; 11 | 12 | if(d == height[left]) 13 | while(left=0 && height[right]<=d) 17 | right--; 18 | } 19 | return max; 20 | } 21 | } -------------------------------------------------------------------------------- /convertSortedArrayToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode sortedArrayToBST(int[] num) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | return sortedArrayToBST(num,0,num.length-1); 15 | } 16 | 17 | public TreeNode sortedArrayToBST(int[] num, int lo, int hi){ 18 | if(loend) return null; 33 | 34 | int mid = start+(end-start)/2; 35 | TreeNode left = sortedListToBST(start,mid-1); 36 | TreeNode parent = new TreeNode(list.val); 37 | parent.left = left; 38 | list=list.next; 39 | parent.right = sortedListToBST(mid+1,end); 40 | return parent; 41 | } 42 | } -------------------------------------------------------------------------------- /countandsay.java: -------------------------------------------------------------------------------- 1 | /* 2 | Although this is a very easy problem, it takes a while before me figuring out the exact right algorithm. 3 | */ 4 | 5 | 6 | public class Solution { 7 | public String countAndSay(int n) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | String current="1", next=""; 11 | if(n==1) 12 | return current; 13 | 14 | for(int i=2;i<=n;i++){ 15 | int count=1; 16 | for(int j=0;j0) 18 | if(current.charAt(j)==current.charAt(j-1)) 19 | count++; 20 | else{ 21 | next=next+count+current.charAt(j-1); 22 | count=1; 23 | } 24 | if(j == current.length()-1) 25 | next=next+count+current.charAt(j); 26 | 27 | 28 | } 29 | current = next; 30 | next = ""; 31 | } 32 | 33 | return current; 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /findmissingpositive.java: -------------------------------------------------------------------------------- 1 | /* 2 | The idea is to apply bucket sort to make A[i]=i if possible 3 | */ 4 | 5 | public class Solution { 6 | public int firstMissingPositive(int[] A) { 7 | 8 | if(A.length==0) 9 | return 1; 10 | 11 | int i=0; 12 | while(i=0 && A[i] generateParenthesis(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList res = new ArrayList(); 6 | ArrayList preres = new ArrayList(); 7 | 8 | if(n==0) 9 | return res; 10 | 11 | res.add("("); 12 | for(int i=1;i<2*n;i++){ 13 | for(String str:res) 14 | if(str.length()==i){ 15 | if(countChar(str,"(")(); 22 | 23 | 24 | } 25 | return res; 26 | } 27 | 28 | public int countChar(String str,String chr){ 29 | return str.length()-str.replace(chr,"").length(); 30 | } 31 | } -------------------------------------------------------------------------------- /graycode.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small : passed 516ms 3 | judge larget : passed 596ms 4 | */ 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collections; 8 | 9 | public class Solution { 10 | public ArrayList grayCode(int n) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | ArrayList res = new ArrayList(); 14 | ArrayList preres = new ArrayList(); 15 | 16 | res.add(0); 17 | if(n==0) 18 | return res; 19 | 20 | res.add(1); 21 | if(n==1) 22 | return res; 23 | 24 | for(int i=2;i<=n;i++){ 25 | for(Integer j:res) 26 | preres.add(j); 27 | Collections.reverse(res); 28 | for(Integer j:res) 29 | preres.add((int)(j+Math.pow(2,i-1))); 30 | 31 | res = preres; 32 | preres= new ArrayList(); 33 | } 34 | return res; 35 | } 36 | } -------------------------------------------------------------------------------- /insertinterval1.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small :540ms 3 | judge large::650ms 4 | 5 | This interview question is tougher than it appears. I tend to make a lot of 6 | mistakes when coding it. 7 | */ 8 | 9 | 10 | /** 11 | * Definition for an interval. 12 | * public class Interval { 13 | * int start; 14 | * int end; 15 | * Interval() { start = 0; end = 0; } 16 | * Interval(int s, int e) { start = s; end = e; } 17 | * } 18 | */ 19 | public class Solution { 20 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 21 | // Start typing your Java solution below 22 | // DO NOT write main() function 23 | ArrayList res = new ArrayList(); 24 | Interval pre= new Interval(newInterval.start,newInterval.end); 25 | 26 | boolean inserted = false; 27 | int i=0; 28 | while(ia.end || a.start> b.end); 58 | } 59 | } -------------------------------------------------------------------------------- /insertinterval2.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small :540ms 3 | judge large::650ms 4 | 5 | This is simplified version of insertinterval1.java : When we are checking each interval i in intervals, once we find i should come after the inserting interval t, we append t, and then go ahead and append the rest of the elements in intervals to the result list and return it. 6 | 7 | Another way is to use segment tree(http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor#Segment_Trees). 8 | */ 9 | 10 | /** 11 | * Definition for an interval. 12 | * public class Interval { 13 | * int start; 14 | * int end; 15 | * Interval() { start = 0; end = 0; } 16 | * Interval(int s, int e) { start = s; end = e; } 17 | * } 18 | */ 19 | import java.util.*; 20 | public class Solution { 21 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 22 | // Start typing your Java solution below 23 | // DO NOT write main() function 24 | ArrayList res = new ArrayList(); 25 | Interval t= new Interval(newInterval.start,newInterval.end); 26 | Iterator itr = intervals.iterator(); 27 | 28 | while(itr.hasNext()){ 29 | Interval i = itr.next(); 30 | if(i.start>t.end){ 31 | res.add(t); 32 | res.add(i); 33 | while(itr.hasNext()){res.add(itr.next());} 34 | return res; 35 | } 36 | 37 | if(t.start>i.end) 38 | res.add(i); 39 | else{ 40 | t.start = Math.min(i.start,t.start); 41 | t.end = Math.max(i.end,t.end); 42 | } 43 | } 44 | res.add(t); 45 | return res; 46 | 47 | } 48 | } -------------------------------------------------------------------------------- /interleavingstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small:590 ms 3 | judge large:640 ms 4 | 5 | dynamic programming. For each pair of the indexes i&j and value in matrix dp, it means whether the interleaving of s1.substring(0:i) and s2.substring(0:j) forms s3.substring(0,i+j). Yes if value == true, No if value ==false. 6 | 7 | */ 8 | 9 | public class Solution { 10 | public boolean isInterleave(String s1, String s2, String s3) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | if(s1.length()+s2.length()!=s3.length()) 14 | return false; 15 | 16 | int M = s1.length(); 17 | int N = s2.length(); 18 | 19 | boolean[][] dp = new boolean[M+1][N+1]; 20 | 21 | /*-------------------block start----------------*/ 22 | dp[0][0] = true; 23 | for(int i=1;i0 && s1.charAt(i-1)==s3.charAt(i+j-1)) 46 | dp[i][j] |= dp[i-1][j]; 47 | if(j>0 && s2.charAt(j-1)==s3.charAt(i+j-1)) 48 | dp[i][j] |= dp[i][j-1]; 49 | } 50 | } 51 | 52 | 53 | */ -------------------------------------------------------------------------------- /jumpgame1.java: -------------------------------------------------------------------------------- 1 | /* 2 | Judge small : passed 490ms 3 | Judge large : passed 560ms 4 | 5 | */ 6 | 7 | public class Solution { 8 | public boolean canJump(int[] A) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | if(A.length==0) 12 | return true; 13 | 14 | boolean[] dp = new boolean[A.length]; 15 | dp[0] = true; 16 | for(int i=0;i=A.length-1) 17 | return true; 18 | i++; 19 | } 20 | return false; 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /jumpgameII.java: -------------------------------------------------------------------------------- 1 | /* 2 | By christian on mitbbs 3 | */ 4 | 5 | public class Solution { 6 | public int jump(int[] A) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | int count = 0; 10 | int start=0, end=0, newend; 11 | while (end < A.length-1){ 12 | count++; 13 | newend = 0; 14 | for (int i=start; i<=end; i++) 15 | newend = i+A[i]>newend ? (i+A[i]) : newend; 16 | start = end+1; 17 | end = newend; 18 | } 19 | return count; 20 | } 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /largestrectangleinhistogram.java: -------------------------------------------------------------------------------- 1 | /* 2 | http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html 3 | */ 4 | 5 | import java.util.*; 6 | public class Solution { 7 | public int largestRectangleArea(int[] height) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | int[] area = new int[height.length]; 11 | int t=0; 12 | Stack stack = new Stack(); 13 | 14 | for(int i=0;i=0;i--){ 31 | while(!stack.empty() && height[i]<=height[stack.peek()]) 32 | stack.pop(); 33 | 34 | if(stack.empty()) 35 | t = height.length; 36 | else 37 | t = stack.peek(); 38 | 39 | area[i] += t-i-1; 40 | stack.push(i); 41 | } 42 | 43 | int max = 0; 44 | //Calculating Area[i] and find max Area 45 | for (int i=0; i max) 48 | max = area[i]; 49 | } 50 | 51 | return max; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /largestrectangleinhistogram1.java: -------------------------------------------------------------------------------- 1 | /* 2 | judge small: passed 3 | judge larget: runtime error(there is a input array is extremely long that leads to stackoverflow error) 4 | */ 5 | 6 | 7 | public class Solution { 8 | public int largestRectangleArea(int[] height) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | return find_largestRectangleArea(height,0,height.length-1); 12 | } 13 | 14 | public int find_largestRectangleArea(int[] height,int l, int r){ 15 | int lowest=0, maxArea = 0; 16 | if(l<=r){ 17 | lowest = find_min(height,l,r); 18 | int area = height[lowest]*(r+1-l); 19 | 20 | maxArea = Math.max( 21 | find_largestRectangleArea(height,l,lowest-1), 22 | find_largestRectangleArea(height,lowest+1,r)); 23 | 24 | return area>maxArea?area:maxArea; 25 | } 26 | return 0; 27 | } 28 | 29 | 30 | public int find_min(int[] A,int l, int r){ 31 | int minIndex =l; 32 | if(l<=r) 33 | for(int i=l;i<=r;i++) 34 | if(A[i]max) 20 | max =area; 21 | } 22 | } 23 | 24 | return max; 25 | } 26 | } -------------------------------------------------------------------------------- /largestrectangleinhistogram3.java: -------------------------------------------------------------------------------- 1 | /* 2 | Explanation here: http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html 3 | */ 4 | 5 | import java.util.*; 6 | public class Solution { 7 | public int largestRectangleArea(int[] height) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | int[] area = new int[height.length]; 11 | int t=0; 12 | Stack stack = new Stack(); 13 | 14 | for(int i=0;i=0;i--){ 31 | while(!stack.empty() && height[i]<=height[stack.peek()]) 32 | stack.pop(); 33 | 34 | if(stack.empty()) 35 | t = height.length; 36 | else 37 | t = stack.peek(); 38 | 39 | area[i] += t-i-1; 40 | stack.push(i); 41 | } 42 | 43 | int max = 0; 44 | //Calculating Area[i] and find max Area 45 | for (int i=0; i max) 48 | max = area[i]; 49 | } 50 | 51 | return max; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /largestrectangleinhistogram4.java: -------------------------------------------------------------------------------- 1 | /* 2 | http://stackoverflow.com/questions/4311694/maximize-the-rectangular-area-under-histogram 3 | It was originially written in Python which has tuple to store height and start. I rewrote 4 | with Java ,with which I had to create a pair class. This is lame. 5 | */ 6 | 7 | import java.util.*; 8 | public class Solution { 9 | public int largestRectangleArea(int[] height) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | Stack stack = new Stack(); 13 | int max_area=0; 14 | int pos=0; 15 | 16 | for(pos=0;posstack.peek().height) 20 | stack.push(new Pair(height[pos],start)); 21 | else if(!stack.empty() && height[pos]=0;i--) 12 | if(s.charAt(i)!=' ') { 13 | lastletter = i; 14 | break; 15 | } 16 | 17 | for(int i=lastletter-1;i>=0;i--) 18 | if(s.charAt(i)==' '){ 19 | firstletter = i+1; 20 | break; 21 | } 22 | 23 | return lastletter-firstletter+1; 24 | } 25 | } -------------------------------------------------------------------------------- /lettercombinationsofphonenumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Applied some syntax sugar in creating the hashmap. 3 | It's called double curly brace initialization. 4 | 5 | It means you're creating an anonymous subclass and the code within 6 | the double braces is basically a constructor. It's often used to add 7 | contents to collections because Java's syntax for creating what are 8 | essentially collection constants is somewhat awkward. 9 | 10 | */ 11 | 12 | import java.util.HashMap; 13 | public class Solution { 14 | public ArrayList letterCombinations(String digits) { 15 | // Start typing your Java solution below 16 | // DO NOT write main() function 17 | ArrayList res = new ArrayList(); 18 | ArrayList preres = new ArrayList(); 19 | res.add(""); 20 | 21 | for(int i=0;i(); 29 | } 30 | return res; 31 | } 32 | 33 | static final HashMap map = new HashMap(){{ 34 | put('2',"abc"); 35 | put('3',"def"); 36 | put('4',"ghi"); 37 | put('5',"jkl"); 38 | put('6',"mno"); 39 | put('7',"pqrs"); 40 | put('8',"tuv"); 41 | put('9',"wxyz"); 42 | 43 | }} ; 44 | } -------------------------------------------------------------------------------- /longestcommonprefix.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public String longestCommonPrefix(String[] strs) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if(strs.length==0) 7 | return ""; 8 | 9 | for(int i=strs[0].length();i>0;i--){ 10 | boolean isSame= true; 11 | String prefix = strs[0].substring(0,i); 12 | for(int j=1;jlp2.length()?lp1:lp2; 10 | lp = longer.length()>lp.length()?longer:lp; 11 | } 12 | return lp; 13 | 14 | } 15 | public String find_prolindrome(String s, int p, int q){ 16 | if( q=0 && q+1=0 && q+1lp.length()) 42 | lp = s.substring(p,q+1); 43 | } 44 | 45 | int j=i+1; 46 | p=i-1; 47 | if(j=0 && j+1lp.length()) 53 | lp = s.substring(p,j+1); 54 | } 55 | } 56 | return lp; 57 | 58 | } 59 | } 60 | 61 | */ 62 | 63 | -------------------------------------------------------------------------------- /longestsubstringwithoutrepeatingcharaters.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public int lengthOfLongestSubstring(String s) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | int count=0; 7 | HashSet substring = new HashSet(); 8 | for(int i=0;i stack = new Stack(); 9 | 10 | for(int i=0;i stack = new Stack(); 37 | int max_area=0; 38 | int pos=0; 39 | 40 | for(pos=0;posstack.peek().height) 44 | stack.push(new Pair(height[pos],start)); 45 | else if(!stack.empty() && height[pos]max_size) 104 | max_size= Math.max(largestRectangleArea(currRow),max_size); 105 | prevRow = currRow; 106 | currRow = new int[N]; 107 | } 108 | return max_size; 109 | } 110 | 111 | 112 | */ 113 | -------------------------------------------------------------------------------- /maximumDepthofBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int maxDepth(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(root==null) 15 | return 0; 16 | 17 | return 1+Math.max(maxDepth(root.right),maxDepth(root.left)); 18 | } 19 | } -------------------------------------------------------------------------------- /maximumsubarray1.java: -------------------------------------------------------------------------------- 1 | /* 2 | This is a little different from the classic maximum subarray problem,which 3 | we can solve by Kadane's algorithm. In that problem, the subarray is allowed to contain none element whereas in this one, the subarray contains 4 | a least one element. But it only requires a minor modification of the kadane's algorithm to solve this one. 5 | 6 | */ 7 | 8 | 9 | public class Solution { 10 | public int maxSubArray(int[] A) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | 14 | int max_ending_here = 0; 15 | int max_so_far =Integer.MIN_VALUE; // modification here 16 | 17 | for(int i = 0; i < A.length; i++) { 18 | max_ending_here =Math.max(A[i],max_ending_here+A[i]);// and here 19 | max_so_far = Math.max(max_so_far,max_ending_here); 20 | } 21 | 22 | return max_so_far; 23 | 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /maximumsubarray2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Another solution to this problem to try divide and conquer as "more practice" indicates. The time complexity is O(nlogn). 3 | */ 4 | 5 | 6 | public class Solution { 7 | public int maxSubArray(int[] A) { 8 | return maxSubArray(A,0,A.length-1); 9 | } 10 | 11 | public int maxSubArray(int[] A,int l, int r){ 12 | int leftSum=Integer.MIN_VALUE,rightSum=Integer.MIN_VALUE,sum=0; 13 | 14 | if(l==r) //base case 15 | return A[l]; 16 | 17 | int mid = (l+r)/2; 18 | int maxLeftSum = maxSubArray(A,l,mid); 19 | int maxRightSum = maxSubArray(A,mid+1,r); 20 | 21 | for(int i=mid;i>=l;i--){ // Note:this part is subtle. 22 | sum+=A[i]; // The code in the brackets is equivalent to one line of code: 23 | if(sum>leftSum) // leftSum = (sum+=A[i])>leftSum?sum:leftSum; // the parentheses are needed because the operator order of += is lower than ?: 24 | leftSum =sum; 25 | } 26 | sum=0; 27 | for(int i=mid+1;i<=r;i++){ 28 | sum+=A[i]; 29 | if(sum>rightSum) 30 | rightSum=sum; 31 | } 32 | 33 | return Math.max(Math.max(maxLeftSum,maxRightSum),rightSum+leftSum); 34 | 35 | } 36 | 37 | 38 | } -------------------------------------------------------------------------------- /medianoftwosortedarrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | http://askmecode.wordpress.com/2012/09/26/median-of-two-sorted-arrays/ 3 | http://blog.unieagle.net/?p=703 4 | 5 | These above two links have right answers for this problem,but they both are too complicated. 6 | 7 | Here is a more concise one: 8 | http://stackoverflow.com/questions/12584648/understanding-the-algorithm-of-median-of-two-sorted-arrays 9 | (Helpful for understanding:http://www.leetcode.com/2011/01/find-k-th-smallest-element-in-union-of.html) 10 | And I rewrote it in Java: 11 | */ 12 | 13 | public class Solution { 14 | public double findMedianSortedArrays(int A[], int B[]) { 15 | return findMedianHelper(A, B, Math.max(0, (A.length-B.length)/2), Math.min(A.length-1,(A.length+B.length)/2));// don't really understand this line 16 | } 17 | 18 | public double findMedianHelper(int A[], int B[], int l, int r) { 19 | int m= A.length; 20 | int n= B.length; 21 | 22 | if (l > r) 23 | return findMedianHelper2(B, A, Math.max(0, (n-m)/2), Math.min(n-1, (m+n)/2)); 24 | int i = (l+r)/2; 25 | int j = (m+n)/2-i; 26 | 27 | assert(i >= 0 && i <= m && j >= 0 && j <= n); 28 | int Ai_1 = ((i == 0) ? Integer.MIN_VALUE : A[i-1]); 29 | int Bj_1 = ((j == 0) ? Integer.MIN_VALUE : B[j-1]); 30 | int Ai = ((i == m) ? Integer.MAX_VALUE : A[i]); 31 | int Bj = ((j == n) ? Integer.MAX_VALUE : B[j]); 32 | 33 | if (Ai < Bj_1) return findMedianHelper2(A,B,i+1,r); 34 | if (Ai > Bj) return findMedianHelper2(A,B,l,i-1); 35 | 36 | if (((m+n) % 2) == 1) return A[i]; 37 | return (Math.max(Ai_1, Bj_1) + Ai) / 2.0; 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /mergeintervals.java: -------------------------------------------------------------------------------- 1 | /* 2 | This problem is trivial if based on the algorithm of inserting interval. 3 | */ 4 | 5 | /** 6 | * Definition for an interval. 7 | * public class Interval { 8 | * int start; 9 | * int end; 10 | * Interval() { start = 0; end = 0; } 11 | * Interval(int s, int e) { start = s; end = e; } 12 | * } 13 | */ 14 | import java.util.*; 15 | public class Solution { 16 | public ArrayList merge(ArrayList intervals) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | ArrayList res = new ArrayList(); 20 | 21 | for(Interval interval: intervals){ 22 | res = insert(res,interval); 23 | } 24 | 25 | return res; 26 | 27 | } 28 | 29 | 30 | //-------------insertinterval2.java---------------- 31 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 32 | // Start typing your Java solution below 33 | // DO NOT write main() function 34 | ArrayList res = new ArrayList(); 35 | Interval t= new Interval(newInterval.start,newInterval.end); 36 | Iterator itr = intervals.iterator(); 37 | 38 | while(itr.hasNext()){ 39 | Interval i = itr.next(); 40 | if(i.start>t.end){ 41 | res.add(t); 42 | res.add(i); 43 | while(itr.hasNext()){res.add(itr.next());} 44 | return res; 45 | } 46 | 47 | if(t.start>i.end) 48 | res.add(i); 49 | else{ 50 | t.start = Math.min(i.start,t.start); 51 | t.end = Math.max(i.end,t.end); 52 | } 53 | } 54 | res.add(t); 55 | return res; 56 | 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /mergeksortedlists.java: -------------------------------------------------------------------------------- 1 | /* 2 | Basically, I revise the min heap to a piority queue to solution this problem. The time complexity is O(nlogk), 3 | k--the number of sorted lists,n--the total number of elements in all the sorted lists. 4 | Hmmm, in fact, we have PriorityQueue in Java. 5 | 6 | 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | public class Solution { 21 | int heap_size ; 22 | public ListNode mergeKLists(ArrayList lists) { 23 | if(lists.size()==0 ) 24 | return null; 25 | 26 | ListNode[] A = new ListNode[lists.size()]; 27 | int i=0; 28 | for(ListNode node : lists){ 29 | if(!(node==null)){ //in stupid leetcode judge, I can say "if(node!=null)" because it will complain that operator ! cannot be applied to " 30 | A[i++]=node; 31 | node = node.next; 32 | heap_size++; 33 | } 34 | } 35 | build_min_heap(A); 36 | return mergeKLists(A); 37 | 38 | } 39 | 40 | public ListNode mergeKLists(ListNode[] A){ 41 | ListNode dumbNode = new ListNode(0); 42 | ListNode currentNode = dumbNode; 43 | 44 | while(heap_size!=0){ 45 | currentNode.next=A[0]; 46 | currentNode = currentNode.next; 47 | if(A[0].next!=null) 48 | A[0]=A[0].next; 49 | else{ 50 | swap(A,0,heap_size-1); 51 | heap_size--; 52 | } 53 | min_heapify(A,0); 54 | } 55 | 56 | return dumbNode.next; 57 | } 58 | 59 | public void build_min_heap(ListNode[] A){ 60 | //heap_size =A.length; 61 | for(int i=A.length/2;i>=0;i--) 62 | min_heapify(A,i); 63 | } 64 | 65 | public void min_heapify(ListNode[] A,int i){ 66 | int l = 2*i; //LEFT(i) 67 | int r = 2*i+1; //RIGHT(i) 68 | int smallest=0; 69 | smallest = (l=0){ 10 | if(a>=0 && b>=0) 11 | A[c] = A[a]>=B[b]?A[a--]:B[b--]; 12 | 13 | else if(a<0) 14 | A[c] = B[b--]; 15 | 16 | else 17 | A[c] = A[a--]; 18 | 19 | c--; 20 | 21 | } 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /mergetwosortedlists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | 17 | ListNode dummyNode = new ListNode(0); 18 | ListNode currentNode = dummyNode; 19 | 20 | while(l1!=null||l2!=null){ 21 | if(l1!=null&&l2!=null) 22 | if(l1.val>l2.val){ 23 | currentNode.next =l2; 24 | l2 = l2.next; 25 | }else{ 26 | currentNode.next =l1; 27 | l1 = l1.next; 28 | } 29 | else if(l1==null){ 30 | currentNode.next =l2; 31 | l2 = l2.next; 32 | }else{ 33 | currentNode.next =l1; 34 | l1 = l1.next; 35 | } 36 | currentNode=currentNode.next; 37 | 38 | } 39 | return dummyNode.next; 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /minimumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int minDepth(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(root==null) 15 | return 0; 16 | else if(root.left!=null && root.right!=null) 17 | return 1+Math.min(minDepth(root.right),minDepth(root.left)); 18 | else if(root.left!=null) 19 | return 1+minDepth(root.left); 20 | else 21 | return 1+minDepth(root.right); 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /minimumpathsum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minPathSum(int[][] grid) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | 6 | for(int i=0;i0) 9 | grid[i][j] += grid[i][j-1]; 10 | else if(i>0&&j==0) 11 | grid[i][j] += grid[i-1][j]; 12 | else if(i>0 && j>0) 13 | grid[i][j] += Math.min(grid[i][j-1],grid[i-1][j]); 14 | 15 | } 16 | return grid[grid.length-1][grid[0].length-1]; 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /minimumwindowsubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | O(n) time complexity solution 3 | Rewritten from http://www.leetcode.com/2010/11/finding-minimum-window-in-s-which.html. 4 | */ 5 | 6 | public class Solution { 7 | public String minWindow(String S, String T) { 8 | int SLen=S.length(); 9 | int TLen=T.length(); 10 | int[] needToFind = new int[256]; 11 | 12 | for(int i=0;i needToFind[bchar]){ 33 | if(hasFound[bchar] > needToFind[bchar]) 34 | hasFound[bchar]--; 35 | bchar = S.charAt(++begin); 36 | 37 | } 38 | 39 | int windowLen = end-begin+1; 40 | if(windowLen < minWindowLen){ 41 | minWindowBegin = begin; 42 | minWindowEnd = end; 43 | minWindowLen = windowLen; 44 | } 45 | } 46 | } 47 | return count==TLen?S.substring(minWindowBegin,minWindowEnd+1):""; 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /palindromeNumber.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(int x) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(x<0) return false; 6 | if(x<10) return true; 7 | 8 | int divident = 10; 9 | while(x/divident>=10) 10 | divident*=10; 11 | 12 | int mod = 10; 13 | boolean yes = true; 14 | while(divident>=mod){ 15 | yes&=x/divident==x%mod; 16 | x = x%divident/10; 17 | divident/=100; 18 | } 19 | return yes; 20 | } 21 | } -------------------------------------------------------------------------------- /pascal'sTriangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> generate(int numRows) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList> res = new ArrayList>(); 6 | generate(numRows,0,res); 7 | return res; 8 | 9 | } 10 | 11 | public void generate(int numRows,int cur, ArrayList> res) { 12 | if(numRows==0 || cur==numRows) return; 13 | if(cur==0){ 14 | ArrayList c = new ArrayList(); 15 | c.add(1); 16 | res.add(c); 17 | }if(cur==1){ 18 | ArrayList c = new ArrayList(); 19 | c.add(1); 20 | c.add(1); 21 | res.add(c); 22 | } 23 | if(cur>1){ 24 | ArrayList p = res.get(res.size()-1); 25 | ArrayList c = new ArrayList(); 26 | c.add(1); 27 | for(int i=0;i> pathSum(TreeNode root, int sum) { 14 | ArrayList> res = new ArrayList>(); 15 | ArrayList path = new ArrayList(); 16 | pathSum(root,sum,path,res); 17 | return res; 18 | } 19 | 20 | public void pathSum(TreeNode root, int sum, ArrayList path, ArrayList> res) { 21 | if(root==null) return; 22 | if(root.left==null && root.right==null && sum==root.val){ 23 | ArrayList p = new ArrayList(); 24 | p.addAll(path); 25 | p.add(root.val); 26 | res.add(p); 27 | return; 28 | } 29 | 30 | path.add(root.val); 31 | pathSum(root.left,sum-root.val,path,res); 32 | pathSum(root.right,sum-root.val,path,res); 33 | path.remove(path.size()-1); // path.remove((Integer)root.val) does not work for 2 cases in judge small. 34 | } 35 | 36 | 37 | } -------------------------------------------------------------------------------- /permutations.java: -------------------------------------------------------------------------------- 1 | /* 2 | The idea is to iterate each value in num, swap it with the first value, and add it to the permutations of the rest of the collection. 3 | for example, say input is a,b,c. First, add a to (b,c) and (c,b), then add b to (a,c) and (c,a), at last, add c to (a,b) and (b,a). 4 | */ 5 | 6 | 7 | public class Solution { 8 | public ArrayList> permute(int[] num) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | return permute(num,0); 12 | } 13 | 14 | public ArrayList> permute(int[] num,int level){ 15 | ArrayList> result = new ArrayList>(); 16 | if(level==num.length-1){ 17 | ArrayList combo = new ArrayList(); 18 | combo.add(num[level]); 19 | result.add(combo); 20 | return result; 21 | } 22 | 23 | for(int i=level;i combo:permute(num,level+1)){ 26 | combo.add(num[level]); 27 | result.add(combo); 28 | } 29 | swap(num,i,level); 30 | } 31 | return result; 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 | } -------------------------------------------------------------------------------- /plusone.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] plusOne(int[] digits) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | boolean isNines = true; 6 | for(int i=0;i=0 && increment>0){ 24 | int sum = digits[p]+increment; 25 | result[p] = sum%10; 26 | increment = sum/10; 27 | p--; 28 | } 29 | return result; 30 | } 31 | } -------------------------------------------------------------------------------- /populatingNextRightPointersInEachNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | It's amazing because the answer resides in the question itself. 3 | */ 4 | 5 | /** 6 | * Definition for binary tree with next pointer. 7 | * public class TreeLinkNode { 8 | * int val; 9 | * TreeLinkNode left, right, next; 10 | * TreeLinkNode(int x) { val = x; } 11 | * } 12 | */ 13 | 14 | public class Solution { 15 | public void connect(TreeLinkNode root) { 16 | // Start typing your Java solution below 17 | // DO NOT write main() function 18 | if(root==null) return; 19 | if(root.right!=null && root.left!=null){ 20 | root.left.next = root.right; 21 | root.right.next = root.next==null?null:root.next.left; 22 | 23 | } 24 | connect(root.left); 25 | connect(root.right); 26 | } 27 | } -------------------------------------------------------------------------------- /populatingNextRightPointersInEachNodeII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * public class TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode left, right, next; 6 | * TreeLinkNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public void connect(TreeLinkNode root) { 11 | // Start typing your Java solution below 12 | // DO NOT write main() function 13 | if(root==null) return; 14 | 15 | TreeLinkNode dummyNode = new TreeLinkNode(0); 16 | TreeLinkNode lastNode = dummyNode; 17 | TreeLinkNode nextNode = root; 18 | while(nextNode!=null){ 19 | if(nextNode.left!=null || nextNode.right!=null) 20 | break; 21 | nextNode = nextNode.next; 22 | } 23 | 24 | while(nextNode!=null){ 25 | if(nextNode.left!=null){ lastNode.next = nextNode.left; lastNode = lastNode.next;} 26 | if(nextNode.right!=null){ lastNode.next = nextNode.right; lastNode = lastNode.next;} 27 | nextNode = nextNode.next; 28 | 29 | } 30 | 31 | connect(dummyNode.next); 32 | } 33 | } -------------------------------------------------------------------------------- /pow.java: -------------------------------------------------------------------------------- 1 | /* 2 | At the beginning, I wrote something like pow(pow(x,n/2),2), which generates infinite loop and leads to stackoverflow error. 3 | 4 | */ 5 | 6 | public class Solution { 7 | public double pow(double x, int n) { 8 | // Start typing your Java solution below 9 | // DO NOT write main() function 10 | if(x==0 && n==0) 11 | return 1; 12 | 13 | if(x==0) 14 | return 0; 15 | 16 | if(n>0){ 17 | if(n%2==0){ 18 | double t =pow(x,n/2); 19 | return t*t; 20 | } 21 | else if(n%2>0) 22 | return pow(x,n-1)*x; 23 | } 24 | 25 | if(n<0){ 26 | if(n==Integer.MIN_VALUE) 27 | return 1.0/(pow(x,Integer.MAX_VALUE)*x); 28 | else 29 | return 1.0/pow(x,-n); 30 | } 31 | 32 | return 1; 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | Sort&Search: 2 | 3Sum 3 | 3SumCloset 4 | 4Sum 5 | sort colors 6 | search for a range 7 | search in a rotated sorted array I && II 8 | search insert position 9 | sqrt(x) 10 | first missing positive 11 | Merge Sorted Array 12 | Search a 2D Matrix 13 | Two Sum 14 | 15 | 16 | 17 | 18 | Linkedlist: 19 | merge two sorted lists 20 | add two numbers 21 | Partition List 22 | Remove Duplicates from Sorted List I,II 23 | Remove Nth Node From End of List 24 | Reverse Linked List II 25 | Reverse Nodes in k-Group 26 | Rotate List 27 | Swap Nodes in Pairs 28 | 29 | 30 | 31 | 32 | String manipulation: 33 | add binary 34 | anagrams 35 | Length of Last Word 36 | Longest Common Prefix 37 | Longest Palindromic Substring 38 | Longest Substring Without Repeating Characters 39 | Substring with Concatenation of All Words 40 | 41 | 42 | 43 | 44 | Tree: 45 | balanced binary tree 46 | binary tree inorder traversal 47 | binary tree level order traversal I,II 48 | binary tree maximum path sum 49 | binary tree zigzag level order traversal 50 | construct binary tree from inorder and postorder traversal 51 | construct binary tree from preorder and inorder traversal 52 | convert sorted array to binary search tree 53 | convert sorted list to binary search tree 54 | flatten binary tree to linked list 55 | Maximum Depth of Binary Tree 56 | Minimum Depth of Binary Tree 57 | Populating Next Right Pointers in Each Node I,II 58 | Recover Binary Search Tree 59 | Same Tree 60 | Symmetric Tree 61 | Unique Binary Search Trees I,II 62 | Validate Binary Search Tree 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | Dynamic programming: 73 | climbing stairs 74 | combination sum I,II 75 | combinations 76 | decode ways 77 | edit distance 78 | generate parentheses 79 | Interleaving String 80 | Letter Combinations of a Phone Number 81 | Minimum Path Sum 82 | Permutations 83 | Unique Paths I,II 84 | 85 | 86 | Recursion: 87 | N-Queens I,II 88 | Path Sum I,II 89 | Pow(x, n) 90 | Subsets I,II 91 | Sudoku Solver 92 | Word Search -dfs 93 | 94 | 95 | 96 | 97 | Miscellaneous: 98 | best time to buy and sell stock I,II,III 99 | container with most water 100 | count and say 101 | gray code 102 | Insert Interval 103 | jump game I,II 104 | Maximal Rectangle 105 | Maximum Subarray 106 | Median of Two Sorted Arrays 107 | Merge Intervals 108 | Minimum Window Substring 109 | Multiply Strings 110 | Palindrome Number 111 | Pascal's Triangle I,II 112 | Plus One 113 | Remove Duplicates from Sorted Array I,II 114 | Restore IP Addresses 115 | Reverse Integer 116 | Rotate Image 117 | Set Matrix Zeroes 118 | Spiral Matrix I,II 119 | Trapping Rain Water 120 | Valid Sudoku 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | Heap: 130 | Merge k Sorted Lists 131 | 132 | 133 | 134 | Stack: 135 | Largest Rectangle in Histogram 136 | Longest Valid Parentheses 137 | Valid Parentheses 138 | 139 | 140 | 141 | 142 | Not done yet: 143 | distinct subsequence 144 | divide two integers 145 | implementing strStr() 146 | Integer to Roman 147 | Next Permutation 148 | Permutation Sequence 149 | Permutations II 150 | Regular Expression Matching 151 | Remove Element 152 | Roman to Integer 153 | Scramble String 154 | Simplify Path 155 | String to Integer (atoi) 156 | Text Justification 157 | Triangle 158 | Valid Number 159 | Wildcard Matching 160 | ZigZag Conversion 161 | 162 | 163 | 164 | 165 | 166 | -------------------------------------------------------------------------------- /recoverbinarysearchtree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | TreeNode firstNode; 12 | TreeNode secondNode; 13 | public void recoverTree(TreeNode root) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | firstNode =null; 17 | secondNode = null; 18 | inorder(root,null); 19 | swap(firstNode,secondNode); 20 | 21 | 22 | } 23 | 24 | public void swap(TreeNode f,TreeNode s){ 25 | int temp = f.val; 26 | f.val = s.val; 27 | s.val = temp; 28 | } 29 | 30 | public TreeNode inorder(TreeNode node, TreeNode prev){ 31 | if(node==null) return prev; 32 | 33 | TreeNode p = inorder(node.left,prev); 34 | 35 | if(p!=null && p.val>node.val){ 36 | if(firstNode==null){ 37 | firstNode = p; 38 | secondNode = node; 39 | } 40 | else 41 | secondNode = node; 42 | } 43 | 44 | p = inorder(node.right,node); 45 | 46 | return p; 47 | } 48 | } -------------------------------------------------------------------------------- /removeduplicatesfromsortedarray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] A) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int i=1; 6 | 7 | while(iA[i-1]) 9 | i++; 10 | else{ 11 | if(A[i-1]>=A[A.length-1]) 12 | return i; 13 | 14 | for(int j=i+1;jA[i-1]){ 16 | swap(A,i,j); 17 | break; 18 | } 19 | } 20 | } 21 | return A.length; 22 | } 23 | 24 | public void swap(int[] A,int i,int j){ 25 | int temp = A[i]; 26 | A[i] = A[j]; 27 | A[j] = temp; 28 | } 29 | } -------------------------------------------------------------------------------- /removeduplicatesfromsortedarrayII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Some minor modifications of remove duplicates from sorted array. 3 | */ 4 | public class Solution { 5 | public int removeDuplicates(int[] A) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | int i=2; // modification here 9 | 10 | while(iA[i-1] || A[i]>A[i-2]) // and here 12 | i++; 13 | else{ 14 | if(A[i-1]>=A[A.length-1] && A[i-2]>=A[A.length-1]) // here 15 | return i; 16 | 17 | for(int j=i+1;jA[i-1] || A[j]>A[i-2]){ // here 19 | swap(A,i,j); 20 | break; 21 | } 22 | } 23 | } 24 | return A.length; 25 | } 26 | 27 | public void swap(int[] A,int i,int j){ 28 | int temp = A[i]; 29 | A[i] = A[j]; 30 | A[j] = temp; 31 | } 32 | } -------------------------------------------------------------------------------- /removeduplicatesfromsortedlistII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode deleteDuplicates(ListNode head) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | ListNode dummy = new ListNode(Integer.MIN_VALUE); 17 | dummy.next = head; 18 | ListNode current = dummy; 19 | while(current.next!=null){ 20 | ListNode prev = current; 21 | current = current.next; 22 | boolean isDuplicate = false; 23 | 24 | while(current!=null && current.next!=null && current.val==current.next.val){ 25 | current = current.next; 26 | isDuplicate = true; 27 | } 28 | 29 | prev.next = isDuplicate?current.next:current; 30 | current = isDuplicate?prev:current; 31 | 32 | } 33 | return dummy.next; 34 | } 35 | } -------------------------------------------------------------------------------- /removeduplicatesfromsortlist.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode deleteDuplicates(ListNode head) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if(head == null) // we can otherwise use dummy node instead. But 17 | return null; // be careful about the value you put in the dummy node. 18 | 19 | ListNode currentNode = head; 20 | while(currentNode.next!=null){ 21 | ListNode p = currentNode.next; 22 | while(p!=null && p.val==currentNode.val) 23 | p = p.next; 24 | if(p == null){ 25 | currentNode.next =null; 26 | break; 27 | } 28 | currentNode.next = p; 29 | currentNode = p; 30 | } 31 | return head; 32 | } 33 | } -------------------------------------------------------------------------------- /removeelement.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeElement(int[] A, int elem) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int i=0, j=A.length-1; 6 | 7 | while(i<=j){ 8 | if(A[i]==elem) 9 | swap(A,i,j--); 10 | else 11 | i++; 12 | } 13 | return j+1; 14 | } 15 | 16 | public void swap(int[] A,int i, int j){ 17 | int temp = A[i]; 18 | A[i] = A[j]; 19 | A[j] = temp; 20 | } 21 | } -------------------------------------------------------------------------------- /removenthnodefromendoflist.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode removeNthFromEnd(ListNode head, int n) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | 17 | ListNode dummy = new ListNode(0); 18 | dummy.next = head; 19 | ListNode p = dummy; 20 | ListNode q = dummy; 21 | for(int i=0;i restoreIpAddresses(String s) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList res = new ArrayList(); 6 | 7 | for(int i=1;i3 ||(e-b>=2 && s.charAt(b)=='0') ) return false; 31 | int num = Integer.parseInt(s.substring(b,e)); 32 | return num>=0 && num <=255; 33 | } 34 | } -------------------------------------------------------------------------------- /reverseinteger.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int reverse(int x) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int sign = x>=0?1:-1; 6 | x = x>=0? x:-x; 7 | 8 | int res = 0; 9 | 10 | while(x!=0){ 11 | res *= 10; 12 | res +=x%10; 13 | x = x/10; 14 | } 15 | 16 | res = res*sign; 17 | 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /reverselinkedlistII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | 13 | /* 14 | It's like my first time to write bug free code despite the fact 15 | that this might not be a decent solution. 16 | helpful link: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf 17 | */ 18 | public class Solution { 19 | public ListNode reverseBetween(ListNode head, int m, int n) { 20 | ListNode dummyNode = new ListNode(0); 21 | dummyNode.next =head; 22 | ListNode p = dummyNode; 23 | ListNode endOfFirstList = null; 24 | ListNode startOfThirdList =null; 25 | ListNode endOfSecondList = null; 26 | int count = 0; 27 | while(count<=n){ 28 | if(count==m-1) 29 | endOfFirstList = p; 30 | if(count==n){ 31 | endOfSecondList = p; 32 | startOfThirdList = p.next; 33 | } 34 | p=p.next; 35 | count++; 36 | } 37 | 38 | endOfSecondList.next = null; 39 | endOfSecondList = endOfFirstList.next; 40 | endOfFirstList.next = reverseLinkedList(endOfFirstList.next); 41 | endOfSecondList.next = startOfThirdList; 42 | return dummyNode.next; 43 | } 44 | 45 | // so called "Push reverse" 46 | public ListNode reverseLinkedList(ListNode head){ 47 | if(head==null) return head; 48 | ListNode prev = null; 49 | ListNode curr = head; 50 | 51 | while(curr!=null){ 52 | ListNode next = curr.next; 53 | curr.next = prev; 54 | // update curr and prev 55 | prev = curr; 56 | curr = next; 57 | } 58 | return prev; 59 | } 60 | 61 | 62 | } 63 | 64 | /* 65 | // recursive reverse 66 | public ListNode reverseLinkedList(ListNode curr){ 67 | if(curr==null) return curr; 68 | ListNode rest = curr.next; 69 | if(rest==null) return curr; 70 | 71 | rest = reverseLinkedList(rest); 72 | curr.next.next = curr; // Here is the trick 73 | curr.next =null; // 74 | return rest; 75 | } 76 | 77 | */ 78 | 79 | -------------------------------------------------------------------------------- /reversenodesinkgroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | Basically my cousin's solution. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | 17 | 18 | public class Solution { 19 | public ListNode reverseKGroup(ListNode head, int k) { 20 | // Start typing your Java solution below 21 | // DO NOT write main() function 22 | 23 | ListNode dummy = new ListNode(0); 24 | dummy.next = head; 25 | ListNode tail = dummy; 26 | ListNode kbegin = null; 27 | ListNode kend = null; 28 | 29 | ListNode node = head; 30 | int count =0; 31 | while(node!=null){ 32 | if(count%k==0) 33 | kbegin = node; 34 | if(count%k==k-1) 35 | kend = node; 36 | node = node.next; 37 | if(count%k==k-1){ 38 | kend.next = null; 39 | ListNode prev = null; 40 | ListNode t = kbegin; 41 | while(t!=null){ 42 | ListNode temp = t.next; 43 | t.next = prev; 44 | prev = t; 45 | t = temp; 46 | } 47 | tail.next = kend; 48 | tail = kbegin; 49 | tail.next = node; 50 | } 51 | count++; 52 | 53 | 54 | } 55 | return dummy.next; 56 | } 57 | } -------------------------------------------------------------------------------- /rotateimage.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | rotate(matrix,0); 6 | } 7 | 8 | public void rotate(int[][] matrix, int layer){ 9 | int n = matrix.length; 10 | if(layer<=n/2){ 11 | for(int j=layer;j tree1 = new LinkedList(); 19 | Queue tree2 = new LinkedList(); 20 | tree1.offer(p); 21 | tree2.offer(q); 22 | 23 | while(tree1.peek()!=null || tree2.peek()!=null){ 24 | TreeNode t1 = tree1.poll(); 25 | TreeNode t2 = tree2.poll(); 26 | if(t1!=null && t2!=null && t1.val == t2.val && ((t1.left==null)==(t2.left==null)) &&((t1.right==null)==(t2.right==null))) { 27 | if(t1.left!=null){ 28 | tree1.offer(t1.left); 29 | tree2.offer(t2.left); 30 | } 31 | if(t1.right!=null){ 32 | tree1.offer(t1.right); 33 | tree2.offer(t2.right); 34 | } 35 | }else 36 | return false; 37 | } 38 | return true; 39 | } 40 | } -------------------------------------------------------------------------------- /sametree2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | 11 | public class Solution { 12 | public boolean isSameTree(TreeNode p, TreeNode q) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(p==null && q==null) 16 | return true; 17 | else if(p!=null && q !=null) 18 | return p.val == q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right); 19 | else 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /searcha2DMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Note: In Arrays.binarySearch(array,target), if it can't find the target, it won't simply return -1. 3 | 4 | Another interesting solution from my cousin:https://github.com/azheanda/leetcode-1/blob/master/search_a_2d_matrix.cpp 5 | */ 6 | 7 | import java.util.Arrays; 8 | public class Solution { 9 | public boolean searchMatrix(int[][] matrix, int target) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | int level = matrix.length-1; 13 | for(int i=0;i=0) 21 | return Arrays.binarySearch(matrix[level],target)<0?false:true; 22 | else 23 | return false; 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /searchforarange.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] searchRange(int[] A, int target) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int[] res = new int[2]; 6 | res[0] = search(A, target-1)+1; 7 | res[1] = search(A, target); 8 | if(res[1] == -1 || A[res[1]] != target){ 9 | res[0] = -1; 10 | res[1] = -1; 11 | } 12 | return res; 13 | 14 | } 15 | 16 | // return the biggest index of the element that is <= target 17 | // if all the elements in A is > x, return -1; 18 | public int search(int [] A, int target){ 19 | int start = 0, end = A.length-1, mid = end/2; 20 | int res = -1; 21 | 22 | while(start<=end){ 23 | if(A[mid]>target) 24 | end = mid-1; 25 | else { 26 | start = mid+1; 27 | res = mid; 28 | } 29 | mid = (start+end)/2; 30 | } 31 | return res; 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /searchinrotatedsortedarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | I vaguely remember this problem in the book, cracking code interview 3 | */ 4 | 5 | public class Solution { 6 | public int search(int[] A, int target) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | int start = 0; 10 | int end = A.length-1; 11 | 12 | while(start<=end){ 13 | int mid = (start+end)/2; 14 | if(A[mid] == target) 15 | return mid; 16 | else if(A[start]<=A[mid]){ // check the first part is sorted or not 17 | if(A[mid]>target && A[start]<=target) 18 | end = mid-1; 19 | else 20 | start = mid+1; 21 | }else{ // check the second part 22 | if(A[mid]=target) 23 | start = mid+1; 24 | else 25 | end = mid-1; 26 | } 27 | } 28 | return -1; 29 | } 30 | 31 | 32 | } -------------------------------------------------------------------------------- /searchinrotatedsortedarrayII.java: -------------------------------------------------------------------------------- 1 | /* 2 | I vaguely remember this problem in the book, cracking code interview 3 | */ 4 | 5 | public class Solution { 6 | public boolean search(int[] A, int target) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | int start = 0; 10 | int end = A.length-1; 11 | 12 | while(start<=end){ 13 | int mid = (start+end)/2; 14 | if(A[mid] == target) 15 | return true; 16 | else if(A[start] == A[mid]) 17 | start++; 18 | else if(A[start]target && A[start]<=target) 20 | end = mid-1; 21 | else 22 | start = mid+1; 23 | }else{ 24 | if(A[mid]=target) 25 | start = mid+1; 26 | else 27 | end = mid-1; 28 | } 29 | } 30 | return false; 31 | } 32 | 33 | 34 | } -------------------------------------------------------------------------------- /searchinsertposition.java: -------------------------------------------------------------------------------- 1 | // The previous method at the bottom is unnecessarily complicated 2 | 3 | public class Solution { 4 | public int searchInsert(int[] A, int target) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | int lo = 0, hi = A.length-1, mid = hi/2; 8 | 9 | while(lo<=hi){ 10 | mid = (lo+hi)/2; 11 | if(target == A[mid]) 12 | return mid; 13 | else if(target > A[mid]) 14 | lo = mid+1; 15 | else 16 | hi = mid-1; 17 | } 18 | return lo; 19 | 20 | } 21 | } 22 | 23 | 24 | public class Solution { 25 | public int searchInsert(int[] A, int target) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | int lo = 0, hi = A.length-1, mid = hi/2; 29 | 30 | while(lo<=hi){ 31 | mid = (lo+hi)/2; 32 | if(target == A[mid]) 33 | return mid; 34 | else if(target > A[mid]){ 35 | if(lo==hi) 36 | return mid+1; 37 | lo = mid+1; 38 | } 39 | else{ 40 | if(lo==hi) 41 | return mid; 42 | hi = mid-1; 43 | } 44 | } 45 | return mid; 46 | 47 | } 48 | } -------------------------------------------------------------------------------- /setmatrixzeroes.java: -------------------------------------------------------------------------------- 1 | // constant space solution 2 | 3 | public class Solution { 4 | public void setZeroes(int[][] matrix) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | int M = matrix.length; 8 | int N = matrix[0].length; 9 | int firstRow = 1; 10 | 11 | for(int i=0;i spiralOrder(int[][] matrix) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | ArrayList res = new ArrayList(); 10 | if(matrix.length==0) 11 | return res; 12 | 13 | int M = matrix.length; 14 | int N = matrix[0].length; 15 | int lvl = M<=N? (M+1)/2:(N+1)/2; 16 | 17 | 18 | for(int clvl=0;clvl=clvl;j--) // bot 26 | res.add(matrix[M-clvl-1][j]); 27 | if(clvl < N-clvl-1) 28 | for(int i=M-clvl-2;i>clvl;i--) // left 29 | res.add(matrix[i][clvl]); 30 | } 31 | 32 | 33 | return res; 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /spiralmatrixII.java: -------------------------------------------------------------------------------- 1 | /* 2 | A little revision of spiralmatrix.java 3 | */ 4 | 5 | public class Solution { 6 | public int[][] generateMatrix(int n) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | int[][] res = new int[n][n]; 10 | if(n==0) 11 | return res; 12 | 13 | int lvl = (n+1)/2; 14 | int c=1; 15 | 16 | 17 | for(int clvl=0;clvl=clvl;j--) // bot 24 | res[n-clvl-1][j]=c++; 25 | if(clvl < n-clvl-1) 26 | for(int i=n-clvl-2;i>clvl;i--) // left 27 | res[i][clvl]=c++; 28 | } 29 | 30 | 31 | return res; 32 | 33 | 34 | 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /sqrt(x).java: -------------------------------------------------------------------------------- 1 | /* 2 | This one is tricky specially in dealing with very large int input. 3 | */ 4 | 5 | 6 | 7 | public class Solution { 8 | public int sqrt(int x) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | long lo = 0; 12 | long hi = x; 13 | 14 | while(hi>=lo){ 15 | long mid = lo+(hi-lo)/2; 16 | if(xlo){ 35 | long mid = lo+(hi-lo+1)/2; 36 | if(x1){ 56 | int mid = (lo+hi)/2; 57 | if(x<(long)mid*mid) // convert mid*mid to long 58 | hi = mid; // not mid-1 59 | else 60 | lo = mid; // not mid+1 61 | } 62 | return x==1?1:lo; // otherwise if x==1, lo==0, so I can't just return lo. 63 | } 64 | } 65 | */ -------------------------------------------------------------------------------- /strStr.java: -------------------------------------------------------------------------------- 1 | /* 2 | The Rabin-Karp Algorithm for string matching. 3 | If BASE = 101 , then it won't pass 3 out of 67 test cases in judge large. 4 | If BASE = 31, then it won't 1 out of 67. 5 | If BASE = 11, then passed. 6 | 7 | I assume that it won't pass the judge when BASE = 101 or 31 is because some hash results 8 | overflow. 9 | 10 | What the most frustrating thing is that the naive algorithm is even a little bit faster than this 11 | Rabin-Karp algorithm with leetcode's test cases. 12 | 13 | 14 | */ 15 | 16 | public class Solution { 17 | public String strStr(String haystack, String needle) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | int M = haystack.length(); 21 | int N = needle.length(); 22 | 23 | if(M> subsets(int[] S) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | Arrays.sort(S); 16 | ArrayList> res = new ArrayList>(); 17 | ArrayList cset = new ArrayList(); 18 | subsets(S,0,res,cset); 19 | return res; 20 | 21 | } 22 | 23 | public void subsets(int[] S, int off, ArrayList> res, ArrayList cset){ 24 | if(off==S.length){ 25 | res.add(new ArrayList(cset)); //When add one subset to the result set, we can't just say "res.add(cset)" because 26 | return; //cset is just a pointer to the ArrayList object(the program would modify cset later on). 27 | } //So we have to invode the copy constructor instead. 28 | cset.add(S[off]); 29 | subsets(S,off+1,res,cset); 30 | cset.remove(cset.size()-1); // Very important--restore the global invariant for next recursive calls. 31 | subsets(S,off+1,res,cset); 32 | } 33 | } -------------------------------------------------------------------------------- /subset||.java: -------------------------------------------------------------------------------- 1 | /* 2 | Another line of code added to subset yeilds this solution to subset2. 3 | However, if this time I don't sort the input set, it would be wrong. 4 | */ 5 | 6 | import java.util.*; 7 | public class Solution { 8 | public ArrayList> subsetsWithDup(int[] num) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | Arrays.sort(num); 12 | ArrayList> res = new ArrayList>(); 13 | ArrayList cset = new ArrayList(); 14 | subsets(num,0,res,cset); 15 | return res; 16 | 17 | } 18 | 19 | public void subsets(int[] S, int off, ArrayList> res, ArrayList cset){ 20 | if(off==S.length){ 21 | res.add(new ArrayList(cset)); 22 | return; 23 | } 24 | if(cset.size()==0 || (cset.size()!=0 && cset.get(cset.size()-1)!=S[off])) // When the value we are looking at is the same with 25 | subsets(S,off+1,res,cset); // the last value in the cset, we skip 26 | cset.add(S[off]); // the call in if clause to avoid redundecy. 27 | subsets(S,off+1,res,cset); 28 | cset.remove(cset.size()-1); 29 | } 30 | } -------------------------------------------------------------------------------- /substringwithconcatenationofallwords.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public ArrayList findSubstring(String S, String[] L) { 5 | // Start typing your Java solution below 6 | // DO NOT write main() function 7 | ArrayList res = new ArrayList(); 8 | HashMap need = new HashMap(); 9 | HashMap meet = new HashMap(); 10 | 11 | for(String s: L) 12 | if(!need.containsKey(s)) 13 | need.put(s,1); 14 | else 15 | need.put(s,need.get(s)+1); 16 | 17 | int wordLen = L[0].length(); 18 | int numOfWords = L.length; 19 | int i=0; 20 | int count=0; 21 | int checkpoint=0; 22 | 23 | while(imeet.get(cWord))) { 26 | count++; 27 | if(meet.containsKey(cWord)) 28 | meet.put(cWord,meet.get(cWord)+1); 29 | else 30 | meet.put(cWord,1); 31 | 32 | if(numOfWords == count){ 33 | res.add(checkpoint); 34 | count=0; 35 | meet.clear(); 36 | i = checkpoint+1; 37 | checkpoint = i; 38 | continue; 39 | } 40 | i += wordLen; 41 | }else{ 42 | if(count!=0){ 43 | count=0; 44 | meet.clear(); 45 | i = checkpoint; 46 | } 47 | checkpoint = ++i; 48 | } 49 | 50 | } 51 | return res; 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /swapnodesinpairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode swapPairs(ListNode head) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | ListNode dummy = new ListNode(0); 17 | dummy.next = head; 18 | ListNode curr = dummy; 19 | ListNode node1 = null; 20 | ListNode node2 = null; 21 | 22 | while(curr.next!=null && curr.next.next!=null){ 23 | node1 = curr.next; 24 | node2 = node1.next; 25 | ListNode next =node2.next; 26 | curr.next = node2; 27 | node2.next = node1; 28 | node1.next = next; 29 | curr=node1; 30 | } 31 | return dummy.next; 32 | } 33 | } -------------------------------------------------------------------------------- /symmetrictree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isSymmetric(TreeNode root) { 12 | if(root==null) 13 | return true; 14 | return isSymmetric(root.left,root.right); 15 | } 16 | 17 | public boolean isSymmetric(TreeNode left, TreeNode right){ 18 | if(left!=null && right!=null) 19 | return left.val==right.val && isSymmetric(left.right,right.left) && 20 | isSymmetric(left.left,right.right); 21 | return left ==null && right ==null; 22 | } 23 | } 24 | 25 | 26 | /** 27 | * Definition for binary tree 28 | * public class TreeNode { 29 | * int val; 30 | * TreeNode left; 31 | * TreeNode right; 32 | * TreeNode(int x) { val = x; } 33 | * } 34 | */ 35 | 36 | /* 37 | iterative version. note: we can actually insert null into a queue 38 | */ 39 | import java.util.*; 40 | public class Solution { 41 | public boolean isSymmetric(TreeNode root) { 42 | // Start typing your Java solution below 43 | // DO NOT write main() function 44 | if(root==null) 45 | return true; 46 | 47 | Queue left = new LinkedList(); 48 | Queue right = new LinkedList(); 49 | 50 | left.add(root.left); 51 | right.add(root.right); 52 | 53 | while(left.peek()!=null || right.peek()!=null){ 54 | if(left.peek()==null || right.peek()==null) 55 | return false; 56 | else{ 57 | TreeNode l = left.poll(); 58 | TreeNode r = right.poll(); 59 | if(l.val==r.val && ((l.right==null)==(r.left==null)) && ((l.left==null)==(r.right==null)) ) { 60 | if(l.right!=null){ 61 | left.add(l.right); 62 | right.add(r.left); 63 | } 64 | if(l.left!=null){ 65 | left.add(l.left); 66 | right.add(r.right); 67 | } 68 | }else 69 | return false; 70 | 71 | } 72 | 73 | } 74 | return true; 75 | 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /trappingrainwater.java: -------------------------------------------------------------------------------- 1 | /* 2 | http://www.leetcode.com/groups/google-interview/forum/topic/rain-water-trap/ 3 | */ 4 | 5 | public class Solution { 6 | public int trap(int[] A) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | 10 | int area = 0; 11 | int n = A.length; 12 | int[] R = new int[n]; 13 | int[] L = new int[n]; 14 | 15 | int rmax=0,lmax=0; 16 | 17 | for(int i=0;i generateTrees(int n) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | ArrayList res = new ArrayList(); 15 | generateTrees(res,1,n); 16 | return res; 17 | 18 | } 19 | 20 | public void generateTrees(ArrayList res,int left,int right){ 21 | if(left > right) 22 | res.add(null); 23 | else 24 | for(int i=left;i<=right;i++){ 25 | ArrayList lefts = new ArrayList(); 26 | generateTrees(lefts,left,i-1); 27 | ArrayList rights = new ArrayList(); 28 | generateTrees(rights,i+1,right); 29 | for(int x=0;xmin && node.val stack = new Stack(); 7 | 8 | for(int i=0;i8 || offset<0) return false; 19 | if((rows[i] & (1<=0 && i=0 && j>. That will do I suppose. 49 | */ 50 | 51 | 52 | import java.util.*; 53 | public class Solution { 54 | public boolean exist(char[][] board, String word) { 55 | // Start typing your Java solution below 56 | // DO NOT write main() function 57 | int N = board.length; 58 | int M = board[0].length; 59 | HashSet set = new HashSet(); 60 | for(int i=0;i set){ 72 | if(p==word.length()) return true; 73 | 74 | if(solve(i,j+1,board,word,p,set)) return true; 75 | if(solve(i+1,j,board,word,p,set)) return true; 76 | if(solve(i,j-1,board,word,p,set)) return true; 77 | if(solve(i-1,j,board,word,p,set)) return true; 78 | 79 | return false; 80 | } 81 | 82 | public boolean solve(int i, int j, char[][] board,String word, int p, HashSet set){ 83 | Pair temp = null; 84 | int N = board.length; 85 | int M = board[0].length; 86 | 87 | if(i>=0 && i=0 && j