Leet - Code Solution
Leet - Code Solution
of Contents
Introduction 1.1
Merge K sorted lists 1.2
1 Two Sum 1.3
2 Add Two Numbers 1.4
3 Longest Substring Without Repeating Characters 1.5
7 Reverse Integer 1.6
11 Container With Most Water 1.7
12 Integer to Roman 1.8
13 Roman to Integer 1.9
14 Longest Common Prefix 1.10
15 3Sum 1.11
16 3Sum closest 1.12
17 Letter Combinations of a Phone Number 1.13
18 4Sum 1.14
20 Valid Parentheses 1.15
22 Generate Parentheses 1.16
23 Merge k Sorted Lists 1.17
24 Swap Nodes in Pairs 1.18
26 Remove Duplicates from Sorted Array 1.19
27 Remove Element 1.20
31 Next Permutation 1.21
32. Longest Valid Parenthesis 1.22
33 Search in Rotated Sorted Array 1.23
34 Search for range 1.24
35 Search Insert Position 1.25
38 Count and Say 1.26
39 Combination Sum 1.27
1
40 Combination Sum II 1.28
41 First Missing Number 1.29
42 Trapping Rain Water 1.30
43 Multiply Strings 1.31
45 Jump Game II 1.32
46 Permutations 1.33
47 Permutations II 1.34
48 Rotate Image 1.35
49. Group Anagrams 1.36
50 Power(x,n) 1.37
51 N-Queens 1.38
52 N-Queens II 1.39
53 Maximum Subarray 1.40
54 Spiral Matrix 1.41
55 Jump Game 1.42
56 Merge Intervals 1.43
57 Insert Interval 1.44
58 Length of Last Word 1.45
59 Spiral Matrix II 1.46
61 Rotate List 1.47
62 Unique Paths 1.48
63 Unique Paths II 1.49
64 Minimum Path Sum 1.50
67 Add Binary 1.51
68 Text Justification 1.52
69 Sqrt(x) 1.53
70 Climbing Stairs 1.54
71 Simplify Path 1.55
72 Edit Distance 1.56
73 Set Matrix Zeroes 1.57
2
74 Search a 2D Matrix 1.58
75 Sort Colors 1.59
76 Minimum Window Substring 1.60
77 Combinations 1.61
78 Subsets 1.62
79 Word Search 1.63
80 Remove Duplicates from Sorted Array II 1.64
81 Search in Rotated Sorted Array II 1.65
82 Remove Duplicates from Sorted List II 1.66
83 Remove Duplicates from Sorted List 1.67
84 Largest Rectangle in Histogram 1.68
85 Maximal Rectangle 1.69
86 Partition List 1.70
88 Merge sorted array 1.71
89 Gray code 1.72
90 Subsets II 1.73
91 Decode Ways 1.74
92 Reverse Linked List II 1.75
93 Restore IP Addresses 1.76
94 Binary Tree Inorder Traversal 1.77
96 Unique Binary Search Trees 1.78
98 Validate Binary Search Tree 1.79
99 Recover Binary Search Tree 1.80
100 Same Tree 1.81
101 Symmetric Tree 1.82
102 Binary Tree Level Order Traversal 1.83
103 Binary Tree Zigzag Level Order Traversal 1.84
104 Maximum Depth of Binary Tree 1.85
105. Construct Binary Tree from Preorder and Inorder Traversal 1.86
106 Construct Binary Tree from Inorder and Postorder Traversal 1.87
3
107 Binary Tree Level Order Traversal II 1.88
108 Convert Sorted Array to Binary Search Tree 1.89
109 Convert Sorted List to Binary Search Tree 1.90
110 Balanced Binary Tree 1.91
111 Minimum Depth of Binary Tree 1.92
112 Path Sum 1.93
113 Path Sum II 1.94
114 Flatten Binary Tree to Linked List 1.95
116 Populating Next Right Pointers in Each Node 1.96
117 Populating Next Right Pointers in Each Node II 1.97
121 Best Time to Buy and Sell Stock 1.98
122 Best Time to Buy and Sell Stock II 1.99
123 Best Time to Buy and Sell Stock III 1.100
125 Valid Palindrome 1.101
127 Word Ladder 1.102
128 Longest Consecutive Sequence 1.103
129 Sum Root to Leaf Numbers 1.104
130 Surrounded Regions 1.105
131 Palindrome Partitioning 1.106
133 Clone Graph 1.107
134 Gas Station 1.108
135 Candy 1.109
138 Copy List with Random Pointer 1.110
136 Single Number 1.111
137 Single Number II 1.112
139 Word Break 1.113
140 Word Break II 1.114
Understanding KMP algorithms 1.115
141 Linked List Cycle 1.116
142 Linked List Cycle II 1.117
4
143 Reorder List 1.118
144 Binary Tree Preorder Traversal 1.119
145 Binary Tree Postorder Traversal 1.120
146 LRU Cache 1.121
150 Evaluate Reverse Polish Notation 1.122
151 Reverse Words in a String 1.123
152. Maximum Product Subarray 1.124
153 Find Minimum in Rotated Sorted Array 1.125
154 Find Minimum in Rotated Sorted Array II 1.126
155 Min Stack 1.127
156 Binary Tree Upside Down 1.128
157 Read N Characters Given Read4 1.129
158 Read N Characters Given Read4 II Call multiple times 1.130
159 Longest Substring with At Most Two Distinct Characters 1.131
160 Intersection of Two Linked Lists 1.132
161 One Edit Distance 1.133
165 Compare Version Numbers 1.134
167 Two Sum II - Input array is sorted 1.135
168 Excel Sheet Column Title 1.136
169 Majority Number 1.137
170 Two Sum III - Data structure design 1.138
171 Excel Sheet Column Number 1.139
174 Dungeon Game 1.140
172 Factorial Trailing Zeros 1.141
173 Binary Search Tree Iterator 1.142
179 Largest Number 1.143
187 Repeated DNA Sequences 1.144
188 Best Time to Buy and Sell Stock IV 1.145
189 Rotate Array 1.146
190 Reverse Bits 1.147
5
198 House Robber 1.148
199 Binary Tree Right Side View 1.149
200 Number of Islands 1.150
201 Bitwise AND of Numbers Range 1.151
202 Happy Number 1.152
203 Remove Linked List Elements 1.153
204 Count Primes 1.154
205 Isomorphic Strings 1.155
206 Reverse Linked List 1.156
207 Course Schedule 1.157
208 Implement Trie (Prefix Tree) 1.158
209 Minimum Size Subarray Sum 1.159
210. Course Schedule II 1.160
212 Word Search II 1.161
214 Shortest Palindrome 1.162
215 Kth Largest Element in an Array 1.163
216 Combination Sum III 1.164
217 Contains Duplicate 1.165
219 Contains Duplicate II 1.166
220 Contains Duplicates III 1.167
221 Maximal Square 1.168
222. Count Complete Tree Nodes 1.169
223 Rectangle Area 1.170
225 Implement Stack using Queues 1.171
226 Invert Binary Tree 1.172
228 Summary Ranges 1.173
229 Majority Number II 1.174
230 Kth Smallest Element in a BST 1.175
234 Palindrome Linked List 1.176
235 Lowest Common Ancestor of a Binary Search Tree 1.177
6
236 Lowest Common Ancestor of a Binary Tree 1.178
237 Delete Node in a Linked List 1.179
238 Product of Array Except Self 1.180
240 Search a 2D Matrix II 1.181
241. Different Ways to Add Parentheses 1.182
242 Valid Anagram 1.183
243 Shortest Word Distance 1.184
244 Shortest Word Distance II 1.185
245 Shortest Word Distance III 1.186
246 Strobogrammatic Number 1.187
247 Strobogrammatic Number II 1.188
249 Group Shifted Strings 1.189
250 Count Univalue Subtrees 1.190
251 Flatten 2D Vector 1.191
252 Meetings Rooms 1.192
253 Meetings Rooms II 1.193
255 Verify Preorder Sequence in Binary Search Tree 1.194
257 Binary Tree Paths 1.195
258 Add digits 1.196
259. 3Sum Smaller 1.197
260 Single Number III 1.198
261 Graph Valid Tree 1.199
263 Ugly Number 1.200
266. Palindrome Permutation 1.201
268 Missing Number 1.202
269 Alien Dictionary 1.203
270 Closest Binary Search Tree Value 1.204
271 Encode and Decode Strings 1.205
272 Closest Binary Search Tree Value II 1.206
274 H-Index 1.207
7
275 H-Index II 1.208
277 Find the Celebrity 1.209
278 First Bad Version 1.210
279 Perfect squares 1.211
280 Wiggle Sort 1.212
281 Zigzag Iterator 1.213
282 Expression Add Operators 1.214
283 Move Zeroes 1.215
284 Peeking Iterator 1.216
285 Inroder Successor in BST 1.217
286 Walls and Gates 1.218
287 Find the Duplicate Number 1.219
286 Walls and Gates 1.220
288 Unique Word Abbreviation 1.221
290 Word Patterns 1.222
293 Flip Game 1.223
294 Flip Game II 1.224
295 something is not riht 1.225
299 Bulls and Cows 1.226
300 Longest Increasing Subsequence 1.227
301 Remove Invalid Parenthesis 1.228
305 number of islands ii 1.229
311 Sparse Matrix Multiplication 1.230
313 Super Ugly number 1.231
314 Binary Tree Vertical Order Traversal 1.232
315 Count of Smaller Numbers After Self 1.233
317 Shortest Distance from All Buildings 1.234
319 Bulb Switcher 1.235
322 Coin Change 1.236
324 Wiggle Sort II 1.237
8
325 Maximum Size Subarray Sum Equals k 1.238
328 Odd Even Linked List 1.239
329 Longest Increasing Path in a Matrix 1.240
330 Patching Array 1.241
333 Largest BST Subtree 1.242
334 Increasing Triplet Subsequence 1.243
337 House Robber III 1.244
339 Nested List Weight Sum 1.245
341 Flatten Nested List Iterator 1.246
342 Power of Four 1.247
343 Integer Break 1.248
344 Reverse String 1.249
345 Reverse Vowels of a String 1.250
346 Moving Average from Data Stream 1.251
347 Top K Frequent Elements 1.252
349 Intersection of Two Arrays 1.253
350 Intersection of Two Arrays II 1.254
352 Data Stream as Disjoint Intervals 1.255
356 Line Reflection 1.256
357 Count Numbers with Unique Digits 1.257
358. Rearrange String k Distance Apart 1.258
359 Logger Rate Limiter 1.259
360 Sort Transformed Array 1.260
362 Design Hit Counter 1.261
364 Nested List Weight Sum II 1.262
366 Find Leaves of Binary Tree 1.263
367 Valid Perfect Square 1.264
369 Plus One Linked List 1.265
370 Range Addition 1.266
371 Sum of Tow Integers 1.267
9
372 Super Pow 1.268
373 Find K Pairs with Smallest Sums 1.269
374 Guess Number Higher or Lower 1.270
378 Kth Smallest Element in a Sorted Matrix 1.271
380 Insert Delete GetRandom O(1) 1.272
398. Random Pick Index 1.273
10
Introduction
QuestionList
1. Two Sum
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
4. Median of Two Sorted Arrays
5. Longest Palindromic Substring
6. ZigZag Conversion
7. Reverse Integer
8. String to Integer (atoi)
9. Palindrome Number
10. Regular Expression Matching
11. Container With Most Water
12. Integer to Roman
14. Longest Common Prefix
16. 3Sum Closest
18. 4Sum
19. Remove Nth Node From End of List
20. Valid Parentheses
21. Merge Two Sorted Lists
22. Generate Parentheses
24. Swap Nodes in Pairs
25. Reverse Nodes in k-Group
27. Remove Element
28. Implement strStr()
29. Divide Two Integers
30. Substring with Concatenation of All Words
31. Next Permutation
32. Longest Valid Parentheses
33. Search in Rotated Sorted Array
34. Search for a Range
35. Search Insert Position
36. Valid Sudoku
37. Sudoku Solver
38. Count and Say
39. Combination Sum
11
Introduction
12
Introduction
13
Introduction
14
Introduction
15
Introduction
16
Introduction
17
Introduction
18
Introduction
19
1 Two Sum
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.
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the
above updated description carefully.
This question has a small trap should pay attention, say the following solution
[0,4,3,0], 0, ===> the above solution gives [3,3], not [0,3]. to fix this bug.
20
1 Two Sum
}
return res;
}
}
21
2 Add Two Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = new ListNode(-1);
ListNode tail = res;
int carry = 0;
while(l1 != null || l2 != null || carry != 0){
int x1 = l1 == null ? 0 : l1.val;
int x2 = l2 == null ? 0 : l2.val;
tail.next = new ListNode((x1+x2+carry)%10);
carry = (x1+x2+carry)/10;
tail = tail.next;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
return res.next;
}
}
22
2 Add Two Numbers
23
3 Longest Substring Without Repeating Characters
Examples:
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.
When search for char in map, you need make sure no search pass the
current starting index.
24
3 Longest Substring Without Repeating Characters
return maxSize;
}
}
25
7 Reverse Integer
7. Reverse Integer
Reverse digits of an integer.
Have you thought about this? Here are some good questions to ask before
coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10,
100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-
bit integer, then the reverse of 1000000003 overflows. How should you handle
such cases?
For the purpose of this problem, assume that your function returns 0 when the
reversed integer overflows.
to protect your code from overflow, when met multiply operation, use divide
operation to check first.
}
}
26
7 Reverse Integer
27
11 Container With Most Water
Find two lines, which together with x-axis forms a container, such that the
container contains the most water.
two pointers.
28
12 Integer to Roman
int i = 0;
StringBuilder sb = new StringBuilder();
for( i=0; n!= 0; i++){
while(n >= value[i]){
n -=aa value[i];
sb.append(symbol[i]);
}
}
return sb.toString();
}
}
29
12 Integer to Roman
int k = 0;
StringBuilder sb = new StringBuilder();
while(num >= 0 && k < value.length){
while(num >= value[k]){
num -= value[k];
sb.append(symbol[k]);
}
k++;
}
return sb.toString();
}
}
30
13 Roman to Integer
31
13 Roman to Integer
int result = 0;
for(int i=0; i< s.length();i++){
String w = s.substring(i, i<= s.length()-2 ? i+ 2 :
i+1);
if(roman.containsKey(w)){
result += roman.get(w);
if(w.length() == 2)i++;
}else{
result += roman.get(s.substring(i, i+1));
}
}
return result;
}
}
32
13 Roman to Integer
return res;
}
}
33
14 Longest Common Prefix
34
14 Longest Common Prefix
if (strs.length == 1) {
return strs[0];
}
int lengthOfCommanPrefix = 0;
while(true) {
for(int i=0;i<strs.length;i++) {
if (strs[i] == null) {
return "";
}
}
}
35
15 3Sum
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.
[
[-1, 0, 1],
[-1, -1, 2]
]
36
15 3Sum
Arrays.sort(nums);
for(int i=0; i< nums.length -2; i++){
if( i > 0 && nums[i] == nums[i-1]) continue;
int l = i+1;
int r = nums.length-1;
while(l < r){
int sum = nums[i] + nums[l] + nums[r];
if(sum ==0){
List<Integer> t = new ArrayList<>();
t.add(nums[i]);
t.add(nums[l]);
t.add(nums[r]);
res.add(t);
l++;
r--;
while(l < r && nums[l] == nums[l-1]) l++;
while(l < r && nums[r] == nums[r+1]) r--;
}else if(sum < 0){
l++;
}else{
r--;
}
}
}
return res;
}
}
37
16 3Sum closest
38
16 3Sum closest
return res;
}
39
17 Letter Combinations of a Phone Number
A mapping of digit to letters (just like on the telephone buttons) is given below.
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
dfs
40
17 Letter Combinations of a Phone Number
combination(digits, 0, "");
return res;
}
41
18 4Sum
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
Arrays.sort(nums);
42
18 4Sum
();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[l]);
list.add(nums[r]);
res.add(list);
l++;
r--;
while(l<r && nums[l] == nums[l-1]) l
++;
while(l<r && nums[r] == nums[r+1]) r
--;
}else if(sum < target){
l++;
}else{
r--;
}
}
}
}
return res;
}
}
`
43
20 Valid Parentheses
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]"
and "([)]" are not.
44
20 Valid Parentheses
if (! currentParen.pop().equals(targetValue)
){
return false;
}
}
}
if (currentParen.isEmpty()) {
return true;
}
return false;
}
}
45
20 Valid Parentheses
return stack.isEmpty();
}
}
46
22 Generate Parentheses
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
47
22 Generate Parentheses
return res;
}
48
22 Generate Parentheses
gen(l-1, r, cur+"(");
gen(l, r-1, cur+")");
}
}
49
23 Merge k Sorted Lists
50
23 Merge k Sorted Lists
return head;
}
}
51
24 Swap Nodes in Pairs
For example, Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in
the list, only nodes itself can be changed.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode p = dummy;
while(p.next != null && p.next.next != null){
ListNode next = p.next;
ListNode next2 = p.next.next;
p.next = next2;
next.next = next2.next;
next2.next = next;
p = next;
}
return dummy.next;
}
}
52
24 Swap Nodes in Pairs
53
26 Remove Duplicates from Sorted Array
Do not allocate extra space for another array, you must do this in place with
constant memory.
For example,
Your function should return length = 2, with the first two elements of nums being 1
and 2 respectively. It doesn't matter what you leave beyond the new length.
another version
54
26 Remove Duplicates from Sorted Array
int l=0;
for(int r =1; r< nums.length; r++){
if(nums[r] != nums[l])
nums[++l] = nums[r];
}
return l+1;
}
}
55
27 Remove Element
Do not allocate extra space for another array, you must do this in place with
constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond
the new length.
Example:
Your function should return length = 2, with the first two elements of nums being 2.
return i;
}
}
56
31 Next Permutation
Here are some examples. Inputs are in the left-hand column and its corresponding
outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
1. find the first pair of index that n[i] < n[i+1], from the end of array.
2. now we are sure from i+1, to the end of array, is a descending sequence,
otherwise, we didn't find the correct pair in the first step.
3. from i+1, find the largest index k, where n[k] > n[i],
4. swap k and i, the i+1 to end still is a descending order.
5. reverse i+1, to end.
57
31 Next Permutation
int k = -1;
for(int i =0; i< nums.length-1; i++){
if(nums[i] < nums[i+1]) k =i;
}
if(k == -1){
reverse(nums, 0, nums.length-1);
return;
}
int l = k+1;
for(int i = k+1; i< nums.length; i++){
if(nums[i] > nums[k]) l = i;
}
58
32. Longest Valid Parenthesis
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()",
which has length = 4.
The char that makes the string invalid parentheses will cut the
string into parts that either is valid parentheses or empty. use a
stack to process the string, then the stack is empty, while met ')',
calculate the size.
return max;
}
}
59
32. Longest Valid Parenthesis
60
33 Search in Rotated Sorted Array
You are given a target value to search. If found in the array return its index,
otherwise return -1.
ATTENTION2 : you need first focus on finding the portion of array that is
ordered.
61
33 Search in Rotated Sorted Array
}
}
62
34 Search for range
For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].
int l =0;
int r = nums.length-1;// eventually l may reach nums.len
gth-1 by `l = mid +1`
63
34 Search for range
res[1] = r-1;
return res;
}
}
64
35 Search Insert Position
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
Think about the left and right change carefully, why return left is alwasy right?
return left;
}
}
65
38 Count and Say
res = sb.toString();
}
return res;
}
}
66
38 Count and Say
67
39 Combination Sum
The same repeated number may be chosen from C unlimited number of times.
[
[7],
[2, 2, 3]
]
question to ask :
backtracking.
68
39 Combination Sum
cause the question mention any number can be used many times, so next
iteration will need to include this number again, which start from i.
BUT it can not start from 0(i.e. replace i with 0), why ? cause this will cause
duplicates,
[2,3,6,7] target is 7, if you start from 0 again, will result in [2,2,3] & [2,3,2(start
from 0 again)], which is duplicate.
69
39 Combination Sum
return res;
}
result.add(num[i]);
dfs(num, i, result, sum+num[i], target);
result.remove(result.size() -1);
}
}
}
70
40 Combination Sum II
Note:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
one number can be used only once(assuming the set includes duplicates),
this is why each generation of dfs start with i+1.
71
40 Combination Sum II
Arrays.sort(num);
List<Integer> list = new ArrayList<>();
dfs(num, 0, list, 0, target);
return res;
}
72
41 First Missing Number
Your algorithm should run in O(n) time and uses constant space.
technical speaking, it is a hash table question. but the hash key here is the array
index. put the corresponding number in their niche. then swipe the array from the
beginning, first not match is what we need,
73
42 Trapping Rain Water
74
42 Trapping Rain Water
int peak = 0;
int max = 0;
for(int i=0; i< height.length; i++){
if(height[i] > max){
max = height[i];
peak = i;
}
}
int amount =0;
int leftMax =0;
for(int i=0; i<peak; i++){
if(height[i] >= leftMax){
leftMax = height[i];
}else{
amount += (leftMax - height[i]);
}
}
int rightMax =0;
for(int i= height.length-1; i> peak; i--){
if(height[i] >= rightMax){
rightMax = height[i];
}else{
amount += (rightMax - height[i]);
}
}
return amount;
}
}
75
43 Multiply Strings
one solution is to use add, for each i in num1, do an addition to num2, then build
the result as add two string.
second is to notice the property of multiply, which is each postions result is added
up by using different postion combination in num1 and num2, which is:
why need to add it self ? cause in any [i, j ] round, num3[i+j+1] may already
been calculated, such as, [i-1, j+1], in this way, there is already a value.
int l1 = num1.length();
int l2 = num2.length();
int l3 = l1 + l2;
int[] num3 = new int[l3];
76
43 Multiply Strings
int i=0;
for(; i< l3; i++){
if(num3[i] != 0) break;
}
return sb.toString();
}
}
77
45 Jump Game II
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
The minimum number of jumps to reach the last index is 2. (Jump 1 step from
index 0 to 1, then 3 steps to the last index.)
Note: You can assume that you can always reach the last index.
return count;
}
}
78
45 Jump Game II
79
46 Permutations
46. Permutations
Given a collection of distinct numbers, return all possible permutations.
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
put each number in the beginning of the array, then process the begging+1 as a
sub issue.
backtracking.
80
46 Permutations
return res;
}
81
47 Permutations II
47. Permutations II
Given a collection of numbers that might contain duplicates, return all possible
unique permutations.
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Same as Permutations, except that when you try to swap, you need to make
sure you are not swaping a number already processed, if you do, which
means there will be duplicate set.
return res;
}
82
47 Permutations II
83
48 Rotate Image
}
}
84
49. Group Anagrams
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
There are question need to ask during interview : all lower case ? mixed ?
char[] c = word.toCharArray();
Arrays.sort(c);
String hash = new String(c);
if(map.containsKey(hash)){
map.get(hash).add(word);
}else{
List<String> l = new ArrayList<>();
l.add(word);
map.put(hash, l);
}
}
85
49. Group Anagrams
//sort a string.
char[] c = word.toCharArray();
Arrays.sort(c);
String hash = new String(c);
86
50 Power(x,n)
50. Pow(x, n)
Implement pow(x, n).
if you check n%2 == 1 it will fail on some extreme case for example. x =
2.00000 & n = -2147483648
87
51 N-Queens
51. N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard
such that no two queens attack each other.
For example, There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
bt(board, 0, n);
88
51 N-Queens
return res;
}
return true;
}
89
51 N-Queens
90
52 N-Queens II
52. N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct
solution
bt(board, 0, n);
return count;
}
91
52 N-Queens II
return true;
}
}
to improve solution, you don't need to save the entire board to get the result, you
only need to remember the index of queens in each row.
bt(board, 0, n);
return count;
}
92
52 N-Queens II
return true;
}
}
93
53 Maximum Subarray
keep two record, max value so far, and current sum. for each number, add to sum,
if sum > max, then set the max-so-far as sum, if sum <0, discard all numbers
visited, cause it is not used for the following numbers. but the max-so-far is kept.
classic dp solution
94
53 Maximum Subarray
}
int max = dp[0];
for(int v: dp){
if(v > max) max = v;
}
return max;
}
}
to improve above solution, notice that only dp[i-1] and dp[i] is used,.
95
53 Maximum Subarray
return max;
}
}
96
54 Spiral Matrix
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You surely can used 'peel-onion' to do this, first your will know the peeling stop at
n/2, m/2, then another round when there is a row /col left. a better solution is to set
stop coordinates.
97
54 Spiral Matrix
int m = matrix.length;
int n = matrix[0].length;
int p1 = 0, q1 = 0;
int p2 = m-1, q2 = n-1;
while(true){
for(int k= q1; k<=q2; k++){
res.add(matrix[p1][k]);
}
if(++p1 > p2) break;
98
55 Jump Game
Each element in the array represents your maximum jump length at that position.
For example:
after entering the loop, you need first check if you can initiate the jump, then
update the max distance to jump.
99
56 Merge Intervals
Sort the intervals by its start time, merge two if not first.end < second.start.
result.add(intervals.get(0));
for(int i=1; i< intervals.size(); i++){
Interval last = result.get(result.size()-1);
Interval cur = intervals.get(i);
if(last.end < cur.start){
result.add(cur);
}else{
last.end = Math.max(last.end, cur.end);
}
}
return result;
}
}
100
56 Merge Intervals
101
57 Insert Interval
You may assume that the intervals were initially sorted according to their start
times.
102
57 Insert Interval
return result;
}
}
103
57 Insert Interval
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public List<Interval> insert(List<Interval> intervals, Inter
val newInterval) {
List<Interval> res = new ArrayList<>();
if(intervals == null) return res;
int i =0;
for(; i< intervals.size(); i++){
if(newInterval.end < intervals.get(i).start){
res.add(newInterval);
break;
}else if(intervals.get(i).end < newInterval.start){
res.add(intervals.get(i));
}else{
newInterval.start = Math.min(intervals.get(i).st
art, newInterval.start);
newInterval.end = Math.max(intervals.get(i).end,
newInterval.end);
}
}
if(i == intervals.size()) res.add(newInterval);
while(i < intervals.size()) res.add(intervals.get(i++));
return res;
}
}
104
58 Length of Last Word
For example,
return 5.
105
59 Spiral Matrix II
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
106
59 Spiral Matrix II
107
61 Rotate List
return 4->5->1->2->3->NULL.
108
61 Rotate List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null || k == 0) return h
ead;
int len = 0;
ListNode tail = head;
while(tail.next != null){
len++;
tail = tail.next;
}
len++;
k = len - k % len;
if(k == len) return head;
ListNode rTail = head;
while(k-- > 1){
rTail = rTail.next;
}
ListNode newHead = rTail.next;
rTail.next = null;
tail.next = head;
return newHead;
}
}
109
61 Rotate List
There is another smart yet simpler solution. after find the last node, link last node
to the head, then move forward len - k%len step, you will reach the new tail, break
the cycle from there, then you find the new head.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null || k == 0) return h
ead;
int len = 0;
ListNode tail = head;
while(tail.next != null){
len++;
tail = tail.next;
}
len++;
k = len - k % len;
if(k == len) return head;
tail.next = head;
while(k-- >0){
tail = tail.next;
}
head =tail.next;
tail.next = null;
return head;
}
}
110
61 Rotate List
111
62 Unique Paths
The robot can only move either down or right at any point in time. The robot is
trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram
below).
O(mn), space(mn)
112
62 Unique Paths
for(int i=1;i<m;i++){
int next = 1- current;
for(int j=1; j<n;j++){
dp[next][j] = dp[current][j] + dp[next][j-1];
}
current = 1- current; //current will be next.
}
}
}
}
}
113
62 Unique Paths
114
63 Unique Paths II
Now consider if some obstacles are added to the grids. How many unique paths
would there be?
For example, There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
115
63 Unique Paths II
return dp[m-1][n-1];
}
}
116
64 Minimum Path Sum
Note: You can only move either down or right at any point in time.
sum[0][0] = grid[0][0];
you can also improve this by using only one array, which sum[j-1] is current line's
result. corresponding to sum[i][j-1], and sum[j] is sum[i-1][j];
117
64 Minimum Path Sum
118
67 Add Binary
For example,
a = "11"
b = "1"
Return "100".
int p = a.length() - 1;
int q = b.length() - 1;
int carry = 0;
sb.append((i1+i2+carry)%2);
carry = (i1+i2+carry)/2;
}
if(carry != 0){
sb.append(carry);
}
return sb.reverse().toString();
}
}
119
67 Add Binary
simpler code
sb.append((x+y+carry)%2);
carry = (x+y+carry)/2;
}
return sb.reverse().toString();
}
}
120
68 Text Justification
You should pack your words in a greedy approach; that is, pack as many words as
you can in each line. Pad extra spaces ' ' when necessary so that each line has
exactly L characters.
For the last line of text, it should be left justified and no extra space is inserted
between words.
For example,
121
68 Text Justification
return res;
}
122
68 Text Justification
if(end == words.length){
for(int i =start; i< end; i++){
String w = words[i];
int j =0;
while(j < w.length()){
array[k++] = w.charAt(j++);
}
array[k++] = ' ';
}
while(k < L) array[k++] = ' ';
res.add(new String(array));
return;
}
int count = 0;
j = 0;
while(j++ < spaces){
array[k++] = ' ';
}
if(extras-- > 0) {
array[k++] = ' ';
}
}
123
68 Text Justification
res.add(new String(array));
}
}
if(!list.isEmpty()){
leftJustify(list, res, len, maxWidth);
}
return res;
}
void leftJustify(List<String> list, List<String> res, int le
n, int maxWidth){
char[] chars = new char[maxWidth];
char[] first = list.get(0).toCharArray();
System.arraycopy(first, 0, chars, 0, first.length);
if( list.size() == 1){
124
68 Text Justification
if (list.size() == 1) {
Arrays.fill(chars, first.length, chars.length, ' ');
res.add(new String(chars));
return;
} else {
int dis = (maxWidth - len) / (list.size() - 1);
int extra = list.size() > 2 ? (maxWidth - len) % (li
st.size() - 1) : 0;
int stop = first.length;
125
68 Text Justification
}
res.add(new String(chars));
}
return;
}
}
126
69 Sqrt(x)
69. Sqrt(x)
Implement int sqrt(int x).
127
70 Climbing Stairs
Each time you can either climb 1 or 2 steps. In how many distinct ways can you
climb to the top?
classic dp
return dp[n];
}
}
constant space.
128
70 Climbing Stairs
return res;
}
}
less variable
129
71 Simplify Path
For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"
}
}
130
72 Edit Distance
a) Insert a character
b) Delete a character
c) Replace a character
DP
131
72 Edit Distance
int m = word1.length()+1;
int n = word2.length()+1;
int[][] dp = new int[m][n];
for(int i=0; i<m;i++) dp[i][0] = i;
for(int i=0;i<n; i++) dp[0][i] = i;
for(int i=1; i<m; i++){
for(int j = 1; j<n;j++){
if(word1.charAt(i-1) == word2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = Math.min(dp[i-1][j], Math.min(dp[
i-1][j-1], dp[i][j-1])) + 1;
}
}
}
return dp[m-1][n-1];
}
}
132
73 Set Matrix Zeroes
Follow up:
A simple improvement uses O(m + n) space, but still not the best solution. Could
you devise a constant space solution?
constant space.
133
73 Set Matrix Zeroes
if(resetFirstColumn){
for(int i=0; i<matrix.length;i++){
matrix[i][0] = 0;
}
}
if(resetFirstRow){
for(int i=0;i<matrix[0].length; i++){
matrix[0][i] = 0;
}
}
}
}
134
74 Search a 2D Matrix
Integers in each row are sorted from left to right. The first integer of each row is
greater than the last integer of the previous row. For example,
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
A linear solution
135
74 Search a 2D Matrix
int x = 0;
int y = j;
while(x <= i&& y>=0){
if(target == matrix[x][y]) return true;
else if( target < matrix[x][y]){
y--;
}else{
x++;
}
}
return false;
}
}
2 binary search
136
74 Search a 2D Matrix
int t = 0;
int b = matrix.length -1;
if(target < matrix[0][0] || target > matrix[matrix.lengt
h-1][matrix[0].length-1]) return false;
while(t <= b){
int mid = t + (b-t)/2;
if(matrix[mid][k] == target) return true;
if(matrix[mid][k] > target){
b = mid-1;
}else{
t = mid+1;
}
}
int l = t;
t = 0;
b = matrix[0].length -1;
while(t <= b){
int mid = t + (b-t)/2;
if(matrix[l][mid] == target) return true;
if(matrix[l][mid] > target){
b = mid -1;
}else{
t = mid + 1;
}
}
return false;
}
}
137
74 Search a 2D Matrix
1 binary search
while(l <=r ){
int mid = l + (r-l)/2;
int val = matrix[mid/col][mid%col];
if(val == target) return true;
if(val > target){
r = mid-1;
}else{
l = mid+1;
}
}
return false;
}
}
138
75 Sort Colors
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and
blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array
with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
two pointers.
139
75 Sort Colors
int k = p + 1;
while(k < q){
switch(nums[k]){
case 0:
swap(nums, ++p, k++);
break;
case 1:
k++;
break;
case 2:
swap(nums, k, --q);
break;
}
}
}
140
76 Minimum Window Substring
Note: If there is no such window in S that covers all characters in T, return the
empty string "".
If there are multiple such windows, you are guaranteed that there will always be
only one unique minimum window in S.
needs two pointers, the front pointer make sure to include all the chars in T,
the end pointer make sure to exclude as many chars as possible to make the
window smallest.
for(char ch : t.toCharArray()){
int count =1;
if(target.containsKey(ch)){
count = target.get(ch) + 1;
}
target.put(ch, count);
}
int start = 0;
int foundNumber = 0;// this means all letter shows up, y
ou need to shrink window when possible.
141
76 Minimum Window Substring
int k = 1;
if(found.containsKey(c)){
k = found.get(c) + 1;
}
found.put(c, k);
//once foundNumber reach t.length(), the number stan
ds. found.get(c) will be updated in the next block
if(found.get(c) <= target.get(c)){
foundNumber++;
}
if(found.containsKey(begin)){
found.put(begin, found.get(begin)-1);
//you can NOT decrease foundNumber here.
there is no go back for foundNumber.
}
start++;
begin = s.charAt(start);
}
142
76 Minimum Window Substring
if(minWindowStart != -1){
return s.substring(minWindowStart, minWindowStart +
minWindowLen);
}
return "";
}
}
143
77 Combinations
77. Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1
... n.
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
backtracking
144
77 Combinations
145
78 Subsets
78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
BACKTRACKING
is a very important sollution:
Notice, next iteration is based on current set status, not from the beginning, so the
dfs will take input from i+1, not start+1.
146
78 Subsets
Solution 1. build a next set based current set, i.e. for each subset in current set,
add current number, add it into the result set, as next set.
147
78 Subsets
for(List<Integer> l : res){
List<Integer> t = new ArrayList<>(l);
t.addAll(v);
r.add(t);
}
//you cannot update the res inside the for loop, unl
ess you will use an iterator there.
res.addAll(r);
res.add(v);
}
res.add(new ArrayList<>());
return res;
}
}
148
79 Word Search
The word can be constructed from letters of sequentially adjacent cell, where
"adjacent" cells are those horizontally or vertically neighboring. The same letter
cell may not be used more than once.
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
149
79 Word Search
visited[x][y] = true;
visited[x][y] = false;
return res;
}
}
150
80 Remove Duplicates from Sorted Array II
Your function should return length = 5, with the first five elements of nums being 1,
1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
return ++i;
}
}
151
80 Remove Duplicates from Sorted Array II
152
80 Remove Duplicates from Sorted Array II
int k = 0;
for(int i =1 ; i< nums.length; i++){
}
}
return ++k;
}
}
153
81 Search in Rotated Sorted Array II
154
81 Search in Rotated Sorted Array II
155
82 Remove Duplicates from Sorted List II
For example,
Keep three pointers, first pointer, tail always points to the tail of found list item.
second pointer, prev, point to the head of to-be-found list head, and a third pointer,
cur, which points the same as prev, while cur and cur's next value are the same,
the move forward cur pointer, if cur and prev is not the same, then we need to cut
prev to cur off, then move next section of list.
156
82 Remove Duplicates from Sorted List II
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode tail = dummy;
ListNode prev = head;
ListNode cur = head;
157
83 Remove Duplicates from Sorted List
For example,
158
83 Remove Duplicates from Sorted List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode h = head;
ListNode p = head;
ListNode q = head.next;
while(q != null){
if(q.val == p.val){
p.next = q.next;
}else{
p.next = q;
p = p.next;
}
q = q.next;
}
return h;
}
}
159
84 Largest Rectangle in Histogram
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
This is a hard question. To solve This problem in linear time, use a stack to track
the index of each number:
160
84 Largest Rectangle in Histogram
If not, this means there is a small rectangle at the top of stack, pop the top of
stack, the next top index and current index is the width of a found rectangle,
and the height is the previous poped item.
return max;
}
}
161
85 Maximal Rectangle
}
return max;
}
162
85 Maximal Rectangle
int max = 0;
int i = 0;
while(i <= data.length){
int val = i < data.length ? data[i] : 0;
if(stack.empty() || val >= data[stack.peek()]){
stack.push(i);
i++;
}else{
int h = stack.pop();
int w = stack.empty() ? i : i-stack.peek()-1;
max = Math.max(max, data[h] * w);
}
}
return max;
}
}
163
86 Partition List
You should preserve the original relative order of the nodes in each of the two
partitions.
For example,
164
86 Partition List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode gt = new ListNode(-1);
ListNode lt = new ListNode(-1);
ListNode t1 = gt;
ListNode t2 = lt;
while(head != null){
if(head.val < x){
t2.next = head;
t2 = t2.next;
}else{
t1.next = head;
t1 = t1.next;
}
head = head.next;
}
t2.next = gt.next;
t1.next = null;
return lt.next;
}
}
the following improvement won't work cause you are CREATING A new
reference to the node ltail/mtail points to, then move it around, you are NOT
REALLY MOVING ltail/mtail.
165
86 Partition List
166
88 Merge sorted array
Note: You may assume that nums1 has enough space (size that is greater or
equal to m + n) to hold additional elements from nums2. The number of elements
initialized in nums1 and nums2 are m and n respectively.
}
}
167
89 Gray code
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:
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.
168
89 Gray code
list.add(0);
if(n <=0) return list;
int i=0;
while(i < n){
int b = 1 << i++;
int size = list.size();
for(int j= size-1; j>=0; j--){
int v = list.get(j);
list.add(v | b);
}
}
return list;
}
}
169
89 Gray code
return list;
}
}
170
90 Subsets II
90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all
possible subsets.
171
90 Subsets II
if you check the size, then for [1,2,2,2], the result is empty.
if(k == nums.length ){
res.add(new ArrayList<Integer>(list));
return;
}
172
91 Decode Ways
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways
to decode it.
DP[i] means how many ways you can decode s.substring(0, i);
173
91 Decode Ways
return dp[s.length()];
}
174
92 Reverse Linked List II
return 1->4->3->2->5->NULL.
1 ≤ m ≤ n ≤ length of list.
175
92 Reverse Linked List II
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n)
{
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode p = dummy;
int k = 0;
while( ++k < m){
if(p != null) p = p.next;
}
//TODO:
ListNode tail = p.next;
while(++k <= n){
ListNode tmp = p.next;
p.next = tail.next;
tail.next = tail.next.next;
p.next.next = tmp;
return dummy.next;
}
}
176
93 Restore IP Addresses
177
93 Restore IP Addresses
if(isValid(q)){
list.add(q);
restore(s, k, list);
list.remove(list.size()-1);
}
}
178
93 Restore IP Addresses
179
94 Binary Tree Inorder Traversal
1
\
2
/
3
return [1,3,2].
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on
OJ.
The serialization of a binary tree follows a level order traversal, where '#' signifies
a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
180
94 Binary Tree Inorder Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
return res;
}
}
181
96 Unique Binary Search Trees
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
from above deduction, so empty subtree is one, if take one node as root, number
smaller than root will form left sub tree. and others to form right sub tree.
182
96 Unique Binary Search Trees
183
98 Validate Binary Search Tree
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's
key. Both the left and right subtrees must also be binary search trees. Example 1:
2
/ \
1 3
Example 2:
1
/ \
2 3
184
98 Validate Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
185
98 Validate Binary Search Tree
nodes.add(root.val);
You notice that you don't really need the array for pre-order traversing, you only
need the previous node.
186
98 Validate Binary Search Tree
prev = root;
187
98 Validate Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode prev = null;
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
root = root.left;
}
TreeNode top = stack.pop();
if(prev != null && top.val <= prev.val) return false
;
else prev = top;
root = top.right;
}
return true;
}
}
188
99 Recover Binary Search Tree
Note: A solution using O(n) space is pretty straight forward. Could you devise a
constant space solution?
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode prev = null;
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
findSwap(root);
findSwap(root.left);
if(prev != null){
if(first == null && prev.val > root.val){
189
99 Recover Binary Search Tree
first = prev;
}
if(first != null && prev.val > root.val){
second = root;
}
}
prev = root;
findSwap(root.right);
}
}
190
100 Same Tree
Two binary trees are considered equal if they are structurally identical and the
nodes have the same value.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
if(p.val != q.val) return false;
return isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right);
}
}
191
101 Symmetric Tree
1
/ \
2 2
/ \ / \
3 4 4 3
1
/ \
2 2
\ \
3 3
Note: Bonus points if you could solve it both recursively and iteratively.
recursive
192
101 Symmetric Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return symmetric(root.left, root.right);
}
}
}
iterative
193
102 Binary Tree Level Order Traversal
3
/ \
9 20
/ \
15 7
[
[3],
[9,20],
[15,7]
]
194
102 Binary Tree Level Order Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> l = new ArrayList<>();
int stop = queue.size();
for(int i=0; i< stop; i++){
TreeNode node = queue.poll();
l.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
res.add(l);
}
return res;
}
}
195
103 Binary Tree Zigzag Level Order Traversal
3
/ \
9 20
/ \
15 7
[
[3],
[20,9],
[15,7]
]
196
103 Binary Tree Zigzag Level Order Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean r2l = false;
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i=0; i< size; i++){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
if(r2l){
r2l = false;
Collections.reverse(list);
}else{
r2l = true;
}
res.add(list);
}
return res;
}
}
197
103 Binary Tree Zigzag Level Order Traversal
198
104 Maximum Depth of Binary Tree
The maximum depth is the number of nodes along the longest path from the root
node down to the farthest leaf node
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right
))+1;
}
199
105. Construct Binary Tree from Preorder and Inorder Traversal
Note: You may assume that duplicates do not exist in the tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
200
105. Construct Binary Tree from Preorder and Inorder Traversal
return root;
}
}
201
106 Construct Binary Tree from Inorder and Postorder Traversal
Note: You may assume that duplicates do not exist in the tree.
202
106 Construct Binary Tree from Inorder and Postorder Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Map<Integer, Integer> map = new HashMap<>();
return root;
}
}
203
106 Construct Binary Tree from Inorder and Postorder Traversal
204
107 Binary Tree Level Order Traversal II
3
/ \
9 20
/ \
15 7
[
[15,7],
[9,20],
[3]
]
205
107 Binary Tree Level Order Traversal II
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<>();
int size = queue.size();
for(int i=0; i< size; i++){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
res.add(list);
}
Collections.reverse(res);
return res;
}
}
206
108 Convert Sorted Array to Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null) return null;
return subArrayBuilder(nums, 0, nums.length - 1);
return root;
}
207
108 Convert Sorted Array to Binary Search Tree
208
109 Convert Sorted List to Binary Search Tree
Top-down approach will take n^2 time, cause each time you need to find the
root in the linked list, then recursively construct the two parts.
Bottom-Up approach, you need to keep track of from where to build the sub
tree and for how many nodes this sub tree has. so the current is used for this
purpose.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode cur = null;
public TreeNode sortedListToBST(ListNode head) {
int size = getLen(head);
cur = head;
return getBST(size);
209
109 Convert Sorted List to Binary Search Tree
return l;
}
}
210
110 Balanced Binary Tree
For this problem, a height-balanced binary tree is defined as a binary tree in which
the depth of the two subtrees of every node never differ by more than 1.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
return getHeightOrDelta(root) != -1;
}
211
111 Minimum Depth of Binary Tree
The minimum depth is the number of nodes along the shortest path from the root
node down to the nearest leaf node.
The take away here is that if any node is empty, there is no path, so cannot count
as a minium depth.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int l = minDepth(root.left);
int r = minDepth(root.right);
if( l !=0 && r != 0){
return Math.min(l,r) + 1;
}else if(l == 0){
return r +1;
}else{
return l+1;
}
}
}
212
112 Path Sum
1. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
that adding up all the values along the path equals the given sum.
For example: Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Solution.
if you reach to a node which is empty, which means there is no such path, when
you reach to a leaf node, check wether it is a valid path. otherwise continue to
next level.
213
112 Path Sum
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left == null && root.right == null){
return root.val == sum;
}
return hasPathSum(root.left, sum-root.val) || hasPathSum
(root.right, sum-root.val);
}
}
214
112 Path Sum
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
return has(root, 0, sum);
}
if(root.right != null){
res = has(root.right, cur,target);
}
return res;
}
}
215
113 Path Sum II
For example: Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
216
113 Path Sum II
return res;
}
217
113 Path Sum II
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> res = new ArrayList<>();
218
113 Path Sum II
219
114 Flatten Binary Tree to Linked List
1
/ \
2 5
/ \ \
3 4 6
1
\
2
\
3
\
4
\
5
\
6
thing to notice:
1 if right sub tree turned into a linked list,and its tail is not empty, this will
be the tail of this sub list,
2 if right sub tree turns to a empty list, then if left sub tree is not empty,
then this sub tree's tail will become the tail of this tree.
other wise the root itself is the tail.
220
114 Flatten Binary Tree to Linked List
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
flat(root);
}
}
if(rtail != null) return rtail;
if(ltail != null) return ltail;
return root;
}
}
221
114 Flatten Binary Tree to Linked List
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
TreeNode* prev;
void flatten(TreeNode *root) {
// write your code here
if(root == nullptr) return;
flatten(root->right);
flatten(root->left);
root->right = prev;
root->left = nullptr;
prev = root;
}
};
222
116 Populating Next Right Pointers in Each Node
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right
node, the next pointer should be set to NULL.
Note:
You may only use constant extra space. You may assume that it is a perfect
binary tree (ie, all leaves are at the same level, and every parent has two
children). For example, Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
223
116 Populating Next Right Pointers in Each Node
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
/*if(root.left != null){
do not need to check here. if root.right exist, then
left for sure exist.
}*/
if(root.right != null){
root.left.next = root.right;
root.right.next = root.next == null ?
null : root.next.left;
}
connect(root.left);
connect(root.right);
}
}
224
117 Populating Next Right Pointers in Each Node II
What if the given tree could be any binary tree? Would your previous solution still
work?
Note:
You may only use constant extra space. For example, Given the following binary
tree,
1
/ \
2 3
/ \ \
4 5 7
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
using a queue
225
117 Populating Next Right Pointers in Each Node II
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
q.add(root);
while(!q.isEmpty()){
int size = q.size();
for(int i=0; i< size; i++){
TreeLinkNode node = q.poll();
node.next = (i == size-1)? null : q.peek();
if(node.left != null) q.add(node.left);
if(node.right != null) q.add(node.right);
}
}
}
}
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
226
117 Populating Next Right Pointers in Each Node II
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
while(current != null){
//retrieve next first if is not set.
if(first == null){
if(current.left != null) first = current.left;
else first = current.right;
}
if(current.left != null){
if(last != null) last.next = current.left;
// IT is not else, if last is not null, then ste
p ahead last
// to next which is current.left,
//if last is null, then current.left become last;
last = current.left;
}
if(current.right != null){
if(last != null) last.next = current.right;
last = current.right;
}
if(current.next != null){
current = current.next;
}else{
current = first;
first = last = null;
227
117 Populating Next Right Pointers in Each Node II
}
}
}
228
121 Best Time to Buy and Sell Stock
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
Related issue
229
121 Best Time to Buy and Sell Stock
dp[0] = 0;
for(int i=1; i<dp.length; i++){
for(int j=0; j<i; j++){
dp[i] = Math.max(prices[i]-prices[j], dp[i]);
}
res = Math.max(dp[i], res);
}
return res;
}
}
However, you only need to keep track of the current minimal value ever found
so far, use current value minus the min value, you get a profit, if current value
is even smaller than the current minimal value, this is potentially a buy-in time,
which will be sold later.
O(n)
230
121 Best Time to Buy and Sell Stock
return res;
}
}
231
122 Best Time to Buy and Sell Stock II
Design an algorithm to find the maximum profit. You may complete as many
transactions as you like (ie, buy one and sell one share of the stock multiple
times). However, you may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
Related issue:
return res;
}
232
123 Best Time to Buy and Sell Stock III
Design an algorithm to find the maximum profit. You may complete at most two
transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must
sell the stock before you buy again).
first find all maximal profit between [0..i], where i reach to n. in this process,
you need to keep track of the mininal buy-in price. if i sell at price[i] what is
the maximal profit.
second find all maximal profit between[n..0] i.e. from the end to the begin. if I
buy-in at price[i], what will be the maximal profit,, in this process, you
need to keep the maximal sell price .
Related issue
233
123 Best Time to Buy and Sell Stock III
int res = 0;
if(prices == null || prices.length <=1) return res;
return res;
}
}
234
125 Valid Palindrome
For example,
Note: Have you consider that the string might be empty? This is a good question
to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
if(Character.toLowerCase(s.charAt(i))
!= Character.toLowerCase(s.charAt(j))) return fa
lse;
i++;
j--;
}
return true;
}
}
235
125 Valid Palindrome
236
127 Word Ladder
Only one letter can be changed at a time Each intermediate word must exist in the
word list For example,
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
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.
wordList.add(endWord);
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
int len = 0;
while(!queue.isEmpty()){
int size = queue.size();
len++;
for(int i=0; i< size; i++){
String s = queue.poll();
if(s.equals(endWord)) return len;
for(String n : getNext(s, wordList)){
queue.offer(n);
}
237
127 Word Ladder
}
}
return 0;
}
238
128 Longest Consecutive Sequence
For example,
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
239
128 Longest Consecutive Sequence
return max;
}
}
240
128 Longest Consecutive Sequence
int up = nums[i] + 1;
while(set.contains(up)){
set.remove(up);
up++;
}
max = Math.max(max, (up - low - 1));
}
return max;
}
}
241
129 Sum Root to Leaf Numbers
An example is the root-to-leaf path 1->2->3 which represents the number 123.
For example,
1
/ \
2 3
242
129 Sum Root to Leaf Numbers
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int res = 0;
public int sumNumbers(TreeNode root) {
243
130 Surrounded Regions
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions
surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
X X X X
X X X X
X X X X
X O X X
bfs/dfs.
int m = board.length;
int n = board[0].length;
for(int i=0; i< m; i++){
244
130 Surrounded Regions
if(board[i][0] == 'O'){
queue.add(new Node(i,0));
}
if(board[i][n-1] == 'O'){
queue.add(new Node(i, n-1));
}
}
for(int i=1; i<n-1; i++){
if(board[0][i] == 'O') queue.add(new Node(0, i));
if(board[m-1][i] == 'O') queue.add(new Node(m-1, i))
;
}
int k =0;
while(k < queue.size()){
Node node = queue.get(k);
int x = node.x;
int y = node.y;
board[node.x][node.y] = 'U';
k++;
if(x > 0 && board[x-1][y] == 'O'){
queue.add(new Node(x-1,y));
}
if(x<m-1 && board[x+1][y] == 'O'){
queue.add(new Node(x+1, y));
}
if(y >0 && board[x][y-1] == 'O'){
queue.add(new Node(x, y-1));
}
if(y < n-1 && board[x][y+1] == 'O'){
queue.add(new Node(x, y+1));
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j] == 'O') board[i][j] = 'X';
if(board[i][j] == 'U') board[i][j] = 'O';
}
}
245
130 Surrounded Regions
}
}
Or you can get a recursive solution. which go ove the border of the board, if find a
'O', then dfs from this point. mark itself and its neighbor as 'U' recursively.
246
131 Palindrome Partitioning
[
["aa","b"],
["a","a","b"]
]
Backtracking
247
131 Palindrome Partitioning
248
131 Palindrome Partitioning
249
133 Clone Graph
We use # as a separator for each node, and , as a separator for node label and
each neighbor of the node. As an example, consider the serialized graph
{0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as
separated by #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2. Second node is
labeled as 1. Connect node 1 to node 2. Third node is labeled as 2. Connect node
2 to node 2 (itself), thus forming a self-cycle. Visually, the graph looks like the
following:
1
/ \
/ \
0 --- 2
/ \
\_/
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new A
rrayList<UndirectedGraphNode>(); }
* };
250
133 Clone Graph
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode no
de) {
if(node == null) return null;
List<UndirectedGraphNode> nodes = new ArrayList<>();
Map<UndirectedGraphNode,UndirectedGraphNode> map = new H
ashMap<>();
nodes.add(node);
map.put(node, new UndirectedGraphNode(node.label));
for(UndirectedGraphNode n : nodes){
for(UndirectedGraphNode nn : n.neighbors){
map.get(n).neighbors.add(map.get(nn));
}
}
return map.get(node);
}
}
251
133 Clone Graph
Input:{0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
Output:{0,1,5#1,2,5#2,3#3,4,4#4,5,5,5,5#5}
Expected:{0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new A
rrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode no
de) {
int k= 0;
while(k < list.size()){
UndirectedGraphNode cur = list.get(k++);
UndirectedGraphNode copy = new UndirectedGraphNode(c
ur.label);
map.put(cur, copy);
Set<UndirectedGraphNode> keys = map.keySet();
for(UndirectedGraphNode n : cur.neighbors){
// if the neighbors is like 4,4,,4. then you add
all the same instance into the list, multiple times.
// But how possible ?
if(!keys.contains(n)){
list.add(n);
252
133 Clone Graph
}
}
}
for(UndirectedGraphNode n : list){
for(UndirectedGraphNode nn : n.neighbors){
map.get(n).neighbors.add(map.get(nn));
}
}
return map.get(node);
}
}
253
134 Gas Station
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from
station i to its next station (i+1). You begin the journey with an empty tank at one
of the gas stations.
Return the starting gas station's index if you can travel around the circuit once,
otherwise return -1.
if sum(gas) - sum(cost) >= 0, then there is a point you can start and
complete.
if at certain point k, if sum(gas[0..k]) - sum(cost[0..k]) <0 then k is not
possible to begin with, then reset the current sum to 0 , k + 1 will be the
result.
254
134 Gas Station
255
135 Candy
135. Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Children with a higher rating get more candies than their neighbors.
Two passes:
left to right, if a[i] > a[i-1], increase the candy of i by 1, if not set it as 1.
right to left, if a[i-1] > a[i], BUT count is less, then increase candy of i.
256
135 Candy
return res;
}
}
257
138 Copy List with Random Pointer
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode p = head;
while(p != null){
RandomListNode next = p.next;
RandomListNode dup = new RandomListNode(p.label);
dup.next = next;
p.next =dup;
p =next;
}
p = head;
while(p != null){
if(p.random != null){
p.next.random = p.random.next;
}
p = p.next.next;
}
258
138 Copy List with Random Pointer
while(p != null){
RandomListNode next = p.next.next;
dupTail.next = p.next;
p.next = next;
dupTail = dupTail.next;
p = next;
}
return dummy.next;
}
}
259
136 Single Number
Note: Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory?
// Xor operation
public class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int v : nums){
res ^= v;
}
return res;
}
}
260
139 Word Break
s = "leetcode",
DP. set the begining to be a dummy char, and the set default value to be true.
return res[res.length-1];
}
}
261
140 Word Break II
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
262
140 Word Break II
263
Understanding KMP algorithms
in the context of brute force to solve the problem "find pattern in text", each time
there is a mismatch between text[i+k] and pattern[k], pointer to text is set to i+1,
and pointer to pattern reset to 0, until find a match(k == pattern.length), or i+k>
tet.length, there is no pattern in text.
This naive approach wastes a lot comparison that is unnecessary, next array in
KMP is trying to improve this mismatch-comparison situation. everytime there is a
mismatch(j as the index), pattern is moved toward text end by LEN, this LEN
means that there is a substring pattern[0..LEN] matches PATTERN[j-LEN..j-1], so
that it can bypass unnecessary comparison.
the LEN is next[j] : there is a length next[j] substring in pattern which appears in
the begin and end of pattern(prefix and suffix).
the relationship between next array and max prefix-suffix is that during KMP
algorithm, there is no need to consider current mismatch char, and there is no
need to keep last max prefix-suffix, cause if match, the algorithm return. so the
values in max prefix-suffix is shift right by one.
264
Understanding KMP algorithms
Calculate the next array is relatively simple. say we already know next[0..j], where
next[j]==k(there is a substringP[0..k-1], length k, is a prefix-suffix, P[j] not
included), to calculate next[j+1]:
265
141 Linked List Cycle
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode p = head, q = head.next;
while(p != null && q != null){
if(p == q) return true;
p = p.next;
q = q.next;
if(q != null) q = q.next;
}
return false;
}
}
266
142 Linked List Cycle II
still two pointers, but DON'T give any pointer a head-start, cause in reality there is
no such thing. in the while loop, run the pointers first, then check
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode slow = head;
ListNode fast = head;
while(fast != null){
slow = slow.next;
fast = fast.next;
if(fast != null) fast = fast.next;
if(fast == slow){
fast = head;
while(slow != fast){
fast = fast.next;
slow = slow.next;
}
return slow;
267
142 Linked List Cycle II
return null;
}
}
268
143 Reorder List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null) return ;
ListNode p = head;
ListNode q = head.next;
while(q != null && q.next != null){
p = p.next;
q = q.next;
if(q != null) q = q.next;
}
q = p.next;
p.next = null;
ListNode newHead = null;
while(q != null){
ListNode tmp = q.next;
q.next = newHead;
newHead = q;
q = tmp;
}
269
143 Reorder List
p = head;
q = newHead;
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
head = dummy.next;
}
}
270
144 Binary Tree Preorder Traversal
1
\
2
/
3
return [1,2,3] .
271
144 Binary Tree Preorder Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
res.add(node.val);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
return res;
}
}
272
145 Binary Tree Postorder Traversal
1
\
2
/
3
return [3,2,1].
to get post-order, you will need 2 stacks to get the result. in the question. the
result array is the second stack.
273
145 Binary Tree Postorder Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack1 = new Stack<>();
stack1.push(root);
while(!stack1.isEmpty()){
TreeNode node = stack1.pop();
res.add(node.val);
if(node.left != null) stack1.push(node.left);
if(node.right != null) stack1.push(node.right);
Collections.reverse(res);
return res;
}
}
274
146 LRU Cache
get(key) - Get the value (will always be positive) of the key if the key exists in the
cache, otherwise return -1.
set(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.
275
146 LRU Cache
}
private void moveToHead(Node node){
if(node.prev == start) return;
node.prev.next = node.next;
node.next.prev = node.prev;
insertToHead(node);
}
private void insertToHead(Node node){
Node next = start.next;
node.next = next;
next.prev = node;
start.next = node;
node.prev = start;
}
public void set(int key, int value)
{
if(map.containsKey(key)){
moveToHead(map.get(key));
Node node = map.get(key);
node.val = value;
}else{
Node node = new Node(key , value);
if(mSize >= mCapacity){
clearCache();
}
insertToHead(node);
mSize++;
map.put(key, node);
}
276
146 LRU Cache
map.remove(tail.key);
mSize--;
}
}
class Node{
int key;
int val;
Node prev, next;
Node(int key, int val){
this.key = key;
this.val = val;
prev = next =null;
}
Node(){};
}
}
277
150 Evaluate Reverse Polish Notation
Some examples:
Stack.
278
150 Evaluate Reverse Polish Notation
break;
case '*':
res = first * second;
break;
case '/':
//exceptions.
res = first/second;
break;
default:
throw new RuntimeException("Invalid oper
ation");
}
stack.push(res);
}
}
return stack.pop();
}
}
279
151 Reverse Words in a String
For example, Given s = "the sky is blue", return "blue is sky the".
Yes. However, your reversed string should not contain leading or trailing spaces.
280
151 Reverse Words in a String
return sb.toString();
}
}
281
152. Maximum Product Subarray
282
153 Find Minimum in Rotated Sorted Array
}
return nums[l];
}
}
283
154 Find Minimum in Rotated Sorted Array II
Would this affect the run-time complexity? How and why? Suppose a sorted array
is rotated at some pivot unknown to you beforehand.
return nums[l];
}
}
284
154 Find Minimum in Rotated Sorted Array II
285
155 Min Stack
Solution. using two stacks, push value as usually, but at mean time, push the top
of another stack, minStack, or the current value onto minStack, whichever is
smaller.
class MinStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();
286
155 Min Stack
}
}
287
156 Binary Tree Upside Down
1
/ \
2 3
/ \
4 5
4
/ \
5 2
/ \
3 1
288
156 Binary Tree Upside Down
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if(root == null) return root;
if(root.left == null && root.right == null) return root;
root.left = null;
root.right = null;
oldLeft.left = newLeft;
oldLeft.right = root;
return newRoot;
}
}
289
157 Read N Characters Given Read4
The return value is the actual number of characters read. For example, it returns 3
if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads
n characters from the file.
Note: The read function will only be called once for each test case.
return index;
}
}
290
157 Read N Characters Given Read4
291
158 Read N Characters Given Read4 II Call multiple times
The return value is the actual number of characters read. For example, it returns 3
if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads
n characters from the file.
292
158 Read N Characters Given Read4 II Call multiple times
int index = 0;
while(!queue.isEmpty() && index < n){
buf[index++] = queue.poll();
}
if(index == n) return n;
return index;
}
}
293
158 Read N Characters Given Read4 II Call multiple times
294
160 Intersection of Two Linked Lists
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
Notes:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode
headB) {
if(headA == null || headB == null) return null;
295
160 Intersection of Two Linked Lists
int a = 0;
int b = 0;
ListNode ha = headA;
ListNode hb = headB;
while(ha != null || hb != null){
if(ha != null){
ha = ha.next;
a++;
}
if(hb != null){
hb = hb.next;
b++;
}
}
int delta = b - a;
ha = headA;
hb = headB;
if(delta > 0){
while(delta-- > 0){
hb = hb.next;
}
}else if(delta < 0){
while(delta++ <0){
ha = ha.next;
}
}
// ping ha and hb to the right pos in the list, so that
both has k distance to the end.
while(ha != null){
if(ha == hb) return ha;
ha = ha.next;
hb = hb.next;
}
return null;
296
160 Intersection of Two Linked Lists
297
161 One Edit Distance
if(s.length() == t.length()){
int count =0;
int i = 0;
while(i < s.length()){
if(s.charAt(i) != t.charAt(i)) count++;
if(count > 1) break;
i++;
}
return count == 1;
}else{
return s.length() > t.length() ? isOneDelete(s, t) :
isOneDelete(t,s);
}
}
298
161 One Edit Distance
return s.substring(i).equals(l.substring(i+1));
}
}
299
165 Compare Version Numbers
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits
and the . character.
The . character does not represent a decimal point and is used to separate
number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth
second-level revision of the second first-level revision.
300
165 Compare Version Numbers
}else{
String ss1 = s1.substring(p);
String ss2 = s2.substring(q);
if(ss1.length() > ss2.length()) return 1;
else if(ss1.length() < ss2.length()) return -
1;
else return ss1.compareTo(ss2);
}
}
};
int i =0;
for(; i< v1.length || i<v2.length; i++){
String vs1 = i< v1.length ? v1[i] : "";
String vs2 = i< v2.length ? v2[i] : "";
return 0;
}
}
301
167 Two Sum II - Input array is sorted
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.
302
168 Excel Sheet Column Title
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
The solution
}
}
303
169 Majority Number
You may assume that the array is non-empty and the majority element always
exist in the array.
brute force solution is to count. one O(n) solution is to keep track of the major
number from the beginning, in this way the major number may vary during the
process, but at the end, only the real major number will remain. for each pair of
number, if they are same increase count of major number, if not, this pair will be
removed.
}
}
304
170 Two Sum III - Data structure design
add - Add the number to an internal data structure. find - Find if there exists any
pair of numbers which sum is equal to the value.
For example,
305
170 Two Sum III - Data structure design
306
171 Excel Sheet Column Number
Given a column title as appear in an Excel sheet, return its corresponding column
number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
307
174 Dungeon Game
Write a function to determine the knight's minimum initial health so that he is able
to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at
least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
The trick here is to go from dungeon place holds princess, and at each point, the
knight's minimum hp should be either 1 or more(if the dungeon cell contains
demons). depends on later need, this why you have to go from bottom right to top-
left.
308
174 Dungeon Game
return hp[0][0];
}
}
309
172 Factorial Trailing Zeros
there should no multiply anywhere in the code, other wise there will be
overflow.
consider 125, there are multiple fives in the number to end up trailing zeros. so
you need to find such number recursively.
310
173 Binary Search Tree Iterator
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h)
memory, where h is the height of the tree.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
311
173 Binary Search Tree Iterator
stack.push(node);
node = node.left;
}
TreeNode top = stack.peek();
stack.pop();
node = top.right;
return top.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
312
179 Largest Number
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an
integer.
313
179 Largest Number
return 0 - c1.compareTo(c2);
}
};
Arrays.sort(ints, comp);
return sb.toString();
}
}
314
187 Repeated DNA Sequences
Write a function to find all the 10-letter-long sequences (substrings) that occur
more than once in a DNA molecule.
For example,
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
315
187 Repeated DNA Sequences
char ch = s.charAt(i);
res <<= 2;
switch (ch){
case 'A':
res |= 0b00;
break;
case 'C':
res |= 0b01;
break;
case 'G':
res |= 0b10;
break;
case 'T':
res |= 0b11; //0x11 means hexdecimal, so it
is 0b00010001.. which is not 3. in binary.
break;
}
}
return res;
}
}
316
188 Best Time to Buy and Sell Stock IV
Design an algorithm to find the maximum profit. You may complete at most k
transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must
sell the stock before you buy again).
For each day i, [1..n], what is the maximal profit after j transaction, [1..k]
at each day i, there will be a profit(or not, depends wether p[i] > p[i-1]) for
transaction j, use a local array to keep track of transaction j's profit built
along the days. local[j] = Math.max(global[j-1] + profit, local[j] + profit)
update global profit.
317
188 Best Time to Buy and Sell Stock IV
return global[k];
}
318
189 Rotate Array
Note: Try to come up as many solutions as you can, there are at least 3 different
ways to solve this problem.
Solution 1. rotate one by one, make a copy of last element, shift all element 1
distance to right, put last element back into the first position, continue k steps.
Solution 2. use extra space to save the last k elements from array. move first
n-k elements to the right by k steps. copy the extra array back into first k
elements.
reverse 3 times.
319
189 Rotate Array
swap(nums, 0, n-1);
swap(nums, 0, k-1);
swap(nums, k, n-1);
320
190 Reverse Bits
Follow up:
If this function is called many times, how would you optimize it?
the solution is of constant time ,which is 32, to improve it on large scale, your code
need to cache certain result, and reduce the number of operation, i.e. from 32 to
smaller number.
return res;
}
}
321
190 Reverse Bits
return res;
}
}
322
198 House Robber
1. House Robber
You are a professional robber planning to rob houses along a street. Each house
has a certain amount of money stashed, the only constraint stopping you from
robbing each of them is that adjacent houses have security system connected and
it will automatically contact the police if two adjacent houses were broken into on
the same night.
DP: while robbing i-th house, the max value is either rob the i-th house and the
max value BEFORE the previous houses, or don't rob i-th house, and max value
of robbing all previous houses
return res[nums.length-1];
}
}
using constant space. you only need prev max, current max, in the next round,
prev + nums[i] will be the current, and max(prev, current) will the prev.
323
198 House Robber
return Math.max(cur,prev);
}
}
324
198 House Robber
325
199 Binary Tree Right Side View
1 <---
/ \
2 3 <---
\ \
5 4 <---
BFS, instead of saving all the numbers in each level, save the last one.
326
199 Binary Tree Right Side View
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=1; i<= size; i++){
TreeNode node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
if(i == size) res.add(node.val);
}
}
return res;
}
}
327
200 Number of Islands
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
328
200 Number of Islands
you can avoid the visited matrix by set the value of grid[i][j] to '2' for instance
329
200 Number of Islands
330
201 Bitwise AND of Numbers Range
For example, given the range [5, 7], you should return 4.
If two numbers cross the boundary of 2^x, i.e. m < 2^x < n, this means there
is no common 1s exist in all the number. so the real question is to find the left-
most common 1s, if any.
331
202 Happy Number
202.Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any
positive integer, replace the number by the sum of the squares of its digits, and
repeat the process until the number equals 1 (where it will stay), or it loops
endlessly in a cycle which does not include 1. Those numbers for which this
process ends in 1 are happy numbers.
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Will this method ever terminate? yes, the number square sum will not increase for
ever. if you get the maximum 3-digit number, 999, 3*9^2 = 243, so the number will
go up, then go down.
332
202 Happy Number
if(set.contains(n)){
return false;
}else{
set.add(n);
}
int res =0;
while(n > 0){
res += (n%10) * (n%10);
n /= 10;
}
n = res;
}
}
}
333
203 Remove Linked List Elements
Example
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(val - 1);
dummy.next =head;
head = dummy;
// if head.next is the val, remove it, don't update head
, continue to check new next.
// otherwise udpate it.
while(head.next != null){
if(head.next.val == val){
head.next = head.next.next;
}else
head = head.next;
}
return dummy.next;
}
}
334
203 Remove Linked List Elements
335
204 Count Primes
To verify a number is prime, you need to divide n by all the number less than
n, to see if remainder is 0, in this case, for each number you need to calculate
in such way, so the total complexity in time is O(n^2).
There is a simple way, for each number less than n, you only need to visit it
once to tell is a primer or not
Start with 2, for all the 2k < n, they are not prime, continue to 2, since all
number less than 3 is not factor of 3, so 3 is prime, continue to 4, since
already visited when 2k, so not, continue this to n.
}
}
336
205 Isomorphic Strings
For example,
Note: You may assume both s and t have the same length.
you can use two maps to map the chars from each string,however, you can use
the index information saved inside two strings, if two chars are 'equal', they should
have same index.
m1[s.charAt(i)] = i+1;
m2[t.charAt(i)] = i+1;
}
return true;
}
}
337
205 Isomorphic Strings
338
206 Reverse Linked List
A linked list can be reversed either iteratively or recursively. Could you implement
both?
iterative
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while(head != null){
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
}
339
206 Reverse Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
//get new tail.
ListNode tail = head.next;
//remove old head.
head.next = null;
ListNode newHead = reverseList(tail);
tail.next = head;
return newHead;
}
340
207 Course Schedule
Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for
you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished
course 0, and to take course 0 you should also have finished course 1. So it is
impossible.
Note:
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera
explaining the basic concepts of Topological Sort.
341
207 Course Schedule
es) {
int[] indegree = new int[numCourses];
Map<Integer, List<Integer>> map = new HashMap<>();
indegree[q]++;
}
//each course in this queue has no dependency on other
courses.
Queue<Integer> queue = new LinkedList<>();
if(map.containsKey(c)){
List<Integer> dep = map.get(c);
for(int cc : dep){
indegree[cc]--;
if(indegree[cc] == 0) queue.offer(cc);
}
}
}
342
207 Course Schedule
}
}
DFS solution, you still need to build the map for the edges, but this time, used a
visited[] array to represent if the course is finished or not. for each course:
mark it as visited
visits it all dependent courses, if you reach any course twice, then there is a
cycle.
mark it as not visited, visit next course.
it has three states: unvisited (=0), visited(=1), searching(=-1). The third states
is to detect the existence of cycle, while the 2nd state indicate that the vertex
is already checked and there is no cycle, there is no need to check this vertex
again, since we already verify that there is no circle from this vertex.
343
207 Course Schedule
344
208 Implement Trie (Prefix Tree)
class TrieNode {
// Initialize your data structure here.
Map<Character, TrieNode> children = new HashMap<>();
public boolean hasWord = false;
public TrieNode() {
public Trie() {
345
208 Implement Trie (Prefix Tree)
class TrieNode {
// Initialize your data structure here.
TrieNode[] children = new TrieNode[26];
String word = "";
public TrieNode() {
}
}
346
208 Implement Trie (Prefix Tree)
public Trie() {
root = new TrieNode();
}
node.word = word;
}
347
208 Implement Trie (Prefix Tree)
348
209 Minimum Size Subarray Sum
For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the
minimal length under the problem constraint.
Two pointers
349
209 Minimum Size Subarray Sum
while(sum >=s){
len = Math.min(len, i - k);
sum -= nums[k++];
}
350
210. Course Schedule II
Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the
ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is
impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished
both courses 1 and 2. Both courses 1 and 2 should be taken after you finished
course 0. So one correct course order is [0,1,2,3]. Another correct ordering
is[0,2,1,3].
351
210. Course Schedule II
while(!queue.isEmpty()){
int node = queue.poll();
res[k++] = node;
List<Integer> list = map.get(node);
if(list == null) continue;
for(int end : list){
indegree[end]--;
if(indegree[end] == 0) queue.offer(end);
}
}
352
212 Word Search II
Each word must be constructed from letters of sequentially adjacent cell, where
"adjacent" cells are those horizontally or vertically neighboring. The same letter
cell may not be used more than once in a word.
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
this question requires usage of Trie, 208. Implement Trie (Prefix Tree) and 79
Word Search
}
}
class Trie {
353
212 Word Search II
public Trie() {
root = new TrieNode();
}
node.word = word;
}
354
212 Word Search II
current += board[x][y];
if(!dict.startsWith(current)) return;
if(dict.search(current)){
res.add(current);
}
visited[x][y] = true;
visited[x][y] = false;
}
355
212 Word Search II
356
214 Shortest Palindrome
For example:
357
215 Kth Largest Element in an Array
For example,
Solution first. remain a min-heap of size k, if size exceed k, pop the top value.
return pq.poll();
}
}
358
216 Combination Sum III
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
backtracking
359
216 Combination Sum III
private void sum3(int val, int curSum, int n, int count, int
k, List<Integer> list){
if(count > k || curSum > n) return;
}
}
better form
360
216 Combination Sum III
void sum3(int start, int stop, int cur, int target, int coun
t, int k, List<Integer> list){
if(count > k) return;
if(count == k){
if(cur == target){
res.add(new ArrayList<Integer>(list));
}
return;
}
361
217 Contains Duplicate
362
219 Contains Duplicate II
}
}
363
220 Contains Duplicates III
if(j>=k){
set.remove((long)nums[j-k]);
}
set.add((long)nums[j]);
}
return false;
}
}
364
220 Contains Duplicates III
365
221 Maximal Square
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
366
221 Maximal Square
int edge = 0;
for(int i =0 ;i < matrix.length; i++){
dp[i][0] = matrix[i][0] == '0' ? 0 : 1;
edge = Math.max(dp[i][0], edge);
}
for(int i=0; i< matrix[0].length; i++){
dp[0][i] = matrix[0][i] == '0' ? 0 : 1;
edge = Math.max(dp[0][i], edge);
}
}
}
367
222. Count Complete Tree Nodes
for complete tree, if h(l) == h(r) then then the nodes are 2^h -1;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
368
222. Count Complete Tree Nodes
root = root.left;
h++;
}
}else{
while(root.right != null){
root = root.right;
h++;
}
}
return h;
}
}
369
223 Rectangle Area
Each rectangle is defined by its bottom left corner and top right corner as shown in
the figure.
Rectangle Area Assume that the total area is never beyond the maximum possible
value of int.
370
223 Rectangle Area
the following python solution is not suitable for java in the case of large number
but no overlap. a pythonic solution:
class Solution:
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
sums = (C - A) * (D - B) + (G - E) * (H - F)
return sums - max(min(C, G) - max(A, E), 0) * max(min(D,
H) - max(B, F), 0)
371
225 Implement Stack using Queues
Notes:
You must use only standard operations of a queue -- which means only push to
back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may
simulate a queue by using a list or deque (double-ended queue), as long as you
use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top
operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of
Stack.
372
225 Implement Stack using Queues
class MyStack {
373
226 Invert Binary Tree
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia: This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but
you can’t invert a binary tree on a whiteboard so fuck off.
374
226 Invert Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
//solution 2:
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
TreeNode invertLeft = invertTree(root.left);
root.left = invertTree(root.right);
root.right = invertLeft;
return root;
}
}
375
226 Invert Binary Tree
376
228 Summary Ranges
Solution 1, Extend the original array to include last number twice, this is deal-
breaker.
start = extend[i];
}
}
return res;
}
}
377
228 Summary Ranges
return res;
}
}
378
229 Majority Number II
379
229 Majority Number II
380
229 Majority Number II
381
230 Kth Smallest Element in a BST
Note:
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find
the kth smallest frequently? How would you optimize the kthSmallest routine?
Hint:
382
230 Kth Smallest Element in a BST
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while(!stack.isEmpty() || node != null){
while(node != null){
stack.push(node);
node = node.left;
}
383
234 Palindrome Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next==null) return true;
fast = slow.next;
slow.next = null;
fast = reverse(fast);
slow = head;
384
234 Palindrome Linked List
fast = fast.next;
}
return true;
}
//recursively
385
234 Palindrome Linked List
//stop recursion
if (right == null)
return true;
return y;
}
}
386
235 Lowest Common Ancestor of a Binary Search Tree
_______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.
387
235 Lowest Common Ancestor of a Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode
p, TreeNode q) {
if(root == null) return null;
if(root.val == p.val || root.val == q.val) return root;
if(root.val > p.val && root.val > q.val){
return lowestCommonAncestor(root.left, p,q);
}else if(root.val < p.val && root.val < q.val){
return lowestCommonAncestor(root.right, p,q);
}else{
return root;
}
}
}
388
235 Lowest Common Ancestor of a Binary Search Tree
389
236 Lowest Common Ancestor of a Binary Tree
_______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.
390
236 Lowest Common Ancestor of a Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode
p, TreeNode q) {
if(root == null) return root;
if(root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
//PLEASE NOTE, IF LEFT AND RIGHT BOTH NOT NULL, MEANS TH
E NODE IS FOUND IN BOTH SUB TREE.
if(left != null && right != null) return root;
return left == null ? right : left;
391
237 Delete Node in a Linked List
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with
value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
392
238 Product of Array Except Self
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.)
393
240 Search a 2D Matrix II
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,
[
[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]
]
394
240 Search a 2D Matrix II
//O(m+n)
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0) return f
alse;
int m = matrix.length-1;
int n = matrix[0].length-1;
int x = 0;
int y = n;
Wrong thinking, you cannot do a binary search row-wise, and then a binary search
on col-wise, THIS IS TOTAL WRONG THINKING. the correct one is divide the
panel to 4 parts
int m = matrix.length;
int n = matrix[0].length;
395
240 Search a 2D Matrix II
if (matrix[rowMid][colMid] == target) {
return true;
}
396
241. Different Ways to Add Parentheses
Given a string of numbers and operators, return all possible results from
computing all the different possible ways to group numbers and operators. The
valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
397
241. Different Ways to Add Parentheses
398
242 Valid Anagram
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?
}
}
399
243 Shortest Word Distance
400
244 Shortest Word Distance II
Design a class which receives a list of words in the constructor, and implements a
method that takes two words word1 and word2 and return the shortest distance
between these two words in the list.
401
244 Shortest Word Distance II
402
244 Shortest Word Distance II
O(n) solution, you can look into the arrays more carefully you only need to
compare each one at a time, and move the smaller pointer ahead.
To further step improve the performance, if you have a string only show up
once, then you can use above solution to achieve a log(k) solution.
403
244 Shortest Word Distance II
return s;
}
}
404
244 Shortest Word Distance II
405
245 Shortest Word Distance III
Given a list of words and two words word1 and word2, return the shortest distance
between these two words in the list.
word1 and word2 may be the same and they represent two individual words in the
list.
406
245 Shortest Word Distance III
407
245 Shortest Word Distance III
return s;
}
}
408
246 Strobogrammatic Number
For example, the numbers "69", "88", and "818" are all strobogrammatic.
}
}
409
247 Strobogrammatic Number II
410
247 Strobogrammatic Number II
for(String s : prev){
if(n != target) res.add("0" + s + "0");
res.add("1" + s + "1");
res.add("8" + s + "8");
res.add("6" + s + "9");
res.add("9" + s + "6");
}
return res;
}
}
iterative
411
247 Strobogrammatic Number II
int i = ((n&1) == 0) ? 2 : 3;
for(; i<= n; i+=2){
List<String> tmp = new ArrayList<>();
for(String s : res){
if(i != n) tmp.add("0" + s +"0");
tmp.add("1" + s +"1");
tmp.add("9" + s +"6");
tmp.add("6" + s +"9");
tmp.add("8" + s +"8");
}
res = tmp;
}
return res;
}
}
412
249 Group Shifted Strings
Given a list of strings which contains only lowercase alphabets, group all strings
that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Note: For the return value, each inner list's elements must follow the lexicographic
order.
things to consider: 1 does each group allow duplicates, such as ["a", "a"]. 2 how to
calculate unique hash key.
For Java to do a mod operation, you need to do (26 + a)%26, if a == -25, then
without 26+, you get a%26 == -25. This is not the case in Python.
413
249 Group Shifted Strings
for(String s : strings){
boolean added =false;
for(String k : map.keySet()){
if(k.length() != s.length()) continue;
if(isShift(k, s)){
added = true;
map.get(k).add(s);
}
}
if(!added){
List<String> l = new ArrayList<>();
l.add(s);
map.put(s, l);
}
}
414
249 Group Shifted Strings
415
249 Group Shifted Strings
for(String s : strings){
String hash = getHash(s);
if(map.containsKey(hash)){
map.get(hash).add(s);
}else{
List<String> l = new ArrayList<>();
l.add(s);
map.put(hash, l);
}
}
return sb.toString();
}
}
416
250 Count Univalue Subtrees
A Uni-value subtree means all nodes of the subtree have the same value.
5
/ \
1 5
/ \ \
5 5 5
return 4.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class CNode{
boolean isUnique;
int val;
int size;
CNode(){
isUnique = true;
size = 0;
val = 0;
417
250 Count Univalue Subtrees
}
}
public int countUnivalSubtrees(TreeNode root) {
CNode c = count(root);
return c.size;
}
c.isUnique = true;
}else{
c.size = left.size + right.size;
c.isUnique = false;
}
}
c.val = root.val;
return c;
}
}
418
251 Flatten 2D Vector
[
[1,2],
[3],
[4,5,6]
]
By calling next repeatedly until hasNext returns false, the order of elements
returned by next should be: [1,2,3,4,5,6].
Attention:
419
251 Flatten 2D Vector
@Override
public Integer next() {
int val = vector.get(p).get(q);
q++;
if(q == vector.get(p).size()){
p++;
q=0;
}
return val;
}
@Override
public boolean hasNext() {
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/
420
251 Flatten 2D Vector
421
252 Meetings Rooms
For example,
return false.
422
252 Meetings Rooms
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
if(intervals == null || intervals.length <= 1) return tr
ue;
}
};
Arrays.sort(intervals, comp);
for(int i=1; i< intervals.length; i++){
Interval cur = intervals[i];
Interval prev = intervals[i-1];
return true;
}
}
423
252 Meetings Rooms
424
253 Meetings Rooms II
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public int minMeetingRooms(Interval[] intervals) {
if(intervals == null || intervals.length == 0) return 0;
if(intervals.length == 1) return 1;
Arrays.sort(intervals, comp);
Comparator<Interval> comp2 = new Comparator<Interval>(){
@Override
public int compare(Interval a, Interval b){
425
253 Meetings Rooms II
comp2);
int count =1;
queue.offer(intervals[0]);
queue.offer(next);
}
return count;
}
}
improve 1 : for comp2, you only need to save the ending time queue, improve
2 : you only need to measure the queue size in the end.
426
255 Verify Preorder Sequence in Binary Search Tree
427
257 Binary Tree Paths
1
/ \
2 3
\
5
["1->2->5", "1->3"]
Solution recursive
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root == null) return result;
List<TreeNode> path = new ArrayList<>();
buildPath(root, path);
return result;
}
428
257 Binary Tree Paths
path.add(root);
if(root.left != null){
buildPath(root.left, path);
}
if(root.right != null){
buildPath(root.right, path);
}
path.remove(root);
}
}
A clear DFS
429
257 Binary Tree Paths
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root == null){
return res;
}
buildPath(root, String.valueOf(root.val));
return res;
}
if(root.right != null){
buildPath(root.right, list + "->" + String.valueOf(r
oot.right.val));
}
}
}
430
257 Binary Tree Paths
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
List<Integer> list = new ArrayList<>();
print(root, list);
return res;
}
431
257 Binary Tree Paths
432
258 Add digits
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one
digit, return it.
Hint:
A naive implementation of the above process is trivial. Could you come up with
other methods? What are all the possible results? How do they occur, periodically
or randomly? You may find this Wikipedia article useful.
the simpler solution, is to use recursion/loop, each time, add all digits number,
until generates a single digit number.
return num;
}
}
433
258 Add digits
There a a constant solution, the result set can only be in [0...9], 0 can only be
generated by 0, so the result set of all positive number is [1...9], each time the
number increase by 10, the number that adds up to 9 shift left by 1, say res(18) =
9, res(27) = 9, ... so this question becomes : how many numbers are there
between this number and the last res(X) = 9;
434
259. 3Sum Smaller
Return 2. Because there are two triplets which sums are less than 2:
because sort array won't change the fact that a good triplet sti
ll stands
Fix first number, then use two pointers, notice that when you find a i(fixed),j,k
triplet, which means all combine between k-j is valid triplet.
435
259. 3Sum Smaller
}
}
}
return count;
}
}
436
260 Single Number III
For example:
Note : The order of the result is not important. So in the above example, [5, 3] is
also correct.
Your algorithm should run in linear runtime complexity. Could you implement it
using only constant space complexity?
for(int v : nums){
if((v & r) != 0) res[0] ^= v;
}
res[1] = res[0]^xor;
return res;
}
}
437
260 Single Number III
438
261 Graph Valid Tree
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Note: you can assume that no duplicate edges will appear in edges. Since all
edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together
in edges.
This is an undirected map, so in-degree methods is not very suitable. Using bfs,
since in a valid tree traversal, each not should be only visited once, if there is a
loop, you end up visit an already visited node, this is not a valid tree. using a
queue, every time, if node is not visited, mark it as visited, then traverse its
neighbors, if is not visited, enque it, if there is any cycle in the graph, your queue
ends up containing multiple instance of certain numbers.
439
261 Graph Valid Tree
for(boolean b : visited){
if(!b) return false;
}
return true;
}
}
This question can be viewed in different perspective, building a set, initially each
node has its own set, with more edges coming, merge two related sets, until the
set remain equals to 1. this union-find algorithm.
440
261 Graph Valid Tree
for(int[] e : edges){
int u = e[0];
int v = e[1];
if(id[u] == id[v]) return false;
merge(id, u, v);
}
for(int i=1; i<n; i++){
if(id[i-1] != id[i]) return false;
}
return true;
}
441
263 Ugly Number
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For
example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
return num == 1;
}
}
442
266. Palindrome Permutation
For example
443
266. Palindrome Permutation
444
268 Missing Number
For example,
Note: Your algorithm should run in linear runtime complexity. Could you implement
it using only constant extra space complexity?
think of the array as newArray = nums + [0...n], so each number show up twice
except the missing one. similar to Single Number
445
269 Alien Dictionary
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
each word itself has no order, ie abc can not deduce the order of a, b ,c
if any chars has not found and there is no dependence what then ?
446
269 Alien Dictionary
if(c1 != c2){
if(!map.containsKey(c1)){
List<Character> list = new ArrayList<>()
;
map.put(c1, list);
}
map.get(c1).add(c2);
indg[c2-'a']++;
break;
}
}
}
PriorityQueue<Character> pq = new PriorityQueue<>();
for(Character c : letters){
if(indg[c-'a'] == 0) pq.offer(c);
}
447
269 Alien Dictionary
}
}
1. find all possible edges, which means, in two adjecent strings, s1, s2, if s1[i] !=
s2[j], there is an edge from s1[i] to s2[j];
2. in the mean time, build a in-degree map to reflect the fact that how many
nodes points to current node, also need to mantain a list of node a current
can reach.
if(c1 != c2){
448
269 Alien Dictionary
if(!map.containsKey(c1)){
List<Character> list = new ArrayList<>()
;
map.put(c1, list);
}
map.get(c1).add(c2);
indg[c2-'a']++;
break;
}
}
}
PriorityQueue<Character> pq = new PriorityQueue<>();
for(Character c : letters){
if(indg[c-'a'] == 0) pq.offer(c);
}
}
}
the below solution is not very clear. ```java public class Solution { public String
alienOrder(String[] words) { Map> graph = new HashMap<>(); StringBuilder
sb = new StringBuilder(); for(int i =0; i< words.length; i++){ String s = words[i];
for(int j=0; j()); } }
449
269 Alien Dictionary
if(i >0){
buildEdge(graph, words[i-1], s);
}
}
return sb.toString();
}
void buildEdge(Map<Character, Set<Character>> graph, String prev
, String cur){
if(prev == null || cur == null){
return;
}
for(int i=0; i< prev.length() && i< cur.length(); i++){
char p = prev.charAt(i);
char q = cur.charAt(i);
if(p != q){
if(!graph.get(p).contains(q)){
graph.get(p).add(q);
}
break;
}
}
}
450
269 Alien Dictionary
}else{
return true;
}
}else{
visited.put(ch, -1);
}
```java
public class Solution {
public String alienOrder(String[] words) {
Map<Character, Set<Character>> graph = new HashMap<>();
Map<Character, Integer> ingrees = new HashMap<>();
StringBuilder sb = new StringBuilder();
for(int i =0; i< words.length; i++){
String s = words[i];
for(int j=0; j<s.length(); j++){
if(!graph.containsKey(s.charAt(j))){
graph.put(s.charAt(j), new HashSet<Character
>());
if(!ingrees.containsKey(s.charAt(j)))
ingrees.put(s.charAt(j), 0);
}
}
451
269 Alien Dictionary
if(i >0){
updateIngrees(graph, ingrees, words[i-1], s);
}else{
if(words[0].length() > 0 ){
ingrees.put(words[0].charAt(0), 0);
}
}
}
Iterator it = ingrees.entrySet().iterator();
while(it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
char ch = (char)pair.getKey();
int val = (int)pair.getValue();
if(val == 0){
queue.offer(ch);
}
}
while(!queue.isEmpty()){
char top = queue.poll();
sb.append(top);
Set<Character> neighbors = graph.get(top);
for(char n : neighbors){
ingrees.put(n, ingrees.get(n)-1);
if(ingrees.get(n) == 0){
queue.offer(n);
}
}
}
452
269 Alien Dictionary
if(ingrees.containsKey(q)){
ingrees.put(q, ingrees.get(q) +1);// this li
ne is actually failing the code, you can simply increase ingree
on q, cause if you have mutiple <p-q> instances while building,
the q's ingree is not properly calculated.
}else{
ingrees.put(q, 1);
}
break;
}
}
}
453
270 Closest Binary Search Tree Value
Note: Given target value is a floating point. You are guaranteed to have only one
unique value in the BST that is closest to the target.
basic observation: if root.val is greater than target value, the right subtree can't be
closer than root/left subtree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
TreeNode child = root.val < target ? root.right : root.l
eft;
if(child == null) return root.val;
int childClose = closestValue(child, target);
return Math.abs(target-childClose) > Math.abs(target-roo
t.val) ? root.val : childClose;
}
}
454
271 Encode and Decode Strings
So Machine 1 does:
455
271 Encode and Decode Strings
return sb.toString();
return res;
}
}
456
271 Encode and Decode Strings
457
272 Closest Binary Search Tree Value II
You are guaranteed to have only one unique set of k values in the BST that are
closest to the target.
Follow up: Assume that the BST is balanced, could you solve it in less than O(n)
runtime (where n = total nodes)?
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> closestKValues(TreeNode root, double ta
rget, int k) {
Queue<Integer> list = new LinkedList<>();
458
272 Closest Binary Search Tree Value II
node = stack.pop();
node = node.right;
}
459
274 H-Index
274. H-Index
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5
papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the
h-index.
count sort.
460
274 H-Index
int sum = 0;
for(int i=cc.length-1; i>=0;i--){
if(sum + cc[i] >= i){
return i;
}else
{
sum += cc[i];
}
}
return 0;
}
}
461
274 H-Index
Arrays.sort(citations);
return citations.length;
}
}
sort the array, if citations[i], then there are citations.length - i of papers are >
citations[i]; so the local H-index is min(citations[i], citations.length-i);
462
275 H-Index II
275. H-Index II
Follow up for H-Index: What if the citations array is sorted in ascending order?
Could you optimize your algorithm?
Hint: Expected runtime complexity is in O(log n) and the input is sorted. Binary
search.
463
277 Find the Celebrity
Now you want to find out who the celebrity is or verify that there is not one. The
only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?"
to get information of whether A knows B. You need to find out the celebrity (or
verify there is not one) by asking as few questions as possible (in the asymptotic
sense).
You are given a helper function bool knows(a, b) which tells you whether A knows
B. Implement a function int findCelebrity(n), your function should minimize the
number of calls to knows.
First approach takes O(n^2), for each pair of person, if A doesn't know B, then
A is a potential candidate of the Celebrity, then the question is reduced to half
size, continue this approach until the size reduced to 1. Then sweep the array
to make sure the Celebrity is known by others, otherwise, he/she is fake
'Celebrity'
464
277 Find the Celebrity
}
}
465
278 First Bad Version
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad
one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version
is bad. Implement a function to find the first bad version. You should minimize the
number of calls to the API.
the real question is : given a sorted array, find the first appearance of certain
number. the trick here is the return value, should it be left ? right? in this case
always left. why ? if middle is not the number, so mid+1 becomes the left. if
middle is the number, there are 2 scenarios, one this is the first number. one it
is not:
in the first case, your left, mid and right eventually become the same, but
the number is not the required, the next is, the binary search in this case
will point left to next value(left = mid +1)
in the second case, your new right, mid -1 may be the desired number. so
continue the search, you will eventually reach the first case.
466
278 First Bad Version
return l;
}
}
467
279 Perfect squares
1. divide by 4, notice that, 2 and 8, 3 and 12, 4 and 16 has the same number of
square factors.
2. if number%8==7, this result in a square factors 2^2 + 1 +1 +1, which is four.
3. if any two numbers can suqare sum to n, return 1 or 2.
4. otherwise result is 3.
Solution 2. recusive.
468
279 Perfect squares
return res;
}
}
Solution 3. DP. this is a forward dp question, using an array dp[], dp[i] means the
number need to square-sum up to i, then, for all the j from 1 to i+jj <=n; calculate
dp[i+jj] = ?, initially set each dp[i] equals to max.
return dp[n];
}
}
469
280 Wiggle Sort
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3,
4].
Solve it in-place.
Arrays.sort(nums);
int i=2;
for( ; i< nums.length-1 ; ) {
int x = nums[i];
nums[i] = nums[i+1];
nums[i+1] = x;
i +=2;
}
}
}
470
280 Wiggle Sort
if the property is not observed, simple swap the property-break number. the
previous relation at i-2 will still stand.
471
281 Zigzag Iterator
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements
returned by next should be: [1, 3, 2, 4, 5, 6].
472
281 Zigzag Iterator
return val;
}
/**
* Your ZigzagIterator object will be instantiated and called
as such:
* ZigzagIterator i = new ZigzagIterator(v1, v2);
* while (i.hasNext()) v[f()] = i.next();
*/
```
:set nu!
473
281 Zigzag Iterator
474
282 Expression Add Operators
Examples:
usually this case you need to traverse the string from the beginning, the
recusively build the result for the left.
475
282 Expression Add Operators
}
}
476
282 Expression Add Operators
477
283 Move Zeroes
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should
be [1, 3, 12, 0, 0].
Note: You must do this in-place without making a copy of the array. Minimize the
total number of operations.
478
283 Move Zeroes
479
284 Peeking Iterator
Here is an example. Assume that the iterator is initialized to the beginning of the
list: [1, 2, 3].
Now you call peek() and it returns 2, the next element. Calling next() after that still
return 2.
You call next() the final time and it returns 3, the last element. Calling hasNext()
after that should return false.
Hint:
Test your design with call order of peek() before next() vs next() before peek().
For a clean implementation, check out Google's guava library source code
Follow up: How would you extend your design to be generic and work with all
types, not just integer?
480
284 Peeking Iterator
iter = iterator;
}
@Override
public boolean hasNext() {
return peeked != null || iter.hasNext();
}
}
481
285 Inroder Successor in BST
Note: If the given node has no in-order successor in the tree, return null.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p)
{
if(root == null) return null;
TreeNode is;
if(root == p){
is = root.right;
while(is != null && is.left != null) is = is.left;
return is;
}else if(root.val < p.val){
return inorderSuccessor(root.right, p);
}else{
is = inorderSuccessor(root.left, p);
}
482
285 Inroder Successor in BST
iterative
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p)
{
TreeNode res = null;
TreeNode target = null;
Stack<TreeNode> stack = new Stack<>();
root = top.right;
}
return res;
}
}
483
285 Inroder Successor in BST
484
286 Walls and Gates
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
485
286 Walls and Gates
if(rooms[i][j] == 0){
dfs(rooms, i, j, visited, 0);
}
}
}
}
}
}
the visited array is to avoid loop, which can be done by checking dis > rooms[x][y]
486
286 Walls and Gates
}
}
}
}
BFS classic
487
286 Walls and Gates
488
286 Walls and Gates
}
}
}
489
286 Walls and Gates
while(!queue.isEmpty()){
Pair p = queue.poll();
for(int[] d : dir){
int x = p.x + d[0];
int y = p.y + d[1];
if(x <0 || x >= rooms.length || y <0 || y>= room
s[0].length
|| rooms[x][y] <= rooms[p.x][p.y] + 1)
continue;
rooms[x][y] = rooms[p.x][p.y] + 1;
queue.offer(new Pair(x,y));
}
}
}
}
490
286 Walls and Gates
int m = rooms.length;
int n = rooms[0].length;
while(!queue.isEmpty()){
int p = queue.poll();
int px = p / n;
int py = p % n;
for(int[] d : dir){
int x = px + d[0];
int y = py + d[1];
if(x <0 || x >= rooms.length || y <0 || y>= room
s[0].length
|| rooms[x][y] <= rooms[px][py] + 1)
continue;
rooms[x][y] = rooms[px][py] + 1;
queue.offer(x*n + y);
}
}
}
}
491
286 Walls and Gates
492
287 Find the Duplicate Number
Note: You must not modify the array (assume the array is read only). You must
use only constant, O(1) extra space. Your runtime complexity should be less than
O(n2). There is only one duplicate number in the array, but it could be repeated
more than once.
O(nlgn) Solution.
O(n) Solution.
493
287 Find the Duplicate Number
494
287 Find the Duplicate Number
int slow = 0;
int fast = 0;
do{
slow = nums[slow];
fast = nums[nums[fast]];
}while(slow != fast);
fast = 0;
while(fast != slow){
fast = nums[fast];
slow = nums[slow];
}
return fast;
}
} ```
495
288 Unique Word Abbreviation
1
b) d|o|g --> d1g
1 1 1
1---5----0----5--8
c) i|nternationalizatio|n --> i18n
1
1---5----0
d) l|ocalizatio|n --> l10n
Assume you have a dictionary and given a word, find whether its abbreviation is
unique in the dictionary. A word's abbreviation is unique if no other word from the
dictionary has the same abbreviation.
Example:
Given dictionary = [ "deer", "door", "cake", "card" ]
The tricky part of this question is the case of duplications in the dictionary. if input
dictionary is ["a", "a", "a"], and query is isUnique("a"), this should return true;
because "a" is unique. another point require attention is to query the exactly word
in the dictionary, this also should return true.
496
288 Unique Word Abbreviation
497
288 Unique Word Abbreviation
498
290 Word Patterns
Here follow means a full match, such that there is a bijection between a letter in
pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes: You may assume pattern contains only lowercase letters, and str contains
lowercase letters separated by a single space.
Solution 1.
Keep two hash tables, one map from pattern.charAt[i] to str[i], one map from the
other direction. if not exists in either map, update the key-value pair. then compare
whether both maps match each other.
499
290 Word Patterns
return true;
}
}
Solution 2.
There is one more smart solution that take advantage of Map.put()'s return value.
and more importantly it utilizes a un-generic map from old java which is not safe.
500
290 Word Patterns
return true;
}
}
501
293 Flip Game
Write a function to compute all possible states of the string after one valid move.
For example, given s = "++++", after one move, it may become one of the
following states:
[
"--++",
"+--+",
"++--"
]
please notice that the input string may be all '+', or all '-', or somewhere in
between.
return res;
}
}
502
293 Flip Game
503
294 Flip Game II
For example, given s = "++++", return true. The starting player can guarantee a
win by flipping the middle "++" to become "+--+".
504
294 Flip Game II
return false;
}
}
505
295 something is not riht
void addNum(int num) - Add a integer number from the data stream to the data
structure. double findMedian() - Return the median of all elements so far. For
example:
add(1)
add(2)
findMedian() -> 1.5
add(3)
findMedian() -> 2
class MedianFinder {
506
295 something is not riht
maxHeap.offer(num);
num = maxHeap.poll();
}
minHeap.offer(num);
}else{
if(minHeap.size() > 0 && num > minHeap.peek()){
minHeap.offer(num);
num = minHeap.poll();
}
maxHeap.offer(num);
}
}
}
};
507
299 Bulls and Cows
For example:
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) Write a function to
return a hint according to the secret number and friend's guess, use A to indicate
the bulls and B to indicate the cows. In the above example, your function should
return "1A3B".
Please note that both secret number and friend's guess may contain duplicate
digits, for example:
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and
your function should return "1A1B". You may assume that the secret number and
your friend's guess only contain digits, and their lengths are always equal.
The question:
if both string has same chars at the same position, it counts as a bull,
if a char instance in guess shows in the secret, it counts as a cow, it behaves like
offset this char from both strings ,if there is another instance of same char shows
both in guess and secret, still counts as a cow.
508
299 Bulls and Cows
Here is a nicer solution, worth remembering and learning from this method.
509
300 Longest Increasing Subsequence
For example,
Don't really know how to solve this for a long time. The equation is:
510
300 Longest Increasing Subsequence
The O(nlogn) algorithms keep an result array, all the number is initialized to
MAX_VALUE, then for each number in the data array, try to find the first index that
result[index] > number[i]; if so, update result[index] = number[i]; continue doing
this, first index whose value is not MAX_VALUE is the result max increasing
sequence.
511
300 Longest Increasing Subsequence
512
300 Longest Increasing Subsequence
}
}
513
300 Longest Increasing Subsequence
514
301 Remove Invalid Parenthesis
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
queue.offer(s);
// if found in certain level(bfs), traverse all in the q
ueue, don't go deeper.
boolean found = false;
while(!queue.isEmpty()){
String t = queue.poll();
if(isP(t)){
res.add(t);
found = true;
}
if(found) continue; // get all the valid ones from q
ueue.
515
301 Remove Invalid Parenthesis
;
if(!visited.contains(nt)){
queue.offer(nt);
visited.add(nt);
}
}
}
return res;
}
516
301 Remove Invalid Parenthesis
void dfs(String s, int k, int lM, int rM, int open, StringBu
ilder sb){
if(k == s.length() && lM == 0 && rM==0 && open == 0){
res.add(sb.toString());
return;
}
if( k == s.length() || lM < 0 || rM < 0 || open < 0) ret
urn;
int len = sb.length();
if(s.charAt(k) == '('){
dfs(s, k+1, lM-1, rM, open, sb);
dfs(s, k+1, lM, rM, open+1, sb.append('('));
sb.setLength(len);
}
}
Why the following not working, StringBuilder is shared between all dfs
instances, and the following code set the length to be longer than its need in
the second line, then the error, you should use a String instance instead of
StringBuilder
517
301 Remove Invalid Parenthesis
518
305 number of islands ii
Example:
Given m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]. Initially, the 2d grid grid is
filled with water. (Assume 0 represents water and 1 represents land).
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0 Number of islands = 1
0 0 0
1 1 0
0 0 0 Number of islands = 1
0 0 0
1 1 0
0 0 1 Number of islands = 2
0 0 0
519
305 number of islands ii
1 1 0
0 0 1 Number of islands = 3
0 1 0
Use Union-Find Set to solve this problem. to use this alogrithm, we need to design
a set of APIs we can follow while updating the required data structure, this API +
data structure will:
count++;
lands[pX*n+pY] = pX*n+pY;
520
305 number of islands ii
if(nX >=0 && nX<m && nY >=0 && nY <n && lands[nX
*n+nY]!=-1 && lands[nX*n+nY] != lands[pX*n+pY]){
count--;
union(lands, lands[nX*n+nY], lands[pX*n+pY])
;
}
}
result.add(count);
}
return result;
}
Quick-Union, O(klgmn)
521
305 number of islands ii
if(nX >=0 && nX<m && nY >=0 && nY <n && lands[nX
*n+nY]!=-1){
int pRoot = find(lands, pX*n+pY);
int nRoot = find(lands, nX*n+nY);
if(pRoot != nRoot){
count--;
lands[pRoot] = nRoot;// union happens he
re
}
}
}
result.add(count);
}
return result;
}
the problem with above solution is that when union happens, each set connects
randomly, which cause the next find may be a deep traverse along the tree. by
using a weighted method this can be reduced.
522
305 number of islands ii
bit.
we can still improve the performance using path compression, simply update the
root information in the find() method
523
311 Sparse Matrix Multiplication
You may assume that A's column number is equal to B's row number.
Example:
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]
| 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
Even direct multiplying gives better result. this question is expecting you to use
hash table.
524
311 Sparse Matrix Multiplication
return C;
}
}
HashTable solution takes more time to solve the test cases, and it will pay off
in larger set.
525
311 Sparse Matrix Multiplication
526
313 Super Ugly number
Super ugly numbers are positive numbers whose all prime factors are in the given
prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is
the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of
size 4.
Note: (1) 1 is a super ugly number for any given primes. (2) The given numbers in
primes are in ascending order. (3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
527
313 Super Ugly number
while(true){
if(res.size() == n) return res.get(res.size()-1);
int tmp = Integer.MAX_VALUE;
int smallestIndex = -1;
for(int i=0; i< index.length;i++){
int t = res.get(index[i])*primes[i];
if(t < tmp){
tmp = t;
smallestIndex = i;
}
}
index[smallestIndex]++;
if(res.get(res.size()-1) != tmp)
res.add(tmp);
}
}
to be finished
528
314 Binary Tree Vertical Order Traversal
If two nodes are in the same row and column, the order should be from left to
right.
Examples:
3
/\
/ \
9 20
/\
/ \
15 7
[
[9],
[3,15],
[20],
[7]
]
529
314 Binary Tree Vertical Order Traversal
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
[
[4],
[9],
[3,0,1],
[8],
[7]
]
Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left
child is 5),
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2
530
314 Binary Tree Vertical Order Traversal
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Map<Integer, List<Integer>> dict = new TreeMap<>();
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> code = new LinkedList<>();
queue.offer(root);
code.offer(0);
while(!queue.isEmpty()){
TreeNode front = queue.poll();
int val = code.poll();
if(!dict.containsKey(val)){
dict.put(val, new ArrayList<>());
}
dict.get(val).add(front.val);
if(front.left != null){
queue.offer(front.left);
code.offer(val-1);
}
531
314 Binary Tree Vertical Order Traversal
if(front.right != null){
queue.offer(front.right);
code.offer(val+1);
}
}
res.addAll(dict.values());
return res;
}
}
532
315 Count of Smaller Numbers After Self
You are given an integer array nums and you have to return a new counts array.
The counts array has the property where counts[i] is the number of smaller
elements to the right of nums[i].
Example:
Segment Tree
class SegmentTreeNode {
int start, end;
int num;
SegmentTreeNode ltree, rtree;
public SegmentTreeNode(int s, int e) {
start = s;
end = e;
}
}
533
315 Count of Smaller Numbers After Self
return root;
}
534
315 Count of Smaller Numbers After Self
Use binary to insert each node from back of array, tail element is the root node.
this is an augmented binary search tree where each node contains how many
nodes have less values than current node, then when new node is inserted and
the new value is greater than root node, there will be root.count number of nodes,
the count is initialized to 1, cause root node itself count when greater value is
inserted.
535
315 Count of Smaller Numbers After Self
}else{
root = root.left;
}
}else{
c += root.count;
if(root.right == null){
root.right = new TreeNode(val);
break;
}else{
root = root.right;
}
}
}
return c;
}
class TreeNode{
TreeNode left;
TreeNode right;
int val;
int count = 1;
public TreeNode(int val){
this.val = val;
}
}
}
536
317 Shortest Distance from All Buildings
For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
1 - 0 - 2 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
The point (1,2) is an ideal empty land to build a house, as the total travel distance
of 3+3+1=7 is minimal. So return 7.
Note: There will be at least one building. If it is not possible to build such house
according to the above rules, return -1.
537
317 Shortest Distance from All Buildings
int buildingNums = 0;
538
317 Shortest Distance from All Buildings
dist++;
int size = queue.size();// all size number of node,
their neigbors belongs to next dist, which for distance.
for(int i=0 ; i<size; i++){
int[] top = queue.poll();
for(int j=0; j< 4;j++){
int k = top[0] + neighbor[j][0];
int l = top[1] + neighbor[j][1];
if(k>=0 && k< row && l >= 0 && l < col && gr
id[k][l] == 0 && !visited[k][l]){
visited[k][l] = true;
dis[k][l] += dist;
num[k][l]++;
queue.add(new int[]{k,l});
}
}
}
}
}
}
539
319 Bulb Switcher
Example:
Given n = 3.
prime number: only factor is 1 and itself, when at 1, the bulb is set, when at
itself, the bulb is unset, and there is not other way the prime-number-index
bulb get accessed again.
regular number(not perfect square number), since each such number will
have factors count in pairs. so the result of such bulb is reset to off.
perfect square number, it may have several pairs of factors, but it also has a
factor which x^2 = n, this x number only access the bulb once, so all the
perfect-square number is will keep the bulb on.
540
319 Bulb Switcher
541
322 Coin Change
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note: You may assume that you have an infinite number of each kind of coin.
This is a forward DP, by knowing DP[i], calculate DP[i + x]. Note the direction,
also here we need to caculate dp[i] + 1, which may overflow. so the MAX value is
actually Integer.MAX_VALUE -1, or 0x7ffffffe;
542
322 Coin Change
543
324 Wiggle Sort II
Example: (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1,
6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
Solution
first sort the array, then cut the array 2 parts, each round , pick a number from
the end of each parts.
}
}
544
324 Wiggle Sort II
545
325 Maximum Size Subarray Sum Equals k
Example 1: Given nums = [1, -1, 5, -2, 3], k = 3, return 4. (because the subarray
[1, -1, 5, -2] sums to 3 and is the longest)
Example 2: Given nums = [-2, -1, 2, 1], k = 1, return 2. (because the subarray [-1,
2] sums to 1 and is the longest)
546
325 Maximum Size Subarray Sum Equals k
547
328 Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even
nodes. Please note here we are talking about the node number and not the value
in the nodes.
You should try to do it in place. The program should run in O(1) space complexity
and O(nodes) time complexity.
Note: The relative order inside both the even and odd groups should remain as it
was in the input. The first node is considered odd, the second node even and so
on ...
548
328 Odd Even Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode odd = new ListNode(-1);
ListNode even = new ListNode(-1);
ListNode o = odd;
ListNode e = even;
int count = 0;
while(head != null){
count++;
if((count&1) == 1){
o.next = head;
o = o.next;
}else{
e.next = head;
e = e.next;
}
head = head.next;
}
e.next = null;
o.next = even.next;
return odd.next;
}
}
549
329 Longest Increasing Path in a Matrix
From each cell, you can either move to four directions: left, right, up or down. You
may NOT move diagonally or move outside of the boundary (i.e. wrap-around is
not allowed).
Example 1:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
Example 2:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
DONT think too hard. it is simply a dfs traversal on each node, while traversing,
remember the longest distance from each node.
550
329 Longest Increasing Path in a Matrix
if(matrix.length == 0) return 0;
int[][] dis = new int[matrix.length][matrix[0].length];
int res = 0;
for(int i=0; i< matrix.length; i++){
for(int j=0; j< matrix[0].length; j++){
res = Math.max(res, dfs(matrix, i, j, dis));
}
}
return res;
}
551
330 Patching Array
Example 1:
Return 1.
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3],
[1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
Example 2:
Return 2.
Example 3:
Return 0
Consider [1,2,4,11,30]
with 1,2,4, we can represent [1...7], but 8 cannot, so patch 8, after patch 8, the
entire array can represent [1...15], can the patched array combine to 16 ? anwser
is yes, [1...15] + 11 can represent up to 26, so no need to add 16 or any number
552
330 Patching Array
before 27, then just same as patching 8, we need to patch 27, now the entire
array can combine to 53, which is > 50, so only need to patch 2 numbers.
return count;
}
}
553
333 Largest BST Subtree
10
/ \
5 15
/ \ \
1 8 7
The Largest BST Subtree in this case is the highlighted one. The return value is
the subtree's size, which is 3.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/*
1. you need to track each subtree is bst or not.
2. you need to track the size of subtree if it is a bst.
3. thus global variable/TreeNode won't keep consistent i
nfo
regarding 1&2.
4. you need a wrapper to hold such 2 information. along
with the
current range of substree.
554
333 Largest BST Subtree
*/
class Node{
int size;
int left,right;
boolean isBst;
Node(){
size = 0;
isBst = true;
left = Integer.MAX_VALUE;
right = Integer.MIN_VALUE;
}
}
public int largestBSTSubtree(TreeNode root) {
Node n = isBST(root);
return n.size;
}
Node l = isBST(root.left);
Node r = isBST(root.right);
if(l.isBst && r.isBst && l.right <= root.val && r.left >
= root.val){
node.size = l.size + r.size +1;
node.isBst = true;
}else{
node.size = Math.max(l.size, r.size);
node.isBst = false;
}
555
333 Largest BST Subtree
return node;
}
}
556
334 Increasing Triplet Subsequence
Formally the function should: Return true if there exists i, j, k such that arr[i] <
arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
Use two variables, min, seondMin to narrow the search range, initially, both set to
MAX_VALUE, min is the smallest number so far, and secondMin is a number
larger than min, but after min's position.
557
334 Increasing Triplet Subsequence
558
337 House Robber III
The thief has found himself a new place for his thievery again. There is only one
entrance to this area, called the "root." Besides the root, each house has one and
only one parent house. After a tour, the smart thief realized that "all houses in this
place forms a binary tree". It will automatically contact the police if two directly-
linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without
alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Example 2:
3
/ \
4 5
/ \ \
1 3 1
This one has to be recursive, cause you don't really know which is going to be
picked during the process. RobValue(Root)=Max of
1. RobValue(Root.left) + RobValue(Root.right)
2. RobValue(Root.left without left child) + RobValue(Root.right without right
child) + Root.val;
559
337 House Robber III
The trick of this question is to return a pair of value from recursive call, res[2], first
value is the max rob value from the current node, and res[1] is the max rob value
without rob current node.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int rob(TreeNode root) {
return rob_(root)[0];
}
return res;
}
}
560
339 Nested List Weight Sum
Each element is either an integer, or a list -- whose elements may also be integers
or other lists.
Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)
Example 2:
Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6
at depth 3; 1 + 42 + 63 = 27)
/**
* // This is the interface that allows for creating nested list
s.
* // You should not implement it, or speculate about its implem
entation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single inte
ger, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger hol
ds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds,
if it holds a nested list
* // Return null if this NestedInteger holds a single integ
er
* public List<NestedInteger> getList();
* }
561
339 Nested List Weight Sum
*/
public class Solution {
public int depthSum(List<NestedInteger> nestedList) {
int res = 0;
for(NestedInteger ni : nestedList){
res += weight(ni, 1);
}
return res;
}
a clearer solution.
562
339 Nested List Weight Sum
}
private int sum(List<NestedInteger> nl, int depth){
int sum = 0;
for(NestedInteger ni : nl){
if(ni.isInteger()){
sum += ni.getInteger() * depth;
}else{
sum += sum(ni.getList(), depth+1);
}
}
return sum;
}
563
341 Flatten Nested List Iterator
Each element is either an integer, or a list -- whose elements may also be integers
or other lists.
Example 1:
By calling next repeatedly until hasNext returns false, the order of elements
returned by next should be: [1,1,2,1,1].
Example 2:
By calling next repeatedly until hasNext returns false, the order of elements
returned by next should be: [1,4,6].
/**
* // This is the interface that allows for creating nested list
s.
* // You should not implement it, or speculate about its implem
entation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single inte
ger, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger hol
ds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds,
if it holds a nested list
564
341 Flatten Nested List Iterator
@Override
public Integer next() {
return mList.get(index++);
}
@Override
public boolean hasNext() {
return index < mList.size();
}
}
/**
* Your NestedIterator object will be instantiated and called as
565
341 Flatten Nested List Iterator
such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
/**
* // This is the interface that allows for creating nested list
s.
* // You should not implement it, or speculate about its implem
entation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single inte
ger, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger hol
ds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds,
if it holds a nested list
* // Return null if this NestedInteger holds a single integ
er
* public List<NestedInteger> getList();
* }
*/
public class NestedIterator implements Iterator<Integer> {
566
341 Flatten Nested List Iterator
stack.push(nestedList.get(i));
}
}
@Override
public Integer next() {
return stack.pop().getInteger();
}
@Override
public boolean hasNext() {
while(!stack.isEmpty()){
NestedInteger ni = stack.peek();
if(ni.isInteger()){
return true;
}else{
stack.pop();
List<NestedInteger> lni = ni.getList();
for(int i = lni.size() -1; i>= 0; i--){
stack.push(lni.get(i));
}
}
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as
such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
567
342 Power of Four
Example: Given num = 16, return true. Given num = 5, return false.
return num != 0 && (num & (num-1)) == 0 && (num & 0xAAAA
AAAA) == 0;
}
}
568
343 Integer Break
DP.
569
344 Reverse String
}
}
570
345 Reverse Vowels of a String
Example 1:
Example 2:
NOTICE THAT left cannot go beyond right, otherwise you end up swap already
swapped pairs.
571
345 Reverse Vowels of a String
int left = 0;
int right = d.length-1;
while(left < right){
while(left < d.length && dict.indexOf(d[left]) == -1
) left++;
if(left >= d.length || left >= right) break;
while(right >= 0 && dict.indexOf(d[right]) == -1) ri
ght--;
if(right < 0 || right <= left) break;
572
346 Moving Average from Data Stream
For example,
573
346 Moving Average from Data Stream
return sum/size;
}else{
sum += val;
data.offer(val);
return sum / data.size();
}
}
}
/**
* Your MovingAverage object will be instantiated and called as
such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
574
347 Top K Frequent Elements
Your algorithm's time complexity must be better than O(n log n), where n is the
array's size.
class Pair{
int key;
int count;
Pair(int k, int c){
key = k;
count = c;
}
}
575
347 Top K Frequent Elements
}
};
}
}
576
349 Intersection of Two Arrays
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
577
349 Intersection of Two Arrays
//TODO: you don't really need the set after sort arrays.
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int i=0, j=0;
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
while( i < nums1.length && j < nums2.length){
if(nums1[i] > nums2[j]){
j++;
}else if(nums1[i] < nums2[j]){
i++;
}else{
set.add(nums1[i]);
i++;j++;
}
}
return res;
}
}
578
349 Intersection of Two Arrays
for(int v : nums1){
set.add(v);
}
for(int v : nums2){
if(set.contains(v)) res.add(v);
}
return r;
}
}
579
350 Intersection of Two Arrays II
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note: Each element in the result should appear as many times as it shows in both
arrays. The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your
algorithm?
Use Hashmap.
What if elements of nums2 are stored on disk, and the memory is limited such
that you cannot load all elements into the memory at once?
580
350 Intersection of Two Arrays II
581
352 Data Stream as Disjoint Intervals
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then
the summary will be:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
Follow up: What if there are lots of merges and the number of disjoint intervals are
small compared to the data stream's size?
Time limit exceeded. since it is O(n) complexity. since fast set is O(1), fast get
is O(n).
TreeSet
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class SummaryRanges {
Set<Integer> set = new TreeSet<>();
/** Initialize your data structure here. */
public SummaryRanges() {
582
352 Data Stream as Disjoint Intervals
/**
* Your SummaryRanges object will be instantiated and called as
such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* List<Interval> param_2 = obj.getIntervals();
*/
/**
583
352 Data Stream as Disjoint Intervals
Interval f = set.floor(v);
if(f != null){
if(f.end >= val) return;
if(f.end + 1 == val){
v.start = f.start;
set.remove(f);
}
}
Interval h = set.higher(v);
584
352 Data Stream as Disjoint Intervals
set.add(v);
}
/**
* Your SummaryRanges object will be instantiated and called as
such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* List<Interval> param_2 = obj.getIntervals();
*/
585
356 Line Reflection
}
}
586
356 Line Reflection
587
357 Count Numbers with Unique Digits
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0
≤ x < 100, excluding [11,22,33,44,55,66,77,88,99] )
Hint:
Backtracking should contains three states which are (the current number, number
of steps to get that number and a bitmask which represent which number is
marked as visited so far in the current number). Start with state (0,0,0) and count
all valid number till we reach number of steps equals to 10n.
This problem can also be solved using a dynamic programming approach and
some knowledge of combinatorics.
Let f(k) = count of numbers with unique digits with length equals k.
f(1) = 10, ..., f(k) = 9 9 8 * ... (9 - k + 2) [The first factor is 9 because a number
cannot start with 0].
The Unique digits here means no-duplicates digits for this number.
dp, if n:
0, result is 1, f(0)
1, 10, which is 9 + f(0);
2, 91, which is 9*9 + f(1), first number gets 9 choice(no zero), next is still
9(with zero),
3, 9*9*8 + f(2), each bit will get a choice of 9 - (i-2), i is current bit, -2
means excludes first two bits.
588
357 Count Numbers with Unique Digits
res += tmp;
}
return res;
}
}
589
358. Rearrange String k Distance Apart
All input strings are given in lowercase letters. If it is not possible to rearrange the
string, return an empty string "".
Result: "abcabc"
The same letters are at least distance 3 from each other. Example 2: str =
"aaabc", k = 3
Answer: ""
Answer: "abacabcd"
This question is tricky, not only need you process the string tally the number,
then you need to use heap to pull char out, and in a defined sequence.
590
358. Rearrange String k Distance Apart
}
counts.put(ch, n);
}
return sb.toString();
591
358. Rearrange String k Distance Apart
class Pair{
char ch;
int cnt;
Pair(char c, int t){
ch = c;
cnt = t;
}
};
}
592
359 Logger Rate Limiter
Given a message and a timestamp (in seconds granularity), return true if the
message should be printed in the given timestamp, otherwise returns false.
Example:
593
359 Logger Rate Limiter
return false;
}
}
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/
594
360 Sort Transformed Array
Example:
int l = 0;
int r = nums.length -1;
int[] res = new int[nums.length];
int k = 0;
while(l <= r){ // need to equal to get the final number.
int v1 = eval(nums[l], a, b, c);
int v2 = eval(nums[r], a, b, c);
595
360 Sort Transformed Array
return res;
}
596
360 Sort Transformed Array
int tl = getT(nums[l],a,b,c);
int tr = getT(nums[r],a,b,c);
597
360 Sort Transformed Array
}
}
}
return res;
}
598
362 Design Hit Counter
Each function accepts a timestamp parameter (in seconds granularity) and you
may assume that calls are being made to the system in chronological order (ie,
the timestamp is monotonically increasing). You may assume that the earliest
timestamp starts at 1.
Example:
// hit at timestamp 1.
counter.hit(1);
// hit at timestamp 2.
counter.hit(2);
// hit at timestamp 3.
counter.hit(3);
599
362 Design Hit Counter
Follow up: What if the number of hits per second could be very large? Does your
design scale?
use a queue to cache the hit, if the head of queue is of the 5min limit. pop it.
/**
* Your HitCounter object will be instantiated and called as suc
h:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
600
362 Design Hit Counter
601
364 Nested List Weight Sum II
Each element is either an integer, or a list -- whose elements may also be integers
or other lists.
Different from the previous question where weight is increasing from root to leaf,
now the weight is defined from bottom up. i.e., the leaf level integers have weight
1, and the root level integers have the largest weight.
Example 1: Given the list [[1,1],2,[1,1]], return 8. (four 1's at depth 1, one 2 at
depth 2)
Example 2: Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2,
and one 6 at depth 1; 13 + 42 + 6*1 = 17)
/**
* // This is the interface that allows for creating nested list
s.
* // You should not implement it, or speculate about its implem
entation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single inte
ger, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger hol
ds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds,
if it holds a nested list
* // Return null if this NestedInteger holds a single integ
er
602
364 Nested List Weight Sum II
for(NestedInteger ni : nestedList){
if(ni.isInteger()){
list.set(depth, list.get(depth) + ni.getInteger(
));
}else{
sum(ni.getList(), list, depth+1);
}
}
}
}
603
366 Find Leaves of Binary Tree
1
/ \
2 3
/ \
4 5
Explanation:
1
/
2
1. Now removing the leaf [1] would result in the empty tree:
[]
DFS
604
366 Find Leaves of Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> l = findLeaves(root.left);
List<List<Integer>> r = findLeaves(root.right);
605
366 Find Leaves of Binary Tree
List<List<Integer>> small){
for(int i=0; i< small.size(); i++){
large.get(i).addAll(small.get(i));
}
return large;
}
}
AND the concept of Tree Depth, which the root node has most deepest
depth. and left has depth of 0.
606
366 Find Leaves of Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> findLeaves(TreeNode root) {
find(root);
return res;
}
res.get(depth).add(root.val);
return depth;
}
}
607
367 Valid Perfect Square
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Binary search
return false;
}
}
608
367 Valid Perfect Square
return false;
}
}
609
369 Plus One Linked List
The digits are stored such that the most significant digit is at the head of the list.
Output: 1->2->4
610
369 Plus One Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode plusOne(ListNode head) {
int c = po(head);
if(c != 0){
ListNode newHead = new ListNode(c);
newHead.next = head;
head = newHead;
}
return head;
}
return c;
}
}
611
370 Range Addition
Example:
Given:
length = 5,
updates = [
[1, 3, 2],
[2, 4, 3],
[0, 2, -2]
]
Output:
[-2, 0, 3, 5, 3]
Explanation:
Initial state: [ 0, 0, 0, 0, 0 ]
612
370 Range Addition
613
371 Sum of Tow Integers
return a;
}
}
614
372 Super Pow
Example1:
a = 2
b = [3]
Result: 8
Example2:
a = 2
b = [1,0]
Result: 1024
Two points:
615
372 Super Pow
return res;
}
private int quickPow(int a, int b){
int res = 1;
a = a % mod;
616
373 Find K Pairs with Smallest Sums
Define a pair (u,v) which consists of one element from the first array and one
element from the second array.
Example 1:
Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Return: [1,2],[1,4],[1,6]
The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Return: [1,1],[1,1]
The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Given nums1 = [1,2], nums2 = [3], k = 3
Return: [1,3],[2,3]
All possible pairs are returned from the sequence:
[1,3],[2,3]
Solution samiliar to Meeting Room II, using priority queue to save next result.
617
373 Find K Pairs with Smallest Sums
class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y =y;
}
}
618
373 Find K Pairs with Smallest Sums
}
}
return res;
}
}
619
374 Guess Number Higher or Lower
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1,
or 0):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example:
n = 10, I pick 6.
Return 6.
620
374 Guess Number Higher or Lower
return left;
}
}
621
378 Kth Smallest Element in a Sorted Matrix
Note that it is the kth smallest element in the sorted order, not the kth distinct
element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
622
378 Kth Smallest Element in a Sorted Matrix
class Pair{
int x;
int y;
Pair(int a, int b){
x = a;
y = b;
}
};
p = pq.poll();
return matrix[p.x][p.y];
}
}
623
378 Kth Smallest Element in a Sorted Matrix
624
380 Insert Delete GetRandom O(1)
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:
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
625
380 Insert Delete GetRandom O(1)
/** Inserts a value to the set. Returns true if the set did
not already contain the specified element. */
public boolean insert(int val) {
if(map.containsKey(val)) return false;
list.add(val);
map.put(val, list.size()-1);
return true;
}
/** Removes a value from the set. Returns true if the set co
ntained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val)) return false;
int index = map.get(val);
int last = list.get(list.size()-1);
list.set(index, last);
list.remove(list.size()-1);
map.put(last, index);
map.remove(val);
return true;
626
380 Insert Delete GetRandom O(1)
}
}
/**
* Your RandomizedSet object will be instantiated and called as
such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
627
398. Random Pick Index
Note: The array size can be very large. Solution that uses too much extra space
will not pass the judge.
Example:
offline algorithm
628
398. Random Pick Index
online
629
398. Random Pick Index
return res;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
630