bloomberg
49. Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter.
1. Use Hashtable to store (string, list) 2. iterate through the input array, sort each item and put it into the hashtable if(strs.length == 0) return new ArrayList(); Map<String, List<String>> anagrams = new HashMap<>(); for(String s : strs) { char[] sArr = s.toCharArray(); Arrays.sort(sArr); String sorted = String.valueOf(sArr); if(!anagrams.containsKey(sorted)) anagrams.put(sorted, new ArrayList()); anagrams.get(sorted).add(s); } return new ArrayList(anagrams.values());
56. Merge Intervals Medium Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
1. sort intervals array by its start index using the customized comparator. 2. for each if(result.isEmpty() || result.getLast().end < i.start) result.add(i) else result.getLast().end = Math.max(i.end, result.getLast().end);
435. Non-overlapping Intervals Medium Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note: You may assume the interval's end point is always bigger than its start point. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. Example 1: Input: [ [1,2], [2,3], [3,4], [1,3] ] Output: 1 Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. Example 2: Input: [ [1,2], [1,2], [1,2] ] Output: 2 Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping. Example 3: Input: [ [1,2], [2,3] ] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
1. sort the interval array by the end value, if same, by the start value 2. iterate through the sorted array, if start >= end, set end = interval.end else count++ Arrays.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { if (o1.end != o2.end) return o1.end - o2.end; //first sort by end return o2.start - o1.start; //second sort by start } }); int end = Integer.MIN_VALUE; int count = 0; for (Interval interval : intervals) { if (interval.start >= end) end = interval.end; else count++; } return count;
200. Number of Islands Medium 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: Input: 11110 11010 11000 00000 Output: 1 Example 2: Input: 11000 11000 00100 00011 Output: 3
1. two for loop iterate through the grid if gird[i][j] == 'i' use dfs marking to mark the surrounding increase count by 1 private int m; private int n; public int numIslands(char[][] grid) { m = grid.length; if (m == 0) return 0; n = grid[0].length; int count = 0; for(int i = 0; i < m; i++) { for(int j =0; j < n; j++) { if(grid[i][j] == '1') { DFSMarking(grid, i, j); count++; } } } return count; } private void DFSMarking(char[][] grid, int i, int j) { if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] != '1') return; grid[i][j] = '0'; DFSMarking(grid, i + 1, j); DFSMarking(grid, i - 1, j); DFSMarking(grid, i, j + 1); DFSMarking(grid, i, j - 1); }
703. Kth Largest Element in a Stream Easy 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
1. use priorityQueue to maintains k biggest number and the top of the queue is the kth biggest number. 2. Change the add function: if the size of q less than k: just add it else if the current kth biggest number(top) of the queue is smaller than the adding number: replace it with the new number and finally, return the top one final PriorityQueue<Integer> q; final int k; public KthLargest(int k, int[] a) { this.k = k; q = new PriorityQueue<>(k); for (int n : a) add(n); } // The top of the queue is the kth biggest number public int add(int n) { if (q.size() < k) q.offer(n); // if smallest item in the queue is smaller than n // replace it with n else if (q.peek() < n) { q.poll(); q.offer(n); } return q.peek(); }
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".
Sliding window algorithm create the map for p <char, ocurrence> start, end two pointers, diff = remaining towards the answer check the first k (p.length), and move end forward. while end < length undo start start++ check end end++
a347. Top K Frequent Elements Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1]
Using three for loop: 1. Map(nums, count) 2. list[nums + 1]: use frequency as index to store nums 3. find the top k from the back of list Map<Integer, Integer> freqMap = new HashMap<>(); for(int num : nums) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } List<Integer>[] bucket = new List[nums.length + 1]; for(int num : freqMap.keySet()) { int freq = freqMap.get(num); if(bucket[freq] == null) { bucket[freq] = new ArrayList<>(); } bucket[freq].add(num); } List<Integer> result = new ArrayList<>(); for(int i = bucket.length - 1; i > 0 && k>0; i--) { if(bucket[i]!=null){ List<Integer> list = bucket[i]; result.addAll(list); k-= list.size(); } } return result;
692. Top K Frequent Words Medium Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. Example 1: Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 Output: ["i", "love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. Example 2: Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 Output: ["the", "is", "sunny", "day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Using three for loop: 1. Map(nums, count) 2. list[nums + 1]: use frequency as index to store nums 3. find the top k from the back of list ( for each bucket, sort it by string) Map<String, Integer> count = new HashMap<>(); for (String word : words) { count.put(word, count.getOrDefault(word, 0) + 1); } List<String>[] bucket = new ArrayList[words.length]; for (String key : count.keySet()) { int frequent = count.get(key); if (bucket[frequent] == null) { bucket[frequent] = new ArrayList<>(); } bucket[frequent].add(key); } //int index = 0; List<String> topK = new ArrayList<>(); for (int i = bucket.length - 1; i >= 0; i--) { if (topK.size() >= k) { break; } if (bucket[i] == null) { continue; } Collections.sort(bucket[i]); for (int j = 0; j < bucket[i].size() && topK.size() < k; j++) { topK.add(bucket[i].get(j)); } } return topK; }
242. Valid Anagram Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false
if(s.length() != t.length()) return false; int[] map = new int[256]; for(char c : s.toCharArray()) { map[c]++; } for(char c : t.toCharArray()) { map[c]--; if(map[c] < 0) return false; } return true;