Leetcode easy

¡Supera tus tareas y exámenes ahora con Quizwiz!

public int minCostClimbingStairs(int[] cost) { for(int x = 2; x < cost.length; x++) { cost[x] += Math.min(cost[x-1], cost[x-2]); } return Math.min(cost[cost.length - 1], cost[cost.length - 2]); }

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

public int maxProfit(int[] prices) { int maxprofit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) maxprofit += prices[i] - prices[i - 1]; } return maxprofit; }

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

public int maxDepth(TreeNode root) { if(root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7

Compare With Top-Left Neighbor Every element belongs to some diagonal, and it's previous element (if it exists) is it's top-left neighbor. Thus, for the square (r, c), we only need to check r == 0 OR c == 0 OR matrix[r-1][c-1] == matrix[r][c]. public boolean isToeplitzMatrix(int[][] matrix) { for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length; j++) { if(i > 0 && j > 0 && matrix[i][j] != matrix[i - 1][j - 1]) { return false; } } } return true; }

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an M x N matrix, return True if and only if the matrix is Toeplitz. Example 1: Input: matrix = [ [1,2,3,4], [5,1,2,3], [9,5,1,2] ] Output: True Explanation: In the above grid, the diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True. Example 2: Input: matrix = [ [1,2], [2,2] ] Output: False Explanation: The diagonal "[1, 2]" has different elements.

public boolean isRectangleOverlap(int[] rec1, int[] rec2) { return (Math.min(rec1[2], rec2[2]) > Math.max(rec1[0], rec2[0]) && // width > 0 Math.min(rec1[3], rec2[3]) > Math.max(rec1[1], rec2[1])); // height > 0 }

A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two (axis-aligned) rectangles, return whether they overlap. Example 1: Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] Output: true Example 2: Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] Output: false

public int sumOfLeftLeaves(TreeNode root) { if(root==null) return 0; return (isLeave(root.left)? root.left.val : sumOfLeftLeaves(root.left)) + sumOfLeftLeaves(root.right); } private boolean isLeave(TreeNode node){ return node !=null && node.left == null && node.right == null; }

Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int i = 0; int j = 0; int count = 0; while (i < g.length && j < s.length) { if(s[j] >= g[i]) { count++; i++; } j++; } return count; }

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Note: You may assume the greed factor is always positive. You cannot assign more than one cookie to one child. Example 1: Input: [1,2,3], [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: [1,2], [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2.

public boolean lemonadeChange(int[] bills) { int five = 0, ten = 0; for (int bill: bills) { if (bill == 5) five++; else if (bill == 10) { if (five == 0) return false; five--; ten++; } else { if (five > 0 && ten > 0) { five--; ten--; } else if (five >= 3) { five -= 3; } else { return false; } } } return true; }

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5. Note that you don't have any change in hand at first. Return true if and only if you can provide every customer with correct change. Example 1: Input: [5,5,5,10,20] Output: true Explanation: From the first 3 customers, we collect three $5 bills in order. From the fourth customer, we collect a $10 bill and give back a $5. From the fifth customer, we give a $10 bill and a $5 bill. Since all customers got correct change, we output true. Example 2: Input: [5,5,10] Output: true Example 3: Input: [10,10] Output: false

public boolean leafSimilar(TreeNode root1, TreeNode root2) { List<Integer> leaves1 = new ArrayList(); List<Integer> leaves2 = new ArrayList(); dfs(root1, leaves1); dfs(root2, leaves2); return leaves1.equals(leaves2); } public void dfs(TreeNode node, List<Integer> leafValues) { if (node != null) { if (node.left == null && node.right == null) leafValues.add(node.val); dfs(node.left, leafValues); dfs(node.right, leafValues); } }

Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

public int countPrimes(int n) { n--; if(n < 2) return 0; boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = false; prime[1] = false; int m = (int) Math.sqrt(n); for(int i = 2; i <= m; i++) { if(prime[i]) { for(int k = i * i; k <= n; k += i) { prime[k] = false; } } } int count = 0; for(int i = 0; i < prime.length; i++) { if(prime[i]) count++; } return count; }

Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

public int countSegments(String s) { s = s.trim(); if("".equals(s)) return 0; String[] segments = s.split("\\s+"); return segments.length; }

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. Please note that the string does not contain any non-printable characters. Example: Input: "Hello, my name is John" Output: 5

class KthLargest { private PriorityQueue<Integer> queue; private int k; public KthLargest(int k, int[] nums) { this.k = k; queue = new PriorityQueue<>(k + 1); for(int i = 0; i < nums.length; i++) { queue.add(nums[i]); if(queue.size() > k) { queue.poll(); } } } public int add(int val) { queue.add(val); if(queue.size() > k) { queue.poll(); } return queue.peek(); } }

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream. Example: int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8

public int reverse(int x) { long rev= 0; while( x != 0){ rev= rev*10 + x % 10; x= x/10; if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0; } return (int) rev; }

Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321

private Integer res = Integer.MAX_VALUE; private Integer pre = null; public int minDiffInBST(TreeNode root) { if (root.left != null) minDiffInBST(root.left); if (pre != null) res = Math.min(res, root.val - pre); pre = root.val; if (root.right != null) minDiffInBST(root.right); return res; }

Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. Example : Input: root = [4,2,6,1,3,null,null] Output: 1 Explanation: Note that root is a TreeNode object, not an array. The given tree [4,2,6,1,3,null,null] is represented by the following diagram: 4 / \ 2 6 / \ 1 3 while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

private int sum = 0; public TreeNode convertBST(TreeNode root) { if(root == null) return null; convertBST(root.right); sum += root.val; root.val = sum; convertBST(root.left); return root; }

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(!covers(root, p) || !covers(root, q)) return null; if(root == null || root == p || root == q) return root; boolean isPOnLeft = covers(root.left, p); boolean isQOnLeft = covers(root.left, q); if(isPOnLeft != isQOnLeft) return root; if(isPOnLeft) return lowestCommonAncestor(root.left, p, q); else return lowestCommonAncestor(root.right, p, q); } private boolean covers(TreeNode root, TreeNode p) { if(root == null) return false; if(root == p) return true; return covers(root.left, p) || covers(root.right, p); }

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)." Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] _______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5 Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.

public TreeNode trimBST(TreeNode root, int L, int R) { if (root == null) return root; if (root.val > R) return trimBST(root.left, L, R); if (root.val < L) return trimBST(root.right, L, R); root.left = trimBST(root.left, L, R); root.right = trimBST(root.right, L, R); return root; }

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree. Example 1: Input: 1 / \ 0 2 L = 1 R = 2 Output: 1 \ 2 Example 2: Input: 3 / \ 0 4 \ 2 / 1 L = 1 R = 3 Output: 3 / 2 / 1

private int min = Integer.MAX_VALUE; private Integer prev = null; public int getMinimumDifference(TreeNode root) { if (root == null) return min; getMinimumDifference(root.left); if (prev != null) { min = Math.min(min, root.val - prev); } prev = root.val; getMinimumDifference(root.right); return min; }

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. Example: Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

// recursive public boolean isSymmetric(TreeNode root) { return isMirror(root, root); } public boolean isMirror(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return true; if (t1 == null || t2 == null) return false; return (t1.val == t2.val) && isMirror(t1.right, t2.left) && isMirror(t1.left, t2.right); } // iterative public boolean isSymmetric(TreeNode root) { Queue<TreeNode> q = new LinkedList<>(); q.add(root); q.add(root); while (!q.isEmpty()) { TreeNode t1 = q.poll(); TreeNode t2 = q.poll(); if (t1 == null && t2 == null) continue; if (t1 == null || t2 == null) return false; if (t1.val != t2.val) return false; q.add(t1.left); q.add(t2.right); q.add(t1.right); q.add(t2.left); } return true; }

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively.

public List<String> binaryTreePaths(TreeNode root) { List<String> answer = new ArrayList<String>(); if (root != null) searchBT(root, "", answer); return answer; } private void searchBT(TreeNode root, String path, List<String> answer) { if (root.left == null && root.right == null) answer.add(path + root.val); if (root.left != null) searchBT(root.left, path + root.val + "->", answer); if (root.right != null) searchBT(root.right, path + root.val + "->", answer); }

Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3

public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if(root == null) return result; Queue<TreeNode> toExplore = new LinkedList<>(); toExplore.add(root); while(!toExplore.isEmpty()) { List<Integer> currList = new ArrayList<>(); int size = toExplore.size(); while(size > 0) { TreeNode curr = toExplore.poll(); currList.add(curr.val); if(curr.left != null) toExplore.add(curr.left); if(curr.right != null) toExplore.add(curr.right); size--; } result.add(currList); } Collections.reverse(result); return result; }

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ]

public int findTilt(TreeNode root) { if (root == null) return 0; int currentTilt = Math.abs(findNodeSum(root.left) - findNodeSum(root.right)); return currentTilt + findTilt(root.left) + findTilt(root.right); } private int findNodeSum(TreeNode root) { if (root == null) return 0; return root.val + findNodeSum(root.left) + findNodeSum(root.right); }

Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0. The tilt of the whole tree is defined as the sum of all nodes' tilt. Example: Input: 1 / \ 2 3 Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1

private int ans; public int diameterOfBinaryTree(TreeNode root) { ans = 0; depth(root); return ans; } public int depth(TreeNode node) { if (node == null) return 0; int L = depth(node.left); int R = depth(node.right); ans = Math.max(ans, L + R); return Math.max(L, R) + 1; }

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them.

public int findLUSlength(String a, String b) { if(a.equals(b)) return -1; return Math.max(a.length(), b.length()); }

Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings. A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1. Example 1: Input: "aba", "cdc" Output: 3 Explanation: The longest uncommon subsequence is "aba" (or "cdc"), because "aba" is a subsequence of "aba", but not a subsequence of any other strings in the group of two strings.

public int[][] transpose(int[][] A) { int row = A.length; int col = A[0].length; int[][] result = new int[col][row]; for(int r = 0; r < row; r++) { for(int c = 0; c < col; c++) { result[c][r] = A[r][c]; } } return result; }

Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]

/** Given class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { val = _val; children = _children; } } **/ public int maxDepth(Node root) { if(root == null) return 0; if(root.children == null) return 1; int maxDepth = 0; for(Node child : root.children) { maxDepth = Integer.max(maxDepth, maxDepth(child)); } return maxDepth + 1; }

Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example, given a 3-ary tree: We should return its max depth, which is 3. Note: The depth of the tree is at most 1000. The total number of nodes is at most 5000.

private int[][] grid; private boolean[][] seen; public int area(int r, int c) { if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || seen[r][c] || grid[r][c] == 0) return 0; seen[r][c] = true; return (1 + area(r+1, c) + area(r-1, c) + area(r, c-1) + area(r, c+1)); } public int maxAreaOfIsland(int[][] grid) { this.grid = grid; seen = new boolean[grid.length][grid[0].length]; int ans = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[0].length; c++) { ans = Math.max(ans, area(r, c)); } } return ans; }

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) Example 1: [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]] Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. Example 2: [[0,0,0,0,0,0,0,0]] Given the above grid, return 0.

public boolean isPerfectSquare(int num) { if(num == 0 || num == 1) return true; long lo = 0; long hi = num / 2; while(lo <= hi) { long mid = lo + (hi - lo) / 2; long prod = mid * mid; if(prod == num) return true; else if(prod < num) lo = mid + 1; else if(prod > num) hi = mid - 1; } return false; }

Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false

public int thirdMax(int[] nums) { Integer max1 = null; Integer max2 = null; Integer max3 = null; for (Integer n : nums) { if (n.equals(max1) || n.equals(max2) || n.equals(max3)) continue; if (max1 == null || n > max1) { max3 = max2; max2 = max1; max1 = n; } else if (max2 == null || n > max2) { max3 = max2; max2 = n; } else if (max3 == null || n > max3) { max3 = n; } } return max3 == null ? max1 : max3; }

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

public boolean repeatedSubstringPattern(String s) { int size = s.length(); for(int i = 1; i <= size/2; i++){ // i is the length of the substring if(size % i == 0){ int count = 0; String subs = s.substring(0, i); for(int j = i; j < size; j = j + i){ String temp = s.substring(j, j+i); // check whether the rest part of the string has the same pattern, use count to memorize // if it is not a repeated pattern, the count will not be 0 if(! temp.equals(subs)) count++; } if(count == 0) return true; } } return false; }

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the substring "ab" twice. Example 2: Input: "aba" Output: False Example 3: Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

public ListNode middleNode(ListNode head) { int size = getSize(head); if(size == 0) return null; int mid = size / 2; ListNode tmp = head; while(mid > 0) { tmp = tmp.next; mid--; } return tmp; } private int getSize(ListNode head) { int size = 0; ListNode tmp = head; while(tmp != null) { size++; tmp = tmp.next; } return size; }

Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a ListNode object ans, such that: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has two middle nodes with values 3 and 4, we return the second one.

public boolean judgeSquareSum(int c) { for (long a = 0; a * a <= c; a++) { int b = c - (int)(a * a); if (binary_search(0, b, b)) return true; } return false; } public boolean binary_search(long lo, long hi, int target) { if (lo > hi) return false; long mid = lo + (hi - lo) / 2; if (mid * mid == target) return true; if (mid * mid > target) return binary_search(lo, mid - 1, target); return binary_search(mid + 1, hi, target); }

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: 3 Output: False

public int addDigits(int num) { while((num + "").length() != 1) { String numStr = num + ""; int tmpSum = 0; for(int i = 0; i < numStr.length(); i++) { tmpSum += numStr.charAt(i) - '0'; } num = tmpSum; } return num; } followup: public int addDigits(int num) { return (num != 0 && num % 9 == 0) ? 9 : num % 9; } I think like this: num = 10 * a + b = a + b + 9 * a when you add all digits, the result is sum = num - 9*a, make sum the smallest, while sum > 0, when you get the new sum If sum > 10, do sum1 = sum - 9*a1 again else sum is the result so we can get the answer, result = num - num / 9 * 9 Only thing you have to do is: when num == 0, ok the result is right when num%9 == 0, oops, the result is 0, but the real result is result > 0, so it is 9.

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime?

public String mostCommonWord(String paragraph, String[] banned) { String[] words = paragraph.replaceAll("[^a-zA-Z ]", "").split("\\s+"); Set<String> bannedSet = new HashSet<>(Arrays.asList(banned)); String common = ""; int max = 0; Map<String, Integer> map = new HashMap<>(); for(int i = 0; i < words.length; i++) { String str = words[i].toLowerCase(); if(!bannedSet.contains(str)) { map.put(str, map.getOrDefault(str, 0) + 1); if(max < map.get(str)) { common = str; max = map.get(str); } } } return common; }

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique. Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase. Example: Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] Output: "ball" Explanation: "hit" occurs 3 times, but it is a banned word. "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as "ball,"), and that "hit" isn't the answer even though it occurs more because it is banned.

public boolean wordPattern(String pattern, String str) { if(pattern == null || "".equals(pattern)) return false; if(pattern.equals(str)) return false; String[] strArr = str.split(" "); if(pattern.length() != strArr.length) return false; Map<Character, String> map = new HashMap<>(); for(int i = 0; i < pattern.length(); i++) { char key = pattern.charAt(i); String val = strArr[i]; if(!map.containsKey(key)) { if(map.containsValue(val)) return false; map.put(key, val); } else { if(!map.get(key).equals(val)) return false; } } return true; }

Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Example 1: Input: pattern = "abba", str = "dog cat cat dog" Output: true Example 2: Input:pattern = "abba", str = "dog cat cat fish" Output: false Example 3: Input: pattern = "aaaa", str = "dog cat cat dog" Output: false Example 4: Input: pattern = "abba", str = "dog dog dog dog" Output: false

public int[] shortestToChar(String S, char C) { int N = S.length(); int[] ans = new int[N]; int prev = Integer.MIN_VALUE / 2; for (int i = 0; i < N; ++i) { if (S.charAt(i) == C) prev = i; ans[i] = i - prev; } prev = Integer.MAX_VALUE / 2; for (int i = N-1; i >= 0; --i) { if (S.charAt(i) == C) prev = i; ans[i] = Math.min(ans[i], prev - i); } return ans; }

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. Example 1: Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

public List<String> letterCasePermutation(String S) { List<String> result = new ArrayList<>(); char[] charArr = new char[S.length()]; letterCasePermutation(S, result, charArr, 0); return result; } private void letterCasePermutation(String S, List<String> result, char[] charArr, int i) { if(i == S.length()) { result.add(String.valueOf(charArr)); } else { if(Character.isLetter(S.charAt(i))) { charArr[i] = Character.toLowerCase(S.charAt(i)); letterCasePermutation(S, result, charArr, i + 1); charArr[i] = Character.toUpperCase(S.charAt(i)); letterCasePermutation(S, result, charArr, i + 1); } else { charArr[i] = S.charAt(i); letterCasePermutation(S, result, charArr, i + 1); } } }

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["12345"]

public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '(' || c == '[' || c == '{') { stack.push(c); } else { if(stack.isEmpty()) return false; if(c == ')') { char cc = stack.pop(); if(cc != '(') return false; } else if(c == ']') { char cc = stack.pop(); if(cc != '[') return false; } else if(c == '}') { char cc = stack.pop(); if(cc != '{') return false; } } } return stack.isEmpty(); }

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true

// naive approach public List<Integer> findAnagrams(String s, String p) { char[] keyChar = p.toCharArray(); Arrays.sort(keyChar); Map<String, String> map = new HashMap<>(); map.put(new String(keyChar), p); int len = p.length(); List<Integer> result = new ArrayList<>(); for(int i = 0; i <= s.length() - len; i++) { String tmp = s.substring(i, i + len); char[] tmpKey = tmp.toCharArray(); Arrays.sort(tmpKey); if(map.containsKey(new String(tmpKey))) { result.add(i); } } return result; }

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc".

public static int longestPalindrome(String s) { int inputLength = s.length(); HashSet<Character> charWithOddNumber = new HashSet<>(); for( int i = 0 ; i < s.length(); i++){ char c = s.charAt(i); if(charWithOddNumber.contains(c)){ charWithOddNumber.remove(c); } else{ charWithOddNumber.add(c); } } int sizeOfOddNumber = charWithOddNumber.size(); int palindromeLength = sizeOfOddNumber <= 1 ? inputLength : (inputLength - (sizeOfOddNumber -1)); return palindromeLength; }

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

public int firstUniqChar(String s) { int[] map = new int[26]; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); map[c - 'a']++; } for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(map[c - 'a'] == 1) return i; } return -1; }

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2.

public String reverseWords(String s) { if(s == null || "".equals(s)) return s; char[] arr = s.toCharArray(); int j = 0; for(int i = 0; i < arr.length && j < arr.length; i++) { if(arr[i] == ' ') { reverse(arr, j, i - 1); j = i + 1; } } // don't forget about this part if(j < arr.length) { reverse(arr, j, arr.length - 1); } return new String(arr); } private void reverse(char[] arr, int i, int j) { while(i < j) { char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } }

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string.

(1) if the first letter is non-capital, then the rest CAN NOT be capital, like "abcdefg". (2) if the first letter is capital, then: (1) if the second is capital, then all letters MUST be capitals, like "ABCDEFG". (2) if the second is non-capital, then all the rest letters MUST be non-capitals, like "Abcdefg" public boolean detectCapitalUse(String word) { if(word.length() == 1) return true; if(word.charAt(0) - 'a' >= 0) { for(int i = 0; i < word.length(); i++){ if(word.charAt(i) - 'a' < 0) return false; } } else { if(word.charAt(1) - 'a' >= 0) { for(int i = 1; i < word.length(); i++) { if(word.charAt(i) - 'a' < 0) return false; } } else { for(int i = 1; i < word.length(); i++) { if(word.charAt(i) - 'a' >= 0) return false; } } } return true; }

Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital if it has more than one letter, like "Google". Otherwise, we define that this word doesn't use capitals in a right way. Example 1: Input: "USA" Output: True Example 2: Input: "FlaG" Output: False

public boolean canConstruct(String ransomNote, String magazine) { int[] map = new int[26]; for(char c : magazine.toCharArray()) { map[c - 'a']++; } for(char c : ransomNote.toCharArray()) { --map[c - 'a']; if(map[c - 'a'] < 0) { return false; } } return true; }

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note: You may assume that both strings contain only lowercase letters. canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true

public int missingNumber(int[] nums) { //edge case if (nums == null || nums.length == 0) { return 0; } int res = 0; for(int i = 0; i < nums.length; i++) { res += i - nums[i]; } res += nums.length; return res; }

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

public void moveZeroes(int[] nums) { int i = 0; while(i < nums.length) { if(nums[i] == 0) { int j = i + 1; while(j < nums.length) { if(nums[j] != 0) break; j++; } if(j >= nums.length) break; swap(nums, i, j); } i++; } } private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

Let's maintain anchor, the start position of the contiguous group of characters we are currently reading. Now, let's read from left to right. We know that we must be at the end of the block when we are at the last character, or when the next character is different from the current character. When we are at the end of a group, we will write the result of that group down using our write head. chars[anchor] will be the correct character, and the length (if greater than 1) will be read - anchor + 1. We will write the digits of that number to the array. public int compress(char[] chars) { int anchor = 0, write = 0; for (int read = 0; read < chars.length; read++) { if (read + 1 == chars.length || chars[read + 1] != chars[read]) { chars[write++] = chars[anchor]; if (read > anchor) { for (char c: ("" + (read - anchor + 1)).toCharArray()) { chars[write++] = c; } } anchor = read + 1; } } return write; }

Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space? Example 1: Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer, Integer> indices = new HashMap<>(); for (int i = 0; i < nums.length; i++) { Integer lastIndex = indices.put(nums[i], i); // put returns the previous value associated with key, or null if (lastIndex != null && (i - lastIndex) <= k) return true; } return false; }

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true

public int findPairs(int[] nums, int k) { if (nums == null || nums.length == 0 || k < 0) return 0; Map<Integer, Integer> map = new HashMap<>(); int count = 0; for (int i : nums) { map.put(i, map.getOrDefault(i, 0) + 1); } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (k == 0) { //count how many elements in the array that appear more than twice. if (entry.getValue() >= 2) { count++; } } else { if (map.containsKey(entry.getKey() + k)) { count++; } } } return count; }

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input:[1, 2, 3, 4, 5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

index: 1, 2, 3, ..., n - continuous numbers value: continuous numbers We get value, convert it to index and negate number in that index. Missing numbers will not be converted to indexes and be negated. This is how we know what numbers are missing. public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> result = new ArrayList<>(); for(int i = 0; i < nums.length; i++) { nums[Math.abs(nums[i]) - 1] = -Math.abs(nums[Math.abs(nums[i]) - 1]); } for(int i = 0; i < nums.length; i++) { if(nums[i] >= 0) result.add(i + 1); } return result; }

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6]

public int majorityElement(int[] nums) { int majority = 0; int count = 0; for(int i = 0; i < nums.length; i++) { if(count == 0) { majority = nums[i]; count = 1; } else if(majority == nums[i]) { count++; } else { count--; } } return majority; }

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2

public boolean checkPossibility(int[] nums) { int cnt = 0, n = nums.length; for (int i = 0; i < n - 1; i++) { if (nums[i] > nums[i + 1]) { cnt++; if (i >= 1 && nums[i + 1] < nums[i - 1]) nums[i + 1] = nums[i]; } if (cnt > 1) return false; } return true; }

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element.

public boolean isPowerOfFour(int num) { // we have to convert to double // because for num = 5, int doesn't work double n = num * 1.0; while (n >= 4){ n = n / 4; } return n == 1; }

Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion?

private int[] nums; public NumArray(int[] nums) { for(int i = 1; i < nums.length; i++) nums[i] += nums[i - 1]; this.nums = nums; } public int sumRange(int i, int j) { if(i == 0) return nums[j]; return nums[j] - nums[i - 1]; }

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function.

public int distributeCandies(int[] candies) { //corner case if(candies == null || candies.length == 0){ return 0; } Set<Integer> set = new HashSet<>(); //iteration for(int candy: candies){ if(!set.contains(candy)){ set.add(candy); } } return set.size() > candies.length / 2 ? candies.length / 2 : set.size(); }

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. Example 1: Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies. Example 2: Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.

public boolean isPowerOfThree(int n) { if (n < 1) { return false; } while (n % 3 == 0) { n /= 3; } return n == 1; }

Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false

public boolean isPowerOfTwo(int n) { if(n <= 0) return false; return ( (Integer.bitCount(n) > 1) ? false : true); } 0b001 == 1 0b010 == 2 0b100 == 4 However e.g. 0b011 == 3 So, by definition of binary system, if there is one and only one bit that equals to 1 in the number, then the number is power of 2. Alternatively, that line could be rewritten from return ( (Integer.bitCount(n) >1) ?false:true); to return Integer.bitCount(n) == 1;

Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 2^0 = 1 Example 2: Input: 16 Output: true Explanation: 2^4 = 16 Example 3: Input: 218 Output: false

public List<List<Integer>> levelOrder(Node root) { Queue<Node> toExplore = new LinkedList<>(); List<List<Integer>> result = new ArrayList<>(); if(root == null) return result; toExplore.offer(root); while(!toExplore.isEmpty()) { int size = toExplore.size(); List<Integer> subres = new ArrayList<>(); for(int i = 0; i < size; i++) { Node curr = toExplore.poll(); subres.add(curr.val); List<Node> children = curr.children; for(Node child : children) { toExplore.add(child); } } result.add(subres); } return result; }

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example, given a 3-ary tree: We should return its level order traversal: [ [1], [3,2,4], [5,6] ] Note: The depth of the tree is at most 1000. The total number of nodes is at most 5000.

// iterative public List<Integer> postorder(Node root) { List<Integer> list = new ArrayList<>(); if (root == null) return list; Stack<Node> stack = new Stack<>(); stack.add(root); while(!stack.isEmpty()) { root = stack.pop(); list.add(root.val); for(Node node: root.children) stack.add(node); } Collections.reverse(list); return list; } // recursion public List<Integer> postorder(Node root) { List<Integer> list = new ArrayList<>(); return order(root, list); } public List<Integer> order(Node root, List<Integer> list){ if (root == null) return list; for(Node node: root.children) order(node, list); list.add(root.val); return list; }

Given an n-ary tree, return the postorder traversal of its nodes' values. For example, given a 3-ary tree: Return its postorder traversal as: [5,6,3,2,4,1]. Note: Recursive solution is trivial, could you do it iteratively?

public List<Integer> preorder(Node root) { Stack<Node> toExplore = new Stack<>(); List<Integer> result = new ArrayList<>(); if(root == null) return result; toExplore.push(root); while(!toExplore.isEmpty()) { Node curr = toExplore.pop(); result.add(curr.val); int tempSize = curr.children.size() - 1; while(tempSize >= 0){ toExplore.push(curr.children.get(tempSize)); tempSize--; } } return result; } // recursion public List<Integer> preorder(Node root) { List<Integer> result = new ArrayList<>(); if(root == null) return result; preorder(root, result); return result; } private void preorder(Node root, List<Integer> result) { if(root == null) return; result.add(root.val); for(Node child : root.children) { preorder(child, result); } }

Given an n-ary tree, return the preorder traversal of its nodes' values. For example, given a 3-ary tree: Return its preorder traversal as: [1,3,5,6,2,4]. Note: Recursive solution is trivial, could you do it iteratively?

Select M numbers from N numbers has N * (N-1) * (N-2) * ..... different possible. M elements do multiplication. For this case, select 2 numbers from N numbers has N * (N-1) possible. So does why author use val * (val-1); public int numberOfBoomerangs(int[][] points) { int res = 0; Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < points.length; i++) { for(int j = 0; j < points.length; j++) { if(i == j) continue; int d = getDistance(points[i], points[j]); map.put(d, map.getOrDefault(d, 0) + 1); } for(int val : map.values()) { /* * for all the groups of points, * number of ways to select 2 from n = * nP2 = n!/(n - 2)! = n * (n - 1) */ res += val * (val-1); } map.clear(); } return res; } private int getDistance(int[] a, int[] b) { int dx = a[0] - b[0]; int dy = a[1] - b[1]; return dx * dx + dy * dy; }

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive). Example: Input: [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]

public int[] intersect(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); ArrayList<Integer> result = new ArrayList<Integer>(); for(int i = 0; i < nums1.length; i++) { if(map.containsKey(nums1[i])) map.put(nums1[i], map.get(nums1[i])+1); else map.put(nums1[i], 1); } for(int i = 0; i < nums2.length; i++) { if(map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) { result.add(nums2[i]); map.put(nums2[i], map.get(nums2[i])-1); } } int[] r = new int[result.size()]; for(int i = 0; i < result.size(); i++) { r[i] = result.get(i); } return r; }

Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); List<Integer> intList = new ArrayList<>(); for(int num : nums1) { set.add(num); } for(int num : nums2) { if(set.contains(num)) { set.remove(num); intList.add(num); } } int[] result = new int[intList.size()]; for(int i = 0; i < intList.size(); i++) { result[i] = intList.get(i); } return result; }

Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must be unique. The result can be in any order.

public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if(t1 == null && t2 == null) return null; if(t1 == null && t2 != null) return t2; if(t2 == null && t1 != null) return t1; int sum = 0; if(t1 != null) { sum += t1.val; } if(t2 != null) { sum += t2.val; } TreeNode root = new TreeNode(sum); TreeNode left = mergeTrees(t1.left, t2.left); TreeNode right = mergeTrees(t1.right, t2.right); root.left = left; root.right = right; return root; }

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 Note: The merging process must start from the root nodes of both trees.

public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int carry = 0; int i = num1.length() - 1; int j = num2.length() - 1; while(i >= 0 || j >= 0) { int sum = 0; if(i >= 0) { sum += Integer.parseInt(String.valueOf(num1.charAt(i))); } if(j >= 0) { sum += Integer.parseInt(String.valueOf(num2.charAt(j))); } i--; j--; sum += carry; carry = sum / 10; sb.append(sum % 10 + ""); } if(carry != 0){ sb.append(carry); } return sb.reverse().toString(); }

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.

public boolean backspaceCompare(String S, String T) { Stack<Character> stack1 = new Stack<>(); Stack<Character> stack2 = new Stack<>(); for(int i = 0; i < S.length(); i++) { char c = S.charAt(i); if(c == '#') { if(!stack1.isEmpty()) stack1.pop(); } else stack1.push(c); } for(int j = 0; j < T.length(); j++) { char c = T.charAt(j); if(c == '#') { if(!stack2.isEmpty()) stack2.pop(); } else stack2.push(c); } if(stack1.size() != stack2.size()) return false; while(!stack1.isEmpty() && !stack2.isEmpty()) { if(stack1.pop() != stack2.pop()) return false; } return true; }

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b".

public char findTheDifference(String s, String t) { char[] map = new char[26]; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); map[c - 'a']++; } for(int i = 0; i < t.length(); i++) { char c = t.charAt(i); map[c - 'a']--; } for(int i = 0; i < t.length(); i++) { char c = t.charAt(i); if(map[c - 'a'] > 0) { return c; } } return ' '; }

Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.

public boolean isIsomorphic(String s, String t) { if(s == null && t == null) return true; if(s.length() == 0 && t.length() == 0) return true; Map<Character, Character> map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { char c1 = s.charAt(i); char c2 = t.charAt(i); if(map.containsKey(c1)) { if(c2 != map.get(c1)) return false; } else { if(map.containsValue(c2)) return false; map.put(c1, c2); } } return true; }

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false

public int mySqrt(int x) { if (x < 0) throw new IllegalArgumentException("Cannot obtain an integer root of a negative number!"); if (x < 2) return x; int left = 1, right = x/2; while (left <= right) { int mid = left + (right - left)/2; if (mid > x/mid) { right = mid - 1; } else if (mid == x/mid) { return mid; } else { left = mid + 1; } } return right; }

Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example 1: Input: 4 Output: 2

public boolean canWinNim(int n) { return n % 4 != 0; }

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. Example: Input: 4 Output: false Explanation: If there are 4 stones in the heap, then you will never win the game; No matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

// iterative public TreeNode invertTree(TreeNode root) { if(root == null) return null; if(root.left == null && root.right == null) return root; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()) { TreeNode curr = queue.remove(); TreeNode tmp = curr.left; curr.left = curr.right; curr.right = tmp; if(curr.right != null) { queue.add(curr.right); } if(curr.left != null) { queue.add(curr.left); } } return root; } // recursive public TreeNode invertTree(TreeNode root) { if(root == null) return null; TreeNode leftNode = invertTree(root.left); TreeNode rightNode = invertTree(root.right); root.left = rightNode; root.right = leftNode; return root; }

Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so f*** off.

public int peakIndexInMountainArray(int[] A) { int lo = 0; int hi = A.length - 1; while(lo <= hi) { int mid = lo + (hi - lo) / 2; if(A[mid] > A[mid - 1] && A[mid] > A[mid + 1]) return mid; else if(A[mid] > A[mid - 1] && A[mid] < A[mid + 1]) { lo = mid + 1; } else if(A[mid] < A[mid - 1] && A[mid] > A[mid + 1]) { hi = mid - 1; } } return -1; }

Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. Example 1: Input: [0,1,0] Output: 1 Example 2: Input: [0,2,1,0] Output: 1

public int romanToInt(String s) { Map<Character, Integer> map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); char[] chars = s.toCharArray(); int result = 0; int i = 0; for(int j = 1; j < chars.length; i++, j++) { if (map.get(chars[i]) >= map.get(chars[j])) { result += map.get(chars[i]); } else { result -= map.get(chars[i]); } } result += map.get(chars[i]); return result; }

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Example 1: Input: "III" Output: 3

// The logic to solve this problem is same as "max subarray problem" using Kadane's Algorithm public int maxProfit(int[] prices) { if(prices == null || prices.length <= 1) return 0; int min = prices[0]; int profit = 0; for(int i = 1; i < prices.length; i++) { min = Math.min(prices[i], min); profit = Math.max(profit, prices[i] - min); } return profit; }

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.

public String[] findRestaurant(String[] list1, String[] list2) { Map<String, Integer> map = new HashMap<>(); for(int i = 0; i < list1.length; i++) { map.put(list1[i], i); } List<String> tmp = new ArrayList<>(); int min = Integer.MAX_VALUE; for(int i = 0; i < list2.length; i++) { if(map.containsKey(list2[i])) { if(map.get(list2[i]) + i < min) { tmp.clear(); tmp.add(list2[i]); min = map.get(list2[i]) + i; } else if(map.get(list2[i]) + i == min) { tmp.add(list2[i]); } } } String[] result = new String[tmp.size()]; return tmp.toArray(result); }

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. Example 1: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun".

public String countAndSay(int n) { if (n == 1) { return "1"; } final String s = countAndSay(n - 1); StringBuilder builder = new StringBuilder(); char say = s.charAt(0); int count = 1; for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (c == say) { count++; } else { builder.append(count).append(say); count = 1; say = c; } } builder.append(count).append(say); return builder.toString(); }

The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Example 2: Input: 4 Output: "1211"

public String[] uncommonFromSentences(String A, String B) { Map<String, Integer> count = new HashMap(); for (String word: A.split(" ")) count.put(word, count.getOrDefault(word, 0) + 1); for (String word: B.split(" ")) count.put(word, count.getOrDefault(word, 0) + 1); List<String> ans = new LinkedList(); for (String word: count.keySet()) if (count.get(word) == 1) ans.add(word); return ans.toArray(new String[ans.size()]); }

We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.) A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Return a list of all uncommon words. You may return the list in any order. Example 1: Input: A = "this apple is sweet", B = "this apple is sour" Output: ["sweet","sour"] Example 2: Input: A = "apple apple", B = "banana" Output: ["banana"]

public int guessNumber(int n) { int lo = 1; int hi = n; while(lo <= hi) { int mid = lo + (hi - lo) / 2; if(guess(mid) < 0) { hi = mid - 1; } else if(guess(mid) > 0) { lo = mid + 1; } else return mid; } return -1; }

We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): -1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! Example : Input: n = 10, pick = 6 Output: 6

The idea is to leverage decent Arrays.binarySearch() function provided by Java. For each house, find its position between those heaters (thus we need the heaters array to be sorted). Calculate the distances between this house and left heater and right heater, get a MIN value of those two values. Corner cases are there is no left or right heater. Get MAX value among distances in step 2. It's the answer. Time complexity: max(O(nlogn), O(mlogn)) - m is the length of houses, n is the length of heaters. public int findRadius(int[] houses, int[] heaters) { Arrays.sort(heaters); int result = Integer.MIN_VALUE; for (int house : houses) { int index = Arrays.binarySearch(heaters, house); if (index < 0) { index = -(index + 1); } int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE; int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE; result = Math.max(result, Math.min(dist1, dist2)); } return result; }

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters. Note: Numbers of houses and heaters you are given are non-negative and will not exceed 25000. Positions of houses and heaters you are given are non-negative and will not exceed 10^9. As long as a house is in the heaters' warm radius range, it can be warmed. All the heaters follow your radius standard and the warm radius will the same. Example 1: Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

public String reverseVowels(String s) { char[] charArray = s.toCharArray(); int i = 0; int j = charArray.length-1; while(i <= j) { while (i <= j && !isVowel(s.charAt(i))) { i++; } while (i <= j && !isVowel(s.charAt(j))) { j--; } if (i > j) { break; } char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; i++; j--; } return new String(charArray); } private boolean isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); }

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello" Output: "holle" Example 2: Input: "leetcode" Output: "leotcede" Note: The vowels does not include the letter "y".

public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; }

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: 4 -> 5 -> 1 -> 9 Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

public boolean isUgly(int num) { if (num == 0) return false; if (num == 1) return true; while (num % 2 == 0){ num = num / 2; } while (num % 3 == 0){ num = num / 3; } while (num % 5 == 0){ num = num / 5; } return num == 1; }

Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example 1: Input: 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: 8 Output: true Explanation: 8 = 2 × 2 × 2 Example 3: Input: 14 Output: false Explanation: 14 is not ugly since it includes another prime factor 7.

public boolean isHappy(int n) { Set<Integer> visited = new HashSet<>(); Queue<Integer> toExplore = new LinkedList<>(); toExplore.add(n); visited.add(n); while(!toExplore.isEmpty()) { int sum = getDigSum(toExplore.poll() + ""); if(sum == 1) return true; if(visited.contains(sum)) return false; toExplore.add(sum); visited.add(sum); } return false; } private int getDigSum(String s) { int result = 0; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); result += (int) Math.pow(c - '0', 2); } return result; }

Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1

public int firstBadVersion(int n) { int lo = 0; int hi = n; while(lo <= hi) { int mid = lo + (hi - lo) / 2; if(isBadVersion(mid)) { hi = mid - 1; } else if(!isBadVersion(mid)) { lo = mid + 1; } } return lo; }

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example: Given n = 5, and version = 4 is the first bad version. call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.

// recursive public int rob(int[] nums) { return rob(nums, nums.length - 1); } private int rob(int[] nums, int hi) { if(hi < 0) return 0; return Math.max(rob(nums, hi - 1), rob(nums, hi - 2) + nums[hi]); } // recursion + memo private int[] memo; public int rob(int[] nums) { memo = new int[nums.length]; Arrays.fill(memo, -1); return rob(nums, nums.length - 1); } private int rob(int[] nums, int hi) { if(hi < 0) { return 0; } if(memo[hi] >= 0) return memo[hi]; memo[hi] = Math.max(rob(nums, hi - 1), rob(nums, hi - 2) + nums[hi]); return memo[hi]; } // Iterative + memo (bottom-up) public int rob(int[] nums) { if (nums.length == 0) return 0; int[] memo = new int[nums.length + 1]; memo[0] = 0; memo[1] = nums[0]; for (int i = 1; i < nums.length; i++) { int val = nums[i]; memo[i+1] = Math.max(memo[i], memo[i-1] + val); } return memo[nums.length]; } // Iterative + 2 variables (bottom-up) /* the order is: prev2, prev1, num */ public int rob(int[] nums) { if (nums.length == 0) return 0; int prev1 = 0; int prev2 = 0; for (int num : nums) { int tmp = prev1; prev1 = Math.max(prev2 + num, prev1); prev2 = tmp; } return prev1; }

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.

public int pathSum(TreeNode root, int sum) { if (root == null) return 0; return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } private int pathSumFrom(TreeNode node, int sum) { if (node == null) return 0; return (node.val == sum ? 1 : 0) + pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val); }

You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. Example: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11

public int islandPerimeter(int[][] grid) { int count = 0; for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { if(grid[i][j] == 1) { if(i - 1 < 0 || grid[i - 1][j] == 0) count++; if(i + 1 >= grid.length || grid[i + 1][j] == 0) count++; if(j - 1 < 0 || grid[i][j - 1] == 0) count++; if(j + 1 >= grid[0].length || grid[i][j + 1] == 0) count++; } } } return count; }

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:

public boolean checkRecord(String s) { int countA = 1; int countL = 2; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); // count As if(c == 'A') countA--; // count Ls if(c == 'L') { countL--; } else countL = 2; if(countA < 0 || countL < 0) return false; } return true; }

You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : Absent. 'L' : Late. 'P' : Present. A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). You need to return whether the student could be rewarded according to his attendance record. Example 1: Input: "PPALLP" Output: True

public int[] nextGreaterElement(int[] nums1, int[] nums2) { if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) return new int[0]; Stack<Integer> stack = new Stack<>(); Map<Integer, Integer> map = new HashMap<>(); for(int num : nums2) { while(!stack.isEmpty() && num > stack.peek()) { map.put(stack.pop(), num); } stack.push(num); } while(!stack.isEmpty()) { map.put(stack.pop(), -1); } int[] result = new int[nums1.length]; int i = 0; for(int num : nums1) { result[i++] = map.get(num); } return result; }

You are given two arrays (without duplicates) nums1 and nums2 where nums1's elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

public int arrangeCoins(int n) { int i = 1; int coins = n; int result = 0; for(int j = 0; j < n; j++) { if(coins >= i) { coins -= i; result++; } else if(coins < i) break; i++; } return result; }

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3.

public String tree2str(TreeNode t) { if(t==null) return ""; if(t.left==null && t.right==null) return t.val+""; if(t.right==null) return t.val+"("+tree2str(t.left)+")"; return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")"; }

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. Example 1: Input: Binary tree: [1,2,3,4] 1 / \ 2 3 / 4 Output: "1(2(4))(3)" Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)". Example 2: Input: Binary tree: [1,2,3,null,4] 1 / \ 2 3 \ 4 Output: "1(2()(4))(3)" Explanation: Almost the same as the first example, except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

public int numJewelsInStones(String J, String S) { Set<Character> jewels = new HashSet<>(); for(int i = 0; i < J.length(); i++) { jewels.add(J.charAt(i)); } int counter = 0; for(int i = 0; i < S.length(); i++) { if(jewels.contains(S.charAt(i))) counter++; } return counter; }

You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3 Example 2: Input: J = "z", S = "ZZ" Output: 0


Conjuntos de estudio relacionados

Symptoms of Right and Left Sided Heart Failure

View Set

3 Domains/6 Kingdoms of Life (EXTENDED)

View Set

FINN 3120 Exam 4: Reading Questions

View Set