LeetCode - Amazon

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

98. Validate Binary Search Tree

In order traversal and check if arraylist is sorted or not

663. Equal Tree Partition

Locked

138. Copy List with Random Pointer

Make a map to store the Node . new Node combination. HashMap<Node, Node> map = new HashMap<>(); Node curr = head; while(curr!= null){ map.put(curr, new Node(curr.val)); curr = curr.next; } curr = head; while(curr!=null){ map.get(curr).next = map.get(curr.next); map.get(curr).random = map.get(curr.random); curr = curr.next; } return map.get(head);

53. Maximum Subarray

class Solution { public int maxSubArray(int[] nums) { int max_sum = nums[0]; for(int i =1; i < nums.length; i++){ if(nums[i-1] > 0) nums[i]+=nums[i-1]; max_sum = Math.max(nums[i], max_sum); } return max_sum; } }

661. Image Smoother

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

532. K-diff Pairs in an Array

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

645. Set Mismatch

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

640. Solve the Equation

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

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

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

5. Longest Palindromic Substring

if middle is palindrome, extreme ends are matching then its palindrome. Fill base condition dp[i][i] as true (starting with i and ending at i - 1 length char) and two size strings (starting at i, ending at i+1) Only consider upper or bottom half of n*n dp matrix. (as dp[i][j] = dp[j][i]) str[i] == str[j] && dp[i+1][j-1] int n = s.length(); boolean[][] dp = new boolean[n][n]; String result = ""; for(int i = n - 1; i >= 0; i--){ for(int j = i; j < n; j++){ dp[i][j] = (i == j) || (s.charAt(i) == s.charAt(j) && (((j-i) < 3) || dp[i+1][j-1])); if(dp[i][j] && result.length() < (j -i + 1)) result = s.substring(i,j+1); } } return result;

Reorder Data in Log Files

new PriorityQueue<>(Comparator.comparing((Data d) -> d.val).thenComparing(d -> d.key)); String[] words = log.split(" ", 2); // at max split 2

451. Sort Characters By Frequency

p459 Medium

Partition Labels (Break into max possible chunks)

A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. 2 pointers, greedy Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] a -> max occurence (map) split class Solution { public List<Integer> partitionLabels(String S) { char[] array = S.toCharArray(); int[] last = new int[26]; for (int i = 0; i < array.length; ++i) last[array[i] - 'a'] = i; List<Integer> result = new ArrayList<Integer>(); for(int i = 0, curr_max = 0, prev_max = 0; i < array.length; i++){ int local_max = last[array[i] -'a']; if(local_max > curr_max) curr_max = local_max; if(curr_max == i){ result.add(i+1 - prev_max); prev_max = i+1; } } return result; } }

994. Rotting Oranges

BFS from every rotten orange and use counter for ones to break if no fresh orange is left int[][] direction = new int[][]{{0,1}, {0,-1}, {1,0}, {-1,0}}; Queue<Point> q = new LinkedList<Point>(); int ones = 0; for(int i =0; i< grid.length; i++){ for(int j =0; j< grid[0].length; j++){ if(grid[i][j] == 2) q.add(new Point(i,j)); if(grid[i][j] == 1) ones++; } } int result = 0; while(!q.isEmpty()){ if(ones == 0) break; int size = q.size();

572. Subtree of Another Tree

Check if its same or left is same of right is same public boolean isSubtree(TreeNode s, TreeNode t) { if(s == null && t == null) return true; if(s == null || t == null) return false; return isSame(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t); } public boolean isSame(TreeNode s, TreeNode t) { if(s == null && t == null) return true; if(s == null || t == null) return false; return s.val == t.val && isSame(s.left, t.left) && isSame(s.right, t.right); }

221. Maximal Square

Check left and up cell and lefup cell to decide the current cell value dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1; public class Solution { public int maximalSquare(char[][] matrix) { int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0; int[][] dp = new int[rows + 1][cols + 1]; int maxsqlen = 0; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { if (matrix[i-1][j-1] == '1'){ dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1; maxsqlen = Math.max(maxsqlen, dp[i][j]); } } } return maxsqlen * maxsqlen; } }

863. All Nodes Distance K in Binary Tree

Convert tree to graph and dfs for K

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

DFS from each non zero and make 1 to 0 (visited) 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); }

545. Boundary of Binary Tree

Left, append children, append right For left.. keep going left if left exists otherwise go right (if it exist) and vice-versa for right public List<Integer> boundaryOfBinaryTree(TreeNode root) { if(root == null) return nodes; nodes.add(root.val); if(root.left == null && root.right == null) return nodes; leftBoundary(root.left); leaves(root); rightBoundary(root.right); return nodes; } public void leftBoundary(TreeNode root) { if(root == null || (root.left == null && root.right == null)) return; nodes.add(root.val); if(root.left == null) leftBoundary(root.right); else leftBoundary(root.left); } public void rightBoundary(TreeNode root) { if(root == null || (root.right == null && root.left == null)) return; if(root.right == null)rightBoundary(root.left); else rightBoundary(root.right); nodes.add(root.val); // add after child visit(reverse) } public void leaves(TreeNode root) { if(root == null) return; if(root.left == null && root.right == null) { nodes.add(root.val); return; } leaves(root.left); leaves(root.right); }

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

694. Number of Distinct Islands

Locked

711. Number of Distinct Islands II

Locked

266. Palindrome Permutation

Map and if it contains 2s and 1s at max 1 time.. it can be palindrome

973. K Closest Points to Origin

PriorityQueue<Point> q = new PriorityQueue<Point>(Comparator.comparing((Point p) -> p.dist)); for(int i =0; i < points.length; i++){ q.offer(new Point(distance(points[i][0], points[i][1]), points[i])); }

692. Top K Frequent Words

Put in q and pop it PriorityQueue<Word> sorted = new PriorityQueue<>(Comparator.comparing((Word w) -> w.val).reversed().thenComparing(w -> w.s)); for(String word: words) map.put(word, map.getOrDefault(word, 0) + 1); for(Map.Entry<String, Integer> entry: map.entrySet()){ sorted.add(new Word(entry.getKey(), entry.getValue())); }

74. Search a 2D Matrix

Search as if its a single array . Apply Binary search for m*n matrix. Note: Log(m*n) = Log(m) + log(n) row = index/n and col = index%n (n is col length) public boolean searchMatrix(int[][] matrix, int target) { if(matrix ==null || matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length; // no of rows int n = matrix[0].length; // no if cols int start = 0, end = m*n-1; while(start <= end){ int mid = (start+end)/2; int elem = matrix[mid/n][mid % n]; if(elem == target){ return true; } else if(elem > target){ end = mid-1; } else{ start = mid+1; } } return false; }

287. Find the Duplicate Number

Sort and check duplicate

253. Meeting Rooms II

Sort the slots by start time. Add their end times to queue and keep updating the end time. Count on queue is total count. PriorityQueue<Integer> queue = new PriorityQueue<>(); ArrayList<Slot> slots = new ArrayList<Slot>(); for(int[] slot: intervals){ slots.add(new Slot(slot[0], slot[1])); } Collections.sort(slots, Comparator.comparing((Slot s) -> s.start)); //[5 -> 10, 15 -> 20, 0 -> 30] queue.add(slots.remove(0).end); for(Slot slot: slots){ if(slot.start >= queue.peek()){ queue.poll(); queue.add(slot.end); } else{ queue.add(slot.end); } } return queue.size();

151. Reverse Words in a String

Split and collection.reverse class Solution { public String reverseWords(String s) { String[] arr = s.strip().split("\\s+"); Collections.reverse(Arrays.asList(arr)); return Arrays.toString(arr).replace(", ", " ").replace("[", "").replace("]", ""); } }

240. Search a 2D Matrix II

Start from bottom left and keep tracking to target. If number encountered is less, go right and if its more, go up. class Solution { public boolean searchMatrix(int[][] matrix, int target) { // start our "pointer" in the bottom-left int row = matrix.length-1; int col = 0; while (row >= 0 && col < matrix[0].length) { if (matrix[row][col] > target) { row--; } else if (matrix[row][col] < target) { col++; } else { // found it return true; } } return false; } }

819. Most Common Word

String [] words = paragraph.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase().split("\\s+"); and put it in map (and banned in set to exclude them in o(1))

1573. Number of Ways to Split a String (into 3 strings)

There are 2 splits.. (Count number of zeroes between those 1s (of equal sizes - onecOunt/3, oneCount*2/3) thus (b1Max - b1Min + 1) * (b2Max - b2Min + 1) char[] arr = s.toCharArray(); int n = s.length(); int oneCount = 0; for(Character c: arr) if(c == '1') oneCount++; if(oneCount == 0) return (n-2)*(n-1)/2; if(oneCount % 3 != 0) return 0; int b1Min = 0, b2Min = 0, b1Max = 0, b2Max = 0; int temp1 = 0; for(int i =0; i < n; i++){ if(s.charAt(i) == '1'){ temp1++; } if(b1Min ==0 && temp1 == oneCount/3){ b1Min = i+1; b1Max = s.indexOf("1", i+1); } if(b2Min == 0 && temp1 == (oneCount*2/3)){ b2Min = i+1; b2Max = s.indexOf("1", i+1); break; } } return (b1Max - b1Min + 1) * (b2Max - b2Min + 1) % 1000_000_7;

121. Best Time to Buy and Sell Stock

Track min and make profit as current day value - min and make a max of it public int maxProfit(int[] prices) { int profit = 0; int min = Integer.MAX_VALUE; for(int i =0; i < prices.length; i++){ min = Math.min(prices[i], min); profit = Math.max(prices[i] - min, profit); } return profit; }

767. Reorganize String (check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. If possible, output any possible result. If not possible, return the empty string. Example 1: Input: S = "aab" Output: "aba")

Use Map and PQ (sort by freq desc ) o pick top two distinct chars and keep appending on string builder. check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. If possible, output any possible result. If not possible, return the empty string. Example 1: Input: S = "aab" Output: "aba"

54. Spiral Matrix

Use four pointers (variables tracking index - 2 for min and max row (up/down) and two for min and max col (left/right)) and keep stripping the coverered area by them List<Integer> result = new ArrayList<>(); int total = matrix.length * matrix[0].length; int top = 0; int bottom = matrix.length -1; int left = 0; int right = matrix[0].length-1; while(result.size() < total){ for(int i = left; i <= right && result.size() < total; i++){ result.add(matrix[top][i]); } top++; for(int i = top; i <= bottom && result.size() < total; i++){ result.add(matrix[i][right]); } right--; for(int i = right; i >= left && result.size() < total; i--){ result.add(matrix[bottom][i]); } bottom--; for(int i = bottom; i >= top && result.size() < total; i--){ result.add(matrix[i][left]); } left++; } return result;

1188. Design Bounded Blocking Queue

Use semaphore to get this done. One semaphore for size, one for empty, one for full empty = new Semaphore(capacity); (so that one once can add more than the capacity) full = new Semaphore(0); (So that no one can read of no element is inserted) mutex = new Semaphore(1); class BoundedBlockingQueue { Semaphore full; Semaphore empty; Semaphore mutex; Deque<Integer> q; public BoundedBlockingQueue(int capacity) { q = new LinkedList<>(); empty = new Semaphore(capacity); full = new Semaphore(0); mutex = new Semaphore(1); } public void enqueue(int element) throws InterruptedException { empty.acquire(); mutex.acquire(); q.addFirst(element); mutex.release(); full.release(); } public int dequeue() throws InterruptedException { full.acquire(); mutex.acquire(); int ret = q.pollLast(); mutex.release(); empty.release(); return ret; } public int size() { return q.size(); } }

443. String Compression

Use two pointers and counter to keep finding the count and overwrite the count to current array IMPORTANT -> (convert to string and char array for more than 1 digit) if(chars.length == 1) return 1; int i = 0; for(int j = 0; j < chars.length; i++,j++){ int count = 1; while(j < (chars.length - 1) && chars[j] == chars[j+1]){ count++;j++; } if(i != 0 && j < chars.length && i < chars.length){ chars[i] = chars[j]; } if(count != 1 && i < chars.length-1){ // For double digit counts (22 -> '2','2') char[] countArr = String.valueOf(count).toCharArray(); for(char each: countArr){ chars[i+1] = each; i++; } } } return i;

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?

class LRUCache extends LinkedHashMap<Integer, Integer>{ private int capacity; public LRUCache(int capacity) { super(capacity, 0.75F, true); this.capacity = capacity; } public int get(int key) { return super.getOrDefault(key, -1); } public void put(int key, int value) { super.put(key, value); } @Override protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { return size() > capacity; } }

139. Word Break

dp[0] as \text{true}true, since the null string is always present in the dictionary, and the rest of the elements of \text{dp}dp as \text{false}false. We consider substrings of all possible lengths starting from the beginning by making use of index ii. For every such substring, we partition the string into two further substrings s1's1′ and s2's2′ in all possible ways using the index jj (Note that the ii now refers to the ending index of s2's2′). Now, to fill in the entry \text{dp}[i]dp[i], we check if the \text{dp}[j]dp[j] contains \text{true}true, i.e. if the substring s1's1′ fulfills the required criteria. If so, we further check if s2's2′ is present in the dictionary. If both the strings fulfill the criteria, we make \text{dp}[i]dp[i] as \text{true}true, otherwise as \text{false}false. HashSet<String> dict = new HashSet<>(wordDict); boolean[] dp = new boolean[s.length()+1]; dp[0] = true; for(int i =0; i <= s.length(); i++){ for(int j =0; j < i; j++){ if(dp[j] && dict.contains(s.substring(j,i))){ dp[i] = true; break; } } } return dp[s.length()];

1010. Pairs of Songs With Total Durations Divisible by 60

for(int i = 0; i<time.length; i++){ time[i] = time[i] % 60; } HashMap<Integer, Integer> map = new HashMap<>(); int result = 0; for(int i = time.length-1; i>=0; i--){ int searchVal = (60 - time[i]) % 60; if(map.containsKey(searchVal)){ result += map.get(searchVal); } map.put(time[i],map.getOrDefault(time[i], 0) + 1); } return result;

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

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

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

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

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

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

617. Merge Two Binary Trees

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

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

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; } } }

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

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

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

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

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

957. Prison Cells After N Days

repeats after for (N = (N - 1) % 14 + 1; N > 0; --N) { // or may be 256 (Max states) int[] cells2 = new int[8]; for (int i = 1; i < 7; ++i) cells2[i] = cells[i - 1] == cells[i + 1] ? 1 : 0; cells = cells2; } return cells;


संबंधित स्टडी सेट्स

Florence - Cultural Tour of Italy

View Set

IT Exam Revision: E-commerce & other Internet Services

View Set

Chapter 11 Business Cycles, Unemployment, and Inflation

View Set

Respect the Life of Aretha Franklin

View Set

OB My Nursing Lab ?s 80Qw/exp (for the most part) good for complications

View Set