LeetCode - Amazon

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

49. Group Anagrams Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lower-case.

https://leetcode.com/problems/group-anagrams/description/ Medium

661. Image Smoother

https://leetcode.com/problems/image-smoother/description/ Easy

617. Merge Two Binary Trees

https://leetcode.com/problems/merge-two-binary-trees/description/ Easy

146. LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. Follow up: Could you do both operations in O(1) time complexity?

L Hard class Node { int key; int value; Node prev; Node next; public Node(int key, int value) { this.key = key; this.value = value; } @Override public String toString() { return "Node{" + "key=" + key + ", value=" + value + '}'; } } private final int capacity; private Map<Integer, Node> cache = new HashMap<>(); private Node head, tail; public LRUCache(int capacity) { this.capacity = capacity; this.head = new Node(0, 0); this.tail = new Node(0, 0); this.head.next = tail; this.tail.prev = head; } public int get(int key) { Node node = cache.get(key); if (node == null) { return -1; } removeNode(node); appendNode(node); return node.value; } public void put(int key, int value) { Node node = cache.get(key); if (node != null) { removeNode(node); node.value = value; } else { if (cache.size() == capacity) { node = removeLru(); cache.remove(node.key); System.out.println("remove node: " + node); } node = new Node(key, value); cache.put(key, node); } appendNode(node); } private void removeNode(Node node) { node.prev.next = node.next; node.next.prev = node.prev; } private void appendNode(Node node) { tail.prev.next = node; node.prev = tail.prev; node.next = tail; tail.prev = node; } private Node removeLru() { Node node = head.next; head.next = node.next; node.next.prev = head; return node; } @Override public String toString() { return "LRUCache{" + "capacity=" + capacity + ", cache=" + cache + '}'; }

186. Reverse Words in a String II Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. The input string does not contain leading or trailing spaces and the words are always separated by a single space. For example, Given s = "the sky is blue", return "blue is sky the". Could you do it in-place without allocating extra space?

Locked

579. Find Cumulative Salary of an Employee

Locked

663. Equal Tree Partition

Locked

694. Number of Distinct Islands

Locked

711. Number of Distinct Islands II

Locked

42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

https://leetcode.com/problems/trapping-rain-water/description/ Hard

545. Boundary of Binary Tree Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root.Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes. Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees. The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node. The right-most node is also defined by the same way with left and right exchanged. Example 1 Input: 1 \ 2 / \ 3 4 Ouput: [1, 3, 4, 2] Explanation: The root doesn't have left subtree, so the root itself is left boundary. The leaves are node 3 and 4. The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary. So order them in anti-clockwise without duplicates and we have [1,3,4,2]. Example 2 Input: ____1_____ / \ 2 3 / \ / 4 5 6 / \ / \ 7 8 9 10 Ouput: [1,2,4,7,8,9,10,6,3]

http://www.cnblogs.com/dongling/p/6622312.html Locked

15. 3Sum Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]

https://leetcode.com/problems/3sum/description/ Medium

2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

https://leetcode.com/problems/add-two-numbers/description/ Medium public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode sum = null, l1Ptr = l1, l2Ptr = l2, last = null, current; int value1 = 0, value2 = 0, digit = 0; while (true) { if (l1Ptr == null && l2Ptr == null && digit == 0) { break; } if (l1Ptr != null) { value1 = l1Ptr.val; l1Ptr = l1Ptr.next; } else { value1 = 0; } if (l2Ptr != null) { value2 = l2Ptr.val; l2Ptr = l2Ptr.next; } else { value2 = 0; } int result = value1 + value2 + digit; digit = result / 10; current = new ListNode(result%10); if (last == null) { sum = current; } else { last.next = current; } last = current; } return sum; }

682. Baseball Game

https://leetcode.com/problems/baseball-game/description/ Easy

121. Best Time to Buy and Sell Stock 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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) Example 2: Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ Easy

199. Binary Tree Right Side View Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example: Given the following binary tree, 1 <--- / \ 2 3 <--- \ \ 5 4 <--- You should return [1, 3, 4].

https://leetcode.com/problems/binary-tree-right-side-view/description/ Medium

537. Complex Number Multiplication

https://leetcode.com/problems/complex-number-multiplication/description/ Medium

538. Convert BST to Greater Tree

https://leetcode.com/problems/convert-bst-to-greater-tree/description/ Easy

138. Copy List with Random Pointer A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list.

https://leetcode.com/problems/copy-list-with-random-pointer/description/ Medium

204. Count Primes Description: Count the number of prime numbers less than a non-negative number, n.

https://leetcode.com/problems/count-primes/description/ Easy

675. Cut Off Trees for Golf Event

https://leetcode.com/problems/cut-off-trees-for-golf-event/description/ Hard

534. Design TinyURL

https://leetcode.com/problems/design-tinyurl/description/ Medium

355. Design Twitter

https://leetcode.com/problems/design-twitter/description/ Medium

438. Find All Anagrams in a String . *** 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". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab".

https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ Easy

387. First Unique Character in a String 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.

https://leetcode.com/problems/first-unique-character-in-a-string/description/ Easy

89. Gray Code The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 00 - 0 01 - 1 11 - 3 10 - 2 Note: For a given n, a gray code sequence is not uniquely defined. For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

https://leetcode.com/problems/gray-code/description/ Medium

380. Insert Delete GetRandom O(1) Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. Example: // Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomSet.insert(1); // Returns false as 2 does not exist in the set. randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomSet.insert(2); // getRandom should return either 1 or 2 randomly. randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. randomSet.remove(1); // 2 was already in the set, so return false. randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. randomSet.getRandom();

https://leetcode.com/problems/insert-delete-getrandom-o1/description/ Medium

160. Intersection of Two Linked Lists Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 begin to intersect at node c1. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory.

https://leetcode.com/problems/intersection-of-two-linked-lists/description/ Easy

532. K-diff Pairs in an Array

https://leetcode.com/problems/k-diff-pairs-in-an-array/description/ Easy

215. Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k is always valid, 1 ≤ k ≤ array's length.

https://leetcode.com/problems/kth-largest-element-in-an-array/description/ Medium

17. Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. 2-abc, 3-def, 4-ghi, 5-jkl, 6-mno, 7-pqrs, 8-tuv, 9-wxyz, 0-_ Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ Medium

141. Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space?

https://leetcode.com/problems/linked-list-cycle/description/ Easy

516. Longest Palindromic Subsequence

https://leetcode.com/problems/longest-palindromic-subsequence/description/ Medium

5. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example: Input: "cbbd" Output: "bb"

https://leetcode.com/problems/longest-palindromic-substring/description/ Medium private int start, maxLen; public String longestPalindrome(String s) { int len = s.length(); if (len < 2) { return s; } for (int i = 0; i < len-1; i++) { findPalindrome(s, i, i); // Palindrome with odd length findPalindrome(s, i, i+1); // Palindrome with even length. } return s.substring(start, start + maxLen); } private void findPalindrome(String s, int down, int up) { while (down >= 0 && up < s.length() && s.charAt(down) == s.charAt(up)) { down--; up++; } int len = up - down - 1; if (maxLen < len) { start = down + 1; // roll back to the beginning of the polindrome maxLen = len; } }

3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ Medium public int lengthOfLongestSubstring(String s) { if (s.length() <= 1) return s.length(); int max = 0; int start = 0, foundAt, len; for (int i = 0; i < s.length(); i++) { foundAt = s.substring(start, i).indexOf(s.charAt(i)); if (foundAt >= 0) { len = i - start; start = start + foundAt + 1; max = len > max ? len : max; } } len = s.length() - start; max = len > max ? len : max; return max; }

235. Lowest Common Ancestor of a Binary Search Tree 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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself)." _______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5 For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ Easy

236. Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself)." _______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4 For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ Medium

646. Maximum Length of Pair Chain

https://leetcode.com/problems/maximum-length-of-pair-chain/description/ Medium

662. Maximum Width of Binary Tree

https://leetcode.com/problems/maximum-width-of-binary-tree/description/ Medium

23. Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

https://leetcode.com/problems/merge-k-sorted-lists/description/ Hard

155. Min Stack Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.

https://leetcode.com/problems/min-stack/description/ Easy

529. Minesweeper Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine. Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules: If a mine ('M') is revealed, then the game is over - change it to 'X'. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed. Example 1: Input: [['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'M', 'E', 'E'], ['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E']] Click : [3,0] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Explanation: Example 2: Input: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Click : [1,2] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'X', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Explanation: Note: The range of the input matrix's height and width is [1,50]. The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square. The input board won't be a stage when game is over (some mines have been revealed). For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.

https://leetcode.com/problems/minesweeper/description/ Medium

738. Monotone Increasing Digits

https://leetcode.com/problems/monotone-increasing-digits/description/ Medium

508. Most Frequent Subtree Sum

https://leetcode.com/problems/most-frequent-subtree-sum/description/ Medium

200. Number of Islands Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3

https://leetcode.com/problems/number-of-islands/description/ Medium private int width; private int height; public int numIslands(char[][] grid) { int count = 0; if (grid.length == 0 || grid[0].length == 0) { return count; } width = grid[0].length; height = grid.length; for (int i = 0; i < height; i++) { for (int j = 0 ; j < width; j++) { if (grid[i][j] == '1') { mark(grid, i, j); count++; } } } return count; } private void mark(char[][] grid, int i, int j) { if (i < 0 || i >= height || j < 0 || j >= width || grid[i][j] == '0') { return; } grid[i][j] = '0'; mark(grid, i, j+1); mark(grid, i, j-1); mark(grid, i + 1, j); mark(grid, i - 1, j); }

553. Optimal Division Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4. However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis. Example: Input: [1000,100,10,2] Output: "1000/(100/10/2)" Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/((100/10)/2)" are redundant, since they don't influence the operation priority. So you should return "1000/(100/10/2)". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 Note: The length of the input array is [1, 10]. Elements in the given array will be in range [2, 1000]. There is only one optimal division for each test case.

https://leetcode.com/problems/optimal-division/description/ Medium

234. Palindrome Linked List Given a singly linked list, determine if it is a palindrome. Palindrome: a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction.

https://leetcode.com/problems/palindrome-linked-list/description/ Easy

238. Product of Array Except Self Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Follow up: Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

https://leetcode.com/problems/product-of-array-except-self/description/ Medium

459. Repeated Substring Pattern

https://leetcode.com/problems/repeated-substring-pattern/description/ Easy

206. Reverse Linked List Reverse a singly linked list.

https://leetcode.com/problems/reverse-linked-list/description/ Easy

189. Rotate Array Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

https://leetcode.com/problems/rotate-array/description/ Easy

396. Rotate Function

https://leetcode.com/problems/rotate-function/description/ Medium

48. Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Example 2: Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ]

https://leetcode.com/problems/rotate-image/description/ Medium private int n; public void rotate(int[][] matrix) { if (matrix == null || matrix.length <= 1) { return; } n = matrix.length; swapLayer(matrix); flip(matrix); } private void swapLayer(int[][] matrix) { int[] tmp; for (int i = 0; i < n / 2; i++) { tmp = matrix[i]; matrix[i] = matrix[n - i - 1]; matrix[n - i - 1] = tmp; } } private void flip(int[][] matrix) { int tmp; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { System.out.println("i = " + i + "; j = " + j); tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } }

240. Search a 2D Matrix II Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. For example, Consider the following matrix: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true. Given target = 20, return false.

https://leetcode.com/problems/search-a-2d-matrix-ii/description/ Medium

297. Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. For example, you may serialize the following tree 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/ Hard

449. Serialize and Deserialize BST Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

https://leetcode.com/problems/serialize-and-deserialize-bst/description/ Medium

73. Set Matrix Zeroes Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution?

https://leetcode.com/problems/set-matrix-zeroes/description/ Medium

645. Set Mismatch

https://leetcode.com/problems/set-mismatch/description/ Easy

239. Sliding Window Maximum Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Therefore, return the max sliding window as [3,3,5,5,6,7]. Note: You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. Follow up: Could you solve it in linear time?

https://leetcode.com/problems/sliding-window-maximum/description/ Hard

640. Solve the Equation

https://leetcode.com/problems/solve-the-equation/description/ Medium

725. Split Linked List in Parts

https://leetcode.com/problems/split-linked-list-in-parts/description/ Medium

8. String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. In Java, the integer ranges from -2,147,483,648 to +2,147,483,647

https://leetcode.com/problems/string-to-integer-atoi/description/ Medium public int myAtoi(String str) { if (str.length() == 0) { return 0; } int sign = 1, base = 0, i = 0; while (str.charAt(i) == ' ') { i++; } if (str.charAt(i) == '-') { sign = -1; i++; } else if (str.charAt(i) == '+') { i++; } int threshold = Integer.MAX_VALUE / 10, digit; while (i < str.length() &&str.charAt(i) >= '0' && str.charAt(i) <= '9') { digit = str.charAt(i++) - '0'; if (base > threshold || base == threshold && digit > 7) { if (sign == 1) { return Integer.MAX_VALUE; } else { return Integer.MIN_VALUE; } } base = 10 * base + digit; } return base * sign; }

78. Subsets Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

https://leetcode.com/problems/subsets/description/ Medium

517. Super Washing Machines You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time . Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1. Example1 Input: [1,0,5] Output: 3 Explanation: 1st move: 1 0 <-- 5 => 1 1 4 2nd move: 1 <-- 1 <-- 4 => 2 1 3 3rd move: 2 1 <-- 3 => 2 2 2 Example2 Input: [0,3,0] Output: 2 Explanation: 1st move: 0 <-- 3 0 => 1 2 0 2nd move: 1 2 --> 0 => 1 1 1 Example3 Input: [0,2,0] Output: -1 Explanation: It's impossible to make all the three washing machines have the same number of dresses. Note: The range of n is [1, 10000]. The range of dresses number in a super washing machine is [0, 1e5].

https://leetcode.com/problems/super-washing-machines/description/ Hard

414. Third Maximum Number

https://leetcode.com/problems/third-maximum-number/description/ Easy

692. Top K Frequent Words

https://leetcode.com/problems/top-k-frequent-words/description/ Medium

167. Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ Easy

1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

https://leetcode.com/problems/two-sum/description/ Easy public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> numMap = new HashMap<>(); int other; for (int i = 0; i < nums.length; i++) { other = target - nums[i]; if (numMap.containsKey(other)) { return new int[] {numMap.get(other), i}; } numMap.put(nums[i], i); } return new int[] {}; }

242. Valid Anagram Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

https://leetcode.com/problems/valid-anagram/description/ Easy if (s == null || t == null) { return false; } if (s.length() == 0 && t.length() == 0) { return true; } if (s.length() != t.length()) { return false; } Map<Character, Integer> map = new HashMap<>(); Integer count; Character ch; for (int i = 0; i < s.length(); i++) { ch = s.charAt(i); count = map.get(ch); if (count == null) { map.put(ch, 1); } else { map.put(ch, count + 1); } } for (int i = 0; i < s.length(); i++) { ch = t.charAt(i); count = map.get(ch); if (count == null || count == 0) { return false; } if (--count == 0) { map.remove(ch); } else { map.put(ch, count); } } if (map.isEmpty()) { return true; } return false;

20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

https://leetcode.com/problems/valid-parentheses/description/ Easy Map<String, String> matchMap = new HashMap<>(); private Map<String, String> getMatchMap() { if (matchMap.isEmpty()) { matchMap.put(")", "("); matchMap.put("]", "["); matchMap.put("}", "{"); } return matchMap; } public boolean isValid(String s) { Stack<String> stack = new Stack<>(); String token, match, poped; for (int i = 0; i < s.length(); i ++) { token = String.valueOf(s.charAt(i)); match = getMatchMap().get(token); if (match == null) { stack.push(token); } else if (stack.isEmpty()) { // stack is empty return false; } else { poped = stack.pop(); if (!match.equals(poped)) { return false; } } } return stack.isEmpty(); }

139. Word Break Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code".

https://leetcode.com/problems/word-break/description/ Medium

126. Word Ladder II Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the word list. Note that beginWord is not a transformed word. For example, Given: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"] Return [ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ] Note: Return an empty list if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same.

https://leetcode.com/problems/word-ladder-ii/description/ Hard

127. Word Ladder Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transformed word. For example, Given: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"] As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5. Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same.

https://leetcode.com/problems/word-ladder/description/ Medium

451. Sort Characters By Frequency

p459 Medium


Ensembles d'études connexes

Ch 46, Brunners CH 46 Gastric and Duodenal Disorders, Chapter 45: Caring for Clients with Disorders of the Upper Gastrointestinal Tract, GI Pharm Practice Questions, Med Surg Chapter 23: Nursing Management: Patients With Gastric and Duodenal Disorder...

View Set

Lesson 18 In-Class Quiz & Self-Assessment

View Set

Accounting 1 - Quiz over Purchases and Sales JE

View Set

Digital Skills for the Workplace Final Exam

View Set