├── 4-sum-ii.java ├── README.md ├── Roman-to-integer.java ├── add-and-search-word-data-structure-design.java ├── add-two-numbers.java ├── array-nesting.java ├── battleships-in-a-board.java ├── best-time-to-buy-and-sell-stocks-ii.java ├── binary-numbers-with-alternating-bits.cpp ├── binary-tree-maximum-path-sum.java ├── binary-tree-paths.java ├── boundary-of-binary-tree.java ├── brick-wall.java ├── bulls-and-cows.java ├── burst-balloons. ├── can-I-win.java ├── climbing-stairs.cpp ├── closest-binary-search-tree-value.java ├── combination-sum.cpp ├── complex-number-multiplication.java ├── concatenated-words.java ├── construct-binary-tree-from-inorder-and-postorder-traversal.java ├── construct-the-rectangle.java ├── contains-duplicate-ii.java ├── contains-duplicate.java ├── continuous-subarray-sum.java ├── convert-BST-to-greater-tree.java ├── copy-node-with-random-pointers.java ├── count-of-smaller-numbers-after-self.java ├── count-the-repetitions.java ├── count-univalue-subtrees.java ├── counting-bits.java ├── course-schedule.java ├── decode-string.java ├── decode-string.py ├── delete-and-earn.java ├── delete-node-in-a-BST.java ├── delete-node.java ├── design-a-vending-machine.java ├── design-twitter.java ├── diagonal-traverse.java ├── distribute-candies.java ├── employee-importance.java ├── encode-and-decode-tinyurl.java ├── encode-string-with-shortest-length.java ├── evaluate-division.java ├── falling-squares.cpp ├── find-all-duplicates-in-an-array.java ├── find-all-numbers-disappeared-in-an-array.java ├── find-bottom-left-tree-value.java ├── find-largest-smaller-key.java ├── find-largest-value-in-each-tree-row.java ├── find-leaves-of-binary-tree.java ├── find-leaves-of-binary-tree.py ├── find-median-from-data-stream.java ├── find-minimum-in-rotated-sorted-array.java ├── find-peak-element.java ├── find-the-duplicate-number.java ├── flatten-binary-tree-to-linked-list.java ├── flip-game.java ├── freedom-trail.java ├── friend-circles.java ├── game-of-life.java ├── generate-parantheses.cpp ├── generating-parenthesis.java ├── hamming-distance.java ├── heaters.java ├── house-robber.java ├── increasing-subsequences.java ├── interleaving-strings.java ├── intersection-of-two-arrays-ii.java ├── island-perimeter.java ├── jump-game.cpp ├── jump_game.java ├── k-diff-pairs-in-an-array.java ├── k-smallest-element-in-BST.java ├── kill-process.java ├── kth-smallest-element-in-a-bst.java ├── largest-number.java ├── letter-combination-of-a-phone-number.cpp ├── linked-list-cycle-ii.java ├── longest-consecutive-sequence.java ├── longest-palindromic-subsequence.java ├── longest-substring-without-repeating-character.java ├── lowest-common-ancestor-of-a-binary-tree.java ├── lowest-common-ancestor-of-binary-search-tree.java ├── lowest-common-ancestor.java ├── matchsticks-to-square.java ├── max-chunks-to-sort.java ├── max-consecutive-ones-ii.java ├── max-consecutive-ones.java ├── max-sub-array.java ├── maximum-depth-of-binary-tree.java ├── maximum-subarray.java ├── maximum-vacation-days.java ├── merge-intervals.java ├── merge-k-sorted-lists.java ├── merge-sorted-array.cpp ├── merge-two-sorted-lists.java ├── min-cost-climbing-stairs.cpp ├── mini-parser.java ├── most-common-word.java ├── move-zeros.java ├── multiply-strings.java ├── next-closest-time.java ├── next-greater-element-i.java ├── number-complement.java ├── number-of-segments-in-a-string.java ├── number-of-segments.java ├── odd-even-linkedlist.java ├── ones-and-zeroes.java ├── out_of_boundary_paths.java ├── output-contest-matches.java ├── pacific-atlantic-water-flow.java ├── palindrome-number.java ├── palindrome-pairs.java ├── palindrome.java ├── partition-list.java ├── pascals-triangle-ii.java ├── pascals-triangle.java ├── path-sum-ii.java ├── path-sum-iii.java ├── path-sum.java ├── perfect-numbers.java ├── perfect-rectangle.java ├── predict-the-winner.java ├── prefix-and-suffix-search.java ├── product-of-array-except-self.java ├── range-minimum-query-mutable.java ├── range-sum-query-immutable.java ├── reconstruct-itinerary.java ├── regular-expression-matching.java ├── remove-boxes.java ├── remove-duplicates-from-sorted-array-II.java ├── remove-duplicates-from-sorted-array.java ├── remove-k-digits.java ├── reorder-list.java ├── repeated-substring-pattern.java ├── reverse-integer.java ├── reverse-pairs.java ├── reverse-words-in-a-string.java ├── rotate-image.java ├── rotate-list.java ├── same-tree.java ├── search-a-2d-matrix.cpp ├── search-a-2d-matrix.java ├── search-for-a-range.cpp ├── search-insert-position.cpp ├── search-insert-position.java ├── serialize-and-deserialize-bst.java ├── shopping-offers.java ├── shortest-completing-word.cpp ├── shortest-palindrome.java ├── shortest-word-distance.java ├── single-number-ii.java ├── sort-characters-by-frequency.java ├── spiral-order.java ├── strong-password-checker.java ├── student-attendance-record-ii.java ├── sudoku-solver.java ├── sum-of-left-leaves.java ├── summary-ranges.java ├── super-washing-machine.java ├── symmetric-tree.java ├── target-sum.java ├── task-scheduler.java ├── ternary-expression-parser.java ├── third-maximum-number.java ├── toeplitz-matrix.java ├── trapping-rain-water.cpp ├── trapping-rain-water.java ├── two-sum-ii-input-array-sorted.java ├── ugly-number.java ├── unique-binary-search-tree.java ├── unique-email-addresses.java ├── valid-palindrome.java ├── valid-parentheses.java ├── valid-sudoku.java ├── validate-binary-search-tree.java ├── walls-and-gates.java ├── world-search.java ├── zigzag-conversion.java └── zuma-game.java /4-sum-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { 3 | int cnt = 0; 4 | HashMap map = new HashMap(); 5 | for (int i = 0; i < A.length; i++) 6 | for (int j = 0; j < B.length; j++) { 7 | int sum = A[i] + B[i]; 8 | map.put(sum, map.getOrDefault(sum, 0)+1); 9 | } 10 | 11 | for (int i = 0; i < C.length; i++) 12 | for (int j = 0; j < D.length; j++) { 13 | int remainder = C[i] + D[j]; 14 | cnt += map.getOrDefault(-1*remainder, 0); 15 | } 16 | 17 | return cnt; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode 2 | Problems on Leetcode 3 | 4 | I made this repo after a failed technical interview with an easy programming question (Game of life). It reminded me of another technical interview with an easy question that I failed. I realized simply taking a class in Algorithms and Data Structures wasn't enough, and that I needed to practice more questions. A few weeks before Chrismast 2016, I set out a goal of doing one problem on Leetcode a day. 5 | 6 | I've switched to a more structured way of learning algorithms (with topics and problems on the topic to familiarize myself using Competitive Programming by Steven and Felix Halim). I will still do problems on Leetcode once in a while. 7 | 8 | # Structure 9 | 10 | This repo has a flat structure with no sub directories. For the problems, I tried solving them first, then if stuck I would look at the solution, then I tried to reimplement them. 11 | 12 | # Lessons learned 13 | The journey in the past 8-9 months has been fun. It taught me discipline. I realized that if I want to be good at something I need to constantly practice it. Sitting down to my laptop everyday and tried to read and understand the problems and created a commit has shaped a habit in my mind. I'm no longer afraid of doing a technical programming question (I still suck at that, though). An author on Quora has said habitual everyday tasks are boring, but they bring me greater rewards in the future. At least, at the end of the day, when I reflect on what I've done today, I'm glad I did something to better myself 14 | 15 | I also welcome contributions. 16 | -------------------------------------------------------------------------------- /Roman-to-integer.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public int romanToInt(String s) { 4 | HashMap m = new HashMap(); 5 | m.put("I", 1); m.put("II", 2); m.put("III", 3); m.put("V", 5); 6 | m.put("X", 10); m.put("L", 50); m.put("C", 100); m.put("D", 500); 7 | m.put("M", 1000); 8 | int n = m.get(s.substring(0, 1)); 9 | for (int i = 1; i < s.length(); i++) { 10 | if (m.get(s.substring(i, i+1)) <= m.get(s.substring(i-1, i))) { 11 | n += m.get(s.substring(i, i+1)); 12 | } else { 13 | n += m.get(s.substring(i, i+1)) - 2 * m.get(s.substring(i-1, i)); 14 | } 15 | } 16 | return n; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /add-and-search-word-data-structure-design.java: -------------------------------------------------------------------------------- 1 | public class WordDictionary { 2 | 3 | public class TrieNode { 4 | TrieNode links[]; 5 | boolean isWord = false; 6 | 7 | public TrieNode() { 8 | links = new TrieNode[26]; 9 | for (int i = 0; i < 26; i++) links[i] = null; 10 | } 11 | } 12 | TrieNode head = new TrieNode(); 13 | // Adds a word into the data structure. 14 | public void addWord(String word) { 15 | TrieNode cur = head; 16 | for (int i = 0; i < word.length(); i++) { 17 | int index = word.charAt(i) - 'a'; 18 | if (cur.links[index] == null) { 19 | cur.links[index] = new TrieNode(); 20 | } 21 | cur = cur.links[index]; 22 | } 23 | cur.isWord = true; 24 | } 25 | 26 | 27 | // Returns if the word is in the data structure. A word could 28 | // contain the dot character '.' to represent any one letter. 29 | public boolean search(String word) { 30 | return searchFrom(word, head); 31 | } 32 | 33 | public boolean searchFrom(String word, TrieNode root) { 34 | TrieNode cur = root; 35 | for (int i = 0; i < word.length(); i++) { 36 | // System.out.println(word.charAt(i)); 37 | if (cur != null) { 38 | 39 | if (word.charAt(i) == '.') { 40 | for (int j = 0; j < 26; j++) { 41 | // System.out.println(j + " " + cur.links[j]); 42 | if (searchFrom(word.substring(i+1), cur.links[j])) 43 | return true; 44 | } 45 | cur = null; 46 | } else { 47 | int index = word.charAt(i) - 'a'; 48 | // if (cur.links[index] != null) { 49 | cur = cur.links[index]; 50 | // } 51 | } 52 | } else { 53 | break; 54 | } 55 | } 56 | return cur != null && cur.isWord; 57 | } 58 | } 59 | 60 | // Your WordDictionary object will be instantiated and called as such: 61 | // WordDictionary wordDictionary = new WordDictionary(); 62 | // wordDictionary.addWord("word"); 63 | // wordDictionary.search("pattern"); 64 | -------------------------------------------------------------------------------- /add-two-numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 | ListNode p1 = l1, p2 = l2, result = new ListNode(-1), dummy = result; 12 | int carryOver = 0, v1 = 0, v2 = 0, sum = 0; 13 | while (p1 != null || p2 != null) { 14 | if (p1 != null) v1 = p1.val; else v1 = 0; 15 | if (p2 != null) v2 = p2.val; else v2 = 0; 16 | sum = v1 + v2 + carryOver; 17 | if (sum > 9) { 18 | carryOver = 1; 19 | sum = sum - 10; 20 | } else carryOver = 0; 21 | result.next = new ListNode(sum); 22 | if (p1 != null) p1 = p1.next; 23 | if (p2 != null) p2 = p2.next; 24 | result = result.next; 25 | } 26 | if (carryOver > 0) result.next = new ListNode(1); 27 | return dummy.next; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /array-nesting.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int arrayNesting(int[] nums) { 3 | int res = 0; 4 | int n = nums.length; 5 | boolean[] visited = new boolean[n]; 6 | for (int i = 0; i < n; i++) { 7 | if (!visited[i]) { 8 | int start = nums[i], count = 0; 9 | do { 10 | count++; 11 | start = nums[start]; 12 | visited[start] = true; 13 | } while (start != nums[i]); 14 | res = Math.max(res, count); 15 | } 16 | } 17 | } 18 | public static void main(String args[]) { 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /battleships-in-a-board.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int countBattleships(char[][] board) { 3 | int total = 0; 4 | for (int i = 0; i < board.length; i++) 5 | for (int j = 0; j < board[0].length; j++) 6 | if (board[i][j] == 'X') { 7 | // System.out.println("i= " + i + ", j= " + j); 8 | if ((j == board[0].length-1 && (j == 0 || board[i][j-1] == '.')) || (j == 0 && (j == board[0].length-1 || board[i][j+1] == '.')) || (j >= 0 && j < board[0].length-1 && board[i][j+1] == '.' && board[i][j-1] == '.')) { 9 | System.out.println("1"); 10 | if (i == 0 || board[i-1][j] == '.') total++; 11 | } else { 12 | System.out.println("2"); 13 | if (j == 0 || board[i][j-1] == '.') total++; 14 | } 15 | } 16 | return total; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stocks-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices == null || prices.length == 0) return 0; 4 | int minBought = prices[0], maxDiff = 0; 5 | for (int i = 0; i < prices.length; i++) { 6 | if (prices[i] >= minBought) maxDiff = Math.max(maxDiff, prices[i] - minBought); 7 | else minBought = prices[i]; 8 | } 9 | return maxDiff; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /binary-numbers-with-alternating-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasAlternatingBits(int n) { 4 | int cur = n % 2; 5 | while (n) { 6 | n >>= 1; 7 | if (n % 2 == cur) return false; 8 | cur = !cur; 9 | } 10 | return true; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /binary-tree-maximum-path-sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } -11 9 | * /\ 10 | * -7 10 11 | * / \ 12 | * 2 3 13 | * / \ / \ 14 | * 4 5 6 7 15 | * / / \ \ 16 | * 8 13 9 12 17 | */ 18 | public class Solution { 19 | int max = Integer.MIN_VALUE; 20 | public int maxPath(TreeNode root) { 21 | if (root == null) return 0; 22 | int left = Math.max(maxPathSum(root.left), 0); 23 | int right = Math.max(maxPathSum(root.right), 0); 24 | root.val = root.val + Math.max(left, right); 25 | max = Math.max(max, root.val); 26 | return root.val; 27 | } 28 | public int maxPathSum(TreeNode root) { 29 | int res = maxPath(root); 30 | return max; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /binary-tree-paths.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 List binaryTreePaths(TreeNode root) { 12 | List list = new ArrayList(); 13 | if (root == null) return list; 14 | list.add(""); 15 | binaryPaths(list, root); 16 | return list; 17 | } 18 | 19 | public void binaryPaths(List list, TreeNode root) { 20 | if (root == null) return; 21 | String cur = list.remove(list.size()-1); 22 | // System.out.println("root.val= " + root.val + ", cur= " + cur + ", " + Arrays.toString(list.toArray())); 23 | if (root.left == null && root.right == null) { 24 | list.add(cur + String.valueOf(root.val)); 25 | return; 26 | } else { 27 | if (root.left != null) { 28 | list.add(cur + String.valueOf(root.val) + "->"); 29 | binaryPaths(list, root.left); 30 | } 31 | if (root.right != null) { 32 | list.add(cur + String.valueOf(root.val) + "->"); 33 | binaryPaths(list, root.right); 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /boundary-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List boundaryOfBinaryTree(TreeNode root) { 3 | List res = new ArrayList(); 4 | if (root == null) return res; 5 | if (root.left == null) res.add(root.val); 6 | else { 7 | TreeNode cur = root.left; 8 | while (cur.next != null) {res.add(cur.val); cur = cur.next;} 9 | } 10 | findLeaves(res, root); 11 | addRightBoundary(res, root); 12 | } 13 | public void findLeaves(List res, TreeNode root) { 14 | if (root.left == null && root.right == null) res.add(root.val); 15 | if (root.left != null) findLeaves(res, root.left); 16 | if (root.right != null) findLeaves(res, root.right); 17 | } 18 | public void addRightBoundary(List res, TreeNode root) { 19 | if (root == null) return; 20 | if (root.right != null) addRightBoundary(res, root.right); 21 | res.add(root.val); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /brick-wall.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int leastBricks(List> wall) { 3 | HashMap cuts = new HashMap<>(); 4 | int maxCuts = 0; 5 | for (int row = 0; row < wall.size(); row++) { 6 | List bricks = wall.get(row); 7 | int bSum = 0; 8 | for (int b = 0; b < bricks.size()-1; b++) { 9 | bSum += bricks.get(b); 10 | cuts.put(bSum, cuts.getOrDefault(bSum, 0)+1); 11 | maxCuts = Math.max(maxCuts, cuts.get(bSum)); 12 | } 13 | } 14 | return wall.size()-maxCuts; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /bulls-and-cows.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String getHint(String secret, String guess) { 3 | HashMap map = new HashMap(); 4 | for (int i = 0; i < secret.size(); i++) { 5 | map.put(secret.charAt(i), i); 6 | } 7 | int bull = 0, cow = 0; 8 | for (int i = 0; i < guess.size(); i++) { 9 | if (map.containsKey(secret.charAt(i)) { 10 | if (map.get(secret.charAt(i) == i) bull++; 11 | else cow++; 12 | 13 | } 14 | } 15 | return bull + "A" + cow + "B"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /burst-balloons.: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxCoins(int[] numArr) { 3 | int nums[] = new int[numArr.length+2]; 4 | int n = 1; 5 | for (int num : numArr) if (num > 0) nums[n++] = num; 6 | nums[0] = 1; nums[n++] = 1; 7 | int dp[][] = new dp[n][n]; 8 | for (int len = 2; len < n; len++) { 9 | for (int left = 0; left < n-len; left++) { 10 | int right = left + len; 11 | for (int i = left+1; i < right; i++) { 12 | dp[left][right] = Math.max(dp[left][right], nums[left]*nums[i]*nums[right] + dp[left][i] + dp[i][right]); 13 | } 14 | } 15 | } 16 | return dp[0][n-1]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /can-I-win.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | HashMap hm; 4 | boolean[] used; 5 | public boolean canIWin(int maxChoosableInteger, int desiredTotal) { 6 | int sum = (maxChoosableInteger+1) * maxChoosableInteger / 2; 7 | if (sum < desiredTotal) return false; 8 | if (desiredTotal <= 0) return true; 9 | hm = new HashMap(); 10 | used = new boolean[maxChoosableInteger+1]; 11 | return canFirstWin(desiredTotal); 12 | } 13 | 14 | public boolean canWin(int total) { 15 | if (total <= 0) return false; 16 | int usedArray = format(used); 17 | if (!hm.containsKey(usedArray)) { 18 | for (int i = 1; i <= used.length; i++) { 19 | if (!used[i]) { 20 | used[i] = true; 21 | if (!canWin(total - i)) { 22 | hm.put(usedArray, true); 23 | used[i] = false; 24 | return true; 25 | } 26 | used[i] = false; 27 | } 28 | } 29 | hm.put(key, false); 30 | } 31 | return false; 32 | } 33 | 34 | public int binaryToInteger(boolean[] used) { 35 | int retVal = 0; 36 | for (boolean i : used) { 37 | retVal <<= 1; 38 | if (i) retVal |= 1; 39 | } 40 | return retVal; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | int steps[n+2]; 5 | steps[1] = 1; 6 | steps[2] = 2; 7 | for (int i = 3; i <= n; i++) { 8 | steps[i] = steps[i-1] + steps[i-2]; 9 | } 10 | return steps[n]; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /closest-binary-search-tree-value.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static class TreeNode { 11 | int val; 12 | TreeNode left, right; 13 | TreeNode(int value) {this.val = value;} 14 | } 15 | 16 | public static void main (String[] args) { 17 | TreeNode root = new TreeNode(3); 18 | root.left = new TreeNode(9); 19 | root.right = new TreeNode(20); 20 | root.right.left = new TreeNode(15); 21 | root.right.right = new TreeNode(7); 22 | System.out.println(closestValue(root, 15.5)); 23 | } 24 | 25 | static int minVal = Integer.MAX_VALUE; 26 | public static int closestValue(TreeNode root, double target) { 27 | if (root == null) {return Integer.MAX_VALUE;} 28 | if (root.val < target) { 29 | int rightVal = closestValue(root.right, target); 30 | if (Math.abs(rightVal - target) < Math.abs(root.val - target)) { 31 | return rightVal; 32 | } else { 33 | return root.val; 34 | } 35 | } else { 36 | int leftVal = closestValue(root.left, target); 37 | if (Math.abs(leftVal - target) < Math.abs(root.val - target)) { 38 | return leftVal; 39 | } else { 40 | return root.val; 41 | } 42 | } 43 | } 44 | 45 | // Shorter 46 | static double minVal = Integer.MAX_VALUE; 47 | static int curMin = Integer.MAX_VALUE; 48 | public static int closestValue(TreeNode root, double target) { 49 | if (root == null) {return Integer.MAX_VALUE;} 50 | if (Math.abs(root.val - target) < minVal) { 51 | minVal = Math.abs(root.val - target); 52 | curMin = root.val; 53 | } 54 | if (root.val < target) { 55 | closestValue(root.right, target); 56 | } else { 57 | closestValue(root.left, target); 58 | } 59 | return curMin; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum(vector& candidates, int target) { 4 | sort(candidates.begin(), candidates.end()); 5 | vector curNum; 6 | vector> result; 7 | findSum(result, candidates, curNum, 0, target); 8 | return result; 9 | } 10 | private: 11 | void findSum(vector> &result, vector& candidates, vector& curNum, int index, int remain) { 12 | if (remain == 0) { 13 | result.push_back(curNum); 14 | return; 15 | } 16 | for (int i = index; i < candidates.size() && remain >= candidates[i]; i++) { 17 | // if (i > 0 && candidates[i] == candidates[i-1]) continue; 18 | curNum.push_back(candidates[i]); 19 | findSum(result, candidates, curNum, i, remain - candidates[i]); 20 | curNum.pop_back(); 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /complex-number-multiplication.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String complexNumberMultiply(String a, String b) { 3 | String[] parts = a.split("+"); 4 | String areal = parts[0], avirtual = parts[1].substring(0, parts[1].length-1); 5 | parts = b.split("+"); 6 | String breal = parts[0], bvirtual = parts[1].substring(0, parts[1].length-1); 7 | int arealInt, brealInt, avirtualInt, bvirtualInt; 8 | if (areal.charAt(0) == '-') arealInt = -1*Integer.valueOf(areal); else arealInt = Integer.valueOf(areal); 9 | if (avirtual.charAt(0) == '-') avirtualInt = -1*Integer.valueOf(avirtual); else avirtualInt = Integer.valueOf(avirtual); 10 | if (breal.charAt(0) == '-') brealInt = -1*Integer.valueOf(breal); else brealInt = Integer.valueOf(breal); 11 | if (bvirtual.charAt(0) == '-') bvirtualInt = -1*Integer.valueOf(bvirtual); else bvirtualInt = Integer.valueOf(bvirtual); 12 | int real = -1*avirtual*bvirtual + areal*breal; 13 | int virtual = avirtual*breal + bvirtual*areal; 14 | String res = ""; 15 | if (real < 0) res += "-"; 16 | res += real + " + "; 17 | if (virtual < 0) res += "-"; 18 | res += virtual; 19 | return res; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /concatenated-words.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public class TrieNode { 4 | TrieNode[] links; 5 | boolean isEnd; 6 | public TrieNode() { 7 | links = new TrieNode[26]; 8 | isEnd = false; 9 | } 10 | } 11 | 12 | public class Trie { 13 | TrieNode root; 14 | public Trie() { 15 | root = new TrieNode(); 16 | } 17 | 18 | void insert(String word) { 19 | TrieNode cur = root; 20 | for (char c : word.toCharArray()) { 21 | int index = c - 'a'; 22 | if (cur.links[index] == null) { 23 | cur.links[index] = new TrieNode(); 24 | } 25 | cur = cur.links[index]; 26 | } 27 | cur.isEnd = true; 28 | } 29 | 30 | boolean isConcat(String word, int offset, TrieNode cur, int num) { 31 | 32 | if (offset == word.length() && num > 1) { 33 | return true; 34 | } 35 | for (int i = offset; i < word.length(); i++) { 36 | int index = word.charAt(i) - 'a'; 37 | cur = cur.links[index]; 38 | if (cur == null) { 39 | return false; 40 | } 41 | if (cur.isEnd && isConcat(word, i+1, root, num+1)) { 42 | return true; 43 | } 44 | } 45 | return false; 46 | } 47 | } 48 | public List findAllConcatenatedWordsInADict(String[] words) { 49 | List res = new ArrayList<>(); 50 | if (words == null || words.length == 1) return res; 51 | Trie trie = new Trie(); 52 | for (String word: words) { 53 | trie.insert(word); 54 | } 55 | for (String word: words) { 56 | if (trie.isConcat(word, 0, trie.root, 0)) { 57 | res.add(word); 58 | } 59 | } 60 | return res; 61 | } 62 | } 63 | 64 | 65 | -------------------------------------------------------------------------------- /construct-binary-tree-from-inorder-and-postorder-traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 | /** 13 | * 1 14 | * 5 10 15 | * 3 4 8 9 16 | * 2 6 7 11 12 13 14 15 17 | * inorder: 2, 3, 6, 5, 7, 4, 11, 1, 12, 8, 13, 10, 14, 9, 15 18 | * postorder:2, 6, 3, 7, 11, 4, 5, 12, 13, 8, 14, 15, 9, 10, 1 19 | **/ 20 | HashMap hm = new HashMap(); 21 | for (int i = 0; i < inorder.length; i++) hm.put(inorder[i], i); 22 | TreeNode root = buildHelper(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1, hm); 23 | return root; 24 | 25 | } 26 | public TreeNode buildHelper(int[] inorder, int[] postorder, int is, int ie, int ps, int pe, HashMap hm) { 27 | if (is > ie || ps > pe) { 28 | return null; 29 | } else { 30 | TreeNode root = new TreeNode(postorder[pe]); 31 | int index = hm.get(postorder[pe]); 32 | root.left = buildHelper(inorder, postorder, is, index-1, ps, ps + (index - is) - 1, hm); 33 | root.right = buildHelper(inorder, postorder, index+1, ie, ps + (index - is), pe, hm); 34 | return root; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /construct-the-rectangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] constructRectangle(int area) { 3 | int n = (int) Math.sqrt(area); 4 | for (int i = n; i > 0; i--) { 5 | if (area % i == 0) return new int[] {i, area/i}; 6 | } 7 | return new int[] {1, area}; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /contains-duplicate-ii.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean containsNearbyDuplicate(int[] nums, int k) { 3 | HashMap hm = new HashMap(); 4 | for (int i = 0; i < nums.length; i++) { 5 | if (!hm.containsKey(nums[i])) { 6 | hm.put(nums[i], i); 7 | } else { 8 | if (Math.abs(hm.get(nums[i]) - i) <= k) { 9 | return true; 10 | } 11 | hm.put(nums[i], i); 12 | } 13 | } 14 | return false; 15 | } 16 | 17 | public boolean containsNearbyDuplicate(int[] nums, int k) { 18 | HashSet hs = new HashSet(); 19 | for (int i = 0; i < nums.length; i++) { 20 | if (i > k) hs.remove(nums[i-k-1]); 21 | if (!hs.add(nums[i])) return true; 22 | } 23 | 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /contains-duplicate.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | HashSet hs = new HashSet(); 4 | for (int n : nums) { 5 | if (hs.contains(n)) { 6 | return true; 7 | } 8 | hs.add(n); 9 | } 10 | return false; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /continuous-subarray-sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean checkSubarraySum(int[] nums, int k) { 3 | HashMap hm = new HashMap(); 4 | int r = 0; 5 | for (int i = 0; i < nums.length; i++) { 6 | r += nums[i]; 7 | r %= k; 8 | if (hm.containsKey(r) && hm.get(r) - i > 1) return true; 9 | else hm.put(r, i); 10 | } 11 | return false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /convert-BST-to-greater-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | 10 | 10 11 | / \ 12 | 8 13 13 | / \ / \ 14 | 5 9 12 15 15 | It is reversed inorder traversal 16 | */ 17 | public class Solution { 18 | int sum = 0; 19 | public TreeNode convert(TreeNode root) { 20 | if (root == null) return; 21 | convert(root.right); 22 | sum += cur.val; 23 | cur.val = sum; 24 | convert(root.left); 25 | } 26 | public TreeNode convertBST(TreeNode root) { 27 | convert(root); 28 | return root; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /copy-node-with-random-pointers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list with a random pointer. 3 | * class RandomListNode { 4 | * int label; 5 | * RandomListNode next, random; 6 | * RandomListNode(int x) { this.label = x; } 7 | * }; 8 | */ 9 | public class Solution { 10 | public RandomListNode copyRandomList(RandomListNode head) { 11 | if (head == null) return null; 12 | RandomListNode cur = head; 13 | HashMap map = new HashMap(); 14 | while (cur != null) { 15 | map.put(cur, new RandomListNode(cur.label)); 16 | cur = cur.next; 17 | } 18 | cur = head; 19 | while (cur != null) { 20 | map.get(cur).random = map.get(cur.random); 21 | map.get(cur).next = map.get(cur.next); 22 | cur = cur.next; 23 | } 24 | return map.get(head); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /count-of-smaller-numbers-after-self.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] smallerRight; 3 | public List countSmaller(int[] nums) { 4 | int n = nums.length; 5 | int[] indexes = new int[n]; 6 | smallerRight = new int[n]; 7 | for (int i = 0; i < n; i++) { 8 | indexes[i] = i; 9 | } 10 | mergeSort(nums, indexes, 0, n-1); 11 | List res = new ArrayList(); 12 | for (int i = 0; i < n; i++) { 13 | res.add(smallerRight[i]); 14 | } 15 | return res; 16 | } 17 | 18 | public void mergeSort(int[] nums, int[] indexes, int start, int end) { 19 | if (end <= start) return; 20 | int mid = (end+start)/2; 21 | 22 | mergeSort(nums, indexes, start, mid); 23 | mergeSort(nums, indexes, mid+1, end); 24 | merge(nums, indexes, start, end); 25 | } 26 | 27 | public void merge(int[] nums, int[] indexes, int start, int end) { 28 | int[] sortArr = new int[end - start + 1]; 29 | int sortIndex = 0, rightCount = 0, mid = (start+end)/2, left = start, right = mid+1; 30 | 31 | while (left <= mid && right <= end) { 32 | if (nums[indexes[left]] > nums[indexes[right]]) { 33 | rightCount++; 34 | sortArr[sortIndex] = indexes[right++]; 35 | } else { 36 | smallerRight[indexes[left]] += rightCount; 37 | sortArr[sortIndex] = indexes[left++]; 38 | } 39 | sortIndex++; 40 | } 41 | 42 | while (right <= end) { 43 | sortArr[sortIndex++] = indexes[right++]; 44 | } 45 | while (left <= mid) { 46 | smallerRight[indexes[left]] += rightCount; 47 | sortArr[sortIndex++] = indexes[left++]; 48 | } 49 | for (int i = start; i <= end; i++) { 50 | indexes[i] = sortArr[i-start]; 51 | } 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /count-the-repetitions.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int getMaxRepetitions(String s1, int n1, String s2, int n2) { 3 | 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /count-univalue-subtrees.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | static class TreeNode { 11 | int val; 12 | TreeNode left, right; 13 | public TreeNode(int value) {this.val = value;} 14 | } 15 | public static void main (String[] args) throws java.lang.Exception 16 | { 17 | TreeNode root = new TreeNode(5); 18 | root.left = new TreeNode(1); 19 | root.right = new TreeNode(5); 20 | root.left.left = new TreeNode(5); 21 | root.left.right = new TreeNode(5); 22 | root.right.right = new TreeNode(5); 23 | System.out.println(countUnivalSubtrees(root)); 24 | } 25 | public static int countUnivalSubtrees(TreeNode root) { 26 | if (root == null) return 0; 27 | return countUnivals(root); 28 | } 29 | public static int countUnivals(TreeNode root) { 30 | if (root.left == null && root.right == null) { 31 | return 1; 32 | } else if (root.left != null && root.right != null) { 33 | int left = countUnivals(root.left); 34 | int right = countUnivals(root.right); 35 | if (root.left.val == root.val && root.right.val == root.val) 36 | return 1 + right + left; 37 | else return left + right; 38 | } else if (root.left != null) { 39 | int left = countUnivals(root.left); 40 | if (root.left.val == root.val) 41 | return left + 1; 42 | else return left; 43 | } else { 44 | int right = countUnivals(root.right); 45 | if (root.right.val == root.val) 46 | return right + 1; 47 | else return right; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /counting-bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] countBits(int num) { 3 | int[] arr = new int[num+1]; arr[0] = 0; arr[1] = 1; 4 | int power = 1; 5 | while (power*2 <= num) { 6 | for (int i = power+1; i < power*2; i++) { 7 | arr[i] = arr[power] + arr[i-power]; 8 | } 9 | power *= 2; 10 | arr[power] = 1; 11 | } 12 | for (int i = power+1; i <= num; i++) { 13 | arr[i] = arr[power] + arr[i-power]; 14 | } 15 | } 16 | return arr; 17 | } 18 | -------------------------------------------------------------------------------- /course-schedule.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canFinish(int numCourses, int[][] prereq) { 3 | ArrayList[] graph = new ArrayList[numCourses]; 4 | int[] degree = new int[numCourses]; 5 | for (int i = 0; i < numCourses; i++) graph[i] = new ArrayList(); 6 | for (int i = 0; i < prereq.length; i++) { 7 | degree[prereq[i][1]]++; 8 | graph[prereq[i][0]].add(prereq[i][1]); 9 | } 10 | 11 | for (int i = 0; i < numCourses; i++) 12 | if (degree[i] == 0) { 13 | q.add(i); 14 | count++; 15 | } 16 | 17 | Queue q = new LinkedList(); 18 | int count = 0; 19 | while (!q.isEmpty()) { 20 | int v = q.poll(); 21 | for (int i : graph[v]) { 22 | degree[i]--; 23 | if (degree[i] == 0) { 24 | q.add(i); 25 | count++; 26 | } 27 | } 28 | } 29 | if (count == numCourses) { return true; } 30 | else { return false; } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /decode-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String decodeString(String s) { 3 | Stack sbSt = new Stack<>(); 4 | Stack intSt = new Stack<>(); 5 | StringBuffer curSb = new StringBuffer(); 6 | int num = 0, n = s.length(), i = 0; 7 | char[] cs = s.toCharArray(); 8 | while (i < n) { 9 | if (cs[i] == '[') { 10 | intSt.push(num); 11 | num = 0; 12 | sbSt.push(curSb); 13 | curSb = new StringBuffer(); 14 | } 15 | if (Character.isLetter(cs[i])) { 16 | curSb.append(cs[i]); 17 | } 18 | if (cs[i] == ']') { 19 | String dupSt = genDup(intSt.pop(), curSb.toString()); 20 | curSb = sbSt.pop(); 21 | curSb.append(dupSt); 22 | } 23 | if (cs[i] >= '0' && cs[i] <= '9') { 24 | num = num * 10 + cs[i] - '0'; 25 | } 26 | i++; 27 | } 28 | return curSb.toString(); 29 | } 30 | 31 | public String genDup(int times, String st) { 32 | StringBuffer sb = new StringBuffer(); 33 | for (int i = 0; i < times; i++) sb.append(st); 34 | return sb.toString(); 35 | } 36 | } 37 | 38 | /** 39 | 3[a2[c]] 40 | generateDup(2) 41 | 42 | **/ 43 | -------------------------------------------------------------------------------- /decode-string.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | def decodeString(self, s: str) -> str: 5 | numStack = deque() 6 | strStack = deque() 7 | curNum = 0 8 | curStr = '' 9 | 10 | for cur in s: 11 | if cur.isdecimal(): 12 | curNum = curNum*10 + int(cur) 13 | elif cur.isalpha(): 14 | curStr += cur 15 | elif cur == '[': 16 | numStack.append(int(curNum)) 17 | strStack.append(curStr) 18 | curNum = 0 19 | curStr = '' 20 | elif cur == ']': 21 | multiplier = numStack.pop() 22 | repeatedString = multiplier * curStr 23 | curStr = strStack.pop() 24 | curStr = curStr + repeatedString 25 | 26 | return curStr 27 | -------------------------------------------------------------------------------- /delete-and-earn.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int deleteAndEarn(int[] nums) { 3 | if (nums.length == 0) return 0; 4 | int[] points = new int[10005], earn = new int[nums.length]; 5 | for (int i = 0; i < nums.length; i++) { 6 | points[nums[i]] += nums[i]; 7 | } 8 | earn[0] = points[0]; earn[1] = Math.max(points[0], points[1]); 9 | for (int i = 2; i < 10001; i++) { 10 | earn[i] = Math.max(earn[i] + earn[i-2], earn[i-1]); 11 | } 12 | return earn[10000]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /delete-node-in-a-BST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 static TreeNode successor(TreeNode cur) { 12 | while (cur.left != null) { 13 | cur = cur.left; 14 | } 15 | return cur; 16 | } 17 | public TreeNode deleteNode(TreeNode root, int key) { 18 | if (root == null) { 19 | return root; 20 | } 21 | TreeNode temp = null; 22 | if (key < root.val) { 23 | root.left = deleteNode(root.left, key); 24 | } else if (key > root.val) { 25 | root.right = deleteNode(root.right, key); 26 | } else { 27 | if (root.left == null) { 28 | temp = root.right; 29 | root.right = null; 30 | return temp; 31 | } else if (root.right == null) { 32 | temp = root.left; 33 | root.left = null; 34 | return temp; 35 | } 36 | temp = successor(root.right); 37 | root.val = temp.val; 38 | root.right = deleteNode(root.right, temp.val); 39 | } 40 | return root; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /delete-node.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | static class TreeNode { 4 | TreeNode left, right; 5 | int val; 6 | public TreeNode(val) {this.val = val;} 7 | } 8 | class Solution { 9 | 10 | public static TreeNode deleteNode(TreeNode root, int key) { 11 | TreeNode parent = root; 12 | TreeNode keyNode = findKeyInTree(root, key, parent); 13 | if (keyNode.right == null && keyNode.left == null) { 14 | keyNode = null; 15 | } else if (keyNode.right != null && keyNode.left != null) { 16 | if (keyNode.val < parent.val) { 17 | parent.left = keyNode.right; 18 | 19 | } else { 20 | parent.right = keyNode.right; 21 | } 22 | keyNode.right.left = keyNode.left; 23 | keyNode = null; 24 | } else { 25 | if (keyNode.right == null) { 26 | keyNode = keyNode.left; 27 | } else { 28 | keyNode = keyNode.right; 29 | } 30 | } 31 | return root; 32 | } 33 | 34 | public static TreeNode findKeyInTree(TreeNode root, int key, TreeNode parent) { 35 | TreeNode cur = root; 36 | parent = root; 37 | if (key == cur.val) { 38 | return cur; 39 | } else if (key < cur.val) { 40 | parent = cur; 41 | cur = cur.left; 42 | } else { 43 | parent = cur; 44 | cur = cur.right 45 | } 46 | } 47 | 48 | public static void main(String[] args) { 49 | TreeNode root = new TreeNode(5); 50 | root.left = new TreeNode(3); 51 | root.right = new TreeNode(6); 52 | root.left.left = new TreeNode(2); 53 | root.left.right = new TreeNode(4); 54 | root.right.right = new TreeNode(6); 55 | TreeNode res = deleteNode(root, 3); 56 | } 57 | 58 | } 59 | 60 | /** 61 | 5 62 | / \ 63 | 3 8 64 | / \ / 65 | 2 6 66 | 67 | 5 68 | / \ 69 | 3 6 70 | / \ \ 71 | 2 4 7 72 | 73 | 74 | **/ 75 | -------------------------------------------------------------------------------- /design-a-vending-machine.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public enum BillsType { 3 | ONE, TWO, FIVE, TEN, TWENTY, FIFTY 4 | } 5 | public class VendingMachine { 6 | int shelves, rows, cols, totalSales; 7 | Product products[][][] = new Product[shelves][rows][cols]; 8 | List productList = new ArrayList(); 9 | int currentBalance; 10 | HashMap coins = new HashMap(); 11 | public Product vend(Product product) { 12 | if (product.quantity <= 0) { 13 | displayMessage("SOLD OUT. SORRY"); 14 | return null; 15 | } else { 16 | displayMessage("INSERT MONEY"); 17 | HashMap bills = getPayment(); 18 | acceptPayment(product, bills); 19 | } 20 | } 21 | public int tellPrice(int shelf, int row, int col) { 22 | return products[shelf][row][col].price; 23 | } 24 | public int acceptPayment(Product product, HashMap billsList) { 25 | int amountReceived = getTotal(billsList); 26 | while (product.price > amountReceived) { 27 | displayMessage("NOT ENOUGH. GIVE ME MORE"); 28 | HashMap bills = getPayment(); 29 | amountReceived += getTotal(bills); 30 | billsList.addAll(bills); 31 | } 32 | if (!canMakeChange(amountReceived - product.price, billsList)) { 33 | displayMessage("OUT OF CHANGE"); 34 | refund(); 35 | } else { 36 | int change = amountReceived - product.price; 37 | returnChange(change); 38 | updateCurrentBalance(amountReceived, billsMap); 39 | } 40 | } 41 | public void refund() {} 42 | public void returnChange(int change) {} 43 | public void requestRestock(Product product) {} 44 | public boolean checkInventory(Product product) { 45 | return Inventory.hasItem(product); 46 | } 47 | 48 | } 49 | public class NotFullPaidException extends Exception {} 50 | public class SoldOutException extends Exception {} 51 | public class NotEnoughChangeException extends Exception {} 52 | public class Product { 53 | int quantity, dateImported, expirationDate, price; 54 | String name, seller; 55 | } 56 | public class Inventory { 57 | public static int getQuantity(Product product) {} 58 | public static void addProduct(Product product, int amount) {} 59 | public static void deductProduct(Product product) {} 60 | public static void hasItem(Product product) {} 61 | } 62 | public static void main(String args[]) { 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /design-twitter.java: -------------------------------------------------------------------------------- 1 | public class Twitter { 2 | 3 | /** Initialize your data structure here. */ 4 | public Twitter() { 5 | HashMap> followees = new HashMap>(); 6 | HashMap> followers = new HashMap>(); 7 | HashMap> newsfeeds = new HashMap>(); 8 | } 9 | 10 | /** Compose a new tweet. */ 11 | public void postTweet(int userId, int tweetId) { 12 | for (List followerList : followers.get(userId)) { 13 | for (Integer followerId : followerList) { 14 | newsfeeds.get(followerId).add(tweetId); 15 | } 16 | } 17 | } 18 | 19 | /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ 20 | public List getNewsFeed(int userId) { 21 | List newsfeedUserId = new ArrayList(); 22 | for (int i = 0; i < 10 && i < newsfeed.get(userId).length; i++) { 23 | newsfeedUserId.add(newsfeed.get(userId).getFirst()); 24 | } 25 | return newsfeedUserId; 26 | } 27 | 28 | /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ 29 | public void follow(int followerId, int followeeId) { 30 | followees.get(followerId).add(followeeId); 31 | followers.get(followeeId).add(followerId); 32 | } 33 | 34 | /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ 35 | public void unfollow(int followerId, int followeeId) { 36 | followees.get(followerId).remove(followeeId); 37 | followers.get(followeeId).remove(followerId); 38 | } 39 | } 40 | 41 | /** 42 | * Your Twitter object will be instantiated and called as such: 43 | * Twitter obj = new Twitter(); 44 | * obj.postTweet(userId,tweetId); 45 | * List param_2 = obj.getNewsFeed(userId); 46 | * obj.follow(followerId,followeeId); 47 | * obj.unfollow(followerId,followeeId); 48 | */ 49 | -------------------------------------------------------------------------------- /diagonal-traverse.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] findDiagonalOrder(int[][] matrix) { 3 | boolean up = true; 4 | int layers = Math.max(matrix.length, matrix[0].length); 5 | for (int l = 0; l < layers; l++) { 6 | if (!up) { 7 | int j = l-1; 8 | for (int i = 0; i < l; i++) 9 | System.out.println(matrix[i][j--]); 10 | } else { 11 | int i = l-1; 12 | for (int j = 0; j < l; j++) 13 | System.out.println(matrix[i--][j]); 14 | } 15 | up = !up; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /distribute-candies.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int distributeCandies(int[] candies) { 3 | HashMap map = new HashMap(); 4 | for (int i = 0; i < candies.length; i++) { 5 | map.put(candies[i], map.getOrDefault(candies[i], 0) + 1); 6 | } 7 | return map.size() < candies.length/2 ? map.size() : candies.length/2; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /employee-importance.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Employee info 3 | class Employee { 4 | // It's the unique id of each node; 5 | // unique id of this employee 6 | public int id; 7 | // the importance value of this employee 8 | public int importance; 9 | // the id of direct subordinates 10 | public List subordinates; 11 | }; 12 | */ 13 | class Solution { 14 | int total = 0; 15 | HashMap map = new HashMap(); 16 | boolean[] visited = new boolean[2005]; 17 | public int getImportance(List employees, int id) { 18 | for (Employee emp : employees) { 19 | map.put(emp.id, emp); 20 | } 21 | Employee curEmp = map.get(id); 22 | findSubordinates(curEmp); 23 | return total; 24 | } 25 | public void findSubordinates(Employee curEmp) { 26 | total += curEmp.importance; 27 | visited[curEmp.id] = true; 28 | for (int subId : curEmp.subordinates) { 29 | findSubordinates(map.get(subId)); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /encode-and-decode-tinyurl.java: -------------------------------------------------------------------------------- 1 | public class Codec { 2 | HashMap urlMap = new HashMap(); 3 | // Encodes a URL to a shortened URL. 4 | public String encode(String longUrl) { 5 | String hashCode = generateRandomHashCode(longUrl); 6 | if (urlMap.containsKey(hashCode)) return urlMap.get(hashCode); 7 | else { 8 | urlMap.put(hashCode, longUrl); 9 | return "http://tinyurl.com/" + hashCode; 10 | } 11 | } 12 | 13 | // Decodes a shortened URL to its original URL. 14 | public String decode(String shortUrl) { 15 | return urlMap.get(shortUrl.substring(20)); 16 | } 17 | } 18 | 19 | // Your Codec object will be instantiated and called as such: 20 | // Codec codec = new Codec(); 21 | // codec.decode(codec.encode(url)); 22 | -------------------------------------------------------------------------------- /encode-string-with-shortest-length.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | String s = "abcdeabcde"; 13 | System.out.println(encode(s)); 14 | } 15 | 16 | public static String encode(String s) { 17 | int n = s.length(); 18 | String dp[][] = new String[n][n]; 19 | for (int l = 0; l < n; l++) { 20 | for (int i = 0; i < n-l; i++) { 21 | int j = i + l; 22 | String sub = s.substring(i, j+1); 23 | if (sub.length() < 5) { 24 | dp[i][j] = sub; 25 | } else { 26 | dp[i][j] = sub; 27 | for (int k = i; k < j; k++) { 28 | if (dp[i][j].length() > dp[i][k].length() + dp[k+1][j].length()) { 29 | dp[i][j] = dp[i][k] + dp[k+1][j]; 30 | } 31 | } 32 | for (int k = 0; k < sub.length(); k++) { 33 | String repeat = sub.substring(0,k+1); 34 | if (repeat != null && sub.length()%repeat.length() == 0 35 | && sub.replaceAll(repeat, "").length() == 0) { 36 | String shorter = sub.length()/repeat.length() + "[" + 37 | dp[i][i+k] + "]"; 38 | if (shorter.length() < dp[i][j].length()) { 39 | dp[i][j] = shorter; 40 | } 41 | } 42 | } 43 | } 44 | } 45 | } 46 | return dp[0][n-1]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /evaluate-division.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | String[][] equations = new String[][]{ 13 | {"a", "b"}, {"b", "c"} 14 | }; 15 | double[] values = new double[] {2.0, 3.0}; 16 | String[][] queries = new String[][]{{"a", "c"}, {"b", "a"}, {"a", "e"}, {"a", "a"}, {"x", "x"}}; 17 | Ideone o = new Ideone(); 18 | double[] results = o.calcEquation(equations, values, queries); 19 | System.out.println(Arrays.toString(results)); 20 | } 21 | 22 | 23 | public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { 24 | HashMap> pairs = new HashMap>(); 25 | HashMap> weights = new HashMap>(); 26 | 27 | for (int i = 0; i < equations.length; i++) { 28 | if (!pairs.containsKey(equations[i][0])) { 29 | pairs.put(equations[i][0], new ArrayList()); 30 | weights.put(equations[i][0], new ArrayList()); 31 | } 32 | if (!pairs.containsKey(equations[i][1])) { 33 | pairs.put(equations[i][1], new ArrayList()); 34 | weights.put(equations[i][1], new ArrayList()); 35 | } 36 | pairs.get(equations[i][0]).add(equations[i][1]); 37 | weights.get(equations[i][0]).add(values[i]); 38 | pairs.get(equations[i][1]).add(equations[i][0]); 39 | weights.get(equations[i][1]).add(1/values[i]); 40 | } 41 | double[] results = new double[queries.length]; 42 | for (int i = 0; i < queries.length; i++) { 43 | double retVal = dfs(queries[i][0], queries[i][1], 1.0, pairs, weights, new HashSet()); 44 | if (retVal == 0.0) results[i] = -1.0; else results[i] = retVal; 45 | } 46 | return results; 47 | } 48 | public double dfs(String startNode, String endNode, double value, HashMap> pairs, 49 | HashMap> weights, HashSet visited) { 50 | if (visited.contains(startNode)) return 0.0; 51 | if (!pairs.containsKey(startNode)) return 0.0; 52 | if (startNode.equals(endNode)) return value; 53 | List toNodes = pairs.get(startNode); 54 | visited.add(startNode); 55 | double retVal = 0.0; 56 | for (int i = 0; i < toNodes.size(); i++) { 57 | String next = toNodes.get(i); 58 | retVal = dfs(next, endNode, value * weights.get(startNode).get(i), pairs, weights, visited); 59 | if (retVal != 0.0) { 60 | break; 61 | } 62 | } 63 | visited.remove(startNode); // remove because there might be a case of a/b = 3.0 and c/b = 2.0 64 | return retVal; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /falling-squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | struct block { 4 | int left, right, height; 5 | block(int l, int r, int h) {left = l; right = r; height = h;} 6 | }; 7 | vector fallingSquares(vector>& positions) { 8 | vector blocks; 9 | vector ans; 10 | int maxHeight = 0; 11 | for (int i = 0; i < positions.size(); i++) { 12 | int maxH = 0, left = positions[i].first, right = positions[i].first+positions[i].second, height = positions[i].second; 13 | for (int j = blocks.size()-1; j >= 0; j--) { 14 | if (blocks[j].left <= left && blocks[j].right > left || blocks[j].left >= left && blocks[j].left < right) { 15 | maxH = max(maxH, blocks[j].height); 16 | } 17 | // cout << "i= " << i << ", j= " << j << ", left= " << blocks[j].left << ", right= " << blocks[j].right << ", maxH= " << maxH << "\n"; 18 | } 19 | height += maxH; 20 | blocks.push_back(block(left, right, height)); 21 | maxHeight = max(maxHeight, height); 22 | ans.push_back(maxHeight); 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /find-all-duplicates-in-an-array.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | int[] nums = new int[] {1,1}; 13 | List list = findDuplicates(nums); 14 | // System.out.println("result: "); 15 | for (int i : list) { 16 | System.out.print(i + " "); 17 | } 18 | } 19 | public static List findDuplicates(int[] nums) { 20 | List res = new ArrayList(); 21 | for (int i = 0; i < nums.length; i++) { 22 | if (nums[Math.abs(nums[i])-1] < 0) { 23 | res.add(Math.abs(nums[i])); 24 | } else { 25 | nums[Math.abs(nums[i])-1] *= -1; 26 | } 27 | } 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /find-all-numbers-disappeared-in-an-array.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class Solution { 3 | public List findDisappearedNumbers(int[] nums) { 4 | Arrays.sort(nums); 5 | // for (int i : nums) System.out.print(i + " "); 6 | // System.out.println(); 7 | 8 | List res = new ArrayList(); 9 | if (nums.length < 2) return res; 10 | // if (nums[0] == 2) {res.add(1); nums[0] = 1;} 11 | int need = 1; 12 | for (int i = 0; i < nums.length; i++) { 13 | if (nums[i] == need) { 14 | need++; 15 | } else if (nums[i] - need > 0) { 16 | for (int j = need; j < nums[i]; j++) { 17 | res.add(j); 18 | } 19 | need = nums[i] + 1; 20 | } 21 | } 22 | for (int j = need; j <= nums.length; j++) { 23 | res.add(j); 24 | } 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /find-bottom-left-tree-value.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 | int val, maxRow = -1; 12 | public void traverse(TreeNode root, int level) { 13 | if (root == null) return; 14 | if (level > maxRow) { 15 | maxRow = level; 16 | val = root.val; 17 | } 18 | if (root.left != null) traverse(root.left, level+1); 19 | if (root.right != null) traverse(root.right, level+1); 20 | } 21 | public int findBottomLeftValue(TreeNode root) { 22 | traverse(root, 0); 23 | return val; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /find-largest-smaller-key.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | class Node { 11 | int value; 12 | Node left; 13 | Node right; 14 | } 15 | public static void main (String[] args) throws java.lang.Exception 16 | { 17 | /** 18 | Example tree: 19 | 10 20 | 5 21 21 | 3 7 15 35 22 | 2 4 13 18 89 23 | 12 14 16 20 24 | **/ 25 | } 26 | 27 | public static int findLargestSmaller(int x, Node root) { 28 | Node cur = root; 29 | int lastSmall = -1; 30 | while (cur != null) { 31 | if (cur.value >= x) { 32 | cur = cur.left; 33 | } else { 34 | lastSmall = cur.value; 35 | cur = cur.right; 36 | } 37 | } 38 | return lastSmall; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /find-largest-value-in-each-tree-row.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 | int level = 0; 12 | public List largestValues(TreeNode root) { 13 | ArrayList list = new ArrayList(); 14 | if (root == null) return list; 15 | else { 16 | largestLevel(0, root, list); 17 | return list; 18 | } 19 | } 20 | public void largestLevel(int level, TreeNode root, ArrayList list) { 21 | if (root == null) return; 22 | if (level >= list.size()) list.add(root.val); 23 | list.set(level, Math.max(list.get(level), root.val)); 24 | largestLevel(level+1, root.left, list); 25 | largestLevel(level+1, root.right, list); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /find-leaves-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | static class TreeNode { 11 | int val; 12 | TreeNode left = null, right = null; 13 | TreeNode(int value) {this.val = value;} 14 | } 15 | public static void main (String[] args) throws java.lang.Exception 16 | { 17 | TreeNode root = new TreeNode(0); 18 | root.left = new TreeNode(2); 19 | root.right = new TreeNode(3); 20 | root.left.left = new TreeNode(4); 21 | root.left.right = new TreeNode(5); 22 | while (root != null) { 23 | // more preferred way to create a stack 24 | Deque stack = new ArrayDeque(); 25 | helper(root, root.left, stack); 26 | helper(root, root.right, stack); 27 | if (stack.isEmpty()) { 28 | stack.addFirst(root.val); 29 | System.out.println(Arrays.toString(stack.toArray())); 30 | root = null; 31 | } else { 32 | System.out.println(Arrays.toString(stack.toArray())); 33 | } 34 | 35 | } 36 | } 37 | 38 | public static void helper(TreeNode rootOfRoot,TreeNode root, Deque stack) { 39 | if (root == null) return; 40 | else if (root.left == null && root.right == null) { 41 | System.out.println("root.val= " + root.val); 42 | stack.addFirst(root.val); 43 | if (root == rootOfRoot.left) rootOfRoot.left = null; 44 | else rootOfRoot.right = null; 45 | return; 46 | } else { 47 | helper(root, root.left, stack); 48 | helper(root, root.right, stack); 49 | } 50 | } 51 | 52 | 53 | // The second way of using height of node 54 | 55 | public static List> findLeaves(TreeNode root) { 56 | // The height of a node is the number of edges from the node to the deepest leaf 57 | List> list = new ArrayList>(); 58 | height(root, list); 59 | return list; 60 | } 61 | 62 | public static int height(TreeNode node, List> list) { 63 | if (node == null) return -1; 64 | // the height of leaf is 0 65 | // h(node) = 1 + max(h(node.left), h(node.right)) 66 | int level = 1+Math.max(height(node.left, list), height(node.right, list)); 67 | if (level >= list.size()) list.add(new ArrayList()); 68 | list.get(level).add(node.val); 69 | return level; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /find-leaves-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]: 9 | heights = [] 10 | def getHeight(root, heights): 11 | if root == None: 12 | return -1 13 | right = getHeight(root.right, heights) 14 | left = getHeight(root.left, heights) 15 | height = 1 + max(right, left) 16 | 17 | if len(heights) == height: 18 | heights.append([]) 19 | heights[height].append(root.val) 20 | return height 21 | getHeight(root, heights) 22 | return heights 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /find-median-from-data-stream.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | 3 | /** initialize your data structure here. */ 4 | PriorityQueue minQueue, maxQueue; 5 | public MedianFinder() { 6 | maxQueue = new PriorityQueue<>(1000, Collections.reverseOrder()); 7 | minQueue = new PriorityQueue<>(); 8 | } 9 | 10 | public void addNum(int num) { 11 | maxQueue.offer(num); 12 | minQueue.offer(maxQueue.poll()); 13 | 14 | if (maxQueue.size() < minQueue.size()) { 15 | maxQueue.offer(minQueue.poll()); 16 | } 17 | 18 | } 19 | 20 | public double findMedian() { 21 | if (maxQueue.size() == minQueue.size()) return (maxQueue.peek() + minQueue.peek())/2.0; 22 | else return maxQueue.peek(); 23 | } 24 | } 25 | 26 | /** 27 | * Your MedianFinder object will be instantiated and called as such: 28 | * MedianFinder obj = new MedianFinder(); 29 | * obj.addNum(num); 30 | * double param_2 = obj.findMedian(); 31 | */ 32 | -------------------------------------------------------------------------------- /find-minimum-in-rotated-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] nums) { 3 | int n = nums.length; 4 | for (int i = 1; i < n; i++) { 5 | if (nums[i] <= nums[i-1]) { 6 | return nums[i]; 7 | } 8 | } 9 | return nums[0]; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /find-peak-element.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findPeakElement(int[] nums) { 3 | for (int i = 1; i < nums.length; i++) { 4 | if (nums[i] < nums[i-1]) { 5 | return i-1; 6 | } 7 | } 8 | return nums.length-1; 9 | } 10 | } 11 | 12 | /** O(logN) **/ 13 | import java.util.*; 14 | import java.lang.*; 15 | import java.io.*; 16 | class Ideone 17 | { 18 | public static void main (String[] args) throws java.lang.Exception 19 | { 20 | int[] nums = new int[] {1,2,3,4,5,6,7,3,1}; 21 | System.out.println(findPeakElement(nums)); 22 | } 23 | public static int findPeakElement(int[] nums) { 24 | int low = 0, high = nums.length-1; 25 | while (low < high) { 26 | int mid = (low + high) / 2; 27 | System.out.println("low= " + low + ", high= " + high + ", mid= " + mid); 28 | if (nums[mid] < nums[mid+1]) { 29 | low = mid+1; 30 | } else { 31 | high = mid; 32 | } 33 | } 34 | return low; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /find-the-duplicate-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findDuplicate(int[] nums) { 3 | int n = nums.length-1; 4 | int p1 = nums[0], p2 = nums[nums[0]]; 5 | while (p1 != p2) { 6 | p1 = nums[p1]; 7 | p2 = nums[nums[p2]]; 8 | } 9 | 10 | p2 = 0; 11 | 12 | while (p1 != p2) { 13 | p1 = nums[p1]; 14 | p2 = nums[p2]; 15 | } 16 | 17 | return p1; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /flatten-binary-tree-to-linked-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | TreeNode prev; 12 | public void flatten(TreeNode root) { 13 | if (root == null) return; 14 | 15 | flatten(root.right); 16 | flatten(root.left); 17 | 18 | root.right = prev; 19 | root.left = null; 20 | 21 | prev = root; 22 | } 23 | 24 | 25 | } 26 | 27 | /** 28 | 29 | 2 30 | / \ 31 | 3 4 32 | 33 | 2 34 | \ 35 | 3 36 | \ 37 | 4 38 | 39 | 1 40 | / \ 41 | 2 5 42 | / \ \ 43 | 3 4 6 44 | 45 | 46 | **/ 47 | -------------------------------------------------------------------------------- /flip-game.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | String s = "++++"; 13 | System.out.println(generatePossibleNextMoves(s)); 14 | } 15 | public static List generatePossibleNextMoves (String s) { 16 | List l = new LinkedList(); 17 | for (int i = 0; i < s.length() - 1; i++) { 18 | if (s.charAt(i) == '+' && s.charAt(i+1) == '+') { 19 | StringBuilder sb = new StringBuilder(s); 20 | sb.replace(i, i+2, "--"); 21 | l.add(sb.toString()); 22 | } 23 | } 24 | return l; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /freedom-trail.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findRotateSteps(String ring, String key) { 3 | // use dp 4 | int[][] dp = new int[][]; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /friend-circles.java: -------------------------------------------------------------------------------- 1 | /****************************************Union find solution***************************************/ 2 | public class Solution { 3 | int[] parent = new int[]; 4 | int count; 5 | public int findCircleNum(int[][] M) { 6 | for (int i = 0; i < parent.length; i++) { 7 | parent[i] = i; 8 | } 9 | count = M.length; 10 | for (int i = 0; i < M.length; i++) 11 | for (int j = 0; j < M[0].length; j++) { 12 | if (M[i][j] == 1) union(i, j); 13 | } 14 | return count; 15 | } 16 | 17 | public void union(int i, int j) { 18 | int root_i = find(i); 19 | int root_j= find(j; 20 | if (root_i == root_j) return; 21 | parent[root_i] = parent[root_j]; 22 | count--; // still don't get this one 23 | } 24 | public int find(int i) { 25 | while (i != parents[i]) { 26 | parent[i = parent[parent[i]]; 27 | i = parent[i]; 28 | } 29 | return i; 30 | } 31 | } 32 | 33 | /********************DFS solution***************************/ 34 | 35 | public class Solution { 36 | public int findCircleNum(int[][] M) { 37 | boolean[] visited = new boolean[M.length]; 38 | for (int i = 0; i < M.length; i++) { 39 | if (!visited[i]) { 40 | count++; 41 | dfs(M, visited, i); 42 | } 43 | } 44 | return count; 45 | } 46 | public void dfs(int[][] M, boolean[] visited, int i) { 47 | for (int j = 0; j < M.length; j++) { 48 | if (M[i][j] && !visited[j]) { 49 | dfs(M, visited, j); 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /game-of-life.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public void gameOfLife(int[][] board) { 4 | int[][] board2 = new int[board.length][board[0].length]; 5 | for (int i = 0; i < board.length; i++) { 6 | int[] temp = board[i]; 7 | System.arraycopy(board[i], 0, board2[i], 0, board[i].length); 8 | } 9 | for (int i = 0; i < board.length; i++) { 10 | for (int j = 0; j < board[0].length; j++) { 11 | // int i = 1, j = 1; 12 | int n = aliveNeighbors(board2, i, j); 13 | // System.out.print("n= " + n + " "); 14 | if (board[i][j] == 1) { 15 | if (n < 2 || n > 3) board[i][j] = 0; 16 | } else { 17 | if (n == 3) board[i][j] = 1; 18 | } 19 | } 20 | // System.out.println(); 21 | } 22 | } 23 | public int aliveNeighbors(int[][] board2, int x, int y) { 24 | // System.out.println("x= " + x + ", y= " + y); 25 | // for (int i = 0; i < board2.length; i++) { 26 | // for (int j = 0; j < board2[0].length; j++) 27 | // System.out.print(board2[i][j] + " "); 28 | // System.out.println(); 29 | // } 30 | // System.out.println(); 31 | int retVal = 0; 32 | if (x - 1 >= 0 && y - 1 >= 0) retVal += board2[x-1][y-1]; 33 | if (x - 1 >= 0 && y >= 0) retVal += board2[x-1][y]; 34 | if (x - 1 >= 0 && y + 1 < board2[0].length) retVal += board2[x-1][y+1]; 35 | if (x >= 0 && y - 1 >= 0) retVal += board2[x][y-1]; 36 | if (x < board2.length && y + 1 < board2[0].length) retVal += board2[x][y+1]; 37 | if (x + 1 < board2.length && y - 1 >= 0) retVal += board2[x+1][y-1]; 38 | if (x + 1 < board2.length && y >= 0) retVal += board2[x+1][y]; 39 | if (x + 1 < board2.length && y + 1 < board2[0].length) retVal += board2[x+1][y+1]; 40 | // System.out.print("r= " + retVal + " " ); 41 | return retVal; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /generate-parantheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generateParenthesis(int n) { 4 | vector list; 5 | string str = ""; 6 | generate(list, n, str, 0, 0); 7 | return list; 8 | } 9 | 10 | void generate(vector &list, int n, string str, int left, int right) { 11 | if (str.size() == 2*n) { 12 | list.push_back(str); 13 | return; 14 | } 15 | if (left < n) generate(list, n, str + "(", left + 1, right); 16 | if (right < left) generate(list, n, str + ")", left, right + 1); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /generating-parenthesis.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | System.out.println(generateParenthesis(4)); 13 | } 14 | public static List generateParenthesis(int n) { 15 | List res = new LinkedList(); 16 | if (n == 0) return res; 17 | else { 18 | Set oldSet = new HashSet(); 19 | oldSet.add(""); 20 | Set newSet; 21 | for (int i = 0; i < n; i++) { 22 | newSet = new HashSet(); 23 | for (String str : oldSet) { 24 | newSet.add(str + "()"); 25 | newSet.add("()" + str); 26 | newSet.add("(" + str + ")"); 27 | } 28 | System.out.println(newSet); 29 | oldSet = new HashSet(newSet); 30 | } 31 | return new LinkedList(oldSet); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /hamming-distance.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int hammingDistance(int x, int y) { 3 | int res = 0; 4 | String sx = Integer.toBinaryString(x), sy = INteger.toBinaryString(y); 5 | for (int i = 0; i < x.lnegth; x++) if (sx.charAt(i) != sy.charAt(i)) res++; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /heaters.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | Solved using binary search 4 | **/ 5 | import java.util.*; 6 | import java.lang.*; 7 | import java.io.*; 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | Ideone m = new Ideone(); 13 | int[] houses = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; 14 | int[] heaters = new int[] {1,4,9}; 15 | System.out.println("radius: " + m.findRadius(houses, heaters)); 16 | } 17 | // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 18 | // [1], 2, 3, [4], 5, 6, 7, 8, [9], 10, 11, 12 19 | // 1, 2, [3], 4, 5, 6, [7], 8, [9], 10, 11, 12 20 | 21 | public int findRadius(int[] houses, int[] heaters) { 22 | long left = -1, right = 10000000000L; 23 | while (left + 1 < right) { 24 | long mid = (left + right) / 2; 25 | int i = 0, j = 0; 26 | while (i < houses.length && j < heaters.length) { 27 | if (houses[i] - heaters[j] <= mid) { 28 | i++; 29 | } else { 30 | j++; 31 | } 32 | } 33 | if (i >= houses.length) { 34 | right = mid; 35 | } else { 36 | left = mid; 37 | } 38 | } 39 | return (int) right; 40 | } 41 | } 42 | 43 | // Solved with TreeSet 44 | 45 | public class Solution { 46 | 47 | // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 48 | // 1, 4, 9 49 | // 2, 5, 9 50 | public int findRadius(int[] houses, int[] heaters) { 51 | Arrays.sort(houses); Arrays.sort(heaters); 52 | TreeSet heats = new TreeSet(); 53 | int maxDis = 0; 54 | for (int i = 0; i < heaters.length; i++) heats.add(heaters[i]); 55 | for (int h = 0; h < houses.length; h++) { 56 | Integer heater1 = heats.ceiling(houses[h]); 57 | int m = Integer.MAX_VALUE; 58 | if (heater1 != null) m = Math.abs(heater1 - houses[h]); 59 | Integer heater2 = heats.floor(houses[h]); 60 | if (heater2 != null) m = Math.min(m, Math.abs(heater2 - houses[h])); 61 | maxDis = Math.max(maxDis, m); 62 | } 63 | return maxDis; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /house-robber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | int n = nums.length; 4 | if (n == 0) return 0; 5 | if (n == 1) return nums[0]; 6 | int[] robbed = new int[n]; 7 | robbed[0] = nums[0]; robbed[1] = Math.max(nums[0], nums[1]); 8 | for (int i = 2; i < n; i++) { 9 | robbed[i] = Math.max(nums[i] + robbed[i-2], robbed[i-1]); 10 | //robbed[i] = Math.max(robbed[i], robbed[i-1] + robbed[i+1]); 11 | } 12 | return Math.max(robbed[n-1], robbed[n-2]); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /increasing-subsequences.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> findSubsequences(int[] nums) { 3 | int n = nums.length; 4 | Set> ans = new HashSet>(); 5 | List temp = new ArrayList(); 6 | findSubsequencesHelper(nums, ans, temp, 0); 7 | return new ArrayList(ans); 8 | } 9 | public void findSubsequencesHelper(int[] nums, Set> ans, List temp, int index) { 10 | if (temp.size() >= 2) ans.add(new ArrayList(temp)); 11 | for (int i = index; i < nums.length; i++) { 12 | if (temp.size() == 0 || temp.get(temp.size()-1) <= nums[i]) { 13 | temp.add(nums[i]); 14 | findSubsequencesHelper(nums, ans, temp, index+1); 15 | temp.remove(temp.size()-1); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /interleaving-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isInterleave(String s1, String s2, String s3) { 3 | int n1 = s1.length(), n2 = s2.length(), n3 = s3.length(); 4 | int[][] memo = new int[n1][n2]; 5 | for (int i = 0; i < n1; i++) 6 | for (int j = 0; j < n2; j++) 7 | memo[i][j] = -1; 8 | for (int i = 0; i < n1; i++) { 9 | for (int j = 0; j < n2; j++) { 10 | int k = i + j - 1; 11 | if (i == 0 && j == 0) { 12 | memo[i][j] = true; 13 | } else if (i == 0) { 14 | memo[i][j] = memo[i][j-1] && s2.charAt(j-1) == s3.charAt(k); 15 | } else if (j == 0) { 16 | memo[i][j] = memo[i-1][j] && s1.charAt(i-1) == s3.charAt(k); 17 | } else { 18 | if (s1.charAt(i-1) == s3.charAt(k)) memo[i][j] = memo[i-1][j]; 19 | if (s2.charAt(j-1) == s3.charAt(k)) memo[i][j] == memo[i][j-1]; 20 | } 21 | } 22 | } 23 | return memo[n1][n2]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /intersection-of-two-arrays-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] intersect(int[] nums1, int[] nums2) { 3 | int n1 = nums1.length, n2 = nums2.length; 4 | HashMap map = new HashMap(); 5 | for (int i1 = 0; i1 < n1; i1++) { 6 | if (!map.containsKey(nums1[n1])) map.put(nums1[n1], 0); 7 | map.put(nums1[n1], map.get(nums1[n1]) + 1); 8 | } 9 | for (int i2 = 0; i2 < n2; i2++) { 10 | if (map.containsKey(nums2[i2])) { 11 | nums2[i2] = -1; 12 | map.put(nums2[i2], map.get(nums2[i2]) + 1); 13 | if (map.get(nums2[i2]) == 0) map.remove(nums2[i2]); 14 | } 15 | } 16 | LinkedList list = new LinkedList(); 17 | for (int i2 = 0; i2 < n2; i2++) { 18 | if (nums2[i2] != -1) list.add(nums2[i2]); 19 | } 20 | return list.toArray(new Integer[list.size()]); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /island-perimeter.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | int[][] grid = { 13 | {1,1}, 14 | {1,1}}; 15 | System.out.println(islandPerimeter(grid)); 16 | } 17 | public static int islandPerimeter(int[][] grid) { 18 | int i = 0, j = 0; 19 | for (i = 0; i < grid.length; i++) { 20 | for (j = 0; j < grid[0].length; j++) { 21 | if (grid[i][j] == 1) { 22 | // System.out.println("main. i= " + i + ", j= " + j); 23 | return findPerimeter(grid, i, j); 24 | } 25 | } 26 | } 27 | return 0; 28 | } 29 | public static int findPerimeter(int[][] grid, int i, int j) { 30 | int sum = 0; 31 | System.out.println("i= " + i + ", j= " + j); 32 | grid[i][j] = -1; 33 | if (isValid(grid, i, j-1)) { 34 | if (grid[i][j-1] == 1) sum = findPerimeter(grid, i, j-1); 35 | else if (grid[i][j-1] == 0) sum = 1; 36 | } else sum = 1; 37 | if (isValid(grid, i, j+1)) { 38 | if (grid[i][j+1] == 1) sum += findPerimeter(grid, i, j+1); 39 | else if (grid[i][j+1] == 0) sum += 1; 40 | } else sum += 1; 41 | if (isValid(grid, i-1, j)) { 42 | if (grid[i-1][j] == 1) sum += findPerimeter(grid, i-1, j); 43 | else if (grid[i-1][j] == 0) sum += 1; 44 | } else sum += 1; 45 | if (isValid(grid, i+1, j)) { 46 | if (grid[i+1][j] == 1) sum += findPerimeter(grid, i+1, j); 47 | else if (grid[i+1][j] == 0) sum += 1; 48 | } else sum += 1; 49 | System.out.println("i= " + i + ", j= " + j + ", sum= " + sum); 50 | return sum; 51 | } 52 | public static boolean isValid(int[][] grid, int i, int j) { 53 | if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length) return true; 54 | else return false; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /jump-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int i = 0, n = nums.size(), reach = 0; 5 | for (int reach = 0; i < n && i <= reach; i++) { 6 | reach = max(reach, i + nums[i]); 7 | } 8 | return i == n; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /jump_game.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canJump(int[] nums) { 3 | int reach = 0; 4 | int n = nums.length; 5 | for (int i = 0; i < n && i <= reach; i++) { 6 | reach = Math.max(i + nums[i], reach); 7 | } 8 | return reach >= nums[n-1]; // or i == n; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /k-diff-pairs-in-an-array.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/contest/leetcode-weekly-contest-22/problems/k-diff-pairs-in-an-array/ 2 | public class Solution { 3 | public int findPairs(int[] nums, int k) { 4 | 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /k-smallest-element-in-BST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | int counter = 0, value; 12 | public int kthSmallest(TreeNode root, int k) { 13 | findkth(root, k); 14 | return value; 15 | } 16 | public void findkth(TreeNode root, int k) { 17 | if (root.left != null) findkth(root.left, k); 18 | counter++; 19 | if (counter == k) { 20 | value = root.val; return; 21 | } 22 | if (root.right != null) findkth(root.right, k); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /kill-process.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | List res = new ArrayList(); 3 | 4 | public List killProcess(List pid, List ppid, int kill) { 5 | res.add(pid, ppid, kill); 6 | for (int i = 0; i < pid.size(); i++) 7 | if (ppid.get(i) == kill) { 8 | killProcess(pid, ppid, pid.get(i)); 9 | } 10 | } 11 | } 12 | 13 | public static void main (String[] args) { 14 | int kill = 5; 15 | List pid = new ArrayList(Arrays.asList({1, 3, 10, 5})); //maybe wrong syntax here 16 | List ppid = new ArrayList(Arrays.asList({3, 0, 5, 3})); //maybe wrong syntax here 17 | System.out.println(res); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /kth-smallest-element-in-a-bst.java: -------------------------------------------------------------------------------- 1 | class IntClass { 2 | int val = 0; 3 | public IntClass(int val) { this.val = val;} 4 | } 5 | class Solution { 6 | int kthMin = -1; 7 | public int kthSmallest(TreeNode root, int k) { 8 | IntClass kth = new IntClass(k); 9 | findkth(root, kth); 10 | return kthMin; 11 | } 12 | 13 | public void findkth(TreeNode root, IntClass kth) { 14 | if (root == null || kth.val == 0) return; 15 | 16 | findkth(root.left, kth); 17 | kth.val = kth.val-1; 18 | if (kth.val == 0) kthMin = root.val; 19 | findkth(root.right, kth); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /largest-number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String largestNumber(int[] nums) { 3 | Arrays.sort(nums, new Comparator() { 4 | public int compare(int n1, int n2) { 5 | String s1 = String.valueOf(n1); 6 | String s2 = String.valueOf(n2); 7 | return Integer.valueOf(s1+s2) - Integer.valueOf(s2+s1); 8 | } 9 | }); 10 | String res = ""; 11 | for (int i = 0; i < nums.length; i++) res += nums[i]; 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /letter-combination-of-a-phone-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void combineLetters(vector &vec, map &m, string s, char str[], int curLen) { 4 | if (curLen == s.size()) { 5 | vec.push_back(str); 6 | } 7 | for (int i = 0; i < m[s[curLen]].size(); i++) { 8 | str[curLen] = m[s[curLen]][i]; 9 | combineLetters(vec, m, s, str, curLen+1); 10 | str[curLen] = '\0'; 11 | } 12 | } 13 | vector letterCombinations(string digits) { 14 | map mapping; 15 | mapping['0'] = ""; 16 | mapping['1'] = ""; 17 | mapping['2'] = "abc"; 18 | mapping['3'] = "def"; 19 | mapping['4'] = "ghi"; 20 | mapping['5'] = "jkl"; 21 | mapping['6'] = "mno"; 22 | mapping['7'] = "pqrs"; 23 | mapping['8'] = "tuv"; 24 | mapping['9'] = "wxyz"; 25 | char str[digits.size()+1]; 26 | str[digits.size()] = '\0'; 27 | vector vec; 28 | if (!digits.empty()) combineLetters(vec, mapping, digits, str, 0); 29 | return vec; 30 | } 31 | 32 | 33 | }; 34 | -------------------------------------------------------------------------------- /linked-list-cycle-ii.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | class Node { 11 | int val; 12 | Node next; 13 | Node(int v) {this.val = v; this.next = null;} 14 | } 15 | public static void main (String[] args) throws java.lang.Exception 16 | { 17 | // your code goes here 18 | } 19 | 20 | public static Node detectAndRemoveLoop(Node head) { 21 | Node slow = head, fast = head; 22 | while (fast != null && fast.next != null) { 23 | if (slow == fast) break; 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | if (slow == fast) { 28 | slow = head; 29 | while (slow != fast) { 30 | slow = slow.next; 31 | fast = fast.next; 32 | } 33 | return slow; 34 | } 35 | return null; 36 | } 37 | 38 | public ListNode detectCycle(ListNode head) { 39 | if (head == null || head.next == null) return null; 40 | ListNode slow = head, fast = head.next; 41 | while (fast != null && fast.next != null) { 42 | // System.out.println("slow: " + slow.val + ", fast= " + fast.val); 43 | if (slow == fast) { 44 | // System.out.println("break"); 45 | break; 46 | } 47 | slow = slow.next; 48 | fast = fast.next.next; 49 | } 50 | // System.out.println("outside of while"); 51 | if (slow == fast) { 52 | slow = head; fast = fast.next; 53 | // System.out.println("going for the start"); 54 | while (slow != fast) { 55 | // System.out.println("slow: " + slow.val + ", fast= " + fast.val); 56 | slow = slow.next; 57 | fast = fast.next; 58 | } 59 | return slow; 60 | } else return null; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /longest-consecutive-sequence.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestConsecutive(int[] nums) { 3 | HashMap hm = new HashMap(); 4 | int maxNum = 0; 5 | for (int val : nums) { 6 | if (!hm.containsKey(val)) { 7 | int left, right; 8 | if (hm.containsKey(val-1)) { 9 | left = hm.get(val-1); 10 | } else { 11 | left = 0; 12 | } 13 | if (hm.containsKey(val+1)) { 14 | right = hm.get(val+1); 15 | } else { 16 | right = 0; 17 | } 18 | int curMax = left + right + 1; 19 | hm.put(val, curMax); 20 | hm.put(val-left, curMax); 21 | hm.put(val+right, curMax); 22 | maxNum = Math.max(maxNum, curMax); 23 | } else { 24 | continue; 25 | } 26 | } 27 | return maxNum; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /longest-palindromic-subsequence.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestPalindromeSubseq(String s) { 3 | int len = s.size(); 4 | int dp[][] = new int[len][len]; 5 | for (int i = len-1; i >= 0; i--) { 6 | dp[i][i] = 1; 7 | for (int j = i+1; j < len; j++) { 8 | if (s.charAt(i) == s.charAt(j)) dp[i][j] = dp[i+1][j-1] + 2; 9 | else { 10 | dp[i][j] = Math.max(dp[i][j-1], dp[i+1][j]); 11 | } 12 | } 13 | } 14 | return dp[0][len-1]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /longest-substring-without-repeating-character.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | int maxLen = 0; 4 | HashSet charSet = new HashSet(); 5 | int j = 0; 6 | for (int i = 0; i < s.length(); i++) { 7 | // System.out.println("i= " + i + ", j= " + j + ", set= " + charSet.toString()); 8 | if (!charSet.add(s.charAt(i))) { 9 | while (s.charAt(j) != s.charAt(i)) charSet.remove(s.charAt(j++)); 10 | j++; 11 | } 12 | if (charSet.size() > maxLen) { 13 | maxLen = charSet.size(); 14 | } 15 | } 16 | return maxLen; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /lowest-common-ancestor-of-a-binary-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | 12 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 13 | if (root == null || root == p || root == q) return root; 14 | TreeNode left = lowestCommonAncestor(root.left, p, q), right = lowestCommonAncestor(root.right, p, q); 15 | if (left != null && right != null) return root; 16 | return left == null? right : left; 17 | } 18 | 19 | } 20 | 21 | /*** brute force way, but still pass **/ 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * public class TreeNode { 26 | * int val; 27 | * TreeNode left; 28 | * TreeNode right; 29 | * TreeNode(int x) { val = x; } 30 | * } 31 | */ 32 | class Solution { 33 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 34 | while (true) { 35 | if (checkNode(root.left, p) && checkNode(root.left, q)) { 36 | root = root.left; 37 | } else if (checkNode(root.right, p) && checkNode(root.right, q)) { 38 | root = root.right; 39 | } else { 40 | break; 41 | } 42 | } 43 | return root; 44 | } 45 | 46 | public boolean checkNode(TreeNode root, TreeNode p) { 47 | if (root == null) return false; 48 | if (root == p) return true; 49 | return checkNode(root.left, p) || checkNode(root.right, p); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /lowest-common-ancestor-of-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | if (root == null) return root; 13 | int curVal = root.val; 14 | // if ((curVal <= p.val && curVal >= q.val) || (curVal >= p.val && curVal <= q.val)) return root; 15 | if (curVal < p.val && curVal < q.val) return lowestCommonAncestor(root.right, p, q); 16 | if (curVal > p.val && curVal > q.val) return lowestCommonAncestor(root.left, p, q); 17 | return root; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lowest-common-ancestor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | if (p.val < root.val && q.val < root.val) { 13 | root = root.left; 14 | } else if (p.val > root.val && q.val > root.val) { 15 | root = root.right; 16 | } else { 17 | return root; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /matchsticks-to-square.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | int sum = 0; 13 | int[] nums = new int[] {1,1,2,2,2,2,1,1}; 14 | for (int v : nums) sum += v; 15 | if (sum % 4 != 0) { 16 | System.out.println("1. " + false); 17 | } else { 18 | // Arrays.sort(nums); 19 | // reverse(nums); 20 | int[] square = new int[4]; 21 | for (int i = 0; i < 4; i++) square[i] = 0; 22 | System.out.println(makeSquare(nums, sum / 4, square, 0)); 23 | } 24 | } 25 | 26 | public static void reverse(int[] nums) { 27 | for (int i = 0; i < nums.length / 2; i++) { 28 | int temp = nums[i]; 29 | nums[i] = nums[nums.length-i-1]; 30 | nums[nums.length-i-1] = nums[i]; 31 | } 32 | } 33 | public static boolean makeSquare(int[] nums, int part, int[] square, int index) { 34 | // System.out.println(square[0] + ", " + square[1] + ", " + square[2] + ", " + square[3]); 35 | if (index == nums.length) { 36 | System.out.println(square[0] + ", " + square[1] + ", " + square[2] + ", " + square[3]); 37 | if (square[0] == part && square[1] == part && square[2] == part) 38 | return true; 39 | return false; 40 | } 41 | for (int i = 0; i < 4; i++) { 42 | if (square[i] + nums[index] > part) continue; 43 | int j = i; 44 | while (--j >= 0) 45 | if (square[i] == square[j]) 46 | break; 47 | if (j < 0) continue; 48 | square[i] += nums[index]; 49 | if (makeSquare(nums, part, square, index+1)) { 50 | return true; 51 | } 52 | square[i] -= nums[index]; 53 | } 54 | return false; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /max-chunks-to-sort.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxChunksToSorted(int[] arr) { 3 | int n = arr.length; 4 | int[] max = new int[n], min = new int[n]; 5 | for (int i = 0; i < n; i++) { 6 | max[i] = max[i-1]; 7 | if (arr[i] > max[i-1]) max[i] = arr[i]; 8 | min[i] = min[i-1]; 9 | if (arr[i] < min[i-1]) min[i] = arr[i]; 10 | } 11 | int res = 0; 12 | for (int i = 0; i < n; i++) { 13 | if (max[i] < min[i+1]) res++; 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /max-consecutive-ones-ii.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | Ideone o = new Ideone(); 13 | int[] nums = new int[] {1,0,1,1,0}; 14 | System.out.println(o.findMaxConsecutiveOnes(nums)); 15 | } 16 | public int findMaxConsecutiveOnes(int[] nums) { 17 | int zero = 0, k = 1; // at most k zeros can be flipped 18 | int maxCon = 0; 19 | for (int l = 0, h = 0; h < nums.length; h++) { 20 | if (nums[h] == 0) zero++; 21 | if (zero > k) { 22 | if (nums[l++] == 0) zero--; 23 | } 24 | maxCon = Math.max(h - l + 1, maxCon); 25 | } 26 | return maxCon; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /max-consecutive-ones.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findMaxConsecutiveOnes(int[] nums) { 3 | int maxCon = 0, curCon = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] == 1) curCon++; 6 | else {maxCon = Math.max(curCon, maxCon); curCon = 0;} 7 | } 8 | return Math.max(maxCon, curCon); 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /max-sub-array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int dp[] = new int[nums.length]; 4 | dp[0] = nums[0]; 5 | int max = 0; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (dp[i-1] > 0) dp[i] = dp[i-1] + nums[i]; 8 | else dp[i] = nums[i]; 9 | max = Math.max(max, dp[i]); 10 | } 11 | return max; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /maximum-depth-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 | static int max = 0; 12 | public int maxDepth(TreeNode root) { 13 | if (root == null) return 0; 14 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /maximum-subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | if (nums == null || nums.length == 0) return 0; 4 | int sum = 0, maxSum = Integer.MIN_VALUE; 5 | for (int i = 0; i < nums.length; i++) { 6 | sum = sum + nums[i]; 7 | maxSum = Math.max(maxSum, sum); 8 | if (sum < 0) { 9 | sum = 0; 10 | } 11 | } 12 | // maxSum = Math.max(maxSum, sum); 13 | 14 | return maxSum; 15 | } 16 | } 17 | 18 | /** 19 | 20 | [-2,1,-3,4,-1,2,1,-5,4], 21 | 0,1, 0,4, 3,5,6, 1,5 22 | 23 | **/ 24 | -------------------------------------------------------------------------------- /maximum-vacation-days.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxVacationDays(int[][] flights, int[][] days) { 3 | int n = flights.length; 4 | int k = days[0].length; 5 | // int[][] dp = new int[n][k]; 6 | // Since the values of week i only depend on the the values of week i-1, we can compress two-dimensional dp array into one dimensional 7 | int[] dp = new int[n]; 8 | Arrays.fill(dp, Integer.MIN_VALUE); 9 | for (int week = 0; week < k; week++) { 10 | int[] temp = new int[n]; 11 | Arrays.fill(temp, Integer.MIN_VALUE); 12 | for (int des = 0; des < n; des++) { 13 | for (int src = 0; src < n; src++) { 14 | if (flight[src][des] || src == des) temp[des] = Math.max(temp[des], dp[src] + days[des][week]); 15 | } 16 | } 17 | dp = temp; 18 | } 19 | int max = 0; 20 | for (int i : dp) { 21 | max - Math.max(max, i); 22 | } 23 | return max; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /merge-intervals.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | private class IntervalComparator implements Comparator { 3 | public int compare(Interval a, Interval b) { 4 | return a.start < b.start ? -1 : a.start == b.start ? 0 : 1; 5 | } 6 | } 7 | public List merge(List intervals) { 8 | // sort the intervals 9 | Collections.sort(intervals, new IntervalComparator()); 10 | LinkedList merged = new LinkedList(); 11 | for (int i = 0; i < intervals.length; i++) { 12 | if (merged.isEmpty() || merged.getLast().end < intervals[i].start) { 13 | merged.add(intervals[i]); 14 | } else { 15 | merged.getLast().end = Math.max(merged.getLast().end, intervals[i].end); 16 | } 17 | } 18 | return merged; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /merge-k-sorted-lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | /* package whatever; // don't place package name! */ 10 | 11 | import java.util.*; 12 | import java.lang.*; 13 | import java.io.*; 14 | 15 | /* Name of the class has to be "Main" only if the class is public. */ 16 | class Ideone 17 | { 18 | 19 | // merge sort style 20 | public static void main (String[] args) throws java.lang.Exception 21 | { 22 | return mergeLists(lists, 0, lists.length-1); 23 | } 24 | 25 | public static ListNode mergeTwoLists (ListNode l1, ListNode l2) { 26 | if (l1 == null) return l2; 27 | if (l2 == null) return l1; 28 | if (l1.val > l2.val) { 29 | l2.next = mergeTwoLists(l1.next, l2); 30 | return l2; 31 | } else { 32 | l1.next = mergeTwoLists(l1, l2.next); 33 | return l1; 34 | } 35 | } 36 | 37 | public static ListNode mergeLists(ListNode[] lists, int left, int right) { 38 | if (left > right) return null; 39 | if (left == right) return lists[left]; 40 | int len = right - left + 1; 41 | return mergeTwoLists(mergeLists(lists, 0, len/2), mergeLists(lists, len/2+1, len)); 42 | } 43 | 44 | // using priority queue 45 | public ListNode mergeKLists(List lists) { 46 | PriorityQueue p = new PriorityQueue() { 47 | public int compareTo(ListNode other) { 48 | return this.val - other.val; 49 | } 50 | } 51 | ListNode head = new ListNode(0); 52 | ListNode dummy = head; 53 | for (ListNode listNode : lists) { 54 | if (listNode != null) p.add(listNode); 55 | } 56 | while (!p.isEmpty()) { 57 | dummy.next = p.poll(); 58 | dummy = dummy.next; 59 | 60 | if (dummy.next != null) 61 | p.add(dummy.next); 62 | } 63 | return head.next; 64 | } 65 | 66 | // for loop finding smallest ListNode in an array with no priority queue 67 | 68 | class Solution { 69 | public ListNode mergeKLists(ListNode[] lists) { 70 | if (lists == null || lists.length == 0) return null; 71 | ListNode dummy = new ListNode(Integer.MAX_VALUE), cur = dummy; 72 | while (cur != null) { 73 | ListNode smallest = dummy; 74 | int index = 0; 75 | for (int i = 0; i < lists.length; i++) { 76 | if (lists[i] != null && smallest.val > lists[i].val) { 77 | smallest = lists[i]; 78 | index = i; 79 | } 80 | } 81 | if (smallest != dummy) cur.next = smallest; 82 | cur = cur.next; 83 | if (lists[index] != null) lists[index] = lists[index].next; 84 | } 85 | return dummy.next; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | vector copyOfNums1(nums1); 5 | int i = 0, j = 0, index = 0; 6 | while (i < m || j < n) { 7 | if (i < m && j < n) { 8 | if (copyOfNums1[i] <= nums2[j]) { 9 | nums1[index++] = copyOfNums1[i++]; 10 | } else if (copyOfNums1[i] > nums2[j]) { 11 | nums1[index++] = nums2[j++]; 12 | } 13 | } else if (i < m) { 14 | nums1[index++] = copyOfNums1[i++]; 15 | } else if (j < n) { 16 | nums1[index++] = nums2[j++]; 17 | } 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /merge-two-sorted-lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | import java.util.*; 10 | public class Solution { 11 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 12 | ListNode res = new ListNode(0); 13 | ListNode head = res; 14 | while (l1 != null && l2 != null) { 15 | if (l1.val > l2.val) { 16 | res.next = l2; 17 | l2 = l2.next; 18 | } else { 19 | res.next = l1; 20 | l1 = l1.next; 21 | } 22 | res = res.next; 23 | } 24 | 25 | while (l1 != null) { 26 | res.next = l1; 27 | l1 = l1.next; 28 | res = res.next; 29 | } 30 | while (l2 != null) { 31 | res.next = l2; 32 | l2 = l2.next; 33 | res = res.next; 34 | } 35 | return head.next; 36 | } 37 | 38 | // Recursively 39 | public ListNode mergeTwoListsRecursively(ListNode l1, ListNode l2) { 40 | if (l1 == null) return l2; 41 | if (l2 == null) return l1; 42 | if (l1.val < l2.val) { 43 | l1.next = mergeTwoListsRecursively(l1.next, l2); 44 | return l1; 45 | } else { 46 | l2.next = mergeTwoListsRecursively(l1, l2.next); 47 | return l2; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /min-cost-climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | int n = cost.size(), total = 0; 5 | for (int i = n-3; i >= 0; i--) { 6 | cost[i] = cost[i] + min(cost[i+1], cost[i+2]); 7 | } 8 | return min(cost[0], cost[1]); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /mini-parser.java: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the interface that allows for creating nested lists. 3 | * // You should not implement it, or speculate about its implementation 4 | * public interface NestedInteger { 5 | * // Constructor initializes an empty nested list. 6 | * public NestedInteger(); 7 | * 8 | * // Constructor initializes a single integer. 9 | * public NestedInteger(int value); 10 | * 11 | * // @return true if this NestedInteger holds a single integer, rather than a nested list. 12 | * public boolean isInteger(); 13 | * 14 | * // @return the single integer that this NestedInteger holds, if it holds a single integer 15 | * // Return null if this NestedInteger holds a nested list 16 | * public Integer getInteger(); 17 | * 18 | * // Set this NestedInteger to hold a single integer. 19 | * public void setInteger(int value); 20 | * 21 | * // Set this NestedInteger to hold a nested list and adds a nested integer to it. 22 | * public void add(NestedInteger ni); 23 | * 24 | * // @return the nested list that this NestedInteger holds, if it holds a nested list 25 | * // Return null if this NestedInteger holds a single integer 26 | * public List getList(); 27 | * } 28 | */ 29 | public class Solution { 30 | // "[123,[456,[789]]]" 31 | // "[[123],[456,[789]]]" 32 | // "[[123], 321,[[456],[789], [101, 112], 131]]" 33 | public NestedInteger deserialize(String str) { 34 | if (str.isEmpty()) return null; 35 | if (str.charAt(0) == '[') return new NestedInteger(Integer.valueOf(str)); 36 | NestedInteger curInt; 37 | Stack s = new Stack(); 38 | int l = 0; // points to start of number substring 39 | int r = 0; // points to end of number substring 40 | for (int i = 0; i < s.length(); i++) { 41 | char c = s.charAt(i); 42 | if (c == '[') { 43 | if (curInt != null) s.push(curInt); 44 | curInt = new NestedInteger(); 45 | } else if (c == ']') { 46 | String num = str.substring(l, r); 47 | if (!num.isEmpty()) curInt.add(new NestedInteger(Integer.valueOf(num))); 48 | if (!s.isEmpty()) { 49 | NestedInteger prevInt = s.pop(); 50 | prevInt.add(curInt); 51 | curInt = prevInt; 52 | } 53 | } else if (c == ',') { 54 | if (s.charAt(i-1) != ']') { 55 | String num = str.substring(l, r); 56 | curInt.add(new NestedInteger(Integer.valueOf(num))); 57 | } 58 | } 59 | l = r + 1; 60 | } 61 | } 62 | return curInt; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /most-common-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String mostCommonWord(String paragraph, String[] banned) { 3 | HashSet set = new HashSet(); 4 | for (int i = 0; i < banned.length; i++) set.add(banned[i]); 5 | HashMap map = new HashMap<>(); 6 | paragraph = paragraph.replaceAll("[!?',;.]", ""); 7 | paragraph = paragraph.toLowerCase(); 8 | String[] words = paragraph.split(" "); 9 | for (int i = 0; i < words.length; i++) { 10 | if (!set.contains(words[i])) { 11 | if (!map.containsKey(words[i])) map.put(words[i], 0); 12 | map.put(words[i], map.get(words[i])+1); 13 | } 14 | 15 | } 16 | int max = Integer.MIN_VALUE; 17 | String lfw = ""; 18 | for (String word : map.keySet()) { 19 | if (map.get(word) > max) { 20 | max = map.get(word); 21 | lfw = word; 22 | } 23 | } 24 | return lfw; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /move-zeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void moveZeroes(int[] nums) { 3 | int zeros = 0, counter = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] != 0) { 6 | nums[counter++] = nums[i]; 7 | } else { 8 | zeros++; 9 | } 10 | } 11 | for (; counter < nums.length; counter++) { 12 | nums[counter] = 0; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /multiply-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String multiply(String num1, String num2) { 3 | int n1 = num1.length(), n2 = num2.length(); 4 | int[] pos = new int[n1+n2+1]; 5 | for (int i = n1-1; i >= 0; i--) { 6 | for (int j = n2-1; j >= 0; j--) { 7 | pos[i+j+1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 8 | } 9 | } 10 | int co = 0, n = 0; 11 | for (int p = n1+n2-1; p >= 0; p--) { 12 | n = pos[p] + co; 13 | pos[p] = n % 10; 14 | co = n / 10; 15 | } 16 | StringBuilder sb = new StringBuilder(); 17 | for (int p = 0; p < n1+n2; p++) { 18 | sb.append(pos[p]); 19 | } 20 | while (sb.length() != 0 && sb.charAt(0) == '0') sb.deleteCharAt(0); 21 | return sb.length() == 0 ? "0" : sb.toString(); 22 | } 23 | } 24 | 25 | /*** 26 | 27 | 28 | 1 2 3 29 | 4 5 6 30 | 7 3 8 31 | 6 1 5 32 | 4 9 2 33 | 5 6 0 8 8 34 | 35 | 3*6 = 18 36 | 2*6 = 12 + 1 = 13 37 | 1*6 = 6 + 1 = 7 38 | --> 738 39 | 40 | 3*5 = 15 41 | 2*5 = 10 + 1 = 11 42 | 1*5 = 5 + 1 = 6 43 | --> 615 44 | ----> 615 + 73 = "688" + "8" = 6888 45 | 46 | 3*4 = 12 47 | 2*4 = 8 + 1 = 9 48 | 1*4 = 4 49 | --> 492 50 | ----> 492 + 68 = "560" + "88" = 56088 51 | 52 | **/ 53 | -------------------------------------------------------------------------------- /next-closest-time.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String nextClosestTime(String timeStr) { 3 | HashSet digits = new HashSet<>(); 4 | String[] hrMin = timeStr.split(":"); 5 | int hr = Integer.valueOf(hrMin[0]), min = Integer.valueOf(hrMin[1]); 6 | for (char d : hrMin[0].toCharArray()) digits.add(d - '0'); 7 | for (char d : hrMin[1].toCharArray()) digits.add(d - '0'); 8 | 9 | int time = hr*60 + min, minDif = Integer.MAX_VALUE, closest = time; 10 | for (int t = time+1; t <= 24*60 + time-1; t++) { 11 | if (checkValidTime(digits, t)) { 12 | // System.out.println("time= " + t + ", hr= " + (t/60)%24 + ", min= " + t%60); 13 | if (minDif > t - time) { 14 | minDif = t - time; 15 | closest = t; 16 | } 17 | } 18 | } 19 | String hrStr = String.valueOf((closest/60) % 24); if (hrStr.length() < 2) hrStr = "0" + hrStr; 20 | String minStr = String.valueOf(closest%60); if (minStr.length() < 2) minStr = "0" + minStr; 21 | return hrStr + ":" + minStr; 22 | } 23 | 24 | public boolean checkValidTime(HashSet set, int t) { 25 | int hr = (t/60)%24, min = t%60; 26 | if (!set.contains(hr/10) || !set.contains(hr%10)) return false; 27 | if (!set.contains(min/10) || !set.contains(min%10)) return false; 28 | return true; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /next-greater-element-i.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] nextGreaterElement(int[] nums1, int[] nums2) { 3 | HashMap indexMap = new HashMap(); 4 | int[] res = new int[nums1.length]; 5 | for (int i = 0; i < nums2.length; i++) { 6 | indexMap.put(nums2[i], i); 7 | } 8 | 9 | for (int i = 0; i < nums1.length; i++) { 10 | res[i] = -1; 11 | if (indexMap.containsKey(nums1[i])) { 12 | for (int j = indexMap.get(nums1[i]); j < nums2.length; j++) { 13 | if (nums2[j] > nums1[i]) { 14 | res[i] = nums2[j]; 15 | break; 16 | } 17 | } 18 | } 19 | } 20 | return res; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /number-complement.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | int num = 12; 13 | System.out.println(findComplement(num)); 14 | } 15 | 16 | public static int findComplement(int num) { 17 | // System.out.println(Integer.toBinaryString(num)); 18 | char[] bits = Integer.toBinaryString(num).toCharArray(); 19 | int m = 1, retVal = 0; 20 | for (int i = bits.length-1; i >= 0; i--) { 21 | if (bits[i] == '0') { 22 | retVal += m; 23 | } 24 | m *= 2; 25 | } 26 | return retVal; 27 | } 28 | 29 | public static int findComplement(int num) { 30 | int m = (Integer.highestOneBit(num) << 1) - 1; 31 | return num ^ m; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /number-of-segments-in-a-string.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | System.out.println(countSegments("Hello, my name is John")); 13 | } 14 | static int countSegments(String s) { 15 | int res = 0; 16 | boolean newWord = true; 17 | for (char c : s.toCharArray()) { 18 | if (Character.isLetterOrDigit(c)) { 19 | if (newWord) {res++; newWord = false;} 20 | } else { 21 | newWord = true; 22 | } 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /number-of-segments.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Solution { 5 | static int countSegments(String s) { 6 | int cnt = 0; 7 | s = " " + s + " "; 8 | for (int i = 1; i < s.length(); i++) { 9 | if (Character.isSpace(s.charAt(i)) && !Character.isSpace(s.charAt(i-1))) { 10 | cnt++; 11 | } 12 | } 13 | return cnt; 14 | } 15 | 16 | public static void main(String[] args) { 17 | String s = "Hello, my name is John a;jg dlsjgl dshgl "; 18 | System.out.println(countSegments(s)); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /odd-even-linkedlist.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode oddEvenList(ListNode head) { 11 | ListNode even = head, odd = head, ptr = head; 12 | while (ptr != null && ptr.next != null) { 13 | odd = ptr.next; 14 | ptr = ptr.next.next; 15 | even.next = ptr; 16 | } 17 | even.next = odd; 18 | return head; 19 | } 20 | } 21 | 22 | /** Another way **/ 23 | 24 | class Solution { 25 | public ListNode oddEvenList(ListNode head) { 26 | if (head == null || head.next == null) return head; 27 | ListNode dummy = new ListNode(-1), tummy = new ListNode(-1); 28 | dummy.next = head; tummy.next = head.next; 29 | ListNode odd = dummy, even = tummy, cur = head; 30 | while (cur != null) { 31 | 32 | odd.next = cur; 33 | odd = odd.next; 34 | cur = cur.next; 35 | even.next = cur; 36 | if (cur == null) break; 37 | even = even.next; 38 | cur = cur.next; 39 | } 40 | odd.next = tummy.next; 41 | return dummy.next; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ones-and-zeroes.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public int findMaxForm(String[] strs, int m, int n) { 4 | // final String replace = (m > n) ? "0" : "1"; 5 | final String replace = "0"; 6 | Arrays.sort(strs, new Comparator() { 7 | public int compare(String s1, String s2) { 8 | // String replace = "0"; 9 | // if (m > n) replace = "1"; 10 | int count1 = s1.length() - s1.replace(replace, "").length(); 11 | // if (count1 == 0) count1 = Math.max(s1.length(), s2.length()); 12 | int count2 = s2.length() - s2.replace(replace, "").length(); 13 | // if (count2 == 0) count2 = Math.max(s1.length(), s2.length()); 14 | // if (s1.length() == s2.length()) 15 | // return count2 - count1; 16 | if (count1 == count2) 17 | return Integer.compare(s1.length(), s2.length()); 18 | else 19 | return Integer.compare(count1, count2); 20 | // else 21 | // return Integer.compare(count2, count1); 22 | // return Integer.compare(s1.length(), s2.length()); 23 | } 24 | }); 25 | // final String replace1 = (m > n) ? "1" : "0"; 26 | final String replace1 = "1"; 27 | Arrays.sort(strs, new Comparator() { 28 | public int compare(String s1, String s2) { 29 | int count1 = s1.length() - s1.replace(replace1, "").length(); 30 | int count2 = s2.length() - s2.replace(replace1, "").length(); 31 | if (count1 == count2) 32 | return Integer.compare(s1.length(), s2.length()); 33 | else 34 | return Integer.compare(count1, count2); 35 | } 36 | }); 37 | int total = 0; 38 | // if (m > n) { 39 | // List strL = Arrays.asList(strs); 40 | // Collections.reverse(strL); 41 | // strs = strL.toArray(strs); 42 | // } 43 | // for (int i = 0; i < strs.length; i++) System.out.print(strs[i] + " "); 44 | // System.out.println(); 45 | for (int i = 0; i < strs.length; i++) { 46 | String cur = strs[i]; 47 | int count0 = cur.length() - cur.replace("0", "").length(); 48 | int count1 = strs[i].length() - count0; 49 | if (count0 <= m && count1 <= n) { 50 | // System.out.println("s= " + strs[i] + ", count0= " + count0 + ", count1= " + count1); 51 | m -= count0; 52 | n -= count1; 53 | total++; 54 | // System.out.println("s= " + strs[i] + ", m= " + m + ", n= " + n); 55 | } 56 | } 57 | return total; 58 | } 59 | } 60 | 61 | // More intelligent solution 62 | public class Solution { 63 | public int findMaxForm(String[] strs, int m, int n) { 64 | int[][] dp = new int[m+1][n+1]; 65 | for (String s: strs) { 66 | int count0 = s.length() - s.replace("0", "").length(); 67 | int count1 = s.length() - count0; 68 | 69 | for (int i = m; i >= count0; i--) { 70 | for (int j = n; j >= count1; j--) { 71 | dp[i][j] = Math.max(dp[i][j], 1 + dp[i-count0][j-count1]); 72 | } 73 | } 74 | } 75 | return dp[m][n]; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /out_of_boundary_paths.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findPaths(int m, int n, int N, int i, int j) { 3 | int dp[][][] = new int[51][50][50]; 4 | for (int ni = 0; ni <= N; i++) 5 | for (int ii = 0; ii < m; ni++) 6 | for (int ji = 0; ji < n; ji++) { 7 | dp[ni][ii][ji] = ((ii == 0 ? 1 : dp[ni-1][ii-1][ji]) + (ii == m ? 1 : dp[ni-1][ii+1][ji]) + 8 | (ji == 0 ? 1 : dp[ni-1][ii][ji-1] + (ji == n ? 1 : dp[ni-1][ii][ji+1])); 9 | } 10 | return dp[N][i][j]; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /output-contest-matches.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static String outputContestMatches(int n) { 3 | StringBuilder s = new StringBuilder(); 4 | ArrayList q = new ArrayList(); 5 | int num = n; 6 | for (int i = 0; i < n; i++) q.add(String.valueOf(i)); 7 | while (q.size() > 1) { 8 | ArrayList cur = new ArrayList(); 9 | for (int i = 0; i < q.size()/2; i++) 10 | cur.add("(" + q.get(i) + "," + q.get(q.size()-i-1) + ")"); 11 | q = cur; 12 | } 13 | } 14 | public static void main (String args[]) { 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /pacific-atlantic-water-flow.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List pacificAtlantic(int[][] matrix) { 3 | List lists = new LinkedList(); 4 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return lists; 5 | int n = matrix.length; int m = matrix[0].length; 6 | boolean[][] pacific = new boolean[n][m]; 7 | boolean[][] atlantic = new boolean[n][m]; 8 | for (int i = 0; i < n; i++) { 9 | dfs(matrix, pacific, Integer.MIN_VALUE, i, 0); 10 | dfs(matrix, atlantic, Integer.MIN_VALUE, i, m-1); 11 | } 12 | for (int i = 0; i < m; i++) { 13 | dfs(matrix, pacific, Integer.MIN_VALUE, 0, i); 14 | dfs(matrix, atlantic, Integer.MIN_VALUE, n-1, i); 15 | } 16 | for (int i = 0; i < matrix.length; i++) 17 | for (int j = 0; j < matrix[0].length; j++) { 18 | if (pacific[i][j] && atlantic[i][j]) lists.add(new int[]{i,j}); 19 | } 20 | return lists; 21 | } 22 | /** 23 | * i-1,j 24 | * i,j-1 i,j i,j+1 25 | * i+1,j 26 | **/ 27 | public void dfs(int[][] matrix, boolean[][] visited, int height, int x, int y) { 28 | int n = matrix.length; int m = matrix[0].length; 29 | if (x<0 || x>=n || y<0 || y >= m || visited[x][y] || height > matrix[x][y]) return; 30 | visited[x][y] = true; 31 | dfs(matrix, visited, matrix[x][y], x-1, y); 32 | dfs(matrix, visited, matrix[x][y], x+1, y); 33 | dfs(matrix, visited, matrix[x][y], x, y-1); 34 | dfs(matrix, visited, matrix[x][y], x, y+1); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /palindrome-number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(int x) { 3 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 4 | int n = x, len = 1, p = 1; 5 | 6 | while (n > 9) { 7 | p *= 10; len++; n /= 10; 8 | } 9 | // p = p / 10; 10 | for (int i = 0; i < len / 2; i++) { 11 | long last = x % 10; 12 | long first = x / p; 13 | if (last != first) { 14 | return false; 15 | } 16 | x = x % p; 17 | x = x / 10; 18 | p /= 100; 19 | } 20 | return true; 21 | } 22 | } 23 | 24 | /** 25 | Best solution 26 | public class Solution { 27 | public boolean isPalindrome(int x) { 28 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 29 | int rev = 0; 30 | while (x > rev) { 31 | rev = rev * 10 + x % 10; 32 | x = x / 10; 33 | } 34 | return ((x == rev) || (x == rev / 10)); 35 | } 36 | } 37 | **/ 38 | -------------------------------------------------------------------------------- /palindrome-pairs.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> palindromePairs(String[] words) { 3 | List> res = new ArrayList>(); 4 | if (words == null || words.length == 0) return res; 5 | HashMap map = new HashMap(); 6 | for (int i = 0; i < words.length; i++) { 7 | map.put(words[i], i); 8 | } 9 | for (int i = 0; i < words.length; i++) { 10 | String cur = words[i]; 11 | for (int j = 0; j <= cut.size(); j++) { 12 | String s1 = cur.substring(0, j)); 13 | String s2 = cur.substring(j); 14 | if (isPalindrome(s1)) { 15 | String revs2 = new StringBuilder(s2).reverse().toString(); 16 | if (map.containsKey(revs2) { 17 | List list = new ArrayList(); 18 | list.add(map.get(revs2), i); 19 | res.add(list); 20 | } 21 | } 22 | } 23 | if (isPalindrome(s2)) { 24 | String revs1 = new StringBuilder(s1).reverse().toString(); 25 | if (map.containsKey(revs1) { 26 | List list = new ArrayList(); 27 | list.add(map.get(revs1), i); 28 | res.add(list); 29 | } 30 | } 31 | } 32 | return true; 33 | } 34 | puclic boolean checkPalindrome(String s) { 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /palindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static boolean checkPalindrome(ListNode head) { 4 | 5 | } 6 | public static void main(String args[]) [ 7 | 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /partition-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode partition(ListNode head, int x) { 11 | ListNode lessHead = new ListNode(-1), moreHead = new ListNode(-1), less = lessHead, more = moreHead; 12 | ListNode cur = head; 13 | while (cur != null) { 14 | if (cur.val < x) { 15 | less.next = cur; 16 | less = less.next; 17 | } else { 18 | more.next = cur; 19 | more = more.next; 20 | } 21 | cur = cur.next; 22 | } 23 | more.next = null; 24 | less.next = moreHead.next; 25 | return lessHead.next; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /pascals-triangle-ii.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List getRow(int rowIndex) { 3 | /** 4 | * [1] 5 | * [1,1] 6 | * [1,2,1] 7 | * [1,3,3,1] 8 | **/ 9 | List res = new ArrayList(); 10 | List helper = new ArrayList(); 11 | helper.add(1); 12 | for (int i = 1; i <= rowIndex; i++) { 13 | res.add(1); 14 | for (int j = 1; j < helper.size(); j++) { 15 | res.add(helper.get(j) + helper.get(j-1)); 16 | } 17 | res.add(1); 18 | helper = res; 19 | res = new ArrayList(); 20 | } 21 | return helper; 22 | } 23 | 24 | // Best solution 25 | 26 | public List getRow(int rowIndex) { 27 | /** 28 | * [1] 29 | * [1,1] 30 | * [1,2,1] 31 | * [1,3,3,1] 32 | **/ 33 | List res = new ArrayList(Collections.nCopies(rowIndex+1, 0)); 34 | res.set(0,1); 35 | for (int i = 1; i <= rowIndex; i++) { 36 | for (int j = i; j > 0; j--) { 37 | res.set(j, res.get(j) + res.get(j-1)); 38 | } 39 | } 40 | return res; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /pascals-triangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> generate(int numRows) { 3 | // [1] 4 | // [1,1] 5 | // [1,2,1] 6 | // [1,3,3,1] 7 | // [1,4,6,4,1] 8 | List> list = new ArrayList>(); 9 | if (numRows > 0) { 10 | List temp = new ArrayList(); 11 | temp.add(1); 12 | list.add(temp); 13 | for (int i = 1; i < numRows; i++) { 14 | temp = new ArrayList(); 15 | temp.add(1); 16 | List temp2 = list.get(i-1); 17 | for (int j = 1; j < temp2.size(); j++) { 18 | temp.add(temp2.get(j) + temp2.get(j-1)); 19 | } 20 | temp.add(1); 21 | list.add(temp); 22 | } 23 | } 24 | return list; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /path-sum-ii.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 List> pathSum(TreeNode root, int sum) { 12 | List> lists = new LinkedList>(); 13 | pathSum(root, sum, new LinkedList(), lists); 14 | return lists; 15 | } 16 | 17 | public void pathSum(TreeNode root, int sum, LinkedList l, List> lists) { 18 | if (root == null) return; 19 | l.add(root.val); 20 | if (root.left == null && root.right == null && root.val == sum) { 21 | lists.add(new LinkedList(l)); 22 | l.remove(l.size()-1); 23 | return; 24 | } else { 25 | pathSum(root.left, sum - root.val, l, lists); 26 | pathSum(root.right, sum - root.val, l, lists); 27 | } 28 | l.remove(l.size()-1); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /path-sum-iii.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 | List> lists = new ArrayList>(); 12 | public int pathSum(TreeNode root, int sum) { 13 | 14 | } 15 | 16 | public void countPaths(TreeNode root, List curList, int runningSum, int sum) { 17 | 18 | if (root == null) return; 19 | 20 | if (runningSum == sum) { 21 | lists.add(curList); 22 | curList = new ArrayList(); 23 | } else if (runningSum + root.val > sum) { 24 | runningSum = root.val; 25 | curList = new ArrayList(); 26 | curList.add(runningSum) 27 | } 28 | 29 | countPaths(root.left, curList, 0, sum); 30 | curList = new ArrayList(); 31 | countPaths(root.right, curList, 0, sum); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /path-sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 hasPathSum(TreeNode root, int sum) { 12 | if (root == null) return false; 13 | if (root.left == null && root.right == null) { 14 | if (root.val == sum) return true; 15 | else return false; 16 | } 17 | return hasPathSum(root.right, sum - root.val) || hasPathSum(root.left, sum - root.val); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /perfect-numbers.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean checkPerfectNumber(int num) { 3 | if (num == 1) return false; 4 | int temp = num; // - 1; 5 | for (int i = 2; i < Math.sqrt(num); i++) { 6 | if (num % i == 0) temp -= i + num/i; 7 | } 8 | return temp - 1 == 0; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /perfect-rectangle.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public boolean isRectangleCover(int[][] rectangles) { 4 | int x1 = Integer.MAX_VALUE; 5 | int x2 = Integer.MIN_VALUE; 6 | int y1 = Integer.MAX_VALUE; 7 | int y2 = Integer.MIN_VALUE; 8 | Set hs = new HashSet(); 9 | int area = 0; 10 | for (int[] rec: rectangles) { 11 | x1 = Math.min(x1, rec[0]); 12 | x2 = Math.max(x2, rec[2]); 13 | y1 = Math.min(y1, rec[1]); 14 | y2 = Math.max(y2, rec[3]); 15 | 16 | area += (rec[2] - rec[0]) * (rec[3] - rec[1]); 17 | 18 | String s1 = rec[0] + "," + rec[1]; 19 | String s2 = rec[0] + "," + rec[3]; 20 | String s3 = rec[2] + "," + rec[1]; 21 | String s4 = rec[2] + "," + rec[3]; 22 | 23 | if (!hs.add(s1)) hs.remove(s1); // those appear twice will be removed, those appear once will stay 24 | if (!hs.add(s2)) hs.remove(s2); 25 | if (!hs.add(s3)) hs.remove(s3); 26 | if (!hs.add(s4)) hs.remove(s4); 27 | 28 | } 29 | System.out.println("x1= " + x1 + ", y1= " + y1 + ", x2= " + x2 + ", y2= " + y2); 30 | if (!hs.contains(x1 + "," + y1) || !hs.contains(x1 + "," + y2) || !hs.contains(x2 + "," + y1) || !hs.contains(x2 + "," + y2) || hs.size() != 4) return false; 31 | return area == (y2 - y1) * (x2 - x1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /predict-the-winner.java: -------------------------------------------------------------------------------- 1 | // 1, 5, 233, 7, 2, 67 2 | 3 | public class Solution { 4 | public boolean PredictTheWinner(int[] nums) { 5 | int n = nums.length; 6 | return predict(nums, 0, n-1) >= 0; 7 | } 8 | 9 | public int predict(int[] nums, int left, int right) { 10 | if (left == right) 11 | return nums[left]; 12 | else { 13 | return Math.max(nums[left] - predict(nums, left+1, right), nums[right] - predict(nums, left, right-1)); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /prefix-and-suffix-search.java: -------------------------------------------------------------------------------- 1 | class WordFilter { 2 | HashMap map = new HashMap(); 3 | public WordFilter(String[] words) { 4 | for (int i = 0; i < words.length; i++) { 5 | for (int j = 0; j <= 10 && j <= words[i].length(); j++) { 6 | for (int k = 0; k <= 10 && k <= words[i].length(); k++) { 7 | map.put(words[i].substring(0, j) + "." + words[i].substring(words[i].length()-k), i); 8 | } 9 | } 10 | } 11 | } 12 | 13 | public int f(String prefix, String suffix) { 14 | if (map.containsKey(prefix + "." + suffix)) return map.get(prefix + "." + suffix); 15 | else return -1; 16 | } 17 | } 18 | 19 | /** 20 | * Your WordFilter object will be instantiated and called as such: 21 | * WordFilter obj = new WordFilter(words); 22 | * int param_1 = obj.f(prefix,suffix); 23 | */ 24 | -------------------------------------------------------------------------------- /product-of-array-except-self.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int[] output = new int[nums.length]; 4 | int n = nums.length; 5 | output[0] = 1; output[1] = nums[0]; 6 | for (int i = 2; i < n; i++) { 7 | output[i] = output[i-1] * nums[i-1]; 8 | } 9 | // for (int i = 0; i < n; i++) System.out.print(output[i] + " "); 10 | int temp = 1; 11 | for (int i = n-2; i >= 0; i--) { 12 | temp *= nums[i+1]; 13 | output[i] = output[i]*temp; 14 | } 15 | return output; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /range-minimum-query-mutable.java: -------------------------------------------------------------------------------- 1 | public class NumArray { 2 | int[] nums; 3 | int[] tree; 4 | int n, t; 5 | public NumArray(int[] num) { 6 | this.nums = num; 7 | this.tree = new int[nums.length*2]; 8 | n = nums.length; 9 | t = tree.length; 10 | build(); 11 | } 12 | 13 | public void build() { 14 | for (int i = n; i < 2*n; i++) tree[i] = nums[i-n]; 15 | for (int i = n-1; i > 0; i--) tree[i] = tree[i<<1] + tree[i<<1|1]; 16 | } 17 | public void update(int i, int val) { 18 | for (tree[i += n] = val; i > 1; i >>= 1) tree[i>>1] = tree[i] + tree[i^1]; 19 | } 20 | 21 | public int sumRange(int i, int j) { 22 | return sumRange(i, j, 0, 0, t-1); 23 | } 24 | 25 | public int sumRange(int i, int j) { 26 | int res = 0; 27 | for (i += n, j += n; i <= j; i >>= 1, j >>= 1) { 28 | if (i % 2 == 1) res += tree[i++]; 29 | if (j % 2 == 0) res += tree[j--]; 30 | } 31 | return res; 32 | } 33 | } 34 | 35 | /** 36 | * Your NumArray object will be instantiated and called as such: 37 | * NumArray obj = new NumArray(nums); 38 | * obj.update(i,val); 39 | * int param_2 = obj.sumRange(i,j); 40 | */ 41 | -------------------------------------------------------------------------------- /range-sum-query-immutable.java: -------------------------------------------------------------------------------- 1 | // Top solution using partial sums 2 | public class NumArray { 3 | int[] nums; 4 | public NumArray(int[] nums) { 5 | for (int i = 1; i < nums.length; i++) { 6 | nums[i] = nums[i-1] + nums[i]; 7 | } 8 | this.nums = nums; 9 | } 10 | 11 | public int sumRange(int i, int j) { 12 | if (i == 0) return nums[j]; 13 | return nums[j] - nums[i-1]; 14 | } 15 | } 16 | 17 | // Tried implementing Segmented Tree but failed horribly 18 | public class NumArray { 19 | 20 | int[] tree; 21 | int[] nums; 22 | public NumArray(int[] nums) { 23 | tree = new int[nums.length * 2]; 24 | this.nums = nums; 25 | } 26 | public int sumRange(int left, int right) { 27 | return query(left, right, 0, 0, nums.length-1); 28 | } 29 | // start and end is range represented by the node at index node 30 | public int query(int l, int r, int node, int start, int end) { 31 | if (l > end || r < start) { 32 | // range represented by a node is completely outside the given range 33 | return 0; 34 | } else if (l <= start && r >= end) { 35 | // range represented by a node is completely inside the given range 36 | return tree[node]; 37 | } else { 38 | // range represented by a node is partially inside and partially outside the given range 39 | int mid = (start + end) / 2; 40 | int p1 = sumRange(l, r, 2*node, start, mid); 41 | int p2 = sumRange(l, r, 2*node+1, mid+1, end); 42 | return p1+p2; 43 | } 44 | } 45 | 46 | public void build(int start, int end, int node) { 47 | if (start == end) { 48 | tree[node] = nums[start]; 49 | } else { 50 | int mid = (start + end) / 2; 51 | build(start, mid, 2*node); 52 | build(mid+1, end, 2*node+1); 53 | tree[node] = tree[2*node] + tree[2*node+1]; 54 | } 55 | } 56 | } 57 | 58 | /** 59 | * Your NumArray object will be instantiated and called as such: 60 | * NumArray obj = new NumArray(nums); 61 | * int param_1 = obj.sumRange(i,j); 62 | */ 63 | -------------------------------------------------------------------------------- /reconstruct-itinerary.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List findItinerary(String[][] tickets) { 3 | HashMap> flights = new HashMap>(); 4 | for (int i = 0; i < tickets.length; i++) { 5 | if (!flights.containsKey(tickets[i][0])) { 6 | flights.put(tickets[i][0], new PriorityQueue()); 7 | } 8 | flights.get(tickets[i][0]).add(tickets[i][1]); 9 | } 10 | ArrayList flightOrder = new ArrayList(); 11 | System.out.println(); 12 | dfs("JFK", flightOrder, flights, tickets.length+1); 13 | flightOrder.add(0,"JFK"); 14 | return flightOrder; 15 | } 16 | public void dfs(String flight, ArrayList flightOrder, HashMap> flights, int len) { 17 | if (flightOrder.size() == len) return; 18 | if (!flights.containsKey(flight) || flights.isEmpty()) return; 19 | PriorityQueue connecting = flights.get(flight); 20 | System.out.println(Arrays.toString(connecting.toArray())); 21 | while (!connecting.isEmpty()) { 22 | String nextFlight = connecting.poll(); 23 | dfs(nextFlight, flightOrder, flights, len); 24 | flightOrder.add(0, nextFlight); 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /regular-expression-matching.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isMatch(String s, String p) { 3 | if (s == null || p == null) return false; 4 | boolean dp[][] = new boolean[s.size()+1][p.size()+1]; 5 | for (int i = 0; i < s.size(); i++) 6 | for (int j = 0; j < p.size(); j++) { 7 | if (p.charAt(j) == s.charAt(i)) dp[i+1][j+1] = dp[i][j]; 8 | if (p.charAt(i) == '.') dp[i+1][j+1] = dp[i][j]; // '.' can replace any character 9 | if (p.charAt(i) == '*') { 10 | if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) == '.') dp[i+1][j+1] = dp[i+1][j-1]; 11 | else { 12 | dp[i+1][j+1] = dp[i+1][j-1] || dp[i][j+1] || dp[i+1][j]; 13 | } 14 | } 15 | } 16 | return dp[s.size()][p.size()]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /remove-boxes.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeBoxes(int[] boxes) { 3 | int n = boxes.length; 4 | int[][][] dp = new int[n+1][n+1][n+1]; 5 | int ans = dfs(boxes, dp, 0, n-1, 0); 6 | } 7 | public int dfs(int[] boxes, int[][][] dp, int l, int r, int k) { 8 | if (l > r) return 0; 9 | if (dp[l][r][k] != 0) return dp[l][r][k]; 10 | while (r > 1 && boxes[r] == boxes[r-1]) {r--; k++;} 11 | dp[l][r][k] = dfs(boxes, dp, l, r-1, 0) + (k+1)*(k+1); 12 | for (int i = l; i < r; i++) 13 | if (boxes[i] == boxes[r]) 14 | dp[l][r][k] = Math.max(dp[l][r][k], dfs(boxes, dp, l, i, k+1) + dfs(i+1, r, 0)); 15 | return dp[l][r][k]; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-II.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | /* Name of the class has to be "Main" only if the class is public. */ 6 | class Ideone 7 | { 8 | public static void main (String[] args) throws java.lang.Exception 9 | { 10 | Ideone m = new Ideone(); 11 | int[] nums = new int[]{1,1,1,1,1}; 12 | System.out.println(m.removeDuplicates(nums)); 13 | for (int i = 0; i < nums.length; i++) 14 | System.out.print(nums[i] + " " ); 15 | } 16 | 17 | public int removeDuplicates(int[] nums) { 18 | if (nums.length < 3) return nums.length; 19 | int i1 = 0, i2 = 1, cur = 2; 20 | while(cur < nums.length) { 21 | if (nums[i1] == nums[i2]) { 22 | while (cur < nums.length && nums[cur] == nums[i2]) cur++; 23 | System.out.println("cur= " + cur); 24 | if (cur < nums.length) {nums[i2+1] = nums[cur++]; i1++;i2++;} 25 | } else { 26 | nums[++i2] = nums[cur++]; 27 | i1++; 28 | } 29 | } 30 | return i2+1; 31 | } 32 | } 33 | 34 | /** More intelligent solution 35 | public class Solution { 36 | public int removeDuplicates(int[] nums) { 37 | int i = 0; 38 | for (int j = 0; j < nums.length; j++) { 39 | if (i < 2 || nums[j] > nums[i-2]) { 40 | nums[i++] = nums[j]; 41 | } 42 | } 43 | return i; 44 | } 45 | } 46 | **/ 47 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums.length == 0) return 0; 4 | int count = 1, curVal = nums[0], curPos = 1; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] != curVal) { 7 | nums[curPos] = nums[i]; 8 | curPos++; 9 | curVal = nums[i]; 10 | } 11 | } 12 | return curPos; 13 | } 14 | } 15 | 16 | /** 17 | Better solution 18 | public class Solution { 19 | public int removeDuplicates(int[] nums) { 20 | if (nums.length < 2) return nums.length; 21 | int curPos = 1; 22 | for (int i = 1; i < nums.length; i++) { 23 | if (nums[i] != nums[i-1]) { 24 | nums[curPos++] = nums[i]; 25 | } 26 | } 27 | return curPos; 28 | } 29 | } 30 | **/ 31 | -------------------------------------------------------------------------------- /remove-k-digits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String removeKdigits(String num, int k) { 3 | int digits = num.length() - k; 4 | int[] s = new int[digits]; 5 | int top = 0; 6 | for (int i = 0; i < num.length(); i++) 7 | int cur = Character.getNumericValue(num.charAt(i)); 8 | while (top > 0 && s[top-1] > c && k > 0) { 9 | top--; 10 | k--; 11 | } 12 | s[top++] = cur; 13 | } 14 | i = 0; 15 | while (i < digits && s[i] == '0') i++; 16 | return i == digits ? "0" : new String(s, i, digits - i); 17 | "143", k = 3 -> "0" 18 | "1432", k = 3 -> "1" 19 | "14323", k = 3 -> "12" 20 | "143236", k = 3 -> "123" 21 | "1432365", k = 3 -> "1235" 22 | "14323659", k = 3 -> "12359" 23 | "14323659" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /reorder-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public void reorderList(ListNode head) { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /repeated-substring-pattern.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean repeatedSubstringPattern(String str) { 3 | for (int i = 0; i < str.length()/2; i++) { 4 | String sub = str.substring(0,i+1); 5 | if (str.length() % sub.length() == 0) { 6 | int m = str.length() / sub.length(); 7 | StringBuilder sb = new StringBuilder(); 8 | for (int t = 0; t < m; t++) { 9 | sb.append(sub); 10 | } 11 | if (str.equals(sb.toString())) return true; 12 | } 13 | } 14 | return false; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /reverse-integer.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int reverse(int x) { 3 | if (x == 0) return x; 4 | int sign = 1; 5 | if (x < 0) {sign = -1; x *= -1;} 6 | String s = new StringBuilder(String.valueOf(x)).reverse().toString(); 7 | String max = String.valueOf(Integer.MAX_VALUE); 8 | System.out.println(s); 9 | if (s.length() < max.length() || s.compareTo(max) <= 0) 10 | return sign * (Integer.valueOf(s)); 11 | else return 0; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /reverse-pairs.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int reversePairs(int[] nums) { 3 | int dp[] = new int[nums.length]; 4 | 5 | } 6 | } 7 | 8 | /* 9 | 2, 1, 4, 3, 20, 31, 27, 23, 13, 12, 15, 4, 5, 6, 7, 11 10 | 1 0 0 0 5 8 7 5 3 2 4 0 0 0 0 0 11 | 0 1 0 0 0 0 0 0 2 2 1 7 7 6 5 2 12 | */ 13 | -------------------------------------------------------------------------------- /reverse-words-in-a-string.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseWords(String s) { 3 | StringBuilder sb = new StringBuilder(s); 4 | if (s.trim().length() <= 0) return ""; 5 | s = sb.reverse().toString(); 6 | String[] strs = s.split(" +"); 7 | // System.out.println(Arrays.toString(strs)); 8 | StringBuilder sb1 = new StringBuilder(""); 9 | for (String str : strs) { 10 | System.out.println("1" + str); 11 | StringBuilder temp = new StringBuilder(str); 12 | sb1.append(temp.reverse() + " "); 13 | } 14 | return sb1.toString().trim(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /rotate-image.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n = matrix.length; 4 | for (int i = 0; i < n; i++) 5 | for (int j = 0; j < n-i-1; j++) { 6 | int temp = matrix[n-j-1][n-i-1]; 7 | matrix[n-j-1][n-i-1] = matrix[i][j]; 8 | matrix[i][j] = temp; 9 | } 10 | for (int i = 0; i < n; i++) System.out.println(Arrays.toString(matrix[i])); 11 | for (int i = 0; i < n/2; i++) 12 | for (int j = 0; j < n; j++) { 13 | int temp = matrix[n-i-1][j]; 14 | matrix[n-i-1][j] = matrix[i][j]; 15 | matrix[i][j] = temp; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /rotate-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode rotateRight(ListNode head, int k) { 11 | ListNode p1 = head, p2 = head; 12 | while (k--) { 13 | p1 = p1.next; 14 | } 15 | while (p1.next != null) { 16 | p1 = p1.next; 17 | p2 = p2.next; 18 | } 19 | p1.next = head; 20 | return p2; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /same-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 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 isSameTree(TreeNode p, TreeNode q) { 12 | if (p == null && q == null) return true; 13 | if (p == null && q != null || q == null && p != null) return false; 14 | if (p.val != q.val) return false; 15 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /search-a-2d-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | bool searchMatrix(vector>& matrix, int target) { 5 | int size = matrix.size(); 6 | if (size == 0) return false; 7 | int colSz = matrix[0].size(), col = colSz-1, row = 0; 8 | while (row < size && col >= 0) { 9 | if (matrix[row][col] == target) return true; 10 | if (matrix[row][col] < target) { 11 | row++; 12 | } else { 13 | col--; 14 | } 15 | } 16 | return false; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /search-a-2d-matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; 4 | int m = matrix.length, n = matrix[0].length; 5 | int start = 0, end = m * n - 1; 6 | 7 | while (start < end) { 8 | int mid = (start + end) / 2; 9 | int i = mid / n, j = mid % n; 10 | if (target > matrix[i][j]) { 11 | start = mid+1; 12 | } else if (target < matrix[i][j]) { 13 | end = mid; 14 | } else { 15 | return true; 16 | } 17 | } 18 | return matrix[end/n][end%n] == target; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /search-for-a-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int n = nums.size(), start = 0, end = n-1, mid, leftmost = -1, rightmost = -1; 5 | vector range; 6 | while (start < end) { 7 | mid = start + (end-start)/2; 8 | if (nums[mid] >= target) { 9 | end = mid; 10 | } else { 11 | start = mid+1; 12 | } 13 | } 14 | leftmost = end; 15 | start = end; end = n-1; 16 | while (start < end) { 17 | mid = start + (end-start)/2; 18 | if (nums[mid] > target) { 19 | end = mid-1; 20 | } else { 21 | start = mid; 22 | } 23 | } 24 | rightmost = start; 25 | range.push_back(leftmost); 26 | range.push_back(rightmost); 27 | return range; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int left = 0, right = nums.size(), mid; 5 | while (left < right) { 6 | mid = left + (right-left)/2; 7 | if (nums[mid] == target) { 8 | return mid; 9 | } else if (nums[mid] > target) { 10 | right = mid; 11 | } else { 12 | left = mid+1; 13 | } 14 | } 15 | return left; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /search-insert-position.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | for (int i = 0; i < nums.length; i++) { 4 | if (nums[i] >= target) { 5 | return i; 6 | } 7 | } 8 | return nums.length; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /serialize-and-deserialize-bst.java: -------------------------------------------------------------------------------- 1 | /** This works but got TLE**/ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static class TreeNode { 11 | int val; 12 | TreeNode left; 13 | TreeNode right; 14 | TreeNode(int x) { val = x; } 15 | } 16 | 17 | public static void main (String[] args) throws java.lang.Exception 18 | { 19 | TreeNode root = new TreeNode(1); 20 | root.left = new TreeNode(2); 21 | root.right = new TreeNode(3); 22 | root.right.left = new TreeNode(4); 23 | root.right.right = new TreeNode(5); 24 | String serial = serialize(root); 25 | // System.out.println(serial); 26 | TreeNode res = deserialize(serial); 27 | // if (res == null) System.out.println("null"); 28 | // else System.out.println(res.val); 29 | } 30 | 31 | public static String serialize(TreeNode root) { 32 | LinkedList s = new LinkedList(); 33 | if (root != null) s.offer(root); 34 | else s.offer(new TreeNode(Integer.MIN_VALUE)); 35 | String res = ""; 36 | while (!s.isEmpty()) { 37 | TreeNode cur = s.poll(); 38 | // System.out.println(cur.val + ", "); 39 | if (cur.val == Integer.MIN_VALUE) res += "null,"; 40 | else { 41 | res += String.valueOf(cur.val) + ","; 42 | if (cur.left == null) s.offer(new TreeNode(Integer.MIN_VALUE)); 43 | else s.offer(cur.left); 44 | // System.out.println(cur.right.val); 45 | if (cur.right == null) s.offer(new TreeNode(Integer.MIN_VALUE)); 46 | else s.offer(cur.right); 47 | } 48 | } 49 | return res; 50 | } 51 | 52 | public static TreeNode deserialize(String data) { 53 | LinkedList list = new LinkedList(); 54 | String[] ss = data.split(","); 55 | int i = 0; 56 | TreeNode cur = null, root = null; 57 | if (!ss[i].equals("null")) { 58 | // System.out.println(Integer.parseInt(ss[i])); 59 | root = new TreeNode(Integer.parseInt(ss[i])); 60 | cur = root; 61 | list.offer(cur); 62 | } 63 | while (!list.isEmpty()) { 64 | cur = list.poll(); 65 | // System.out.print(cur.val + ": "); 66 | if (ss[++i].equals("null")) { 67 | cur.left = null; 68 | // System.out.print("null, "); 69 | } else { 70 | // System.out.print(Integer.parseInt(ss[i]) + ", "); 71 | cur.left = new TreeNode(Integer.parseInt(ss[i])); 72 | list.offer(cur.left); 73 | } 74 | if (ss[++i].equals("null")) { 75 | cur.right = null; 76 | // System.out.println("null, "); 77 | } else { 78 | // System.out.println(Integer.parseInt(ss[i])); 79 | cur.right = new TreeNode(Integer.parseInt(ss[i])); 80 | list.offer(cur.right); 81 | } 82 | } 83 | return root; 84 | } 85 | } 86 | 87 | /** This is the best solution. Very elegant too**/ 88 | 89 | /** 90 | * Definition for a binary tree node. 91 | * public class TreeNode { 92 | * int val; 93 | * TreeNode left; 94 | * TreeNode right; 95 | * TreeNode(int x) { val = x; } 96 | * } 97 | */ 98 | public class Codec { 99 | public static String splitter = ","; 100 | public static String nl = "X"; 101 | // Encodes a tree to a single string. 102 | public String serialize(TreeNode root) { 103 | StringBuilder sb = new StringBuilder(); 104 | buildString(sb, root); 105 | return sb.toString(); 106 | } 107 | public void buildString(StringBuilder sb, TreeNode root) { 108 | if (root == null) { 109 | sb.append(nl).append(splitter); 110 | } else { 111 | sb.append(root.val).append(splitter); 112 | buildString(sb, root.left); 113 | buildString(sb, root.right); 114 | } 115 | } 116 | 117 | // Decodes your encoded data to tree. 118 | public TreeNode deserialize(String data) { 119 | List l = Arrays.asList(data.split(splitter)); 120 | Deque d = new LinkedList(l); 121 | return buildTree(d); 122 | } 123 | public TreeNode buildTree(Deque d) { 124 | String val = d.remove(); 125 | if (val.equals(nl)) { 126 | return null; 127 | } else { 128 | TreeNode root = new TreeNode(Integer.parseInt(val)); 129 | root.left = buildTree(d); 130 | root.right = buildTree(d); 131 | return root; 132 | } 133 | } 134 | } 135 | 136 | // Your Codec object will be instantiated and called as such: 137 | // Codec codec = new Codec(); 138 | // codec.deserialize(codec.serialize(root)); 139 | 140 | -------------------------------------------------------------------------------- /shopping-offers.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public int shoppingOffers(List price, List> special, List needs) { 4 | int total = Integer.MAX_VAL; 5 | for (int o = 0; o < special.size(); o++) { 6 | boolean validOffer = true; 7 | List offer = special.get(o); 8 | for (int i = 0; i < needs.size()-1; i++) { 9 | int remaining = needs.get(i) - offer.get(i); 10 | needs.set(i, remaining); 11 | if (remaining < 0) validOffer = false; 12 | } 13 | if (validOffer) total = Math.min(total, shoppingOffers(price, special, needs) + offer.get(offer.size()-1)); 14 | for (int i = 0; i < needs.size()-1; i++) { 15 | needs.set(i, needs.get(i) + offer.get(i)); 16 | } 17 | } 18 | int noOffers = 0; 19 | for (int i = 0; i < needs.size(); i++) noOffers += price.get(i)*needs.get(i); 20 | return Math.min(noOffers, total); 21 | } 22 | public static void main(String args[]) { 23 | 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /shortest-completing-word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool compareStrings(int freq[], int licenseFreq[], string word, set &plateChars) { 5 | for (int i = 'a'; i <= 'z'; i++) freq[i] = 0; 6 | for (int i = 0; i < word.size(); i++) freq[word[i]]++; 7 | 8 | for (set::iterator itr = plateChars.begin(); itr != plateChars.end(); ++itr) 9 | { 10 | //cout << *itr << " " << freq[*itr] << " " << licenseFreq[*itr] << endl; 11 | if (freq[*itr] < licenseFreq[*itr]) return false; 12 | } 13 | return true; 14 | } 15 | string shortestCompletingWord(string licensePlate, vector& words) { 16 | int charSize = 'z' + 1; 17 | int freq[charSize], licenseFreq[charSize]; 18 | set plateChars; 19 | for (int i = 'a'; i <= 'z'; i++) licenseFreq[i] = 0; 20 | for (int i = 0; i < licensePlate.size(); i++) { 21 | if (isalpha(licensePlate[i])) { 22 | licenseFreq[tolower(licensePlate[i])]++; 23 | plateChars.insert(tolower(licensePlate[i])); 24 | } 25 | } 26 | 27 | int minLength = (unsigned int) (~0) >> 1; 28 | string result; 29 | for (int i = 0; i < words.size(); i++) { 30 | cout << words[i] << "\n"; 31 | if (compareStrings(freq, licenseFreq, words[i], plateChars) && words[i].size() < minLength) { 32 | minLength = words[i].size(); 33 | result = words[i]; 34 | } 35 | } 36 | return result; 37 | } 38 | 39 | }; 40 | -------------------------------------------------------------------------------- /shortest-palindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String shortestPalindrome(String s) { 3 | int n = s.length(), i; 4 | for (i = n-1; i >= 0; i--) { 5 | if (checkPalindrome(s, i)) break; 6 | } 7 | String reversed = ""; 8 | for (int j = n-1; j > i; j--) reversed += s.charAt(j); 9 | return reversed + s; 10 | } 11 | public boolean checkPalindrome(String s, int end) { 12 | for (int i = 0; i < (end+1)/2; i++) { 13 | if (s.charAt(i) != s.charAt(end-i)) 14 | return false; 15 | } 16 | return true; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /shortest-word-distance.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | static HashMap> hm = new HashMap>(); 11 | public static void main (String[] args) throws java.lang.Exception 12 | { 13 | String[] strs = new String[]{"practice", "makes", "perfect", "coding", "makes"}; 14 | System.out.println(shortestWordDistance(hm, strs, "practice", "coding")); 15 | } 16 | public static int shortestWordDistance(HashMap> hm, String[] strs, String word1, String word2) { 17 | for (int i = 0; i < strs.length; i++) { 18 | if (!hm.containsKey(strs[i])) { 19 | hm.put(strs[i], new ArrayList()); 20 | } 21 | ArrayList indices = hm.get(strs[i]); 22 | indices.add(i); 23 | } 24 | ArrayList index1 = hm.get(word1); 25 | ArrayList index2 = hm.get(word2); 26 | int smallest = Integer.MAX_VALUE; 27 | for (int i : index1) { 28 | for (int j : index2) { 29 | if (Math.abs(i-j) < smallest) { 30 | smallest = Math.abs(i-j); 31 | } 32 | } 33 | } 34 | return smallest; 35 | } 36 | 37 | public static int shortestWordDistance(String[] strs, String word1, String word2) { 38 | int smallest = Integer.MAX_VALUE; 39 | int idx1 = -1; 40 | int idx2 = -1; 41 | for (int i = 0; i < strs.length; i++) { 42 | if (strs[i].equals(word1)) { 43 | idx1 = i; 44 | if (idx2 != -1) smallest = Math.min(smallest, Math.abs(idx1 - idx2)); 45 | } 46 | if (strs[i].equals(word2)) { 47 | idx2 = i; 48 | if (idx1 != -1) smallest = Math.min(smallest, Math.abs(idx1 - idx2)); 49 | } 50 | } 51 | return smallest; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /single-number-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNumber(int[] nums) { 3 | HashSet ones = new HashSet(); 4 | HashSet twos = new HashSet(); 5 | HashSet threes = new HashSet(); 6 | for (int i = 0; i < nums.length; i++) { 7 | if (ones.contains(nums[i])) { 8 | twos.add(nums[i]); 9 | ones.remove(nums[i]); 10 | } else if (twos.contains(nums[i])) { 11 | twos.remove(nums[i]); 12 | threes.add(nums[i]); 13 | } else { 14 | ones.add(nums[i]); 15 | } 16 | } 17 | List list = new ArrayList<>(ones); 18 | return list.get(0); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /sort-characters-by-frequency.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | String s = "cccaaa"; 13 | System.out.println(frequencySort(s)); 14 | } 15 | 16 | public static String frequencySort(String s) { 17 | HashMap hm = new HashMap(); 18 | for (int i = 0; i < s.length(); i++) { 19 | Character c = Character.valueOf(s.charAt(i)); 20 | if (!hm.containsKey(c)) hm.put(c, 0); 21 | hm.put(c, hm.get(c) + 1); 22 | } 23 | PriorityQueue> q = new PriorityQueue>(Collections.reverseOrder(Map.Entry.comparingByValue())); 24 | q.addAll(hm.entrySet()); 25 | StringBuilder sb = new StringBuilder(); 26 | // System.out.println(Arrays.toString(q.toArray())); 27 | 28 | while (!q.isEmpty()) { 29 | Map.Entry e = q.poll(); 30 | String repeat = (new String(new char[e.getValue()])).replace("\0", String.valueOf(e.getKey())); 31 | // System.out.println(repeat + " "); 32 | sb.append(repeat); 33 | } 34 | return sb.toString(); 35 | // return s; 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /spiral-order.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List spiralOrder(int[][] matrix) { 3 | List list = new ArrayList<>(); 4 | if (matrix == null || matrix.length == 0) return list; 5 | int i, j, r1 = 0, c1 = 0, r2 = matrix.length-1, c2 = matrix[0].length-1; 6 | 7 | while (r1 <= r2 && c1 <= c2) { 8 | for (i = r1, j = c1; j <= c2; j++) { 9 | list.add(matrix[i][j]); 10 | } 11 | 12 | for (i = r1+1, j = c2; i <= r2; i++) { 13 | list.add(matrix[i][j]); 14 | } 15 | 16 | if(r1 < r2 && c1 < c2) { 17 | for (i = r2, j = c2-1; j > c1; j--) list.add(matrix[i][j]); 18 | for (i = r2, j = c1; i > r1; i--) list.add(matrix[i][j]); 19 | } 20 | 21 | c1++; c2--; 22 | r1++; r2--; 23 | } 24 | 25 | return list; 26 | } 27 | 28 | } 29 | 30 | /** 31 | 32 | [1, 2, 3, 4], 33 | [5, 6, 7, 8], 34 | [9,10,11,12], 35 | [13,14,15,16], 36 | [17,18,19,20] 37 | 38 | i = 0, j = 0 -> m-1 39 | i = 1 -> n-1, j -> m-1 40 | i = n-1, j = m-1 -> 0 41 | i = n-1 -> 1, j = 0 42 | 43 | i = 1, j = 1 -> m-2 44 | i = 2 -> n-2, j = m-2 45 | i = n-2, j = m-2 -> 1 46 | i = n-2 -> 2, j = 1 47 | 48 | for j = col, j < m-col, j++ ; i = row 49 | for i = row+1, i < n-row, i++ ; j = m-col-1 50 | for j = m-col-1, j >= col, j-- ; i = n-row-1 51 | for i = n-row-1, i >= row+1, i-- ; j = col 52 | col++, row++ 53 | **/ 54 | -------------------------------------------------------------------------------- /strong-password-checker.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int strongPasswordChecker(String s) { 3 | int res = 0; 4 | boolean lowerCase, upperCase, oneDigit; 5 | for (int i = 0; i < s.length(); i++) { 6 | if (Character.isLowerCase(s.charAt(i))) lowerCase = true; 7 | if (Character.isUpperCase(s.charAt(i))) upperCase = true; 8 | if (Character.isDigit(s.charAt(i))) oneDigit = true; 9 | if (s.charAt(i) == s.charAt(i-1)) { 10 | if (repeating >= 2) res++; else repeating++; 11 | } else repeating = 0; 12 | } 13 | if (s.length() < 6) res += 6 - s.length(); 14 | if (s.length() > 20) res += s.length() - 20; 15 | if (!lowerCase) res++; 16 | if (!upperCase) res++; 17 | if (!oneDigit) res++; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /student-attendance-record-ii.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int checkRecord(int n) { 3 | // dp[i][a][l] = number of valid sequence with length i, at most a absences and at most l consecutive TRAILING lates 4 | int[][][] dp = new int[n+1][2][3]; 5 | dp[0] = {{1,1,1}, {1,1,1}}; // 0 length, everything is 1 6 | for (int i = 1; i <= n; i++) 7 | for (int j = 0; j < 2; j++) 8 | for (int k = 0; k < 3; k++) { 9 | int value = dp[i-1][j][2]; // P for present 10 | if (j > 0) value = (value + dp[i-1][j-1][2]) % Integer.MAX_VAL; // A for absent 11 | if (k > 0) value = (value + dp[i-1][j][k-1]) % Integer.MAX_VAL; // L for late 12 | dp[i][j][k] = val; 13 | } 14 | return dp[n][1][2]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /sudoku-solver.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void solveSudoku(char[][] board) { 3 | 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Ideone 6 | { 7 | public static class TreeNode { 8 | int val; 9 | TreeNode left; 10 | TreeNode right; 11 | TreeNode(int x) { val = x; } 12 | } 13 | public static void main (String[] args) throws java.lang.Exception 14 | { 15 | TreeNode root = new TreeNode(3); 16 | root.left = new TreeNode(9); 17 | root.right = new TreeNode(20); 18 | root.right.left = new TreeNode(15); 19 | root.right.right = new TreeNode(7); 20 | System.out.println(sumOfLeftLeaves(root)); 21 | } 22 | 23 | /** 24 | * 25 | 1 26 | / \ 27 | 2 3 28 | / \ 29 | 4 5 30 | * */ 31 | // Recursive 32 | public static int sumOfLeftLeaves(TreeNode root) { 33 | // System.out.println("root= " + root.val); 34 | if (root == null) { 35 | return 0; 36 | } 37 | int sum = 0; 38 | if (root.left != null) { 39 | if (root.left.left == null && root.left.right == null) { 40 | sum = root.left.val; 41 | } else { 42 | sum = sumOfLeftLeaves(root.left); 43 | } 44 | } 45 | if (root.right != null) { 46 | sum += sumOfLeftLeaves(root.right); 47 | } 48 | return sum; 49 | } 50 | 51 | // Iterative 52 | public int sumOfLeftLeaves(TreeNode root) { 53 | if(root == null) return 0; 54 | int ans = 0; 55 | Stack s = new Stack(); 56 | s.push(root); 57 | while (!s.empty()) { 58 | root = s.pop(); 59 | if (root.left != null) { 60 | if (root.left.left == null && root.left.right == null) { 61 | ans += root.left.val; 62 | } else { 63 | s.push(root.left); 64 | } 65 | } 66 | if (root.right != null) { 67 | if (root.right.left != null || root.right.right != null) { 68 | s.push(root.right); 69 | } 70 | } 71 | } 72 | return ans; 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /summary-ranges.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List summaryRanges(int[] nums) { 3 | List list = new ArrayList(); 4 | if (nums == null || nums.length == 0) return list; 5 | int start = nums[0], end = nums[0]; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (nums[i] > end+1) { 8 | if (start != end) { 9 | list.add(start + "->" + end); 10 | } else { 11 | list.add(String.valueOf(start)); 12 | } 13 | start = nums[i]; 14 | } 15 | end = nums[i]; 16 | } 17 | 18 | if (start != end) { 19 | list.add(start + "->" + end); 20 | } else { 21 | list.add(String.valueOf(start)); 22 | } 23 | return list; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /super-washing-machine.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findMinMoves(int[] machines) { 3 | int n = machines.length; 4 | int[] sum = new int[n+1]; 5 | for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + machines[i-1]; 6 | int average = 0, res = 0; 7 | if (sum[n] % n != 0) return -1; 8 | else average = sum[n] / n; 9 | for (int i = 0; i < n; i++) { 10 | int left = i * average - sum[i]; 11 | int right = (n-i-1) * average - (sum[n] - sum[i] - machines[i]); 12 | if (left > 0 && right > 0) res = Math.max(res, Math.abs(left) + Math.abs(right)); 13 | else res = Math.max(res, Math.max(Math.abs(left), Math.abs(right))); 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /symmetric-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSymmetric(TreeNode root) { 3 | if (root == null) return true; 4 | return checkSymmetric(root.left, root.right); 5 | } 6 | 7 | public boolean checkSymmetric(TreeNode n1, TreeNode n2) { 8 | if (n1 == null && n2 == null) return true; 9 | if (n1 == null || n2 == null) return false; 10 | return (n1.val == n2.val && checkSymmetric(n1.left, n2.right) && checkSymmetric(n1.right, n2.left)); 11 | } 12 | -------------------------------------------------------------------------------- /target-sum.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | static int[] debug; 11 | public static void main (String[] args) throws java.lang.Exception 12 | { 13 | int[] nums = new int[] {1};//, 1, 1, 1, 1}; 14 | int S = 1; 15 | // debug = Arrays.copyOf(nums, nums.length); 16 | // debug = new int[nums.length]; 17 | Ideone o = new Ideone(); 18 | System.out.println(o.findTargetSumWays(nums, S)); 19 | } 20 | 21 | // Backtracking backtracking all the way 22 | static int cnt = 0; 23 | public int findTargetSumWays(int[] nums, int S) { 24 | findSum(nums, 0, 0, S); 25 | return cnt; 26 | } 27 | 28 | public void findSum(int[] nums, int index, int cur, int S) { 29 | // System.out.println("index= " + index + ", cur= " + cur + ", S= " + S); 30 | // System.out.println(Arrays.toString(debug) + ", cur= " + cur); 31 | if (index == nums.length) { 32 | // System.out.println(Arrays.toString(debug) + ", cur= " + cur); 33 | // System.out.println("done"); 34 | if (cur == S) cnt++; 35 | return; 36 | } else { 37 | // if (cur < 0 || cur > S) return; 38 | // debug[index] = -nums[index]; 39 | findSum(nums, index+1, cur-nums[index], S); 40 | // debug[index] = nums[index]; 41 | findSum(nums, index+1, cur+nums[index], S); 42 | 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /task-scheduler.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // ['A','A','A','B','B','B'], n = 2 3 | // ['A','A','A','A','A','B','B','C','C'], n = 2 4 | // A -> B -> C -> A -> B -> D -> A -> idle -> idle -> A -> idle -> idle -> A 5 | public int leastInterval(char[] tasks, int n) { 6 | Queue q = new LinkedList(); 7 | LinkedList schedule = new LinkedList(); 8 | int[] ts = new int[26]; 9 | for (int i = 0; i < tasks.length; i++) { 10 | if (ts[tasks[i]-'a'] == 0) q.add(String.valueOf(tasks[i]-'a')); 11 | ts[tasks[i]-'a']++; 12 | } 13 | int numTasks = 0; 14 | while (!q.isEmpty()) { 15 | String s = q.poll(); 16 | if (q.size() < n) q.add("idle"); 17 | else { 18 | for (int i = 0; i < ts.length; i++) 19 | if (ts[i] > 0 && String.valueOf(i+'a') != q.peek()) { 20 | q.add(String.valueOf(i+'a')); 21 | break; 22 | } 23 | } 24 | schedule.add(c); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ternary-expression-parser.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | String s = "F?1:T?4:5"; 13 | System.out.println(parseTernary(s)); 14 | } 15 | 16 | public static String parseTernary(String expression) { 17 | if (expression.length() < 2) { 18 | return expression; 19 | } else { 20 | String[] strs = expression.substring(2).split(":"); 21 | if (expression.charAt(0) == 'T') { 22 | return parseTernary(strs[0]); 23 | } else { 24 | return parseTernary(strs[1]); 25 | } 26 | } 27 | } 28 | 29 | public static String parseTernary(String expression) { 30 | if (expression == null || expression.length() == 0) { 31 | return expression; 32 | } 33 | Stack s = new Stack(); 34 | for (int i = expression.length() - 1; i >= 0; i--) { 35 | char c = expression.charAt(i); 36 | if (!s.empty() && s.peek() == '?') { 37 | s.pop(); // remove '?' 38 | char first = s.pop(); 39 | s.pop(); // remove ':' 40 | char second = s.pop(); 41 | if (c == 'T') { 42 | s.push(first); 43 | } else { 44 | s.push(second); 45 | } 46 | } else { 47 | s.push(c); 48 | } 49 | } 50 | return String.valueOf(s.peek()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /third-maximum-number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int thirdMax(int[] nums) { 3 | TreeSet s = new TreeSet(); 4 | for (int i = 0; i < nums.length; i++) { 5 | s.add(nums[i]); 6 | if (s.size() > 3) { 7 | s.pollFirst(); 8 | } 9 | } 10 | if (s.size() < 3) return s.last(); 11 | else return s.first(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /toeplitz-matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isToeplitzMatrix(int[][] matrix) { 3 | int m = matrix.length, n = matrix[0].length; 4 | for (int i = 0; i < matrix.length; i++) { 5 | int row = i, col = 0; 6 | while (row < m && col < n) { 7 | if (matrix[row][col] != matrix[i][0]) return false; 8 | row++; col++; 9 | } 10 | } 11 | for (int i = 1; i < matrix[0].length; i++) { 12 | int row = 0, col = i; 13 | while (row < m && col < n) { 14 | if (matrix[row][col] != matrix[0][i]) return false; 15 | row++; col++; 16 | } 17 | } 18 | return true; 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /trapping-rain-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int prev_height = 0, volume = 0; 5 | for (int i = 1; i < height.size(); i++) { 6 | if (height[i] < height[i-1]) { 7 | if (prev_height < height[i-1]) prev_height = height[i-1]; 8 | } else if (height[i] > height[i-1]) { 9 | if (prev_height < height[i]) prev_height = height[i]; 10 | } 11 | volume += prev_height - height[i]; 12 | } 13 | return volume; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /trapping-rain-water.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] hs) { 3 | int res = 0; 4 | for (int i = 0; i < hs.length; i++) { 5 | int maxL = 0, maxR = 0; 6 | for (int j = 0; j < i; j++) maxL = Math.max(maxL, hs[j]); 7 | for (int j = i+1; j < hs.length; j++) maxR = Math.max(maxR, hs[j]); 8 | res += Math.max(0, Math.min(maxL, maxR) - hs[i]); 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /two-sum-ii-input-array-sorted.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | int left = 0, right = numbers.length-1; 4 | int[] indices = new int[2]; 5 | 6 | while (left < right) { 7 | int sum = numbers[left] + numbers[right]; 8 | if (sum == target) { 9 | indices[0] = left+1; 10 | indices[1] = right+1; 11 | break; 12 | } else if (sum < target) { 13 | left++; 14 | } else { 15 | right--; 16 | } 17 | } 18 | 19 | return indices; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ugly-number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isUgly(int num) { 3 | if (num < 1) return false; 4 | if (num == 1 || num == 2 || num == 3 || num == 5) return true; 5 | while (num > 0) { 6 | if (num % 2 == 0 ) { 7 | while (num > 0 && num % 2 == 0) { 8 | num /= 2; 9 | if (num == 1) return true; 10 | // System.out.println("2num= " + num); 11 | } 12 | } 13 | if (num % 3 == 0) { 14 | while (num > 0 && num % 3 == 0) { 15 | num /= 3; 16 | if (num == 1) return true; 17 | System.out.println("3num= " + num); 18 | } 19 | } 20 | if (num % 5 == 0) { 21 | while (num > 0 && num % 5 == 0) { 22 | num /= 5; 23 | if (num == 1) return true; 24 | System.out.println("5num= " + num); 25 | } 26 | } 27 | return false; 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /unique-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public int numTrees(int n) { 4 | int[] g = new int[n+1]; 5 | g[0] = g[1] = 1; 6 | for (int i = 1; i <= n; i++) { 7 | for (int j = 1; j <= i; j++) { 8 | g[i] += g[j-1]*g[i-j]; 9 | } 10 | } 11 | return g[n]; 12 | } 13 | } 14 | 15 | /** 16 | 17 | 18 | 1 2 19 | \ / 20 | 2 1 21 | 22 | 23 | 1 3 3 2 1 24 | \ / / / \ \ 25 | 3 2 1 1 3 2 26 | / / \ \ 27 | 2 1 2 3 28 | 29 | 30 | 4 4 4 4 4 31 | / / / / / 32 | 1 3 3 2 1 33 | \ / / / \ \ 34 | 3 2 1 1 3 2 35 | / / \ \ 36 | 2 1 2 3 37 | 38 | 39 | 40 | 1 3 3 2 1 41 | \ / \ / \ / \ \ 42 | 3 2 4 1 4 1 3 2 43 | / \ / \ \ \ 44 | 2 4 1 2 4 3 45 | \ 46 | 4 47 | -------------------------------------------------------------------------------- /unique-email-addresses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numUniqueEmails(String[] emails) { 3 | HashSet set = new HashSet(); 4 | for (int i = 0; i < emails.length; i++) { 5 | String[] parts = emails[i].split("@"); 6 | String local = parseLocal(parts[0]); 7 | set.add(local+"@"+parts[1]); 8 | } 9 | return set.size(); 10 | } 11 | 12 | public String parseLocal(String s) { 13 | String[] parts = s.split("\\+"); 14 | return parts[0].replace(".", ""); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /valid-palindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean validPalindrome(String s) { 3 | int n = s.length(); 4 | if (checkPalindrome(s)) return true; 5 | for (int i = 0; i < n/2; i++) { 6 | if (s.charAt(i) != s.charAt(n-i-1)) 7 | if (checkPalindrome(s.substring(i+1, n-i)) || checkPalindrome(s.substring(i, n-i-1))) return true; 8 | } 9 | return false; 10 | } 11 | 12 | public boolean checkPalindrome(String s) { 13 | int n = s.length(); 14 | for (int i = 0; i < n/2; i++) { 15 | if (s.charAt(i) != s.charAt(n-i-1)) return false; 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /valid-parentheses.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValid(String str) { 3 | Stack s = new Stack(); 4 | for (char ch : str.toCharArray()) { 5 | if (ch == '(' || ch == '{' || ch == '[') { 6 | 7 | s.push(ch); 8 | System.out.println(s); 9 | } else { 10 | if (s.empty()) return false; 11 | char top = s.pop(); 12 | if ((top == '(' && ch != ')') || (top == '{' && ch != '}') || (top == '[' && ch != ']')) { 13 | return false; 14 | } 15 | } 16 | } 17 | return s.empty(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /valid-sudoku.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | int[][] flips = {{0,0,0}, {0,0,0}, {0,0,0}}; 4 | for (int i = 0; i < 9; i++) { 5 | int flip = 0; 6 | for (int j = 0; j < 9; j++) { 7 | if (board[i][j] == '.') continue; 8 | int num = board[i][j] - '0'; 9 | if ((flip & (1 << num)) != 0) return false; 10 | else flip = flip | (1 << num); 11 | } 12 | flip = 0; 13 | for (int j = 0; j < 9; j++) { 14 | if (board[j][i] == '.') continue; 15 | int num = board[j][i] - '0'; 16 | if ((flip & (1 << num)) != 0) return false; 17 | else flip = flip | (1 << num); 18 | } 19 | 20 | for (int j = 0; j < 9; j++) { 21 | if (board[i][j] == '.') continue; 22 | int num = board[i][j] - '0'; 23 | if ((flips[i/3][j/3] & (1 << num)) != 0) return false; 24 | else flips[i/3][j/3] = flips[i/3][j/3] | (1 << num); 25 | } 26 | } 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /validate-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public boolean isValidBST(TreeNode root) { 12 | return validBST(root, Long.MIN_VALUE, Long.MAX_VALUE); 13 | } 14 | 15 | public boolean validBST(TreeNode root, long min, long max) { 16 | if (root == null) return true; 17 | if (root.val <= min || root.val >= max) return false; 18 | return validBST(root.left, min, root.val) && validBST(root.right, root.val, max); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /walls-and-gates.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public void wallsAndGates(int[][] rooms) { 3 | if (rooms == null || rooms.length == 0) return; 4 | Queue q = new LinkedList<>(); 5 | for (int i = 0; i < rooms.length; i++) 6 | for (int j = 0; j < rooms[0].length; i++) { 7 | if (rooms[i][j] == 0) q.add(new int[]{i, j}); 8 | } 9 | while (!q.empty()) { 10 | int[] cur = q.remove(); 11 | int row = cur[0], col = cur[1]; 12 | if (row > 0 && rooms[row-1][col] == Integer.MAX_VALUE) { 13 | rooms[row-1][col] = rooms[row][col]+1; 14 | q.add(rooms[row-1][col]); 15 | } 16 | if (row < rooms.length-1 && rooms[row+1][col] == Integer.MAX_VALUE) { 17 | rooms[row+1][col] = rooms[row][col]+1; 18 | q.add(rooms[row+1][col]); 19 | } 20 | if (col > 0 && rooms[row][col-1] == Integer.MAX_VALUE) { 21 | rooms[row][col-1] = rooms[row][col]+1; 22 | q.add(rooms[row][col-1]); 23 | } 24 | if (col < rooms[0].length-1 && rooms[row][col+1] == Integer.MAX_VALUE) { 25 | rooms[row][col+1] = rooms[row][col]+1; 26 | q.add(rooms[row][col+1]); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /world-search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public static boolean exist(char[][] board, String word) { 4 | for (int i = 0; i < board.length; i++) { 5 | for (int j = 0; j < board[0].length; j++) { 6 | if (!visited[i][j] && board[i][j] == word.charAt(0)) return wordExists(board, word, 0, visited, i, j); 7 | } 8 | } 9 | } 10 | 11 | public static boolean wordExists(char[][] board, String word, int iWord, boolean[][] visited, int i, int j) { 12 | if (iWord >= word.length()) return true; 13 | if (board[i][j] != word.charAt(iWord)) return false; 14 | visited[i][j] = true; 15 | boolean top = true, left = true, right = true, bottom = true; 16 | if (inBounds(board, i, j-1) && !visited[i][j-1]) top = wordExists(board, word, iWord+1, visited, i, j-1); 17 | if (inBounds(board, i-1, j) && !visited[i-1][j]) top = wordExists(board, word, iWord+1, visited, i-1, j); 18 | if (inBounds(board, i, j+1) && !visited[i][j+1]) top = wordExists(board, word, iWord+1, visited, i, j+1); 19 | if (inBounds(board, i+1, j) && !visited[i+1][j]) top = wordExists(board, word, iWord+1, visited, i+1, j); 20 | return top || left || right || bottom; 21 | } 22 | 23 | public static boolean inBounds(char[][] board, int row, int col) { 24 | return row >= 0 && row < board.length && col >= 0 && col < board[0].length; 25 | } 26 | 27 | public static void main(String[] args) { 28 | char[][] board = { 29 | {'A','B','C','E'}, 30 | {'S','F','C','S'}, 31 | {'A','D','E','E'} 32 | }; 33 | String word = "ABCCED"; 34 | System.out.println(exist(board, word)); 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /zigzag-conversion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String convert(String s, int numRows) { 3 | if (numRows == 1 || s.length() <= numRows) return s; 4 | String ans = ""; 5 | for (int i = 0; i < numRows; i++) { 6 | int j = i; 7 | ans += s.charAt(j); 8 | while (j < s.length()) { 9 | int next = 2 * (numRows - i - 1); 10 | if (next > 0) { 11 | j += next; 12 | if (j < s.length()) ans += s.charAt(j); 13 | } 14 | next = 2 * i; 15 | if (next > 0) { 16 | j += next; 17 | if (j < s.length()) ans += s.charAt(j); 18 | } 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | 25 | /** 26 | a i q 27 | b h j p r 28 | c g k o s x 29 | d f l n t v 30 | e m u 31 | **/ 32 | -------------------------------------------------------------------------------- /zuma-game.java: -------------------------------------------------------------------------------- 1 | /* package whatever; // don't place package name! */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | /* Name of the class has to be "Main" only if the class is public. */ 8 | class Ideone 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | String board = "WWRRBBWW"; 13 | String hand = "WRBRW"; 14 | Ideone o = new Ideone(); 15 | System.out.println(o.findMinStep(board, hand)); 16 | } 17 | 18 | public int findMinStep(String board, String hand) { 19 | List boards = new ArrayList(); 20 | for (char c : board.toCharArray()) boards.add(c); 21 | HashMap hm = new HashMap(); 22 | hm.put('B', 0); hm.put('G', 0); hm.put('R', 0); hm.put('Y', 0); hm.put('W', 0); 23 | for (char c : hand.toCharArray()) hm.put(c, hm.get(c) + 1); 24 | return find(boards, hm); 25 | 26 | } 27 | 28 | public int find(List boards, HashMap hm) { 29 | removeAdjacents(boards); 30 | if (boards.size() == 0) return 0; 31 | if (isEmpty(hm)) return -1; 32 | int cnt = 0; 33 | int retVal = Integer.MAX_VALUE; 34 | for (int i = 0; i < boards.size(); i++) { 35 | char c = boards.get(i); 36 | cnt++; 37 | if (i == boards.size() || boards.get(i+1) != c) { 38 | int missing = 3 - cnt; 39 | if (missing <= hm.get(c)) { 40 | hm.put(c, hm.get(c) - missing); 41 | List temp = new ArrayList(boards); 42 | for (int j = i; j > i-cnt; j--) temp.remove(j); 43 | int next = find (temp, hm); 44 | if (next != -1) retVal = Math.min(next + missing, retVal); 45 | hm.put(c, hm.get(c) + missing); 46 | } 47 | cnt = 0; 48 | } 49 | } 50 | if (retVal == Integer.MAX_VALUE) return - 1; else return retVal; 51 | } 52 | 53 | public void removeAdjacents(List board) { 54 | int cnt = 0; 55 | boolean done = true; 56 | for (int i = 0; i < board.size(); i++) { 57 | char c = board.get(i); 58 | cnt++; 59 | if (i == board.size()-1 || c != board.get(i+1)) { 60 | if (cnt >= 3) { 61 | for (int j = i; j > i-cnt; j--) board.remove(j); 62 | done = false; 63 | break; 64 | } 65 | cnt = 0; 66 | } 67 | } 68 | if (!done) removeAdjacents(board); 69 | } 70 | public boolean isEmpty(HashMap hand) { 71 | for (int i : hand.values()) { 72 | if (i > 0) return false; 73 | } 74 | return true; 75 | } 76 | } 77 | --------------------------------------------------------------------------------