Leetcode Easy1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1070

Table of Contents

Table of Contents 2
1. Two Sum 17
1. Two Sum(C++) 18
1. Two Sum(Python) 19
2. ZigZag Conversion 20
2. ZigZag Conversion(C++) 21
2. ZigZag Conversion(Python) 22
3. Reverse Integer 23
3. Reverse Integer(C++) 24
3. Reverse Integer(Python) 25
4. String to Integer (atoi) 26
4. String to Integer (atoi)(C++) 28
4. String to Integer (atoi)(Python) 29
5. Palindrome Number 30
5. Palindrome Number(C++) 31
5. Palindrome Number(Python) 32
6. Roman to Integer 33
6. Roman to Integer(C++) 35
6. Roman to Integer(Python) 36
7. Longest Common Prefix 37
7. Longest Common Prefix(C++) 38
7. Longest Common Prefix(Python) 39
8. Valid Parentheses 40
8. Valid Parentheses(C++) 41
8. Valid Parentheses(Python) 42
9. Merge Two Sorted Lists 43
9. Merge Two Sorted Lists(C++) 44
9. Merge Two Sorted Lists(Python) 45
10. Swap Nodes in Pairs 46
10. Swap Nodes in Pairs(C++) 47
10. Swap Nodes in Pairs(Python) 48
11. Remove Duplicates from Sorted Array 49
11. Remove Duplicates from Sorted Array(C++) 50
11. Remove Duplicates from Sorted Array(Python) 51
12. Remove Element 52
12. Remove Element(C++) 54
12. Remove Element(Python) 55
13. Implement strStr() 56
13. Implement strStr()(C++) 57
13. Implement strStr()(Python) 59
14. Valid Sudoku 60
14. Valid Sudoku(C++) 62
14. Valid Sudoku(Python) 64
15. Count and Say 65
15. Count and Say(C++) 66
15. Count and Say(Python) 67
16. Maximum Subarray 68
16. Maximum Subarray(C++) 69
16. Maximum Subarray(Python) 70
17. Length of Last Word 71
17. Length of Last Word(C++) 72
17. Length of Last Word(Python) 73
18. Plus One 74
18. Plus One(C++) 75
18. Plus One(Python) 76
19. Add Binary 77
19. Add Binary(C++) 78
19. Add Binary(Python) 79
20. Climbing Stairs 80
20. Climbing Stairs(C++) 81
20. Climbing Stairs(Python) 82
21. Remove Duplicates from Sorted List 83
21. Remove Duplicates from Sorted List(C++) 84
21. Remove Duplicates from Sorted List(Python) 85
22. Merge Sorted Array 86
22. Merge Sorted Array(C++) 87
22. Merge Sorted Array(Python) 88
23. Same Tree 89
23. Same Tree(C++) 91
23. Same Tree(Python) 92
24. Symmetric Tree 93
24. Symmetric Tree(C++) 94
24. Symmetric Tree(Python) 96
25. Binary Tree Level Order Traversal 97
25. Binary Tree Level Order Traversal(C++) 98
25. Binary Tree Level Order Traversal(Python) 99
26. Maximum Depth of Binary Tree 100
26. Maximum Depth of Binary Tree(C++) 101
26. Maximum Depth of Binary Tree(Python) 102
27. Binary Tree Level Order Traversal II 103
27. Binary Tree Level Order Traversal II(C++) 104
27. Binary Tree Level Order Traversal II(Python) 105
28. Balanced Binary Tree 106
28. Balanced Binary Tree(Python) 108
29. Minimum Depth of Binary Tree 109
29. Minimum Depth of Binary Tree(Python) 110
30. Path Sum 111
30. Path Sum(Python) 113
31. Pascal's Triangle 114
31. Pascal's Triangle(C++) 115
31. Pascal's Triangle(Python) 116
32. Pascal's Triangle II 117
32. Pascal's Triangle II(C++) 118
32. Pascal's Triangle II(Python) 119
33. Best Time to Buy and Sell Stock 120
33. Best Time to Buy and Sell Stock(C++) 121
33. Best Time to Buy and Sell Stock(Python) 122
34. Best Time to Buy and Sell Stock II 123
34. Best Time to Buy and Sell Stock II(C++) 124
34. Best Time to Buy and Sell Stock II(Python) 125
35. Valid Palindrome 126
35. Valid Palindrome(C++) 127
35. Valid Palindrome(Python) 128
36. Single Number 129
36. Single Number(C++) 130
36. Single Number(Python) 131
37. Linked List Cycle 132
37. Linked List Cycle(C++) 133
37. Linked List Cycle(Python) 134
38. Min Stack 135
38. Min Stack(C++) 136
38. Min Stack(Python) 138
39. Read N Characters Given Read4 140
39. Read N Characters Given Read4(C++) 142
39. Read N Characters Given Read4(Python) 143
40. Intersection of Two Linked Lists 144
40. Intersection of Two Linked Lists(C++) 146
40. Intersection of Two Linked Lists(Python) 147
41. Compare Version Numbers 148
41. Compare Version Numbers(C++) 150
41. Compare Version Numbers(Python) 151
42. Excel Sheet Column Title 153
42. Excel Sheet Column Title(C++) 154
42. Excel Sheet Column Title(Python) 155
43. Majority Element 156
43. Majority Element(C++) 157
43. Majority Element(Python) 158
44. Two Sum III - Data structure design 159
44. Two Sum III - Data structure design(C++) 160
44. Two Sum III - Data structure design(Python) 161
45. Excel Sheet Column Number 162
45. Excel Sheet Column Number(C++) 163
45. Excel Sheet Column Number(Python) 164
46. Factorial Trailing Zeroes 165
46. Factorial Trailing Zeroes(C++) 166
46. Factorial Trailing Zeroes(Python) 167
47. Combine Two Tables 168
47. Combine Two Tables(Shell) 169
48. Second Highest Salary 170
48. Second Highest Salary(Shell) 171
49. Employees Earning More Than Their Managers 172
49. Employees Earning More Than Their Managers(Shell) 173
50. Duplicate Emails 174
50. Duplicate Emails(Shell) 175
51. Customers Who Never Order 176
51. Customers Who Never Order(Shell) 177
52. Rotate Array 178
52. Rotate Array(C++) 179
52. Rotate Array(Python) 180
53. Reverse Bits 182
53. Reverse Bits(C++) 183
53. Reverse Bits(Python) 184
54. Number of 1 Bits 185
54. Number of 1 Bits(C++) 186
54. Number of 1 Bits(Python) 188
55. Valid Phone Numbers 189
55. Valid Phone Numbers(Bash) 190
56. Tenth Line 191
56. Tenth Line(Bash) 192
57. Delete Duplicate Emails 193
57. Delete Duplicate Emails(Shell) 194
58. Rising Temperature 195
58. Rising Temperature(Shell) 196
59. House Robber 197
59. House Robber(C++) 198
59. House Robber(Python) 199
60. Happy Number 200
60. Happy Number(C++) 201
60. Happy Number(Python) 202
61. Remove Linked List Elements 203
61. Remove Linked List Elements(C++) 204
61. Remove Linked List Elements(Python) 205
62. Count Primes 206
62. Count Primes(C++) 207
62. Count Primes(Python) 208
63. Isomorphic Strings 209
63. Isomorphic Strings(C++) 210
63. Isomorphic Strings(Python) 211
64. Reverse Linked List 212
64. Reverse Linked List(C++) 213
64. Reverse Linked List(Python) 214
65. Contains Duplicate 215
65. Contains Duplicate(C++) 216
65. Contains Duplicate(Python) 217
66. Contains Duplicate II 218
66. Contains Duplicate II(C++) 219
66. Contains Duplicate II(Python) 220
67. Rectangle Area 221
67. Rectangle Area(C++) 222
67. Rectangle Area(Python) 223
68. Implement Stack using Queues 224
68. Implement Stack using Queues(C++) 225
68. Implement Stack using Queues(Python) 227
69. Invert Binary Tree 229
69. Invert Binary Tree(C++) 230
69. Invert Binary Tree(Python) 232
70. Power of Two 234
70. Power of Two(C++) 235
70. Power of Two(Python) 236
71. Implement Queue using Stacks 237
71. Implement Queue using Stacks(C++) 238
71. Implement Queue using Stacks(Python) 239
72. Palindrome Linked List 240
72. Palindrome Linked List(C++) 241
72. Palindrome Linked List(Python) 242
73. Lowest Common Ancestor of a Binary Search Tree 243
73. Lowest Common Ancestor of a Binary Search Tree(C++) 245
73. Lowest Common Ancestor of a Binary Search Tree(Python) 246
74. Delete Node in a Linked List 247
74. Delete Node in a Linked List(C++) 249
74. Delete Node in a Linked List(Python) 250
75. Valid Anagram 251
75. Valid Anagram(C++) 252
75. Valid Anagram(Python) 253
76. Shortest Word Distance 254
76. Shortest Word Distance(C++) 255
76. Shortest Word Distance(Python) 256
77. Strobogrammatic Number 257
77. Strobogrammatic Number(C++) 258
77. Strobogrammatic Number(Python) 259
78. Group Shifted Strings 260
78. Group Shifted Strings(C++) 261
78. Group Shifted Strings(Python) 262
79. Meeting Rooms 263
79. Meeting Rooms(C++) 264
79. Meeting Rooms(Python) 265
80. Binary Tree Paths 266
80. Binary Tree Paths(C++) 267
80. Binary Tree Paths(Python) 268
81. Add Digits 269
81. Add Digits(C++) 270
81. Add Digits(Python) 271
82. Ugly Number 272
82. Ugly Number(C++) 273
82. Ugly Number(Python) 274
83. Palindrome Permutation 275
83. Palindrome Permutation(C++) 276
83. Palindrome Permutation(Python) 277
84. Closest Binary Search Tree Value 278
84. Closest Binary Search Tree Value(C++) 279
84. Closest Binary Search Tree Value(Python) 280
85. Paint Fence 281
85. Paint Fence(C++) 282
85. Paint Fence(Python) 283
86. First Bad Version 284
86. First Bad Version(C++) 285
86. First Bad Version(Python) 286
87. Move Zeroes 287
87. Move Zeroes(C++) 288
87. Move Zeroes(Python) 289
88. Unique Word Abbreviation 290
88. Unique Word Abbreviation(C++) 291
88. Unique Word Abbreviation(Python) 292
89. Word Pattern 293
89. Word Pattern(C++) 294
89. Word Pattern(Python) 295
90. Nim Game 297
90. Nim Game(C++) 298
90. Nim Game(Python) 299
91. Flip Game 300
91. Flip Game(C++) 301
91. Flip Game(Python) 302
92. Bulls and Cows 303
92. Bulls and Cows(C++) 305
92. Bulls and Cows(Python) 306
93. Range Sum Query - Immutable 307
93. Range Sum Query - Immutable(C++) 308
93. Range Sum Query - Immutable(Python) 309
94. Power of Three 310
94. Power of Three(C++) 311
94. Power of Three(Python) 312
95. Nested List Weight Sum 313
95. Nested List Weight Sum(C++) 314
95. Nested List Weight Sum(Python) 315
96. Power of Four 316
96. Power of Four(C++) 317
96. Power of Four(Python) 318
97. Reverse String 319
97. Reverse String(C++) 320
97. Reverse String(Python) 321
98. Reverse Vowels of a String 322
98. Reverse Vowels of a String(C++) 323
98. Reverse Vowels of a String(Python) 324
99. Moving Average from Data Stream 325
99. Moving Average from Data Stream(C++) 326
99. Moving Average from Data Stream(Python) 327
100. Intersection of Two Arrays 328
100. Intersection of Two Arrays(C++) 329
100. Intersection of Two Arrays(Python) 331
101. Intersection of Two Arrays II 333
101. Intersection of Two Arrays II(C++) 334
101. Intersection of Two Arrays II(Python) 337
102. Logger Rate Limiter 340
102. Logger Rate Limiter(C++) 341
102. Logger Rate Limiter(Python) 342
103. Sum of Two Integers 343
103. Sum of Two Integers(C++) 344
103. Sum of Two Integers(Python) 345
104. Guess Number Higher or Lower 348
104. Guess Number Higher or Lower(C++) 349
104. Guess Number Higher or Lower(Python) 350
105. Ransom Note 351
105. Ransom Note(C++) 352
105. Ransom Note(Python) 353
106. First Unique Character in a String 354
106. First Unique Character in a String(C++) 355
106. First Unique Character in a String(Python) 356
107. Find the Difference 357
107. Find the Difference(C++) 358
107. Find the Difference(Python) 359
108. Rotate Function 360
108. Rotate Function(C++) 361
108. Rotate Function(Python) 362
109. Nth Digit 363
109. Nth Digit(C++) 364
109. Nth Digit(Python) 365
110. Binary Watch 366
110. Binary Watch(C++) 368
110. Binary Watch(Python) 369
111. Sum of Left Leaves 370
111. Sum of Left Leaves(C++) 371
111. Sum of Left Leaves(Python) 372
112. Convert a Number to Hexadecimal 373
112. Convert a Number to Hexadecimal(C++) 374
112. Convert a Number to Hexadecimal(Python) 375
113. Valid Word Abbreviation 376
113. Valid Word Abbreviation(C++) 377
113. Valid Word Abbreviation(Python) 378
114. Longest Palindrome 379
114. Longest Palindrome(C++) 380
114. Longest Palindrome(Python) 381
115. Fizz Buzz 382
115. Fizz Buzz(C++) 383
115. Fizz Buzz(Python) 384
116. Third Maximum Number 385
116. Third Maximum Number(C++) 386
116. Third Maximum Number(Python) 387
117. Add Strings 388
117. Add Strings(C++) 389
117. Add Strings(Python) 390
118. Valid Word Square 391
118. Valid Word Square(C++) 393
118. Valid Word Square(Python) 394
119. Number of Segments in a String 395
119. Number of Segments in a String(C++) 396
119. Number of Segments in a String(Python) 397
120. Path Sum III 398
120. Path Sum III(C++) 399
120. Path Sum III(Python) 400
121. Find All Anagrams in a String 401
121. Find All Anagrams in a String(C++) 402
121. Find All Anagrams in a String(Python) 403
122. Arranging Coins 404
122. Arranging Coins(C++) 406
122. Arranging Coins(Python) 407
123. String Compression 408
123. String Compression(C++) 409
123. String Compression(Python) 410
124. Number of Boomerangs 411
124. Number of Boomerangs(C++) 412
124. Number of Boomerangs(Python) 413
125. Find All Numbers Disappeared in an Array 414
125. Find All Numbers Disappeared in an Array(C++) 415
125. Find All Numbers Disappeared in an Array(Python) 416
126. Minimum Moves to Equal Array Elements 417
126. Minimum Moves to Equal Array Elements(C++) 418
126. Minimum Moves to Equal Array Elements(Python) 419
127. Assign Cookies 420
127. Assign Cookies(C++) 421
127. Assign Cookies(Python) 422
128. Poor Pigs 423
128. Poor Pigs(C++) 424
128. Poor Pigs(Python) 425
129. Repeated Substring Pattern 426
129. Repeated Substring Pattern(C++) 427
129. Repeated Substring Pattern(Python) 428
130. Hamming Distance 429
130. Hamming Distance(C++) 430
130. Hamming Distance(Python) 431
131. Heaters 432
131. Heaters(C++) 433
131. Heaters(Python) 434
132. License Key Formatting 435
132. License Key Formatting(C++) 436
132. License Key Formatting(Python) 437
133. Fibonacci Number 438
133. Fibonacci Number(C++) 439
133. Fibonacci Number(Python) 440
134. Game Play Analysis I 441
134. Game Play Analysis I(Shell) 442
135. Game Play Analysis II 443
135. Game Play Analysis II(Shell) 444
136. Detect Capital 445
136. Detect Capital(C++) 446
136. Detect Capital(Python) 447
137. Longest Uncommon Subsequence I 448
137. Longest Uncommon Subsequence I(C++) 449
137. Longest Uncommon Subsequence I(Python) 450
138. Minimum Absolute Difference in BST 451
138. Minimum Absolute Difference in BST(C++) 453
138. Minimum Absolute Difference in BST(Python) 454
139. K-diff Pairs in an Array 455
139. K-diff Pairs in an Array(C++) 456
139. K-diff Pairs in an Array(Python) 457
140. Convert BST to Greater Tree 458
140. Convert BST to Greater Tree(C++) 460
140. Convert BST to Greater Tree(Python) 461
141. Reverse String II 462
141. Reverse String II(C++) 463
141. Reverse String II(Python) 464
142. Diameter of Binary Tree 465
142. Diameter of Binary Tree(C++) 466
142. Diameter of Binary Tree(Python) 468
143. Student Attendance Record I 469
143. Student Attendance Record I(C++) 470
143. Student Attendance Record I(Python) 471
144. Reverse Words in a String III 472
144. Reverse Words in a String III(C++) 473
144. Reverse Words in a String III(Python) 474
145. Array Partition I 475
145. Array Partition I(C++) 476
145. Array Partition I(Python) 477
146. Binary Tree Tilt 478
146. Binary Tree Tilt(C++) 480
146. Binary Tree Tilt(Python) 481
147. Reshape the Matrix 482
147. Reshape the Matrix(C++) 483
147. Reshape the Matrix(Python) 484
148. Subtree of Another Tree 485
148. Subtree of Another Tree(C++) 487
148. Subtree of Another Tree(Python) 488
149. Distribute Candies 489
149. Distribute Candies(C++) 490
149. Distribute Candies(Python) 491
150. Shortest Unsorted Continuous Subarray 492
150. Shortest Unsorted Continuous Subarray(C++) 493
150. Shortest Unsorted Continuous Subarray(Python) 494
151. Longest Harmonious Subsequence 495
151. Longest Harmonious Subsequence(C++) 496
151. Longest Harmonious Subsequence(Python) 497
152. Range Addition II 498
152. Range Addition II(C++) 499
152. Range Addition II(Python) 500
153. Minimum Index Sum of Two Lists 501
153. Minimum Index Sum of Two Lists(C++) 502
153. Minimum Index Sum of Two Lists(Python) 503
154. Design Compressed String Iterator 504
154. Design Compressed String Iterator(C++) 505
154. Design Compressed String Iterator(Python) 506
155. Can Place Flowers 507
155. Can Place Flowers(C++) 508
155. Can Place Flowers(Python) 509
156. Construct String from Binary Tree 510
156. Construct String from Binary Tree(C++) 512
156. Construct String from Binary Tree(Python) 513
157. Merge Two Binary Trees 514
157. Merge Two Binary Trees(C++) 515
157. Merge Two Binary Trees(Python) 516
158. Maximum Distance in Arrays 517
158. Maximum Distance in Arrays(C++) 518
158. Maximum Distance in Arrays(Python) 519
159. Maximum Product of Three Numbers 520
159. Maximum Product of Three Numbers(C++) 521
159. Maximum Product of Three Numbers(Python) 522
160. Sum of Square Numbers 523
160. Sum of Square Numbers(C++) 524
160. Sum of Square Numbers(Python) 525
161. Average of Levels in Binary Tree 526
161. Average of Levels in Binary Tree(C++) 527
161. Average of Levels in Binary Tree(Python) 528
162. Maximum Average Subarray I 529
162. Maximum Average Subarray I(C++) 530
162. Maximum Average Subarray I(Python) 531
163. Set Mismatch 532
163. Set Mismatch(C++) 533
163. Set Mismatch(Python) 534
164. Two Sum IV - Input is a BST 535
164. Two Sum IV - Input is a BST(C++) 537
164. Two Sum IV - Input is a BST(Python) 539
165. Robot Return to Origin 540
165. Robot Return to Origin(C++) 541
165. Robot Return to Origin(Python) 542
166. Image Smoother 543
166. Image Smoother(C++) 545
166. Image Smoother(Python) 546
167. Non-decreasing Array 547
167. Non-decreasing Array(C++) 548
167. Non-decreasing Array(Python) 549
168. Trim a Binary Search Tree 550
168. Trim a Binary Search Tree(C++) 552
168. Trim a Binary Search Tree(Python) 553
169. Second Minimum Node In a Binary Tree 554
169. Second Minimum Node In a Binary Tree(C++) 556
169. Second Minimum Node In a Binary Tree(Python) 557
170. Longest Continuous Increasing Subsequence 558
170. Longest Continuous Increasing Subsequence(C++) 559
170. Longest Continuous Increasing Subsequence(Python) 560
171. Valid Palindrome II 561
171. Valid Palindrome II(C++) 562
171. Valid Palindrome II(Python) 563
172. Baseball Game 564
172. Baseball Game(C++) 566
172. Baseball Game(Python) 567
173. Repeated String Match 568
173. Repeated String Match(C++) 569
173. Repeated String Match(Python) 571
174. Longest Univalue Path 572
174. Longest Univalue Path(C++) 574
174. Longest Univalue Path(Python) 575
175. Employee Importance 576
175. Employee Importance(C++) 578
175. Employee Importance(Python) 579
176. Binary Number with Alternating Bits 580
176. Binary Number with Alternating Bits(C++) 581
176. Binary Number with Alternating Bits(Python) 582
177. Max Area of Island 583
177. Max Area of Island(C++) 584
177. Max Area of Island(Python) 585
178. Count Binary Substrings 586
178. Count Binary Substrings(C++) 587
178. Count Binary Substrings(Python) 588
179. Degree of an Array 589
179. Degree of an Array(C++) 590
179. Degree of an Array(Python) 591
180. Kth Largest Element in a Stream 592
180. Kth Largest Element in a Stream(C++) 593
180. Kth Largest Element in a Stream(Python) 594
181. Max Stack 595
181. Max Stack(C++) 596
181. Max Stack(Python) 598
182. 1-bit and 2-bit Characters 600
182. 1-bit and 2-bit Characters(C++) 601
182. 1-bit and 2-bit Characters(Python) 602
183. Longest Word in Dictionary 603
183. Longest Word in Dictionary(C++) 604
183. Longest Word in Dictionary(Python) 606
184. Find Pivot Index 607
184. Find Pivot Index(C++) 608
184. Find Pivot Index(Python) 609
185. Max Area of Island 610
185. Max Area of Island(C++) 611
185. Max Area of Island(Python) 612
186. Sentence Similarity 613
186. Sentence Similarity(C++) 614
186. Sentence Similarity(Python) 615
187. Find Smallest Letter Greater Than Target 616
187. Find Smallest Letter Greater Than Target(C++) 617
187. Find Smallest Letter Greater Than Target(Python) 618
188. Min Cost Climbing Stairs 619
188. Min Cost Climbing Stairs(C++) 620
188. Min Cost Climbing Stairs(Python) 621
189. Largest Number At Least Twice of Others 622
189. Largest Number At Least Twice of Others(C++) 623
189. Largest Number At Least Twice of Others(Python) 624
190. Shortest Completing Word 625
190. Shortest Completing Word(C++) 627
190. Shortest Completing Word(Python) 628
191. Bold Words in String 629
191. Bold Words in String(C++) 630
191. Bold Words in String(Python) 632
192. Find Anagram Mappings 634
192. Find Anagram Mappings(C++) 635
192. Find Anagram Mappings(Python) 636
193. Prime Number of Set Bits in Binary Representation 637
193. Prime Number of Set Bits in Binary Representation(C++) 638
193. Prime Number of Set Bits in Binary Representation(Python) 639
194. Toeplitz Matrix 640
194. Toeplitz Matrix(C++) 642
194. Toeplitz Matrix(Python) 643
195. Jewels and Stones 644
195. Jewels and Stones(C++) 645
195. Jewels and Stones(Python) 646
196. Minimum Distance Between BST Nodes 647
196. Minimum Distance Between BST Nodes(C++) 649
196. Minimum Distance Between BST Nodes(Python) 650
197. Letter Case Permutation 651
197. Letter Case Permutation(C++) 652
197. Letter Case Permutation(Python) 653
198. Rotated Digits 654
198. Rotated Digits(C++) 655
198. Rotated Digits(Python) 657
199. Rotate String 659
199. Rotate String(C++) 660
199. Rotate String(Python) 662
200. Similar RGB Color 664
200. Similar RGB Color(C++) 665
200. Similar RGB Color(Python) 666
201. Unique Morse Code Words 667
201. Unique Morse Code Words(C++) 668
201. Unique Morse Code Words(Python) 669
202. Number of Lines To Write String 670
202. Number of Lines To Write String(C++) 671
202. Number of Lines To Write String(Python) 672
203. Subdomain Visit Count 673
203. Subdomain Visit Count(C++) 674
203. Subdomain Visit Count(Python) 675
204. Largest Triangle Area 676
204. Largest Triangle Area(C++) 677
204. Largest Triangle Area(Python) 678
205. Most Common Word 679
205. Most Common Word(C++) 680
205. Most Common Word(Python) 681
206. Shortest Distance to a Character 682
206. Shortest Distance to a Character(C++) 683
206. Shortest Distance to a Character(Python) 684
207. Goat Latin 685
207. Goat Latin(C++) 686
207. Goat Latin(Python) 687
208. Positions of Large Groups 688
208. Positions of Large Groups(C++) 689
208. Positions of Large Groups(Python) 690
209. Flipping an Image 691
209. Flipping an Image(C++) 692
209. Flipping an Image(Python) 693
210. Rectangle Overlap 694
210. Rectangle Overlap(C++) 695
210. Rectangle Overlap(Python) 696
211. Magic Squares In Grid 697
211. Magic Squares In Grid(C++) 699
211. Magic Squares In Grid(Python) 700
212. Backspace String Compare 701
212. Backspace String Compare(C++) 702
212. Backspace String Compare(Python) 703
213. Maximize Distance to Closest Person 704
213. Maximize Distance to Closest Person(C++) 706
213. Maximize Distance to Closest Person(Python) 707
214. Peak Index in a Mountain Array 708
214. Peak Index in a Mountain Array(C++) 709
214. Peak Index in a Mountain Array(Python) 710
215. Buddy Strings 711
215. Buddy Strings(C++) 712
215. Buddy Strings(Python) 713
216. Lemonade Change 714
216. Lemonade Change(C++) 715
216. Lemonade Change(Python) 716
217. Transpose Matrix 717
217. Transpose Matrix(C++) 718
217. Transpose Matrix(Python) 719
218. Binary Gap 720
218. Binary Gap(C++) 721
218. Binary Gap(Python) 722
219. Leaf-Similar Trees 723
219. Leaf-Similar Trees(C++) 725
219. Leaf-Similar Trees(Python) 726
220. Walking Robot Simulation 727
220. Walking Robot Simulation(C++) 728
220. Walking Robot Simulation(Python) 729
221. Middle of the Linked List 730
221. Middle of the Linked List(C++) 731
221. Middle of the Linked List(Python) 732
222. Projection Area of 3D Shapes 733
222. Projection Area of 3D Shapes(C++) 735
222. Projection Area of 3D Shapes(Python) 736
223. Uncommon Words from Two Sentences 737
223. Uncommon Words from Two Sentences(C++) 738
223. Uncommon Words from Two Sentences(Python) 739
224. Fair Candy Swap 740
224. Fair Candy Swap(C++) 741
224. Fair Candy Swap(Python) 742
225. Surface Area of 3D Shapes 743
225. Surface Area of 3D Shapes(C++) 745
225. Surface Area of 3D Shapes(Python) 746
226. Groups of Special-Equivalent Strings 747
226. Groups of Special-Equivalent Strings(C++) 748
226. Groups of Special-Equivalent Strings(Python) 749
227. Monotonic Array 750
227. Monotonic Array(C++) 751
227. Monotonic Array(Python) 752
228. Increasing Order Search Tree 753
228. Increasing Order Search Tree(C++) 754
228. Increasing Order Search Tree(Python) 755
229. Sort Array By Parity 756
229. Sort Array By Parity(C++) 757
229. Sort Array By Parity(Python) 758
230. Smallest Range I 759
230. Smallest Range I(C++) 760
230. Smallest Range I(Python) 761
231. X of a Kind in a Deck of Cards 762
231. X of a Kind in a Deck of Cards(C++) 763
231. X of a Kind in a Deck of Cards(Python) 764
232. Reverse Only Letters 765
232. Reverse Only Letters(C++) 766
232. Reverse Only Letters(Python) 767
233. Sort Array By Parity II 768
233. Sort Array By Parity II(C++) 769
233. Sort Array By Parity II(Python) 770
234. Long Pressed Name 771
234. Long Pressed Name(C++) 772
234. Long Pressed Name(Python) 773
235. Unique Email Addresses 774
235. Unique Email Addresses(C++) 775
235. Unique Email Addresses(Python) 776
236. Number of Recent Calls 777
236. Number of Recent Calls(C++) 778
236. Number of Recent Calls(Python) 779
237. Reorder Log Files 780
237. Reorder Log Files(C++) 781
237. Reorder Log Files(Python) 782
238. Valid Mountain Array 783
238. Valid Mountain Array(C++) 784
238. Valid Mountain Array(Python) 785
239. DI String Match 786
239. DI String Match(C++) 787
239. DI String Match(Python) 788
240. Largest Time for Given Digits 789
240. Largest Time for Given Digits(C++) 790
240. Largest Time for Given Digits(Python) 791
241. Verifying an Alien Dictionary 792
241. Verifying an Alien Dictionary(C++) 793
241. Verifying an Alien Dictionary(Python) 794
242. N-Repeated Element in Size 2N Array 795
242. N-Repeated Element in Size 2N Array(C++) 796
242. N-Repeated Element in Size 2N Array(Python) 797
243. Univalued Binary Tree 798
243. Univalued Binary Tree(C++) 799
243. Univalued Binary Tree(Python) 800
244. Powerful Integers 801
244. Powerful Integers(C++) 802
244. Powerful Integers(Python) 803
245. K Closest Points to Origin 804
245. K Closest Points to Origin(C++) 805
245. K Closest Points to Origin(Python) 806
246. Largest Perimeter Triangle 808
246. Largest Perimeter Triangle(C++) 809
246. Largest Perimeter Triangle(Python) 810
247. Squares of a Sorted Array 811
247. Squares of a Sorted Array(C++) 812
247. Squares of a Sorted Array(Python) 813
248. String Without AAA or BBB 814
248. String Without AAA or BBB(C++) 815
248. String Without AAA or BBB(Python) 816
249. Sum of Even Numbers After Queries 817
249. Sum of Even Numbers After Queries(C++) 818
249. Sum of Even Numbers After Queries(Python) 819
250. Add to Array-Form of Integer 820
250. Add to Array-Form of Integer(C++) 821
250. Add to Array-Form of Integer(Python) 822
251. Cousins in Binary Tree 823
251. Cousins in Binary Tree(C++) 825
251. Cousins in Binary Tree(Python) 826
252. Rotting Oranges 827
252. Rotting Oranges(C++) 828
252. Rotting Oranges(Python) 829
253. Find the Town Judge 830
253. Find the Town Judge(C++) 831
253. Find the Town Judge(Python) 832
254. Available Captures for Rook 833
254. Available Captures for Rook(C++) 835
254. Available Captures for Rook(Python) 836
255. Find Common Characters 837
255. Find Common Characters(C++) 838
255. Find Common Characters(Python) 839
256. Maximize Sum Of Array After K Negations 840
256. Maximize Sum Of Array After K Negations(C++) 841
256. Maximize Sum Of Array After K Negations(Python) 842
257. Complement of Base 10 Integer 844
257. Complement of Base 10 Integer(C++) 845
257. Complement of Base 10 Integer(Python) 846
258. Pairs of Songs With Total Durations Divisible by 60 847
258. Pairs of Songs With Total Durations Divisible by 60(C++) 848
258. Pairs of Songs With Total Durations Divisible by 60(Python) 849
259. Binary Prefix Divisible By 5 850
259. Binary Prefix Divisible By 5(C++) 851
259. Binary Prefix Divisible By 5(Python) 852
260. Partition Array Into Three Parts With Equal Sum 853
260. Partition Array Into Three Parts With Equal Sum(C++) 855
260. Partition Array Into Three Parts With Equal Sum(Python) 856
261. Remove Outermost Parentheses 857
261. Remove Outermost Parentheses(C++) 858
261. Remove Outermost Parentheses(Python) 859
262. Sum of Root To Leaf Binary Numbers 860
262. Sum of Root To Leaf Binary Numbers(C++) 862
262. Sum of Root To Leaf Binary Numbers(Python) 863
263. Divisor Game 864
263. Divisor Game(C++) 865
263. Divisor Game(Python) 866
264. Two City Scheduling 867
264. Two City Scheduling(C++) 868
264. Two City Scheduling(Python) 869
265. Matrix Cells in Distance Order 870
265. Matrix Cells in Distance Order(C++) 871
265. Matrix Cells in Distance Order(Python) 872
266. Moving Stones Until Consecutive 873
266. Moving Stones Until Consecutive(C++) 874
266. Moving Stones Until Consecutive(Python) 875
267. Valid Boomerang 876
267. Valid Boomerang(C++) 877
267. Valid Boomerang(Python) 878
268. Flower Planting With No Adjacent 879
268. Flower Planting With No Adjacent(C++) 880
268. Flower Planting With No Adjacent(Python) 881
269. Last Stone Weight 882
269. Last Stone Weight(C++) 883
269. Last Stone Weight(Python) 884
270. Remove All Adjacent Duplicates In String 885
270. Remove All Adjacent Duplicates In String(C++) 886
270. Remove All Adjacent Duplicates In String(Python) 887
271. Actors and Directors Who Cooperated At Least Three Times 888
271. Actors and Directors Who Cooperated At Least Three Times(Shell) 889
272. Height Checker 890
272. Height Checker(C++) 891
272. Height Checker(Python) 892
273. Confusing Number 893
273. Confusing Number(C++) 895
273. Confusing Number(Python) 896
274. Fixed Point 897
274. Fixed Point(C++) 898
274. Fixed Point(Python) 899
275. Index Pairs of a String 900
275. Index Pairs of a String(C++) 901
275. Index Pairs of a String(Python) 903
276. Product Sales Analysis I 905
276. Product Sales Analysis I(Shell) 907
277. Product Sales Analysis II 908
277. Product Sales Analysis II(Shell) 910
278. Greatest Common Divisor of Strings 911
278. Greatest Common Divisor of Strings(C++) 912
278. Greatest Common Divisor of Strings(Python) 913
279. Project Employees I 914
279. Project Employees I(Shell) 916
280. Project Employees II 917
280. Project Employees II(Shell) 919
281. Occurrences After Bigram 920
281. Occurrences After Bigram(C++) 921
281. Occurrences After Bigram(Python) 922
282. Sales Analysis I 923
282. Sales Analysis I(Shell) 925
283. Sales Analysis II 926
283. Sales Analysis II(Shell) 928
284. Sales Analysis III 929
284. Sales Analysis III(Shell) 931
285. Sum of Digits in the Minimum Number 932
285. Sum of Digits in the Minimum Number(C++) 933
285. Sum of Digits in the Minimum Number(Python) 934
286. High Five 935
286. High Five(C++) 936
286. High Five(Python) 937
287. Duplicate Zeros 938
287. Duplicate Zeros(C++) 939
287. Duplicate Zeros(Python) 940
288. Two Sum Less Than K 941
288. Two Sum Less Than K(C++) 942
288. Two Sum Less Than K(Python) 943
289. Distribute Candies to People 944
289. Distribute Candies to People(C++) 945
289. Distribute Candies to People(Python) 947
290. Path In Zigzag Labelled Binary Tree 949
290. Path In Zigzag Labelled Binary Tree(C++) 950
290. Path In Zigzag Labelled Binary Tree(Python) 951
291. Defanging an IP Address 952
291. Defanging an IP Address(C++) 953
291. Defanging an IP Address(Python) 954
292. Reported Posts 955
292. Reported Posts(Shell) 956
293. Print in Order 957
293. Print in Order(C++) 958
293. Print in Order(Python) 960
294. Number of Days in a Month 961
294. Number of Days in a Month(C++) 962
294. Number of Days in a Month(Python) 963
295. Remove Vowels from a String 964
295. Remove Vowels from a String(C++) 965
295. Remove Vowels from a String(Python) 966
296. Maximum Average Subtree 967
296. Maximum Average Subtree(C++) 968
296. Maximum Average Subtree(Python) 969
297. Relative Sort Array 970
297. Relative Sort Array(C++) 971
297. Relative Sort Array(Python) 972
298. Number of Equivalent Domino Pairs 973
298. Number of Equivalent Domino Pairs(C++) 974
298. Number of Equivalent Domino Pairs(Python) 975
299. Largest Unique Number 976
299. Largest Unique Number(C++) 977
299. Largest Unique Number(Python) 978
300. Armstrong Number 979
300. Armstrong Number(C++) 980
300. Armstrong Number(Python) 981
301. N-th Tribonacci Number 982
301. N-th Tribonacci Number(C++) 983
301. N-th Tribonacci Number(Python) 984
302. User Activity for the Past 30 Days I 985
302. User Activity for the Past 30 Days I(Shell) 986
303. User Activity for the Past 30 Days II 987
303. User Activity for the Past 30 Days II(Shell) 988
304. Article Views I 989
304. Article Views I(Shell) 990
305. Check If a Number Is Majority Element in a Sorted Array 991
305. Check If a Number Is Majority Element in a Sorted Array(C++) 992
305. Check If a Number Is Majority Element in a Sorted Array(Python) 993
306. Day of the Year 994
306. Day of the Year(C++) 995
306. Day of the Year(Python) 996
307. Find Words That Can Be Formed by Characters 997
307. Find Words That Can Be Formed by Characters(C++) 998
307. Find Words That Can Be Formed by Characters(Python) 999
308. Single-Row Keyboard 1000
308. Single-Row Keyboard(C++) 1001
308. Single-Row Keyboard(Python) 1002
309. Compare Strings by Frequency of the Smallest Character 1003
309. Compare Strings by Frequency of the Smallest Character(C++) 1004
309. Compare Strings by Frequency of the Smallest Character(Python) 1005
310. Immediate Food Delivery I 1006
310. Immediate Food Delivery I(Shell) 1007
311. Prime Arrangements 1008
311. Prime Arrangements(C++) 1009
311. Prime Arrangements(Python) 1010
312. Diet Plan Performance 1011
312. Diet Plan Performance(C++) 1012
312. Diet Plan Performance(Python) 1013
313. Reformat Department Table 1014
313. Reformat Department Table(Shell) 1015
314. Count Substrings with Only One Distinct Letter 1016
314. Count Substrings with Only One Distinct Letter(C++) 1017
314. Count Substrings with Only One Distinct Letter(Python) 1018
315. Distance Between Bus Stops 1019
315. Distance Between Bus Stops(C++) 1021
315. Distance Between Bus Stops(Python) 1022
316. Day of the Week 1023
316. Day of the Week(C++) 1024
316. Day of the Week(Python) 1025
317. Maximum Number of Balloons 1026
317. Maximum Number of Balloons(C++) 1027
317. Maximum Number of Balloons(Python) 1028
318. How Many Apples Can You Put into the Basket 1029
318. How Many Apples Can You Put into the Basket(C++) 1030
318. How Many Apples Can You Put into the Basket(Python) 1031
319. Minimum Absolute Difference 1032
319. Minimum Absolute Difference(C++) 1033
319. Minimum Absolute Difference(Python) 1034
320. Unique Number of Occurrences 1035
320. Unique Number of Occurrences(C++) 1036
320. Unique Number of Occurrences(Python) 1037
321. Queries Quality and Percentage 1038
321. Queries Quality and Percentage(Shell) 1039
322. Intersection of Three Sorted Arrays 1040
322. Intersection of Three Sorted Arrays(C++) 1041
322. Intersection of Three Sorted Arrays(Python) 1042
323. Split a String in Balanced Strings 1043
323. Split a String in Balanced Strings(C++) 1044
323. Split a String in Balanced Strings(Python) 1045
324. Missing Number In Arithmetic Progression 1046
324. Missing Number In Arithmetic Progression(C++) 1047
324. Missing Number In Arithmetic Progression(Python) 1048
325. Check If It Is a Straight Line 1049
325. Check If It Is a Straight Line(C++) 1051
325. Check If It Is a Straight Line(Python) 1052
326. Find Positive Integer Solution for a Given Equation 1053
326. Find Positive Integer Solution for a Given Equation(C++) 1055
326. Find Positive Integer Solution for a Given Equation(Python) 1056
327. Number of Comments per Post 1057
327. Number of Comments per Post(Shell) 1058
328. Array Transformation 1059
328. Array Transformation(C++) 1060
328. Array Transformation(Python) 1061
329. Minimum Swaps to Make Strings Equal 1062
329. Minimum Swaps to Make Strings Equal(C++) 1063
329. Minimum Swaps to Make Strings Equal(Python) 1064
330. Average Selling Price 1065
330. Average Selling Price(Shell) 1067
331. Cells with Odd Values in a Matrix 1068
331. Cells with Odd Values in a Matrix(C++) 1069
331. Cells with Odd Values in a Matrix(Python) 1070
*******

1. Two Sum
*******

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up totarget.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9


Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6


Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6


Output: [0,1]

Constraints:

2 <= nums.length <= 10 4


-109 <= nums[i] <= 10 9
-109 <= target <= 10 9
Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
*******

1. Two Sum(C++)
*******

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector twoSum(vector& nums, int target) {
7 unordered_map lookup;
8 for (int i = 0; i < nums.size(); ++i) {
9 if (lookup.count(target - nums[i])) {
10 return {lookup[target - nums[i]], i};
11 }
12 lookup[nums[i]] = i;
13 }
14 return {};
15 }
16 };
*******

1. Two Sum(Python)
*******

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def twoSum(self, nums, target):
6 """
7 :type nums: List[int]
8 :type target: int
9 :rtype: List[int]
10 """
11 lookup = {}
12 for i, num in enumerate(nums):
13 if target - num in lookup:
14 return [lookup[target - num], i]
15 lookup[num] = i
16
17 def twoSum2(self, nums, target):
18 """
19 :type nums: List[int]
20 :type target: int
21 :rtype: List[int]
22 """
23 for i in nums:
24 j = target - i
25 tmp_nums_start_index = nums.index(i) + 1
26 tmp_nums = nums[tmp_nums_start_index:]
27 if j in tmp_nums:
28 return [nums.index(i), tmp_nums_start_index + tmp_nums.index(j)]
29
30
*****************

2. ZigZag Conversion
*****************

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this
pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3


Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4


Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I

Example 3:

Input: s = "A", numRows = 1


Output: "A"

Constraints:

1 <= s.length <= 1000


s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000
*****************

2. ZigZag Conversion(C++)
*****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string convert(string s, int numRows) {
7 if (numRows == 1) {
8 return s;
9 }
10 const int step = 2 * numRows - 2;
11 string zigzag;
12 for (int i = 0; i < numRows; ++i) {
13 for (int j = i; j < s.length(); j += step) {
14 zigzag.push_back(s[j]);
15 if (0 < i && i < numRows - 1 &&
16 j + step - 2 * i < s.length()) {
17 zigzag.push_back(s[j + step - 2 * i]);
18 }
19 }
20 }
21 return zigzag;
22 }
23 };
*****************

2. ZigZag Conversion(Python)
*****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def convert(self, s, numRows):
6 """
7 :type s: str
8 :type numRows: int
9 :rtype: str
10 """
11 if numRows == 1:
12 return s
13 step, zigzag = 2 * numRows - 2, ""
14 for i in xrange(numRows):
15 for j in xrange(i, len(s), step):
16 zigzag += s[j]
17 if 0 < i < numRows - 1 and j + step - 2 * i < len(s):
18 zigzag += s[j + step - 2 * i]
19 return zigzag
20
***************

3. Reverse Integer
***************

Given a signed 32-bit integer x , return x with its digits reversed. If reversing x causes the value to go outside the signed 32-
bit integer range [-231, 2 31 - 1] , then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

-231 <= x <= 2 31 - 1


***************

3. Reverse Integer(C++)
***************

1 // Time: O(logn) = O(1)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int reverse(int x) {
7 int result = 0;
8 while (x) {
9 if (result > numeric_limits::max() / 10 ||
10 (result == numeric_limits::max() / 10 && x % 10 > numeric_limits::max() % 10)) {
11 return 0;
12 }
13 if (result < numeric_limits::min() / 10 ||
14 (result == numeric_limits::min() / 10 && x % 10 < numeric_limits::min() % 10)) {
15 return 0;
16 }
17 result *= 10;
18 result += x % 10;
19 x /= 10;
20 }
21 return result;
22 }
23 };
***************

3. Reverse Integer(Python)
***************

1 # Time: O(logn) = O(1)


2 # Space: O(1)
3
4 class Solution(object):
5 def reverse(self, x):
6 """
7 :type x: int
8 :rtype: int
9 """
10 if x < 0:
11 return -self.reverse(-x)
12
13 result = 0
14 while x:
15 result = result * 10 + x % 10
16 x //= 10
17 return result if result <= 0x7fffffff else 0 # Handle overflow.
18
19 def reverse2(self, x):
20 """
21 :type x: int
22 :rtype: int
23 """
24 if x < 0:
25 x = int(str(x)[::-1][-1] + str(x)[::-1][:-1])
26 else:
27 x = int(str(x)[::-1])
28 x = 0 if abs(x) > 0x7FFFFFFF else x
29 return x
30
31 def reverse3(self, x):
32 """
33 :type x: int
34 :rtype: int
35 """
36 s = cmp(x, 0)
37 r = int(repr(s * x)[::-1])
38 return s * r * (r < 2 ** 31)
39
40
************************

4. String to Integer (atoi)


************************

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'satoi function).

The algorithm for myAtoi(string s) is as follows:

1. Read in and ignore any leading whitespace.


2. Check if the next character (if not already at the end of the string) is'-' or '+' . Read this character in if it is either. This
determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is
ignored.
4. Convert these digits into an integer (i.e. "123" -> 123 , "0032" -> 32). If no digits were read, then the integer is 0. Change the
sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range[-231, 2 31 - 1] , then clamp the integer so that it remains in the range.
Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231
- 1.
6. Return the integer as the final result.

Note:

Only the space character ' ' is considered a whitespace character.


Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Example 1:

Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.

Example 2:

Input: s = " -42"


Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
^
Step 2: " -42" ('-' is read, so the result should be negative)
^
Step 3: " -42" ("42" is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.

Example 3:
Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.

Example 4:

Input: s = "words and 987"


Output: 0
Explanation:
Step 1: "words and 987" (no characters read because there is no leading whitespace)
^
Step 2: "words and 987" (no characters read because there is neither a '-' nor '+')
^
Step 3: "words and 987" (reading stops immediately because there is a non-digit 'w')
^
The parsed integer is 0 because no digits were read.
Since 0 is in the range [-231, 231 - 1], the final result is 0.

Example 5:

Input: s = "-91283472332"
Output: -2147483648
Explanation:
Step 1: "-91283472332" (no characters read because there is no leading whitespace)
^
Step 2: "-91283472332" ('-' is read, so the result should be negative)
^
Step 3: "-91283472332" ("91283472332" is read in)
^
The parsed integer is -91283472332.
Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648.

Constraints:

0 <= s.length <= 200


s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+' , '-', and '.'.
************************

4. String to Integer (atoi)(C++)


************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int myAtoi(string str) {
7 if (str.empty()) {
8 return 0;
9 }
10
11 int ans = 0;
12 int sign = 1;
13 int i = 0;
14
15 // Skip whitespace.
16 while (str[i] == ' ' || str[i] == '\t') {
17 ++i;
18 }
19
20 if (i == str.length()) {
21 return 0;
22 }
23
24 // Parse sign.
25 if (str[i] == '+') {
26 ++i;
27 } else if (str[i] == '-') {
28 sign = -1;
29 ++i;
30 }
31
32 // Compute integer.
33 for (; i < str.length() && isdigit(str[i]); ++i) {
34 if (ans > (numeric_limits::max() - (str[i] - '0')) / 10) {
35 return sign > 0 ? numeric_limits::max() : numeric_limits::min();
36 }
37 ans *= 10;
38 ans += str[i] - '0';
39 }
40
41 ans *= sign;
42 return ans;
43 }
44 };
************************

4. String to Integer (atoi)(Python)


************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def myAtoi(self, str):
6 """
7 :type str: str
8 :rtype: int
9 """
10 INT_MAX = 2147483647
11 INT_MIN = -2147483648
12 result = 0
13
14 if not str:
15 return result
16
17 i = 0
18 while i < len(str) and str[i].isspace():
19 i += 1
20
21 if len(str) == i:
22 return result
23
24 sign = 1
25 if str[i] == "+":
26 i += 1
27 elif str[i] == "-":
28 sign = -1
29 i += 1
30
31 while i < len(str) and '0' <= str[i] <= '9':
32 if result > (INT_MAX - int(str[i])) / 10:
33 return INT_MAX if sign > 0 else INT_MIN
34 result = result * 10 + int(str[i])
35 i += 1
36
37 return sign * result
38
*****************

5. Palindrome Number
*****************

Given an integer x , return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward. For example,121 is palindrome while 123 is not.

Example 1:

Input: x = 121
Output: true

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

Input: x = -101
Output: false

Constraints:

-231 <= x <= 2 31 - 1

Follow up: Could you solve it without converting the integer to a string?
*****************

5. Palindrome Number(C++)
*****************

1 // Time: O(logx) = O(1)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isPalindrome(int x) {
7 if (x < 0) {
8 return false;
9 }
10 int temp = x;
11 int reversed = 0;
12 while (temp != 0) {
13 if (isOverflow(reversed, temp % 10)) {
14 return false;
15 }
16 reversed = reversed * 10 + temp % 10;
17 temp = temp / 10;
18 }
19 return reversed == x;
20 }
21
22 private:
23 bool isOverflow(int q, int r) {
24 static const int max_q = numeric_limits::max() / 10;
25 static const int max_r = numeric_limits::max() % 10;
26 return (q > max_q) || (q == max_q && r > max_r);
27 }
28 };
29
30 // Time: O(logx) = O(1)
31 // Space: O(1)
32 class Solution2 {
33 public:
34 bool isPalindrome(int x) {
35 if(x < 0) {
36 return false;
37 }
38
39 int divisor = 1;
40 while (x / divisor >= 10) {
41 divisor *= 10;
42 }
43
44 for (; x > 0; x = (x % divisor) / 10, divisor /= 100) {
45 int left = x / divisor;
46 int right = x % 10;
47 if (left != right) {
48 return false;
49 }
50 }
51
52 return true;
53 }
54 };
*****************

5. Palindrome Number(Python)
*****************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 # @return a boolean
6 def isPalindrome(self, x):
7 if x < 0:
8 return False
9 copy, reverse = x, 0
10
11 while copy:
12 reverse *= 10
13 reverse += copy % 10
14 copy //= 10
15
16 return x == reverse
17
****************

6. Roman to Integer
****************

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II . The
number 27 is written as XXVII, which is XX + V + II .

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is notIIII. Instead, the
number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the
number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.


X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

Example 1:

Input: s = "III"
Output: 3

Example 2:

Input: s = "IV"
Output: 4

Example 3:

Input: s = "IX"
Output: 9

Example 4:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

1 <= s.length <= 15


s contains only thecharacters ('I', 'V', 'X', 'L', 'C', 'D', 'M') .
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
****************

6. Roman to Integer(C++)
****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int romanToInt(string s) {
7 unordered_map numeral_map = {{'I', 1}, {'V', 5}, {'X', 10},
8 {'L', 50}, {'C', 100}, {'D', 500},
9 {'M', 1000}};
10 int decimal = 0;
11 for (int i = 0; i < s.length(); ++i) {
12 if (i > 0 && numeral_map[s[i]] > numeral_map[s[i - 1]]) {
13 decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]];
14 } else {
15 decimal += numeral_map[s[i]];
16 }
17 }
18 return decimal;
19 }
20 };
21
22 // Time: O(n)
23 // Space: O(1)
24 class Solution2 {
25 public:
26 int romanToInt(string s) {
27 unordered_map numeral_map = {{'I', 1}, {'V', 5}, {'X', 10},
28 {'L', 50}, {'C', 100}, {'D', 500},
29 {'M', 1000}};
30 return accumulate(s.crbegin(), s.crend(), 0,
31 [&numeral_map](int sum , char c) {
32 return sum += ((numeral_map[c] * 5 <= sum) ?
33 -numeral_map[c] : numeral_map[c]);
34 });
35 }
36 };
****************

6. Roman to Integer(Python)
****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @return an integer
6 def romanToInt(self, s):
7 numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100, "D": 500, "M": 1000}
8 decimal = 0
9 for i in xrange(len(s)):
10 if i > 0 and numeral_map[s[i]] > numeral_map[s[i - 1]]:
11 decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]]
12 else:
13 decimal += numeral_map[s[i]]
14 return decimal
15
*********************

7. Longest Common Prefix


*********************

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]


Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]


Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

1 <= strs.length <= 200


0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
*********************

7. Longest Common Prefix(C++)


*********************

1 // Time: O(n * k), k is the length of the common prefix


2 // Space: O(1)
3
4 class Solution {
5 public:
6 string longestCommonPrefix(vector& strs) {
7 if (strs.empty()) {
8 return "";
9 }
10
11 for (int i = 0; i < strs[0].length(); ++i) {
12 for (const auto& str : strs) {
13 if (i >= str.length() || str[i] != strs[0][i]) {
14 return strs[0].substr(0, i);
15 }
16 }
17 }
18 return strs[0];
19 }
20 };
*********************

7. Longest Common Prefix(Python)


*********************

1 # Time: O(n * k), k is the length of the common prefix


2 # Space: O(1)
3
4 class Solution(object):
5 def longestCommonPrefix(self, strs):
6 """
7 :type strs: List[str]
8 :rtype: str
9 """
10 if not strs:
11 return ""
12
13 for i in xrange(len(strs[0])):
14 for string in strs[1:]:
15 if i >= len(string) or string[i] != strs[0][i]:
16 return strs[0][:i]
17 return strs[0]
18
19
20 # Time: O(n * k), k is the length of the common prefix
21 # Space: O(k)
22 class Solution2(object):
23 def longestCommonPrefix(self, strs):
24 """
25 :type strs: List[str]
26 :rtype: str
27 """
28 prefix = ""
29
30 for chars in zip(*strs):
31 if all(c == chars[0] for c in chars):
32 prefix += chars[0]
33 else:
34 return prefix
35
36 return prefix
*****************

8. Valid Parentheses
*****************

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.


2. Open brackets must be closed in the correct order.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

Constraints:

1 <= s.length <= 104


s consists of parentheses only '()[]{}'.
*****************

8. Valid Parentheses(C++)
*****************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool isValid(string s) {
7 const unordered_map symbol_pair = {{')', '('},
8 {']', '['},
9 {'}', '{'}};
10 stack parentheses;
11 for (const auto& c: s) {
12 const auto& it = symbol_pair.find(c);
13 if (it != symbol_pair.cend()) {
14 if (parentheses.empty() ||
15 parentheses.top() != it->second) {
16 return false;
17 }
18 parentheses.pop();
19 } else {
20 parentheses.emplace(c);
21 }
22 }
23 return parentheses.empty();
24 }
25 };
*****************

8. Valid Parentheses(Python)
*****************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 # @return a boolean
6 def isValid(self, s):
7 stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
8 for parenthese in s:
9 if parenthese in lookup:
10 stack.append(parenthese)
11 elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
12 return False
13 return len(stack) == 0
14
**********************

9. Merge Two Sorted Lists


**********************

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first
two lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]


Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]


Output: [0]

Constraints:

The number of nodes in both lists is in the range[0, 50].


-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.
**********************

9. Merge Two Sorted Lists(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
15 ListNode dummy{0};
16 auto curr = &dummy;
17
18 while (l1 && l2) {
19 if (l1->val <= l2->val) {
20 curr->next = l1;
21 l1 = l1->next;
22 } else {
23 curr->next = l2;
24 l2 = l2->next;
25 }
26 curr = curr->next;
27 }
28 curr->next = l1 ? l1 : l2;
29
30 return dummy.next;
31 }
32 };
**********************

9. Merge Two Sorted Lists(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9 def __repr__(self):
10 if self:
11 return "{} -> {}".format(self.val, self.next)
12
13
14 class Solution(object):
15 def mergeTwoLists(self, l1, l2):
16 """
17 :type l1: ListNode
18 :type l2: ListNode
19 :rtype: ListNode
20 """
21 curr = dummy = ListNode(0)
22 while l1 and l2:
23 if l1.val < l2.val:
24 curr.next = l1
25 l1 = l1.next
26 else:
27 curr.next = l2
28 l2 = l2.next
29 curr = curr.next
30 curr.next = l1 or l2
31 return dummy.next
32
33
*******************

10. Swap Nodes in Pairs


*******************

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the
values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]


Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]


Output: [1]

Constraints:

The number of nodes in the list is in the range[0, 100].


0 <= Node.val <= 100
*******************

10. Swap Nodes in Pairs(C++)


*******************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode* swapPairs(ListNode* head) {
15 ListNode dummy{0};
16 dummy.next = head;
17 auto curr = &dummy;
18 while (curr->next && curr->next->next) {
19 auto next_one = curr->next;
20 auto next_two = next_one->next;
21 auto next_three = next_two->next;
22 curr->next = next_two;
23 next_two->next = next_one;
24 next_one->next = next_three;
25 curr = next_one;
26 }
27 return dummy.next;
28 }
29 };
*******************

10. Swap Nodes in Pairs(Python)


*******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9 def __repr__(self):
10 if self:
11 return "{} -> {}".format(self.val, self.next)
12
13 class Solution(object):
14 # @param a ListNode
15 # @return a ListNode
16 def swapPairs(self, head):
17 dummy = ListNode(0)
18 dummy.next = head
19 current = dummy
20 while current.next and current.next.next:
21 next_one, next_two, next_three = current.next, current.next.next, current.next.next.next
22 current.next = next_two
23 next_two.next = next_one
24 next_one.next = next_three
25 current = next_one
26 return dummy.next
27
***********************************

11. Remove Duplicates from Sorted Array


***********************************

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element
appears only once. The relative order of the elements should be kept thesame.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in
the first part of the array nums. More formally, if there arek elements after removing the duplicates, then the firstk elements
of nums should hold the final result. It does not matter what you leave beyond the firstk elements.

Return k after placing the final result in the firstk slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra
memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array


int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will beaccepted.

Example 1:

Input: nums = [1,1,2]


Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]


Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

0 <= nums.length <= 3 * 10 4


-100 <= nums[i] <= 100
nums is sorted in non-decreasing order.
***********************************

11. Remove Duplicates from Sorted Array(C++)


***********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int removeDuplicates(vector& nums) {
7 int last = -1;
8 for (const auto& num : nums) {
9 if (last == -1 || nums[last] != num) {
10 nums[++last] = num;
11 }
12 }
13 return last + 1;
14 }
15 };
***********************************

11. Remove Duplicates from Sorted Array(Python)


***********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param a list of integers
6 # @return an integer
7 def removeDuplicates(self, A):
8 if not A:
9 return 0
10
11 last = 0
12 for i in xrange(len(A)):
13 if A[last] != A[i]:
14 last += 1
15 A[last] = A[i]
16 return last + 1
17
**************

12. Remove Element


**************

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the
elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in
the first part of the array nums. More formally, if there arek elements after removing the duplicates, then the firstk elements
of nums should hold the final result. It does not matter what you leave beyond the firstk elements.

Return k after placing the final result in the firstk slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra
memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array


int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will beaccepted.

Example 1:

Input: nums = [3,2,2,3], val = 3


Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2


Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

0 <= nums.length <= 100


0 <= nums[i] <= 50
0 <= val <= 100
**************

12. Remove Element(C++)


**************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int removeElement(vector& nums, int val) {
7 int left = 0, right = nums.size();
8 while (left < right) {
9 if (nums[left] != val) {
10 ++left;
11 } else {
12 swap(nums[left], nums[--right]);
13 }
14 }
15 return right;
16 }
17 };
**************

12. Remove Element(Python)


**************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param A a list of integers
6 # @param elem an integer, value need to be removed
7 # @return an integer
8 def removeElement(self, A, elem):
9 i, last = 0, len(A) - 1
10 while i <= last:
11 if A[i] == elem:
12 A[i], A[last] = A[last], A[i]
13 last -= 1
14 else:
15 i += 1
16 return last + 1
17
******************

13. Implement strStr()


******************

Implement strStr().

Return the index of the first occurrence of needle in haystack, or-1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 whenneedle is an empty string. This is consistent to C's strstr() and
Java's indexOf().

Example 1:

Input: haystack = "hello", needle = "ll"


Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"


Output: -1

Example 3:

Input: haystack = "", needle = ""


Output: 0

Constraints:

0 <= haystack.length, needle.length <= 5 * 10 4


haystack and needle consist of only lower-case English characters.
******************

13. Implement strStr()(C++)


******************
1 // Time: O(n + k)
2 // Space: O(k)
3
4 // Wiki of KMP algorithm:
5 // http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
6 class Solution {
7 public:
8 int strStr(string haystack, string needle) {
9 if (needle.empty()) {
10 return 0;
11 }
12
13 return KMP(haystack, needle);
14 }
15
16 int KMP(const string& text, const string& pattern) {
17 const vector prefix = getPrefix(pattern);
18 int j = -1;
19 for (int i = 0; i < text.length(); ++i) {
20 while (j > -1 && pattern[j + 1] != text[i]) {
21 j = prefix[j];
22 }
23 if (pattern[j + 1] == text[i]) {
24 ++j;
25 }
26 if (j == pattern.length() - 1) {
27 return i - j;
28 }
29 }
30 return -1;
31 }
32
33 vector getPrefix(const string& pattern) {
34 vector prefix(pattern.length(), -1);
35 int j = -1;
36 for (int i = 1; i < pattern.length(); ++i) {
37 while (j > -1 && pattern[j + 1] != pattern[i]) {
38 j = prefix[j];
39 }
40 if (pattern[j + 1] == pattern[i]) {
41 ++j;
42 }
43 prefix[i] = j;
44 }
45 return prefix;
46 }
47 };
48
49
50 // Time: O(n * k)
51 // Space: O(k)
52 class Solution2 {
53 public:
54 int strStr(string haystack, string needle) {
55 for (int i = 0; i + needle.length() < haystack.length() + 1; ++i) {
56 if (haystack.substr(i, needle.length()) == needle) {
57 return i;
58 }
59 }
60 return -1;
61 }
62 };
******************

13. Implement strStr()(Python)


******************

1 # Time: O(n + k)
2 # Space: O(k)
3
4 class Solution(object):
5 def strStr(self, haystack, needle):
6 """
7 :type haystack: str
8 :type needle: str
9 :rtype: int
10 """
11 if not needle:
12 return 0
13
14 return self.KMP(haystack, needle)
15
16 def KMP(self, text, pattern):
17 prefix = self.getPrefix(pattern)
18 j = -1
19 for i in xrange(len(text)):
20 while j > -1 and pattern[j + 1] != text[i]:
21 j = prefix[j]
22 if pattern[j + 1] == text[i]:
23 j += 1
24 if j == len(pattern) - 1:
25 return i - j
26 return -1
27
28 def getPrefix(self, pattern):
29 prefix = [-1] * len(pattern)
30 j = -1
31 for i in xrange(1, len(pattern)):
32 while j > -1 and pattern[j + 1] != pattern[i]:
33 j = prefix[j]
34 if pattern[j + 1] == pattern[i]:
35 j += 1
36 prefix[i] = j
37 return prefix
38
39
40 # Time: O(n * k)
41 # Space: O(k)
42 class Solution2(object):
43 def strStr(self, haystack, needle):
44 """
45 :type haystack: str
46 :type needle: str
47 :rtype: int
48 """
49 for i in xrange(len(haystack) - len(needle) + 1):
50 if haystack[i : i + len(needle)] == needle:
51 return i
52 return -1
53
54
************

14. Valid Sudoku


************

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validatedaccording to the following rules:

1. Each row must contain the digits 1-9 without repetition.


2. Each column must contain the digits 1-9 without repetition.
3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.

Example 1:

Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true

Example 2:

Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub
Constraints:

board.length == 9
board[i].length == 9
board[i][j] is a digit or '.'.
************

14. Valid Sudoku(C++)


************

1 // Time: O(9^2)
2 // Space: O(9)
3
4 // Better performance solution.
5 class Solution {
6 public:
7 bool isValidSudoku(const vector>& board) {
8 // Check row constraints.
9 for (int i = 0; i < 9; ++i) {
10 if (anyDuplicate(board, i, i + 1, 0, 9)) {
11 return false;
12 }
13 }
14
15 // Check column constraints.
16 for (int j = 0; j < board.size(); ++j) {
17 if (anyDuplicate(board, 0, 9, j, j + 1)) {
18 return false;
19 }
20 }
21
22 // Check region constraints.
23 for (int i = 0; i < 9; i += 3) {
24 for (int j = 0; j < 9; j += 3) {
25 if (anyDuplicate(board, i, i + 3, j, j + 3)) {
26 return false;
27 }
28 }
29 }
30 return true;
31 }
32
33 private:
34 // Return true if subarray board[start_row : end_row - 1][start_col : end_col - 1]
35 // contains any duplicates in [1 : num_elements]; otherwise return false.
36 bool anyDuplicate(const vector>& board, int start_row, int end_row,
37 int start_col, int end_col) {
38 bitset<9> is_present;
39 for (int i = start_row; i < end_row; ++i) {
40 for (int j = start_col; j < end_col; ++j) {
41 if (board[i][j] != '.') {
42 if (is_present[board[i][j] - '1']) {
43 return true;
44 }
45 is_present.flip(board[i][j] - '1');
46 }
47 }
48 }
49 return false;
50 }
51 };
52
53
54 // Time: O(9^2)
55 // Space: O(9)
56 // More generic solution.
57 class Solution2 {
58 public:
59 bool isValidSudoku(const vector>& board) {
60 // Check row constraints.
61 for (int i = 0; i < board.size(); ++i) {
62 if (anyDuplicate(board, i, i + 1, 0, board.size(), board.size())) {
63 return false;
64 }
65 }
66
67 // Check column constraints.
68 for (int j = 0; j < board.size(); ++j) {
69 if (anyDuplicate(board, 0, board.size(), j, j + 1, board.size())) {
70 return false;
71 }
72 }
73
74 // Check region constraints.
75 int region_size = sqrt(board.size());
76 for (int i = 0; i < board.size(); i += region_size) {
77 for (int j = 0; j < board.size(); j += region_size) {
78 if (anyDuplicate(board,
79 i, i + region_size,
80 j, j + region_size,
81 board.size())) {
82 return false;
83 }
84 }
85 }
86 return true;
87 }
88
89 private:
90 // Return true if subarray board[start_row : end_row - 1][start_col : end_col - 1]
91 // contains any duplicates in [1 : num_elements]; otherwise return false.
92 bool anyDuplicate(const vector>& board, int start_row, int end_row,
93 int start_col, int end_col, int num_elements) {
94 vector is_present(num_elements + 1, false);
95 for (int i = start_row; i < end_row; ++i) {
96 for (int j = start_col; j < end_col; ++j) {
97 if (board[i][j] != '.') {
98 if (is_present[board[i][j] - '0']) {
99 return true;
100 }
101 is_present[board[i][j] - '0'] = true;
102 }
103 }
104 }
105 return false;
106 }
107 };
************

14. Valid Sudoku(Python)


************

1 # Time: O(9^2)
2 # Space: O(9)
3
4 class Solution(object):
5 def isValidSudoku(self, board):
6 """
7 :type board: List[List[str]]
8 :rtype: bool
9 """
10 for i in xrange(9):
11 if not self.isValidList([board[i][j] for j in xrange(9)]) or \
12 not self.isValidList([board[j][i] for j in xrange(9)]):
13 return False
14 for i in xrange(3):
15 for j in xrange(3):
16 if not self.isValidList([board[m][n] for n in xrange(3 * j, 3 * j + 3) \
17 for m in xrange(3 * i, 3 * i + 3)]):
18 return False
19 return True
20
21 def isValidList(self, xs):
22 xs = filter(lambda x: x != '.', xs)
23 return len(set(xs)) == len(xs)
24
25
*************

15. Count and Say


*************

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string fromcountAndSay(n-1), which is then converted into a different
digit string.

To determine how you "say" a digit string, split it into theminimal number of groups so that each group is a contiguous
section all of the same character. Then for each group, say the number of characters, then say the character. To convert
the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string"3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

Constraints:

1 <= n <= 30
*************

15. Count and Say(C++)


*************

1 // Time: O(n * 2^n)


2 // Space: O(2^n)
3
4 class Solution {
5 public:
6 string countAndSay(int n) {
7 string seq{"1"};
8 for (int i = 0; i < n - 1; ++i) {
9 seq = getNext(seq);
10 }
11 return seq;
12 }
13
14 private:
15 string getNext(const string& seq) {
16 string next_seq;
17 for(auto i = seq.cbegin(); i != seq.cend();) {
18 auto j = find_if(i, seq.cend(), bind1st(not_equal_to(), *i));
19 next_seq.append(to_string(distance(i, j)));
20 next_seq.push_back(*i);
21 i = j;
22 }
23 return next_seq;
24 }
25 };
*************

15. Count and Say(Python)


*************

1 # Time: O(n * 2^n)


2 # Space: O(2^n)
3
4 class Solution(object):
5 # @return a string
6 def countAndSay(self, n):
7 seq = "1"
8 for i in xrange(n - 1):
9 seq = self.getNext(seq)
10 return seq
11
12 def getNext(self, seq):
13 i, next_seq = 0, ""
14 while i < len(seq):
15 cnt = 1
16 while i < len(seq) - 1 and seq[i] == seq[i + 1]:
17 cnt += 1
18 i += 1
19 next_seq += str(cnt) + seq[i]
20 i += 1
21 return next_seq
22
****************

16. Maximum Subarray


****************

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and
return its sum.

A subarray is a contiguous part of an array.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]


Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]


Output: 1

Example 3:

Input: nums = [5,4,-1,7,8]


Output: 23

Constraints:

1 <= nums.length <= 3 * 10 4


-105 <= nums[i] <= 10 5

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach,
which is more subtle.
****************

16. Maximum Subarray(C++)


****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxSubArray(vector& nums) {
7 int result = numeric_limits::min();
8 int curr = numeric_limits::min();
9 for (const auto &x : nums) {
10 curr = (curr == numeric_limits::min()) ? x : max(curr + x, x);
11 result = max(result, curr);
12 }
13 return result;
14 }
15 };
****************

16. Maximum Subarray(Python)


****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxSubArray(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 result, curr = float("-inf"), float("-inf")
11 for x in nums:
12 curr = max(curr+x, x)
13 result = max(result, curr)
14 return result
*******************

17. Length of Last Word


*******************

Given a string s consists of some words separated by some number of spaces, returnthe length of the last word in the
string.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"


Output: 5

Example 2:

Input: s = " fly me to the moon "


Output: 4

Example 3:

Input: s = "luffy is still joyboy"


Output: 6

Constraints:

1 <= s.length <= 104


s consists of onlyEnglish letters and spaces ' '.
There will be at most one word in s .
*******************

17. Length of Last Word(C++)


*******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int lengthOfLastWord(string s) {
7 const auto is_space = [](const char c) { return isspace(c); };
8 const auto it = find_if_not(s.rbegin(), s.rend(), is_space);
9 const auto jt = find_if(it, s.rend(), is_space);
10 return distance(it, jt);
11 }
12 };
*******************

17. Length of Last Word(Python)


*******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param s, a string
6 # @return an integer
7 def lengthOfLastWord(self, s):
8 length = 0
9 for i in reversed(s):
10 if i == ' ':
11 if length:
12 break
13 else:
14 length += 1
15 return length
16
17 # Time: O(n)
18 # Space: O(n)
19 class Solution2(object):
20 # @param s, a string
21 # @return an integer
22 def lengthOfLastWord(self, s):
23 return len(s.strip().split(" ")[-1])
24
********

18. Plus One


********

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a
single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: digits = [1,2,3]


Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: digits = [4,3,2,1]


Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Example 3:

Input: digits = [0]


Output: [1]

Constraints:

1 <= digits.length <= 100


0 <= digits[i] <= 9
********

18. Plus One(C++)


********

1 // Time: O(n)
2 // Space: O(1)
3
4 // in-place solution
5 class Solution {
6 public:
7 vector plusOne(vector& digits) {
8 for (int i = digits.size() - 1; i >= 0; --i) {
9 if (digits[i] == 9) {
10 digits[i] = 0;
11 } else {
12 ++digits[i];
13 return digits;
14 }
15 }
16 digits[0] = 1;
17 digits.emplace_back(0);
18 return digits;
19 }
20 };
21
22 // Time: O(n)
23 // Space: O(n)
24 class Solution2 {
25 public:
26 vector plusOne(vector& digits) {
27 vector result(digits.rbegin(), digits.rend());
28 int carry = 1;
29 for (auto& num : result) {
30 num += carry;
31 carry = num / 10;
32 num %= 10;
33 }
34 if (carry == 1) {
35 result.emplace_back(carry);
36 }
37 reverse(result.begin(), result.end());
38 return result;
39 }
40 };
********

18. Plus One(Python)


********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def plusOne(self, digits):
6 """
7 :type digits: List[int]
8 :rtype: List[int]
9 """
10 for i in reversed(xrange(len(digits))):
11 if digits[i] == 9:
12 digits[i] = 0
13 else:
14 digits[i] += 1
15 return digits
16 digits[0] = 1
17 digits.append(0)
18 return digits
19
20
21 # Time: O(n)
22 # Space: O(n)
23 class Solution2(object):
24 def plusOne(self, digits):
25 """
26 :type digits: List[int]
27 :rtype: List[int]
28 """
29 result = digits[::-1]
30 carry = 1
31 for i in xrange(len(result)):
32 result[i] += carry
33 carry, result[i] = divmod(result[i], 10)
34 if carry:
35 result.append(carry)
36 return result[::-1]
37
38
**********

19. Add Binary


**********

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"


Output: "100"

Example 2:

Input: a = "1010", b = "1011"


Output: "10101"

Constraints:

1 <= a.length, b.length <= 10 4


a and b consist only of '0' or '1'
characters.
Each string does not contain leading zeros except for the zero itself.
**********

19. Add Binary(C++)


**********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string addBinary(string a, string b) {
7 string res;
8 size_t res_len = max(a.length(), b.length()) ;
9
10 size_t carry = 0;
11 for (int i = 0; i < res_len; ++i) {
12 const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
13 const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
14 size_t sum = carry + a_bit_i + b_bit_i;
15 carry = sum / 2;
16 sum %= 2;
17 res.push_back('0' + sum);
18 }
19 if (carry) {
20 res.push_back('0' + carry);
21 }
22 reverse(res.begin(), res.end());
23
24 return res;
25 }
26 };
27
28 // Iterator solution.
29 class Solution2 {
30 public:
31 string addBinary(string a, string b) {
32 size_t carry = 0;
33 string res;
34
35 for (auto a_it = a.rbegin(), b_it = b.rbegin(); a_it != a.rend() || b_it != b.rend();) {
36 const size_t a_bit_i = (a_it != a.rend()) ? *a_it - '0' : 0;
37 const size_t b_bit_i = (b_it != b.rend()) ? *b_it - '0' : 0;
38 size_t sum = a_bit_i + b_bit_i + carry;
39 carry = sum / 2;
40 sum %= 2;
41 res.push_back('0' + sum);
42
43 if (a_it != a.rend()) {
44 ++a_it;
45 }
46 if (b_it != b.rend()) {
47 ++b_it;
48 }
49 }
50 if (carry) {
51 res.push_back('0' + carry);
52 }
53 reverse(res.begin(), res.end());
54
55 return res;
56 }
57 };
**********

19. Add Binary(Python)


**********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param a, a string
6 # @param b, a string
7 # @return a string
8 def addBinary(self, a, b):
9 result, carry, val = "", 0, 0
10 for i in xrange(max(len(a), len(b))):
11 val = carry
12 if i < len(a):
13 val += int(a[-(i + 1)])
14 if i < len(b):
15 val += int(b[-(i + 1)])
16 carry, val = divmod(val, 2)
17 result += str(val)
18 if carry:
19 result += str(carry)
20 return result[::-1]
21
22
23 # Time: O(n)
24 # Space: O(1)
25 from itertools import izip_longest
26
27
28 class Solution2(object):
29 def addBinary(self, a, b):
30 """
31 :type a: str
32 :type b: str
33 :rtype: str
34 """
35 result = ""
36 carry = 0
37 for x, y in izip_longest(reversed(a), reversed(b), fillvalue="0"):
38 carry, remainder = divmod(int(x)+int(y)+carry, 2)
39 result += str(remainder)
40
41 if carry:
42 result += str(carry)
43
44 return result[::-1]
***************

20. Climbing Stairs


***************

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Constraints:

1 <= n <= 45
***************

20. Climbing Stairs(C++)


***************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int climbStairs(int n) {
7 vector> T = {{1, 1},
8 {1, 0}};
9 return matrixMult({{1, 0}}, matrixExpo(T, n))[0][0]; // [a0, a(-1)] * T^n
10 }
11
12 private:
13 vector> matrixExpo(const vector>& A, int pow) {
14 vector> result(A.size(), vector(A.size()));
15 vector> A_exp(A);
16 for (int i = 0; i < A.size(); ++i) {
17 result[i][i] = 1;
18 }
19 while (pow) {
20 if (pow % 2 == 1) {
21 result = matrixMult(result, A_exp);
22 }
23 A_exp = matrixMult(A_exp, A_exp);
24 pow /= 2;
25 }
26 return result;
27 }
28
29 vector> matrixMult(const vector>& A, const vector>& B) {
30 vector> result(A.size(), vector(B[0].size()));
31 for (int i = 0; i < A.size(); ++i) {
32 for (int j = 0; j < B[0].size(); ++j) {
33 int64_t entry = 0;
34 for (int k = 0; k < B.size(); ++k) {
35 entry = (static_cast(A[i][k]) * B[k][j] + entry);
36 }
37 result[i][j] = static_cast(entry);
38 }
39 }
40 return result;
41 }
42 };
43
44 // Time: O(n)
45 // Space: O(1)
46 class Solution2 {
47 public:
48 int climbStairs(int n) {
49 vector steps(3, 0);
50 steps[0] = 1;
51 steps[1] = 1;
52 for (int i = 2; i <= n; ++i) {
53 steps[i % 3] = steps[(i - 1) % 3] + steps[(i - 2) % 3];
54 }
55 return steps[n % 3];
56 }
57 };
***************

20. Climbing Stairs(Python)


***************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def climbStairs(self, n):
9 """
10 :type n: int
11 :rtype: int
12 """
13 def matrix_expo(A, K):
14 result = [[int(i==j) for j in xrange(len(A))] \
15 for i in xrange(len(A))]
16 while K:
17 if K % 2:
18 result = matrix_mult(result, A)
19 A = matrix_mult(A, A)
20 K /= 2
21 return result
22
23 def matrix_mult(A, B):
24 ZB = zip(*B)
25 return [[sum(a*b for a, b in itertools.izip(row, col)) \
26 for col in ZB] for row in A]
27
28 T = [[1, 1],
29 [1, 0]]
30 return matrix_mult([[1, 0]], matrix_expo(T, n))[0][0] # [a0, a(-1)] * T^n
31
32
33 # Time: O(n)
34 # Space: O(1)
35 class Solution2(object):
36 """
37 :type n: int
38 :rtype: int
39 """
40 def climbStairs(self, n):
41 prev, current = 0, 1
42 for i in xrange(n):
43 prev, current = current, prev + current,
44 return current
**********************************

21. Remove Duplicates from Sorted List


**********************************

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list
sorted as well.

Example 1:

Input: head = [1,1,2]


Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]


Output: [1,2,3]

Constraints:

The number of nodes in the list is in the range[0, 300].


-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
**********************************

21. Remove Duplicates from Sorted List(C++)


**********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode* deleteDuplicates(ListNode* head) {
15 auto iter = head;
16 while (iter) {
17 auto runner = iter->next;
18 while (runner && runner->val == iter->val) {
19 runner = runner->next;
20 }
21 iter->next = runner;
22 iter = runner;
23 }
24 return head;
25 }
26 };
**********************************

21. Remove Duplicates from Sorted List(Python)


**********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9
10 class Solution(object):
11 def deleteDuplicates(self, head):
12 """
13 :type head: ListNode
14 :rtype: ListNode
15 """
16 cur = head
17 while cur:
18 runner = cur.next
19 while runner and runner.val == cur.val:
20 runner = runner.next
21 cur.next = runner
22 cur = runner
23 return head
24
25 def deleteDuplicates2(self, head):
26 """
27 :type head: ListNode
28 :rtype: ListNode
29 """
30 if not head: return head
31 if head.next:
32 if head.val == head.next.val:
33 head = self.deleteDuplicates2(head.next)
34 else:
35 head.next = self.deleteDuplicates2(head.next)
36 return head
37
38
******************

22. Merge Sorted Array


******************

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing
the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead bestored inside the array nums1. To accommodate
this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the lastn
elements are set to 0 and should be ignored. nums2 has a length of n.

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3


Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0


Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1


Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

Constraints:

nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 10 9

Follow up: Can you come up with an algorithm that runs inO(m + n) time?
******************

22. Merge Sorted Array(C++)


******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 void merge(vector& nums1, int m, vector& nums2, int n) {
7 int i = m + n;
8 while (m > 0 && n > 0) {
9 if (nums1[m - 1] > nums2[n - 1]) {
10 nums1[i - 1] = nums1[m - 1];
11 --m;
12 } else {
13 nums1[i - 1] = nums2[n - 1];
14 --n;
15 }
16 --i;
17 }
18
19 while (n > 0) {
20 nums1[i - 1] = nums2[n - 1];
21 --n;
22 --i;
23 }
24 }
25 };
******************

22. Merge Sorted Array(Python)


******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param A a list of integers
6 # @param m an integer, length of A
7 # @param B a list of integers
8 # @param n an integer, length of B
9 # @return nothing
10 def merge(self, A, m, B, n):
11 last, i, j = m + n - 1, m - 1, n - 1
12
13 while i >= 0 and j >= 0:
14 if A[i] > B[j]:
15 A[last] = A[i]
16 last, i = last - 1, i - 1
17 else:
18 A[last] = B[j]
19 last, j = last - 1, j - 1
20
21 while j >= 0:
22 A[last] = B[j]
23 last, j = last - 1, j - 1
24
*********

23. Same Tree


*********

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Example 1:

Input: p = [1,2,3], q = [1,2,3]


Output: true

Example 2:

Input: p = [1,2], q = [1,null,2]


Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]


Output: false

Constraints:
The number of nodes in both trees is in the range[0, 100].
-104 <= Node.val <= 10 4
*********

23. Same Tree(C++)


*********

1 // Time: O(n)
2 // Space: O(h), h is height of binary tree
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 bool isSameTree(TreeNode* p, TreeNode* q) {
16 if (!p && !q) {
17 return true;
18 }
19 return p && q && p->val == q->val &&
20 isSameTree(p->left, q->left) &&
21 isSameTree(p->right, q->right);
22 }
23 };
*********

23. Same Tree(Python)


*********

1 # Time: O(n)
2 # Space: O(h), h is height of binary tree
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10 class Solution(object):
11 # @param p, a tree node
12 # @param q, a tree node
13 # @return a boolean
14 def isSameTree(self, p, q):
15 if p is None and q is None:
16 return True
17
18 if p is not None and q is not None:
19 return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
20
21 return False
22
**************

24. Symmetric Tree


**************

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

Input: root = [1,2,2,3,4,4,3]


Output: true

Example 2:

Input: root = [1,2,2,null,3,null,3]


Output: false

Constraints:

The number of nodes in the tree is in the range[1, 1000].


-100 <= Node.val <= 100

Follow up: Could you solve it both recursively and iteratively?


**************

24. Symmetric Tree(C++)


**************
1 // Time: O(n)
2 // Space: O(h), h is the height of the binary tree.
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13
14 // Iterative solution.
15 class Solution {
16 public:
17 bool isSymmetric(TreeNode* root) {
18 if (!root) {
19 return true;
20 }
21 // isSymmetricHelper(root->left, root->right)
22 stack nodes;
23 nodes.emplace(root->left);
24 nodes.emplace(root->right);
25
26 while (!nodes.empty()) {
27 auto right = nodes.top();
28 nodes.pop();
29 auto left = nodes.top();
30 nodes.pop();
31 if (!left && !right) {
32 continue;
33 }
34 if (!left || !right || left->val != right->val) {
35 return false;
36 }
37 // isSymmetricHelper(left->right, right->left)
38 nodes.emplace(left->right);
39 nodes.emplace(right->left);
40
41 // isSymmetricHelper(left->left, right->right)
42 nodes.emplace(left->left);
43 nodes.emplace(right->right);
44 }
45 return true;
46 }
47 };
48
49
50 // Recursive solution.
51 class Solution2 {
52 public:
53 bool isSymmetric(TreeNode* root) {
54 if (!root) {
55 return true;
56 }
57 return isSymmetricHelper(root->left, root->right);
58 }
59
60 bool isSymmetricHelper(TreeNode *left, TreeNode *right) {
61 if (!left && !right) {
62 return true;
63 }
64 if (!left || !right || left->val != right->val) {
65 return false;
66 }
67 return isSymmetricHelper(left->left, right->right) &&
68 isSymmetricHelper(left->right, right->left);
69 }
70 };
**************

24. Symmetric Tree(Python)


**************

1 # Time: O(n)
2 # Space: O(h), h is height of binary tree
3 # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
4
5 class TreeNode(object):
6 def __init__(self, x):
7 self.val = x
8 self.left = None
9 self.right = None
10
11 # Iterative solution
12 class Solution(object):
13 # @param root, a tree node
14 # @return a boolean
15 def isSymmetric(self, root):
16 if root is None:
17 return True
18 stack = []
19 stack.append(root.left)
20 stack.append(root.right)
21
22 while stack:
23 p, q = stack.pop(), stack.pop()
24
25 if p is None and q is None:
26 continue
27
28 if p is None or q is None or p.val != q.val:
29 return False
30
31 stack.append(p.left)
32 stack.append(q.right)
33
34 stack.append(p.right)
35 stack.append(q.left)
36
37 return True
38
39 # Recursive solution
40 class Solution2(object):
41 # @param root, a tree node
42 # @return a boolean
43 def isSymmetric(self, root):
44 if root is None:
45 return True
46
47 return self.isSymmetricRecu(root.left, root.right)
48
49 def isSymmetricRecu(self, left, right):
50 if left is None and right is None:
51 return True
52 if left is None or right is None or left.val != right.val:
53 return False
54 return self.isSymmetricRecu(left.left, right.right) and self.isSymmetricRecu(left.right, right.left)
55
*********************************

25. Binary Tree Level Order Traversal


*********************************

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]


Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

The number of nodes in the tree is in the range[0, 2000].


-1000 <= Node.val <= 1000
*********************************

25. Binary Tree Level Order Traversal(C++)


*********************************

1 // Time: O(n)
2 // Space: O(n)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 vector> levelOrder(TreeNode* root) {
16 vector> result;
17 queue que;
18
19 if (root != nullptr) {
20 que.emplace(root);
21 }
22
23 while (!que.empty()) {
24 vector level;
25 int size = que.size();
26 for (int i = 0; i < size; i++) {
27 auto *front = que.front();
28 que.pop();
29 level.emplace_back(front->val);
30 if (front->left != nullptr) {
31 que.emplace(front->left);
32 }
33 if (front->right != nullptr) {
34 que.emplace(front->right);
35 }
36 }
37 result.emplace_back(move(level));
38 }
39
40 return result;
41 }
42 };
*********************************

25. Binary Tree Level Order Traversal(Python)


*********************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10
11 class Solution(object):
12 # @param root, a tree node
13 # @return a list of lists of integers
14 def levelOrder(self, root):
15 if root is None:
16 return []
17 result, current = [], [root]
18 while current:
19 next_level, vals = [], []
20 for node in current:
21 vals.append(node.val)
22 if node.left:
23 next_level.append(node.left)
24 if node.right:
25 next_level.append(node.right)
26 current = next_level
27 result.append(vals)
28 return result
29
****************************

26. Maximum Depth of Binary Tree


****************************

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf
node.

Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: 3

Example 2:

Input: root = [1,null,2]


Output: 2

Example 3:

Input: root = []
Output: 0

Example 4:

Input: root = [0]


Output: 1

Constraints:

The number of nodes in the tree is in the range[0, 104].


-100 <= Node.val <= 100
****************************

26. Maximum Depth of Binary Tree(C++)


****************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int maxDepth(TreeNode* root) {
16 if (!root) {
17 return 0;
18 }
19 return max(maxDepth(root->left), maxDepth(root->right)) + 1;
20 }
21 };
****************************

26. Maximum Depth of Binary Tree(Python)


****************************

1 # Time: O(n)
2 # Space: O(h), h is height of binary tree
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10 class Solution(object):
11 # @param root, a tree node
12 # @return an integer
13 def maxDepth(self, root):
14 if root is None:
15 return 0
16 else:
17 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
18
************************************

27. Binary Tree Level Order Traversal II


************************************

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by
level from leaf to root).

Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: [[15,7],[9,20],[3]]

Example 2:

Input: root = [1]


Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

The number of nodes in the tree is in the range[0, 2000].


-1000 <= Node.val <= 1000
************************************

27. Binary Tree Level Order Traversal II(C++)


************************************

1 // Time: O(n)
2 // Space: O(n)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 vector> levelOrderBottom(TreeNode* root) {
16 vector> result;
17 queue que;
18
19 if (root != nullptr) {
20 que.emplace(root);
21 }
22
23 while (!que.empty()) {
24 vector level;
25 int size = que.size();
26 for (int i = 0; i < size; i++) {
27 auto *front = que.front();
28 que.pop();
29 level.emplace_back(front->val);
30 if (front->left != nullptr) {
31 que.emplace(front->left);
32 }
33 if (front->right != nullptr) {
34 que.emplace(front->right);
35 }
36 }
37 result.emplace_back(move(level));
38 }
39
40 // The only difference between binary-tree-level-order-traversal
41 // and binary-tree-level-order-traversal-ii
42 reverse(result.begin(), result.end());
43
44 return result;
45 }
46 };
************************************

27. Binary Tree Level Order Traversal II(Python)


************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10
11 class Solution(object):
12 def levelOrderBottom(self, root):
13 """
14 :type root: TreeNode
15 :rtype: List[List[int]]
16 """
17 if root is None:
18 return []
19
20 result, current = [], [root]
21 while current:
22 next_level, vals = [], []
23 for node in current:
24 vals.append(node.val)
25 if node.left:
26 next_level.append(node.left)
27 if node.right:
28 next_level.append(node.right)
29 current = next_level
30 result.append(vals)
31
32 return result[::-1]
33
********************

28. Balanced Binary Tree


********************

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees ofevery node differ in height by no more than 1.

Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: true

Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]


Output: false

Example 3:

Input: root = []
Output: true

Constraints:
The number of nodes in the tree is in the range[0, 5000].
-104 <= Node.val <= 10 4
********************

28. Balanced Binary Tree(Python)


********************

1 # Time: O(n)
2 # Space: O(h), h is height of binary tree
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10
11 class Solution(object):
12 # @param root, a tree node
13 # @return a boolean
14 def isBalanced(self, root):
15 def getHeight(root):
16 if root is None:
17 return 0
18 left_height, right_height = \
19 getHeight(root.left), getHeight(root.right)
20 if left_height < 0 or right_height < 0 or \
21 abs(left_height - right_height) > 1:
22 return -1
23 return max(left_height, right_height) + 1
24 return (getHeight(root) >= 0)
25
****************************

29. Minimum Depth of Binary Tree


****************************

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]


Output: 5

Constraints:

The number of nodes in the tree is in the range[0, 105].


-1000 <= Node.val <= 1000
****************************

29. Minimum Depth of Binary Tree(Python)


****************************

1 # Time: O(n)
2 # Space: O(h), h is height of binary tree
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10 class Solution(object):
11 # @param root, a tree node
12 # @return an integer
13 def minDepth(self, root):
14 if root is None:
15 return 0
16
17 if root.left and root.right:
18 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
19 else:
20 return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
21
********

30. Path Sum


********

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the
values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22


Output: true

Example 2:

Input: root = [1,2,3], targetSum = 5


Output: false

Example 3:

Input: root = [1,2], targetSum = 0


Output: false

Constraints:
The number of nodes in the tree is in the range[0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
********

30. Path Sum(Python)


********

1 # Time: O(n)
2 # Space: O(h), h is height of binary tree
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10 class Solution(object):
11 # @param root, a tree node
12 # @param sum, an integer
13 # @return a boolean
14 def hasPathSum(self, root, sum):
15 if root is None:
16 return False
17
18 if root.left is None and root.right is None and root.val == sum:
19 return True
20
21 return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
22
*****************

31. Pascal's Triangle


*****************

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

1 <= numRows <= 30


*****************

31. Pascal's Triangle(C++)


*****************

1 // Time: O(n^2)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> generate(int numRows) {
7 vector> result;
8 for (int i = 0; i < numRows; ++i) {
9 result.push_back({});
10 for (int j = 0; j <= i; ++j) {
11 if (j == 0 || j == i) {
12 result[i].emplace_back(1);
13 } else {
14 result[i].emplace_back(result[i - 1][j - 1] +
15 result[i - 1][j]);
16 }
17 }
18 }
19 return result;
20 }
21 };
*****************

31. Pascal's Triangle(Python)


*****************

1 # Time: O(n^2)
2 # Space: O(1)
3
4 class Solution(object):
5 # @return a list of lists of integers
6 def generate(self, numRows):
7 result = []
8 for i in xrange(numRows):
9 result.append([])
10 for j in xrange(i + 1):
11 if j in (0, i):
12 result[i].append(1)
13 else:
14 result[i].append(result[i - 1][j - 1] + result[i - 1][j])
15 return result
16
17 def generate2(self, numRows):
18 if not numRows: return []
19 res = [[1]]
20 for i in range(1, numRows):
21 res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])]
22 return res[:numRows]
23
24 def generate3(self, numRows):
25 """
26 :type numRows: int
27 :rtype: List[List[int]]
28 """
29 if numRows == 0: return []
30 if numRows == 1: return [[1]]
31 res = [[1], [1, 1]]
32
33 def add(nums):
34 res = nums[:1]
35 for i, j in enumerate(nums):
36 if i < len(nums) - 1:
37 res += [nums[i] + nums[i + 1]]
38 res += nums[:1]
39 return res
40
41 while len(res) < numRows:
42 res.extend([add(res[-1])])
43 return res
44
********************

32. Pascal's Triangle II


********************

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

Constraints:

0 <= rowIndex <= 33

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?
********************

32. Pascal's Triangle II(C++)


********************

1 // Time: O(n^2)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector getRow(int rowIndex) {
7 vector result(rowIndex + 1);
8 for (int i = 0; i < result.size(); ++i) {
9 int prev_result = result[0] = 1;
10 for (int j = 1; j <= i; ++j) {
11 const int tmp = result[j];
12 result[j] += prev_result;
13 prev_result = tmp;
14 }
15 }
16 return result;
17 }
18 };
********************

32. Pascal's Triangle II(Python)


********************

1 # Time: O(n^2)
2 # Space: O(1)
3
4 class Solution(object):
5 # @return a list of integers
6 def getRow(self, rowIndex):
7 result = [0] * (rowIndex + 1)
8 for i in xrange(rowIndex + 1):
9 old = result[0] = 1
10 for j in xrange(1, i + 1):
11 old, result[j] = result[j], old + result[j]
12 return result
13
14 def getRow2(self, rowIndex):
15 """
16 :type rowIndex: int
17 :rtype: List[int]
18 """
19 row = [1]
20 for _ in range(rowIndex):
21 row = [x + y for x, y in zip([0] + row, row + [0])]
22 return row
23
24 def getRow3(self, rowIndex):
25 """
26 :type rowIndex: int
27 :rtype: List[int]
28 """
29 if rowIndex == 0: return [1]
30 res = [1, 1]
31
32 def add(nums):
33 res = nums[:1]
34 for i, j in enumerate(nums):
35 if i < len(nums) - 1:
36 res += [nums[i] + nums[i + 1]]
37 res += nums[:1]
38 return res
39
40 while res[1] < rowIndex:
41 res = add(res)
42 return res
43
44
45 # Time: O(n^2)
46 # Space: O(n)
47 class Solution2(object):
48 # @return a list of integers
49 def getRow(self, rowIndex):
50 result = [1]
51 for i in range(1, rowIndex + 1):
52 result = [1] + [result[j - 1] + result[j] for j in xrange(1, i)] + [1]
53 return result
54
55
*******************************

33. Best Time to Buy and Sell Stock


*******************************

You are given an array prices where prices[i] is the price of a given stock on theith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to
sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]


Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]


Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

1 <= prices.length <= 10 5


0 <= prices[i] <= 10 4
*******************************

33. Best Time to Buy and Sell Stock(C++)


*******************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxProfit(vector &prices) {
7 if (prices.empty()) {
8 return 0;
9 }
10
11 int hold1 = numeric_limits::min();
12 int release1 = numeric_limits::min();
13
14 for (const auto& p : prices) {
15 hold1 = max(hold1, -p);
16 release1 = max(release1, hold1 + p);
17 }
18
19 return release1;
20 }
21 };
*******************************

33. Best Time to Buy and Sell Stock(Python)


*******************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param prices, a list of integer
6 # @return an integer
7 def maxProfit(self, prices):
8 max_profit, min_price = 0, float("inf")
9 for price in prices:
10 min_price = min(min_price, price)
11 max_profit = max(max_profit, price - min_price)
12 return max_profit
13
**********************************

34. Best Time to Buy and Sell Stock II


**********************************

You are given an array prices where prices[i] is the price of a given stock on theith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one
share of the stock multiple times).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [7,1,5,3,6,4]


Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: prices = [1,2,3,4,5]


Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sel

Example 3:

Input: prices = [7,6,4,3,1]


Output: 0
Explanation: In this case, no transaction is done, i.e., max profit = 0.

Constraints:

1 <= prices.length <= 3 * 10 4


0 <= prices[i] <= 10 4
**********************************

34. Best Time to Buy and Sell Stock II(C++)


**********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxProfit(vector& prices) {
7 int result = 0;
8 for (int i = 1; i < prices.size(); ++i) {
9 result += max(0, prices[i] - prices[i - 1]);
10 }
11 return result;
12 }
13 };
**********************************

34. Best Time to Buy and Sell Stock II(Python)


**********************************

1 # Time: O(n)
2 # Space: O(1)
3
4
5 class Solution(object):
6 # @param prices, a list of integer
7 # @return an integer
8 def maxProfit(self, prices):
9 profit = 0
10 for i in xrange(len(prices) - 1):
11 profit += max(0, prices[i + 1] - prices[i])
12 return profit
13
14 def maxProfit2(self, prices):
15 return sum(map(lambda x: max(prices[x + 1] - prices[x], 0),
16 xrange(len(prices[:-1]))))
17
****************

35. Valid Palindrome


****************

Given a string s , determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Example 1:

Input: s = "A man, a plan, a canal: Panama"


Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"


Output: false
Explanation: "raceacar" is not a palindrome.

Constraints:

1 <= s.length <= 2 * 10 5


s consists only of printable ASCII characters.
****************

35. Valid Palindrome(C++)


****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isPalindrome(string s) {
7 int i = 0, j = s.length() - 1;
8 while (i < j) {
9 if (!isalnum(s[i])) {
10 ++i;
11 } else if (!isalnum(s[j])) {
12 --j;
13 } else if (tolower(s[i]) != tolower(s[j])) {
14 return false;
15 } else {
16 ++i, --j;
17 }
18 }
19 return true;
20 }
21 };
22
23 // Time: O(n)
24 // Space: O(1)
25 // Iterator solution.
26 class Solution2 {
27 public:
28 bool isPalindrome(string s) {
29 auto left = s.begin();
30 auto right = prev(s.end());
31 while (left < right) {
32 if (!isalnum(*left)) {
33 ++left;
34 } else if (!isalnum(*right)) {
35 --right;
36 } else if (tolower(*left) != tolower(*right)) {
37 return false;
38 } else {
39 ++left, --right;
40 }
41 }
42 return true;
43 }
44 };
****************

35. Valid Palindrome(Python)


****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param s, a string
6 # @return a boolean
7 def isPalindrome(self, s):
8 i, j = 0, len(s) - 1
9 while i < j:
10 while i < j and not s[i].isalnum():
11 i += 1
12 while i < j and not s[j].isalnum():
13 j -= 1
14 if s[i].lower() != s[j].lower():
15 return False
16 i, j = i + 1, j - 1
17 return True
18
*************

36. Single Number


*************

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,1]


Output: 1

Example 2:

Input: nums = [4,1,2,1,2]


Output: 4

Example 3:

Input: nums = [1]


Output: 1

Constraints:

1 <= nums.length <= 3 * 10 4


-3 * 104 <= nums[i] <= 3 * 10 4
Each element in the array appears twice except for one element which appears only once.
*************

36. Single Number(C++)


*************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int singleNumber(vector& nums) {
7 return accumulate(nums.cbegin(), nums.cend(),
8 0, std::bit_xor());
9 }
10 };
*************

36. Single Number(Python)


*************

1 # Time: O(n)
2 # Space: O(1)
3
4 import operator
5 from functools import reduce
6
7
8 class Solution(object):
9 """
10 :type nums: List[int]
11 :rtype: int
12 """
13 def singleNumber(self, A):
14 return reduce(operator.xor, A)
15
*****************

37. Linked List Cycle


*****************

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following
the next pointer. Internally, pos is used to denote the index of the node that tail'snext pointer is connected to. Note that pos is
not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = [3,2,0,-4], pos = 1


Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = [1,2], pos = 0


Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = [1], pos = -1


Output: false
Explanation: There is no cycle in the linked list.

Constraints:

The number of the nodes in the list is in the range[0, 104].


-105 <= Node.val <= 10 5
pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?
*****************

37. Linked List Cycle(C++)


*****************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 bool hasCycle(ListNode *head) {
15 ListNode *slow = head, *fast = head;
16
17 while (fast && fast->next) {
18 slow = slow->next, fast = fast->next->next;
19 if (slow == fast) { // There is a cycle.
20 return true;
21 }
22 }
23 return false; // No cycle.
24 }
25 };
*****************

37. Linked List Cycle(Python)


*****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9 class Solution(object):
10 # @param head, a ListNode
11 # @return a boolean
12 def hasCycle(self, head):
13 fast, slow = head, head
14 while fast and fast.next:
15 fast, slow = fast.next.next, slow.next
16 if fast is slow:
17 return True
18 return False
19
*********

38. Min Stack


*********

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

MinStack() initializes the stack object.


void push(val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

Constraints:

-231 <= val <= 2 31 - 1


Methods pop, top and getMin operations will always be called on non-empty stacks.
At most 3 * 104 calls will be made to push, pop, top, and getMin.
*********

38. Min Stack(C++)


*********

1 // Time: O(n)
2 // Space: O(1)
3
4 class MinStack {
5 public:
6 void push(int number) {
7 if (elements_.empty()) {
8 elements_.emplace(0);
9 stack_min_ = number;
10 } else {
11 elements_.emplace(static_cast(number) - stack_min_);
12 if (number < stack_min_) {
13 stack_min_ = number; // Update min.
14 }
15 }
16 }
17
18 void pop() {
19 auto diff = elements_.top();
20 elements_.pop();
21 if (diff < 0) {
22 stack_min_ -= diff; // Restore previous min.
23 }
24 }
25
26 int top() {
27 if (elements_.top() > 0) {
28 return stack_min_ + elements_.top();
29 } else {
30 return stack_min_;
31 }
32 }
33
34 int getMin() {
35 return stack_min_;
36 }
37
38 private:
39 stack elements_;
40 int stack_min_;
41 };
42
43
44 // Time: O(n)
45 // Space: O(n)
46 class MinStack2 {
47 public:
48 void push(int number) {
49 if (cached_min_with_count_.empty() || cached_min_with_count_.top().first > number) {
50 cached_min_with_count_.emplace(number, 1);
51 } else if (cached_min_with_count_.top().first == number) {
52 ++cached_min_with_count_.top().second;
53 }
54 elements_.emplace(number);
55 }
56
57 void pop() {
58 if (cached_min_with_count_.top().first == elements_.top()) {
59 if (--cached_min_with_count_.top().second == 0) {
60 cached_min_with_count_.pop();
61 }
62 }
63 elements_.pop();
64 }
65
66 int top() {
67 return elements_.top();
68 }
69
70 int getMin() {
71 return cached_min_with_count_.top().first;
72 }
73
74 private:
75 stack elements_;
76 stack> cached_min_with_count_;
77 };
*********

38. Min Stack(Python)


*********

1 # Time: O(n)
2 # Space: O(1)
3
4 class MinStack(object):
5 def __init__(self):
6 self.min = None
7 self.stack = []
8
9 # @param x, an integer
10 # @return an integer
11 def push(self, x):
12 if not self.stack:
13 self.stack.append(0)
14 self.min = x
15 else:
16 self.stack.append(x - self.min)
17 if x < self.min:
18 self.min = x
19
20 # @return nothing
21 def pop(self):
22 x = self.stack.pop()
23 if x < 0:
24 self.min = self.min - x
25
26 # @return an integer
27 def top(self):
28 x = self.stack[-1]
29 if x > 0:
30 return x + self.min
31 else:
32 return self.min
33
34 # @return an integer
35 def getMin(self):
36 return self.min
37
38 # Time: O(n)
39 # Space: O(n)
40 class MinStack2(object):
41 def __init__(self):
42 self.stack, self.minStack = [], []
43 # @param x, an integer
44 # @return an integer
45 def push(self, x):
46 self.stack.append(x)
47 if len(self.minStack):
48 if x < self.minStack[-1][0]:
49 self.minStack.append([x, 1])
50 elif x == self.minStack[-1][0]:
51 self.minStack[-1][1] += 1
52 else:
53 self.minStack.append([x, 1])
54
55 # @return nothing
56 def pop(self):
57 x = self.stack.pop()
58 if x == self.minStack[-1][0]:
59 self.minStack[-1][1] -= 1
60 if self.minStack[-1][1] == 0:
61 self.minStack.pop()
62
63 # @return an integer
64 def top(self):
65 return self.stack[-1]
66
67 # @return an integer
68 def getMin(self):
69 return self.minStack[-1][0]
70
71 # time: O(1)
72 # space: O(n)
73
74 class MinStack3(object):
75
76 def __init__(self):
77 self.stack = []
78
79 def push(self, x):
80 if self.stack:
81 current_min = min(x, self.stack[-1][0])
82 self.stack.append((current_min, x))
83 else:
84 self.stack.append((x, x))
85
86 def pop(self):
87 return self.stack.pop()[1]
88
89 def top(self):
90 return self.stack[-1][1]
91
92 def getMin(self):
93 return self.stack[-1][0]
*****************************

39. Read N Characters Given Read4


*****************************

Given a file and assume that you can only read the file using a given methodread4, implement a method to read n characters.

Method read4:

The API read4 reads four consecutive characters from file, then writes those characters into the buffer arraybuf4.

The return value is the number of actual characters read.

Note that read4() has its own file pointer, much likeFILE *fp in C.

Definition of read4:

Parameter: char[] buf4


Returns: int

buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].

Below is a high-level example of how read4 works:

File file("abcde"); // File is "abcde", initially file pointer (fp) points to 'a'
char[] buf4 = new char[4]; // Create buffer with enough space to store characters
read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file

Method read:

By using the read4 method, implement the method read that reads n characters from file and store it in the buffer array buf.
Consider that you cannot manipulate file directly.

The return value is the number of actual characters read.

Definition of read:
Parameters: char[] buf, int n
Returns: int

buf[] is a destination, not a source. You will need to write the results to buf[].

Note:

Consider that you cannot manipulate the file directly. The file is only accessible forread4 but not for read.
The read function will only be called once for each test case.
You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.

Example 1:

Input: file = "abc", n = 4


Output: 3
Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to.

Example 2:

Input: file = "abcde", n = 5


Output: 5
Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5.

Example 3:

Input: file = "abcdABCD1234", n = 12


Output: 12
Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12.

Example 4:

Input: file = "leetcode", n = 5


Output: 5
Explanation: After calling your read method, buf should contain "leetc". We read a total of 5 characters from the file, so return 5.

Constraints:

1 <= file.length <= 500


file consist of English letters and digits.
1 <= n <= 1000
*****************************

39. Read N Characters Given Read4(C++)


*****************************

1 // Time: O(n)
2 // Space: O(1)
3
4 int read4(char *buf);
5
6 class Solution {
7 public:
8 /**
9 * @param buf Destination buffer
10 * @param n Maximum number of characters to read
11 * @return The number of characters read
12 */
13 int read(char *buf, int n) {
14 int read_bytes = 0;
15 char buffer[4];
16 for (int i = 0; i < (n + 4 - 1) / 4; ++i) {
17 int size = min(read4(buffer), n - read_bytes);
18 for (int j = 0; j < size; ++j) {
19 buf[read_bytes++] = buffer[j];
20 }
21 }
22 return read_bytes;
23 }
24 };
*****************************

39. Read N Characters Given Read4(Python)


*****************************

1 # Time: O(n)
2 # Space: O(1)
3
4 def read4(buf):
5 global file_content
6 i = 0
7 while i < len(file_content) and i < 4:
8 buf[i] = file_content[i]
9 i += 1
10
11 if len(file_content) > 4:
12 file_content = file_content[4:]
13 else:
14 file_content = ""
15 return i
16
17 class Solution(object):
18 def read(self, buf, n):
19 """
20 :type buf: Destination buffer (List[str])
21 :type n: Maximum number of characters to read (int)
22 :rtype: The number of characters read (int)
23 """
24 read_bytes = 0
25 buffer = [''] * 4
26 for i in xrange((n+4-1)//4):
27 size = min(read4(buffer), n-read_bytes)
28 buf[read_bytes:read_bytes+size] = buffer[:size]
29 read_bytes += size
30 return read_bytes
********************************

40. Intersection of Two Linked Lists


********************************

Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect. If the two linked
lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at nodec1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

Note that the linked lists must retain their original structure after the function returns.

Custom Judge:

The inputs to the judge are given as follows (your program is not given these inputs):

intersectVal - The value of the node where the intersection occurs. This is0 if there is no intersected node.
listA - The first linked list.
listB - The second linked list.
skipA - The number of nodes to skip ahead inlistA (starting from the head) to get to the intersected node.
skipB - The number of nodes to skip ahead inlistB (starting from the head) to get to the intersected node.

The judge will then create the linked structure based on these inputs and pass the two heads,headA and headB to your
program. If you correctly return the intersected node, then your solution will be accepted.

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3


Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in

Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; The

Example 3:

Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2


Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectV
Explanation: The two lists do not intersect, so return null.

Constraints:

The number of nodes of listA is in the m.


The number of nodes of listB is in the n.
0 <= m, n <= 3 * 10 4
1 <= Node.val <= 10 5
0 <= skipA <= m
0 <= skipB <= n
intersectVal is 0 if listA and listB do not intersect.
intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.

Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?
********************************

40. Intersection of Two Linked Lists(C++)


********************************

1 // Time: O(m + n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
15 ListNode *curA = headA, *curB = headB;
16 while (curA != curB) {
17 curA = curA ? curA->next : headB;
18 curB = curB ? curB->next : headA;
19 }
20 return curA;
21 }
22 };
********************************

40. Intersection of Two Linked Lists(Python)


********************************

1 # Time: O(m + n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9 class Solution(object):
10 # @param two ListNodes
11 # @return the intersected ListNode
12 def getIntersectionNode(self, headA, headB):
13 curA, curB = headA, headB
14 while curA != curB:
15 curA = curA.next if curA else headB
16 curB = curB.next if curB else headA
17 return curA
***********************

41. Compare Version Numbers


***********************

Given two version numbers, version1 and version2, compare them.

Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain
leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost
revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer
value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not
specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their
revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1 .

Return the following:

If version1 < version2 , return -1.


If version1 > version2 , return 1.
Otherwise, return 0.

Example 1:

Input: version1 = "1.01", version2 = "1.001"


Output: 0
Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".

Example 2:

Input: version1 = "1.0", version2 = "1.0.0"


Output: 0
Explanation: version1 does not specify revision 2, which means it is treated as "0".

Example 3:

Input: version1 = "0.1", version2 = "1.1"


Output: -1
Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.

Example 4:

Input: version1 = "1.0.1", version2 = "1"


Output: 1

Example 5:

Input: version1 = "7.5.2.4", version2 = "7.5.3"


Output: -1

Constraints:
1 <= version1.length, version2.length <= 500
version1 and version2 only contain digits and '.' .
version1 and version2 are valid version numbers.
All the given revisions in version1 and version2 can be stored in a 32-bit integer.
***********************

41. Compare Version Numbers(C++)


***********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int compareVersion(string version1, string version2) {
7 const int n1 = version1.length(), n2 = version2.length();
8 for (int i = 0, j = 0; i < n1 || j < n2; ++i, ++j) {
9 int v1 = 0, v2 = 0;
10 while (i < n1 && version1[i] != '.') {
11 v1 = v1 * 10 + version1[i++] - '0';
12 }
13 while (j < n2 && version2[j] != '.') {
14 v2 = v2 * 10 + version2[j++] - '0';
15 }
16 if (v1 != v2) {
17 return v1 > v2 ? 1 : -1;
18 }
19 }
20 return 0;
21 }
22 };
***********************

41. Compare Version Numbers(Python)


***********************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def compareVersion(self, version1, version2):
9 """
10 :type version1: str
11 :type version2: str
12 :rtype: int
13 """
14 n1, n2 = len(version1), len(version2)
15 i, j = 0, 0
16 while i < n1 or j < n2:
17 v1, v2 = 0, 0
18 while i < n1 and version1[i] != '.':
19 v1 = v1 * 10 + int(version1[i])
20 i += 1
21 while j < n2 and version2[j] != '.':
22 v2 = v2 * 10 + int(version2[j])
23 j += 1
24 if v1 != v2:
25 return 1 if v1 > v2 else -1
26 i += 1
27 j += 1
28
29 return 0
30
31 # Time: O(n)
32 # Space: O(n)
33
34
35 class Solution2(object):
36 def compareVersion(self, version1, version2):
37 """
38 :type version1: str
39 :type version2: str
40 :rtype: int
41 """
42 v1, v2 = version1.split("."), version2.split(".")
43
44 if len(v1) > len(v2):
45 v2 += ['0' for _ in xrange(len(v1) - len(v2))]
46 elif len(v1) < len(v2):
47 v1 += ['0' for _ in xrange(len(v2) - len(v1))]
48
49 i = 0
50 while i < len(v1):
51 if int(v1[i]) > int(v2[i]):
52 return 1
53 elif int(v1[i]) < int(v2[i]):
54 return -1
55 else:
56 i += 1
57
58 return 0
59
60 def compareVersion2(self, version1, version2):
61 """
62 :type version1: str
63 :type version2: str
64 :rtype: int
65 """
66 v1 = [int(x) for x in version1.split('.')]
67 v2 = [int(x) for x in version2.split('.')]
68 while len(v1) != len(v2):
69 if len(v1) > len(v2):
70 v2.append(0)
71 else:
72 v1.append(0)
73 return cmp(v1, v2)
74
75 def compareVersion3(self, version1, version2):
76 splits = (map(int, v.split('.')) for v in (version1, version2))
77 return cmp(*zip(*itertools.izip_longest(*splits, fillvalue=0)))
78
79 def compareVersion4(self, version1, version2):
80 main1, _, rest1 = ('0' + version1).partition('.')
81 main2, _, rest2 = ('0' + version2).partition('.')
82 return cmp(int(main1), int(main2)) or len(rest1 + rest2) and self.compareVersion4(rest1, rest2)
83
84
************************

42. Excel Sheet Column Title


************************

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

Example 1:

Input: columnNumber = 1
Output: "A"

Example 2:

Input: columnNumber = 28
Output: "AB"

Example 3:

Input: columnNumber = 701


Output: "ZY"

Example 4:

Input: columnNumber = 2147483647


Output: "FXSHRXW"

Constraints:

1 <= columnNumber <= 2 31 - 1


************************

42. Excel Sheet Column Title(C++)


************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 // Iterative solution.
5 class Solution {
6 public:
7 string convertToTitle(int n) {
8 string result;
9 int dvd{n};
10
11 while (dvd) {
12 result.push_back((dvd - 1) % 26 + 'A');
13 dvd = (dvd - 1) / 26;
14 }
15 reverse(result.begin(), result.end());
16
17 return result;
18 }
19 };
20
21 // Time: O((logn)^2)
22 // Space: O(logn)
23 // Recursive solution.
24 class Solution2 {
25 public:
26 string convertToTitle(int n) {
27 if (n == 0) {
28 return "";
29 }
30 return convertToTitle((n - 1) / 26) + static_cast((n - 1) % 26 + 'A');
31 }
32 };
************************

42. Excel Sheet Column Title(Python)


************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def convertToTitle(self, n):
6 """
7 :type n: int
8 :rtype: str
9 """
10 result = []
11 while n:
12 result += chr((n-1)%26 + ord('A'))
13 n = (n-1)//26
14 result.reverse()
15 return "".join(result)
16
****************

43. Majority Element


****************

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always
exists in the array.

Example 1:

Input: nums = [3,2,3]


Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]


Output: 2

Constraints:

n == nums.length
1 <= n <= 5 * 10 4
-231 <= nums[i] <= 2 31 - 1

Follow-up: Could you solve the problem in linear time and inO(1) space?
****************

43. Majority Element(C++)


****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int majorityElement(vector& nums) {
7 int ans = nums[0], cnt = 1;
8 for (const auto& i : nums) {
9 if (i == ans) {
10 ++cnt;
11 } else {
12 --cnt;
13 if (cnt == 0) {
14 ans = i;
15 cnt = 1;
16 }
17 }
18 }
19 return ans;
20 }
21 };
****************

43. Majority Element(Python)


****************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def majorityElement(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: int
12 """
13 idx, cnt = 0, 1
14
15 for i in xrange(1, len(nums)):
16 if nums[idx] == nums[i]:
17 cnt += 1
18 else:
19 cnt -= 1
20 if cnt == 0:
21 idx = i
22 cnt = 1
23
24 return nums[idx]
25
26 def majorityElement2(self, nums):
27 """
28 :type nums: List[int]
29 :rtype: int
30 """
31 return sorted(collections.Counter(nums).items(), key=lambda a: a[1], reverse=True)[0][0]
32
33 def majorityElement3(self, nums):
34 """
35 :type nums: List[int]
36 :rtype: int
37 """
38 return collections.Counter(nums).most_common(1)[0][0]
***********************************

44. Two Sum III - Data structure design


***********************************

Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular
value.

Implement the TwoSum class:

TwoSum() Initializes the TwoSum object, with an empty array initially.


void add(int number) Adds number to the data structure.
boolean find(int value) Returns true if there exists any pair of numbers whose sum is equal tovalue, otherwise, it returns false.

Example 1:

Input
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
Output
[null, null, null, null, true, false]

Explanation
TwoSum twoSum = new TwoSum();
twoSum.add(1); // [] --> [1]
twoSum.add(3); // [1] --> [1,3]
twoSum.add(5); // [1,3] --> [1,3,5]
twoSum.find(4); // 1 + 3 = 4, return true
twoSum.find(7); // No two integers sum up to 7, return false

Constraints:

-105 <= number <= 10 5


-231 <= value <= 2 31 - 1
At most 104 calls will be made to add and find.
***********************************

44. Two Sum III - Data structure design(C++)


***********************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class TwoSum {
5 public:
6
7 // Add the number to an internal data structure.
8 void add(int number) {
9 ++lookup_[number];
10 }
11
12 // Find if there exists any pair of numbers which sum is equal to the value.
13 bool find(int value) {
14 for (const auto& kvp : lookup_) {
15 const auto num = value - kvp.first;
16 if (lookup_.count(num) && (num != kvp.first || kvp.second > 1)) {
17 return true;
18 }
19 }
20 return false;
21 }
22
23 private:
24 unordered_map lookup_;
25 };
26
27
28 // Your TwoSum object will be instantiated and called as such:
29 // TwoSum twoSum;
30 // twoSum.add(number);
31 // twoSum.find(value);
***********************************

44. Two Sum III - Data structure design(Python)


***********************************

1 # Time: O(n)
2 # Space: O(n)
3
4 from collections import defaultdict
5
6 class TwoSum(object):
7
8 def __init__(self):
9 """
10 initialize your data structure here
11 """
12 self.lookup = defaultdict(int)
13
14
15
16 def add(self, number):
17 """
18 Add the number to an internal data structure.
19 :rtype: nothing
20 """
21 self.lookup[number] += 1
22
23
24 def find(self, value):
25 """
26 Find if there exists any pair of numbers which sum is equal to the value.
27 :type value: int
28 :rtype: bool
29 """
30 for key in self.lookup:
31 num = value - key
32 if num in self.lookup and (num != key or self.lookup[key] > 1):
33 return True
34 return False
35
36
*************************

45. Excel Sheet Column Number


*************************

Given a string columnTitle that represents the 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
...

Example 1:

Input: columnTitle = "A"


Output: 1

Example 2:

Input: columnTitle = "AB"


Output: 28

Example 3:

Input: columnTitle = "ZY"


Output: 701

Example 4:

Input: columnTitle = "FXSHRXW"


Output: 2147483647

Constraints:

1 <= columnTitle.length <= 7


columnTitle consists only of uppercase English letters.
columnTitle is in the range ["A", "FXSHRXW"] .
*************************

45. Excel Sheet Column Number(C++)


*************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int titleToNumber(string s) {
7 int number = 0;
8 for (const auto& c : s) {
9 number *= 26;
10 number += c - 'A' + 1;
11 }
12 return number;
13 }
14 };
15
16 // Time: O(n)
17 // Space: O(1)
18 class Solution2 {
19 public:
20 int titleToNumber(string s) {
21 return accumulate(s.cbegin(), s.cend(), 0,
22 [](int sum, char c) {
23 return sum * 26 + c - 'A' + 1;
24 });
25 }
26 };
*************************

45. Excel Sheet Column Number(Python)


*************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def titleToNumber(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result = 0
11 for i in xrange(len(s)):
12 result *= 26
13 result += ord(s[i]) - ord('A') + 1
14 return result
15
16
*************************

46. Factorial Trailing Zeroes


*************************

Given an integer n, return the number of trailing zeroes in n!.

Follow up: Could you write a solution that works in logarithmic time complexity?

Example 1:

Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Example 3:

Input: n = 0
Output: 0

Constraints:

0 <= n <= 10 4
*************************

46. Factorial Trailing Zeroes(C++)


*************************

1 // Time: O(logn) = O(1)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int trailingZeroes(int n) {
7 int number = 0;
8 while (n > 0) {
9 number += n / 5;
10 n /= 5;
11 }
12 return number;
13 }
14 };
*************************

46. Factorial Trailing Zeroes(Python)


*************************

1 # Time: O(logn) = O(1)


2 # Space: O(1)
3
4 class Solution(object):
5 # @return an integer
6 def trailingZeroes(self, n):
7 result = 0
8 while n > 0:
9 result += n / 5
10 n /= 5
11 return result
12
******************

47. Combine Two Tables


******************

Table: Person

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+-------------+---------+
PersonId is the primary key column for this table.

Table: Address

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+-------------+---------+
AddressId is the primary key column for this table.

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there
is an address for each of those people:

FirstName, LastName, City, State


******************

47. Combine Two Tables(Shell)


******************

1 # Time: O(n), n is size of Person Table


2 # Space: O(n)
3
4 SELECT FirstName, LastName, City, State FROM Person LEFT JOIN Address
5 ON Person.PersonId=Address.PersonId
6
*********************

48. Second Highest Salary


*********************

Write a SQL query to get the second highest salary from theEmployee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

For example, given the above Employee table, the query should return200 as the second highest salary. If there is no
second highest salary, then the query should return null.

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
*********************

48. Second Highest Salary(Shell)


*********************

1 # Time: O(n)
2 # Space: O(1)
3
4 SELECT (SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)) SecondHighestSalary;
5 # or
6 SELECT (SELECT Salary FROM Employee GROUP BY Salary ORDER BY Salary DESC LIMIT 1,1) SecondHighestSalary;
7
******************************************

49. Employees Earning More Than Their Managers


******************************************

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for
the manager Id.

+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+

Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above
table, Joe is the only employee who earns more than his manager.

+----------+
| Employee |
+----------+
| Joe |
+----------+
******************************************

49. Employees Earning More Than Their Managers(Shell)


******************************************

1 # Time: O(n^2)
2 # Space: O(1)
3
4 SELECT e.Name AS Employee FROM Employee e LEFT JOIN Employee b
5 ON e.ManagerId=b.Id
6 WHERE e.Salary > b.Salary
7
8 SELECT Name AS Employee
9 FROM Employee e
10 WHERE e.ManagerId IS NOT NULL AND e.Salary > (SELECT Salary
11 FROM Employee
12 WHERE e.ManagerId = Id)
13
****************

50. Duplicate Emails


****************

Write a SQL query to find all duplicate emails in a table namedPerson.

+----+---------+
| Id | Email |
+----+---------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+---------+

For example, your query should return the following for the above table:

+---------+
| Email |
+---------+
| [email protected] |
+---------+

Note: All emails are in lowercase.


****************

50. Duplicate Emails(Shell)


****************

1 # Time: O(n^2)
2 # Space: O(n)
3
4 SELECT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1
5
*************************

51. Customers Who Never Order


*************************

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers
who never order anything.

Table: Customers.

+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+

Table: Orders.

+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+

Using the above tables as example, return the following:

+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
*************************

51. Customers Who Never Order(Shell)


*************************

1 # Time: O(n^2)
2 # Space: O(1)
3
4 SELECT Name AS Customers FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders)
5
6 SELECT Customers.Name AS Customers FROM (Customers LEFT JOIN Orders ON Customers.Id = Orders.CustomerId) WHERE Orders.CustomerId
7
************

52. Rotate Array


************

Given an array, rotate the array to the right byk steps, where k is non-negative.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3


Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2


Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Constraints:

1 <= nums.length <= 10 5


-231 <= nums[i] <= 2 31 - 1
0 <= k <= 10 5

Follow up:

Try to come up with as many solutions as you can. There are at leastthree different ways to solve this problem.
Could you do it in-place with O(1) extra space?
************

52. Rotate Array(C++)


************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 void rotate(vector& nums, int k) {
7 if (!nums.empty()) {
8 k %= nums.size();
9 reverse(nums.begin(), nums.begin() + nums.size() - k);
10 reverse(nums.begin() + nums.size() - k, nums.end());
11 reverse(nums.begin(), nums.end());
12 }
13 }
14 };
************

52. Rotate Array(Python)


************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 """
6 :type nums: List[int]
7 :type k: int
8 :rtype: void Do not return anything, modify nums in-place instead.
9 """
10 def rotate(self, nums, k):
11 def reverse(nums, start, end):
12 while start < end:
13 nums[start], nums[end - 1] = nums[end - 1], nums[start]
14 start += 1
15 end -= 1
16
17 k %= len(nums)
18 reverse(nums, 0, len(nums))
19 reverse(nums, 0, k)
20 reverse(nums, k, len(nums))
21
22
23 # Time: O(n)
24 # Space: O(1)
25 from fractions import gcd
26
27
28 class Solution2(object):
29 """
30 :type nums: List[int]
31 :type k: int
32 :rtype: void Do not return anything, modify nums in-place instead.
33 """
34
35 def rotate(self, nums, k):
36 def apply_cycle_permutation(k, offset, cycle_len, nums):
37 tmp = nums[offset]
38 for i in xrange(1, cycle_len):
39 nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)]
40 nums[offset] = tmp
41
42 k %= len(nums)
43 num_cycles = gcd(len(nums), k)
44 cycle_len = len(nums) / num_cycles
45 for i in xrange(num_cycles):
46 apply_cycle_permutation(k, i, cycle_len, nums)
47
48
49 # Time: O(n)
50 # Space: O(1)
51 class Solution3(object):
52 """
53 :type nums: List[int]
54 :type k: int
55 :rtype: void Do not return anything, modify nums in-place instead.
56 """
57
58 def rotate(self, nums, k):
59 count = 0
60 start = 0
61 while count < len(nums):
62 curr = start
63 prev = nums[curr]
64 while True:
65 idx = (curr + k) % len(nums)
66 nums[idx], prev = prev, nums[idx]
67 curr = idx
68 count += 1
69 if start == curr:
70 break
71 start += 1
72
73
74 # Time: O(n)
75 # Space: O(n)
76 class Solution4(object):
77 """
78 :type nums: List[int]
79 :type k: int
80 :rtype: void Do not return anything, modify nums in-place instead.
81 """
82 def rotate(self, nums, k):
83 """
84 :type nums: List[int]
85 :type k: int
86 :rtype: void Do not return anything, modify nums in-place instead.
87 """
88 nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k]
89
90
91 # Time: O(k * n)
92 # Space: O(1)
93 class Solution5(object):
94 """
95 :type nums: List[int]
96 :type k: int
97 :rtype: void Do not return anything, modify nums in-place instead.
98 """
99 def rotate(self, nums, k):
100 while k > 0:
101 nums.insert(0, nums.pop())
102 k -= 1
103
104
************

53. Reverse Bits


************

Reverse bits of a given 32 bits unsigned integer.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be
given as a signed integer type. They should not affect your implementation, as the integer's internal binary
representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above,
the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Follow up:

If this function is called many times, how would you optimize it?

Example 1:

Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its

Example 2:

Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which

Constraints:

The input must be a binary string of length 32


************

53. Reverse Bits(C++)


************

1 // Time: O(32)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 uint32_t reverseBits(uint32_t n) {
7 n = (n >> 16) | (n << 16);
8 n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
9 n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
10 n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
11 n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
12 return n;
13 }
14 };
15
16 // Time: O(logn) = O(32)
17 // Space: O(1)
18 class Solution2 {
19 public:
20 uint32_t reverseBits(uint32_t n) {
21 uint32_t result = 0;
22 int count = 32;
23 while (count--) {
24 result <<= 1;
25 result |= n & 1;
26 n >>= 1;
27 }
28 return result;
29 }
30 };
************

53. Reverse Bits(Python)


************

1 # Time : O(32)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param n, an integer
6 # @return an integer
7 def reverseBits(self, n):
8 n = (n >> 16) | (n << 16)
9 n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
10 n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
11 n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
12 n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
13 return n
14
15
16 # Time : O(logn) = O(32)
17 # Space: O(1)
18 class Solution2(object):
19 # @param n, an integer
20 # @return an integer
21 def reverseBits(self, n):
22 result = 0
23 for i in xrange(32):
24 result <<= 1
25 result |= n & 1
26 n >>= 1
27 return result
28
****************

54. Number of 1 Bits


****************

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as theHamming weight).

Note:

Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a
signed integer type. It should not affect your implementation, as the integer's internal binary representation is the
same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using2's complement notation. Therefore, in Example 3, the input
represents the signed integer. -3.

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Constraints:

The input must be a binary string of length 32.

Follow up: If this function is called many times, how would you optimize it?
****************

54. Number of 1 Bits(C++)


****************
1 // Time: O(logn(logn)) = O(5)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int hammingWeight(uint32_t n) {
7 n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
8 n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
9 n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F);
10 n = (n & 0x00FF00FF) + ((n >> 8) & 0x00FF00FF);
11 n = (n & 0x0000FFFF) + ((n >> 16) & 0x0000FFFF);
12 return n;
13 }
14 };
15
16 // Time: O(logn/4) = O(32/4) = O(8)
17 // Space: O(1)
18 // https://github.com/gcc-mirror/gcc/blob/master/libgcc/libgcc2.c#L856
19 class Solution2 {
20 public:
21 int hammingWeight(uint32_t n) {
22 int result = 0;
23 for (; n; n >>= 8) {
24 result += popcount_tab_[n & 0xff];
25 }
26 return result;
27 }
28
29 private:
30 static constexpr int popcount_tab_[256] = {
31 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
32 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
33 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
34 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
35 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
36 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
37 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
38 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
39 };
40 };
41
42 // Time: O(logn/4) = O(32/4) = O(8)
43 // Space: O(1)
44 class Solution3 {
45 public:
46 int hammingWeight(uint32_t n) {
47 return __builtin_popcount(n);
48 }
49 };
50
51 // Time: O(logn) = O(32)
52 // Space: O(1)
53 class Solution4 {
54 public:
55 int hammingWeight(uint32_t n) {
56 int count = 0;
57 for (; n; n &= n - 1) {
58 ++count;
59 }
60 return count;
61 }
62 };
****************

54. Number of 1 Bits(Python)


****************

1 # Time: O(32), bit shift in python is not O(1), it's O(k), k is the number of bits shifted
2 # , see https://github.com/python/cpython/blob/2.7/Objects/longobject.c#L3652
3 # Space: O(1)
4
5 class Solution(object):
6 # @param n, an integer
7 # @return an integer
8 def hammingWeight(self, n):
9 n = (n & 0x55555555) + ((n >> 1) & 0x55555555)
10 n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
11 n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F)
12 n = (n & 0x00FF00FF) + ((n >> 8) & 0x00FF00FF)
13 n = (n & 0x0000FFFF) + ((n >> 16) & 0x0000FFFF)
14 return n
15
16
17 # Time: O(logn/4) = O(32/4 + 8*4) = O(32)
18 # Space: O(1)
19 # https://github.com/gcc-mirror/gcc/blob/master/libgcc/libgcc2.c#L856
20 class Solution2(object):
21 def __init__(self):
22 self.__popcount_tab = \
23 [ \
24 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, \
25 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, \
26 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, \
27 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, \
28 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, \
29 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, \
30 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, \
31 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8 \
32 ]
33
34 # @param n, an integer
35 # @return an integer
36 def hammingWeight(self, n):
37 result = 0
38 while n:
39 result += self.__popcount_tab[n & 0xff]
40 n >>= 8
41 return result
42
43
44 # Time: O(logn) = O(32)
45 # Space: O(1)
46 class Solution3(object):
47 # @param n, an integer
48 # @return an integer
49 def hammingWeight(self, n):
50 result = 0
51 while n:
52 n &= n - 1
53 result += 1
54 return result
55
*******************

55. Valid Phone Numbers


*******************

Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone
numbers.

You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx.
(x means a digit)

You may also assume each line in the text file must not contain leading or trailing white spaces.

Example:

Assume that file.txt has the following content:

987-123-4567
123 456 7890
(123) 456-7890

Your script should output the following valid phone numbers:

987-123-4567
(123) 456-7890
*******************

55. Valid Phone Numbers(Bash)


*******************

1 #!/usr/bin/env bash
2 # Time: O(n)
3 # Space: O(1)
4
5 grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt
6
7 sed -n -E '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt
8
9 awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt
10
**********

56. Tenth Line


**********

Given a text file file.txt, print just the 10th line of the file.

Example:

Assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Your script should output the tenth line, which is:

Line 10

Note:
1. If the file contains less than 10 lines, what should you output?
2. There's at least three different solutions. Try to explore all possibilities.
**********

56. Tenth Line(Bash)


**********

1 # Time: O(n)
2 # Space: O(1)
3
4 awk '{if(NR==10) print $0}' file.txt
5 awk 'NR == 10' file.txt
6
7 sed -n 10p file.txt
8
9 tail -n+10 file.txt | head -1
10
***********************

57. Delete Duplicate Emails


***********************

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its
smallest Id.

+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+

Note:

Your output is the whole Person table after executing your sql. Use delete statement.
***********************

57. Delete Duplicate Emails(Shell)


***********************

1 # Time: O(n^2)
2 # Space: O(n)
3
4 DELETE p1
5 FROM Person p1, Person p2
6 WHERE p1.Email = p2.Email AND p1.Id > p2.Id
7
******************

58. Rising Temperature


******************

Table: Weather

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the primary key for this table.
This table contains information about the temperature in a certain day.

Write an SQL query to find all dates' id with higher temperature compared to its previous dates (yesterday).

Return the result table in any order.

The query result format is in the following example:

Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+

Result table:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
In 2015-01-02, temperature was higher than the previous day (10 -> 25).
In 2015-01-04, temperature was higher than the previous day (20 -> 30).
******************

58. Rising Temperature(Shell)


******************

1 # Time: O(n^2)
2 # Space: O(n)
3
4 SELECT wt1.Id
5 FROM Weather wt1, Weather wt2
6 WHERE wt1.Temperature > wt2.Temperature AND
7 TO_DAYS(wt1.DATE)-TO_DAYS(wt2.DATE)=1;
8
************

59. 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 systems connected and it
will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, returnthe maximum amount of money you
can rob tonight without alerting the police.

Example 1:

Input: nums = [1,2,3,1]


Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: nums = [2,7,9,3,1]


Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

Constraints:

1 <= nums.length <= 100


0 <= nums[i] <= 400
************

59. House Robber(C++)


************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int rob(vector& nums) {
7 int last = 0, result = 0;
8 for (const auto& i : nums) {
9 auto tmp = result;
10 result = max(last + i, result);
11 last = tmp;
12 }
13 return result;
14 }
15 };
************

59. House Robber(Python)


************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param num, a list of integer
6 # @return an integer
7 def rob(self, nums):
8 """
9 :type nums: List[int]
10 :rtype: int
11 """
12 last, now = 0, 0
13 for i in nums:
14 last, now = now, max(last + i, now)
15 return now
16
17
************

60. Happy Number


************

Write an algorithm to determine if a number n 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.
Repeat the process until the number equals 1 (where it will stay), or itloops endlessly in a cycle which does not
include 1.
Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2:

Input: n = 2
Output: false

Constraints:

1 <= n <= 2 31 - 1
************

60. Happy Number(C++)


************

1 // Time: O(k), where k is the steps to be happy number


2 // Space: O(k)
3
4 class Solution {
5 public:
6 bool isHappy(int n) {
7 unordered_set visited;
8 while (n != 1 && !visited.count(n)) {
9 visited.emplace(n);
10 n = nextNumber(n);
11 }
12 return n == 1;
13 }
14
15 int nextNumber(int n) {
16 int sum = 0;
17 while (n) {
18 sum += pow(n % 10, 2);
19 n /= 10;
20 }
21 return sum;
22 }
23 };
************

60. Happy Number(Python)


************

1 # Time: O(k), where k is the steps to be happy number


2 # Space: O(k)
3
4 class Solution(object):
5 # @param {integer} n
6 # @return {boolean}
7 def isHappy(self, n):
8 lookup = {}
9 while n != 1 and n not in lookup:
10 lookup[n] = True
11 n = self.nextNumber(n)
12 return n == 1
13
14 def nextNumber(self, n):
15 new = 0
16 for char in str(n):
17 new += int(char)**2
18 return new
19
***************************

61. Remove Linked List Elements


***************************

Given the head of a linked list and an integer val, remove all the nodes of the linked list that hasNode.val == val , and return the
new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6


Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1


Output: []

Example 3:

Input: head = [7,7,7,7], val = 7


Output: []

Constraints:

The number of nodes in the list is in the range[0, 104].


1 <= Node.val <= 50
0 <= val <= 50
***************************

61. Remove Linked List Elements(C++)


***************************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode* removeElements(ListNode* head, int val) {
15 ListNode dummy{0};
16 dummy.next = head;
17 auto *prev = &dummy, *cur = dummy.next;
18
19 while (cur) {
20 if (cur->val == val) {
21 prev->next = cur->next;
22 delete cur;
23 } else {
24 prev = cur;
25 }
26 cur = cur->next;
27 }
28 return dummy.next;
29 }
30 };
31
32 // Time: O(n)
33 // Space: O(1)
34 class Solution2 {
35 public:
36 ListNode* removeElements(ListNode* head, int val) {
37 for (auto *indirect = &head; *indirect != nullptr; ) {
38 if ((*indirect)->val == val) {
39 *indirect = (*indirect)->next;
40 continue;
41 }
42 indirect = &((*indirect)->next) ;
43 }
44 return head;
45 }
46 };
***************************

61. Remove Linked List Elements(Python)


***************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9
10 class Solution(object):
11 # @param {ListNode} head
12 # @param {integer} val
13 # @return {ListNode}
14 def removeElements(self, head, val):
15 dummy = ListNode(float("-inf"))
16 dummy.next = head
17 prev, curr = dummy, dummy.next
18
19 while curr:
20 if curr.val == val:
21 prev.next = curr.next
22 else:
23 prev = curr
24
25 curr = curr.next
26
27 return dummy.next
28
29
30
************

62. Count Primes


************

Count the number of prime numbers less than a non-negative number,n.

Example 1:

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Example 2:

Input: n = 0
Output: 0

Example 3:

Input: n = 1
Output: 0

Constraints:

0 <= n <= 5 * 10 6
************

62. Count Primes(C++)


************

1 // Time: O(n/2 + n/3 + ... + n/p) = O(nlog(logn)), see https://mathoverflow.net/questions/4596/on-the-series-1-2-1-3-1-5-1-7-1-11


2 // Space: O(n)
3
4 class Solution {
5 public:
6 int countPrimes(int n) {
7 if (n <= 2) {
8 return 0;
9 }
10
11 vector is_prime(n / 2, true);
12 auto cnt = is_prime.size();
13 for (int i = 3; i * i < n; i += 2) {
14 if (!is_prime[i / 2]) {
15 continue;
16 }
17 for (int j = i * i; j < n; j += 2 * i) {
18 if (!is_prime[j / 2]) {
19 continue;
20 }
21 --cnt;
22 is_prime[j / 2] = false;
23 }
24 }
25 return cnt;
26 }
27 };
************

62. Count Primes(Python)


************

1 # Time: O(n/2 + n/3 + ... + n/p) = O(nlog(logn)), see https://mathoverflow.net/questions/4596/on-the-series-1-2-1-3-1-5-1-7-1-11


2 # Space: O(n)
3
4 class Solution(object):
5 # @param {integer} n
6 # @return {integer}
7 def countPrimes(self, n):
8 if n <= 2:
9 return 0
10
11 is_prime = [True]*(n//2)
12 cnt = len(is_prime)
13 for i in xrange(3, n, 2):
14 if i * i >= n:
15 break
16 if not is_prime[i//2]:
17 continue
18 for j in xrange(i*i, n, 2*i):
19 if not is_prime[j//2]:
20 continue
21 cnt -= 1
22 is_prime[j//2] = False
23
24 return cnt
25
26 def countPrimes2(self, n):
27 """
28 :type n: int
29 :rtype: int
30 """
31 if n < 3:
32 return 0
33 primes = [True] * n
34 primes[0] = primes[1] = False
35 for i in range(2, int(n ** 0.5) + 1):
36 if primes[i]:
37 primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
38 return sum(primes)
39
******************

63. Isomorphic Strings


******************

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two
characters may map to the same character, but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"


Output: true

Example 2:

Input: s = "foo", t = "bar"


Output: false

Example 3:

Input: s = "paper", t = "title"


Output: true

Constraints:

1 <= s.length <= 5 * 10 4


t.length == s.length
s and t consist of any valid ascii character.
******************

63. Isomorphic Strings(C++)


******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isIsomorphic(string s, string t) {
7 if (s.length() != t.length()) {
8 return false;
9 }
10 vector s2t(256, 0), t2s(256, 0);
11 for (int i = 0; i < s.length(); ++i) {
12 if (s2t[s[i]] == 0 && t2s[t[i]] == 0) {
13 s2t[s[i]] = t[i];
14 t2s[t[i]] = s[i];
15 } else if (s2t[s[i]] != t[i]) {
16 // Contradict mapping.
17 return false;
18 }
19 }
20 return true;
21 }
22 };
******************

63. Isomorphic Strings(Python)


******************

1 # Time: O(n)
2 # Space: O(1)
3
4 from itertools import izip # Generator version of zip.
5
6 class Solution(object):
7 def isIsomorphic(self, s, t):
8 """
9 :type s: str
10 :type t: str
11 :rtype: bool
12 """
13 if len(s) != len(t):
14 return False
15
16 s2t, t2s = {}, {}
17 for p, w in izip(s, t):
18 if w not in s2t and p not in t2s:
19 s2t[w] = p
20 t2s[p] = w
21 elif w not in s2t or s2t[w] != p:
22 # Contradict mapping.
23 return False
24 return True
25
26
27 # Time: O(n)
28 # Space: O(1)
29 class Solution2(object):
30 def isIsomorphic(self, s, t):
31 if len(s) != len(t):
32 return False
33
34 return self.halfIsom(s, t) and self.halfIsom(t, s)
35
36 def halfIsom(self, s, t):
37 lookup = {}
38 for i in xrange(len(s)):
39 if s[i] not in lookup:
40 lookup[s[i]] = t[i]
41 elif lookup[s[i]] != t[i]:
42 return False
43 return True
44
*******************

64. Reverse Linked List


*******************

Given the head of a singly linked list, reverse the list, and returnthe reversed list.

Example 1:

Input: head = [1,2,3,4,5]


Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]


Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

The number of nodes in the list is the range [0, 5000].


-5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
*******************

64. Reverse Linked List(C++)


*******************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode* reverseList(ListNode* head) {
15 auto dummy = ListNode{0};
16
17 while (head) {
18 auto tmp = head->next;
19 head->next = dummy.next;
20 dummy.next = head;
21 head = tmp;
22 }
23
24 return dummy.next;
25 }
26 };
*******************

64. Reverse Linked List(Python)


*******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9 def __repr__(self):
10 if self:
11 return "{} -> {}".format(self.val, repr(self.next))
12
13 # Iterative solution.
14 class Solution(object):
15 # @param {ListNode} head
16 # @return {ListNode}
17 def reverseList(self, head):
18 dummy = ListNode(float("-inf"))
19 while head:
20 dummy.next, head.next, head = head, dummy.next, head.next
21 return dummy.next
22
23 # Time: O(n)
24 # Space: O(n)
25 # Recursive solution.
26 class Solution2(object):
27 # @param {ListNode} head
28 # @return {ListNode}
29 def reverseList(self, head):
30 [begin, end] = self.reverseListRecu(head)
31 return begin
32
33 def reverseListRecu(self, head):
34 if not head:
35 return [None, None]
36
37 [begin, end] = self.reverseListRecu(head.next)
38
39 if end:
40 end.next = head
41 head.next = None
42 return [begin, head]
43 else:
44 return [head, head]
45
******************

65. Contains Duplicate


******************

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is
distinct.

Example 1:

Input: nums = [1,2,3,1]


Output: true

Example 2:

Input: nums = [1,2,3,4]


Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]


Output: true

Constraints:

1 <= nums.length <= 10 5


-109 <= nums[i] <= 10 9
******************

65. Contains Duplicate(C++)


******************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool containsDuplicate(vector& nums) {
7 unordered_set nums_set(nums.begin(), nums.end());
8 return nums_set.size() != nums.size();
9 }
10 };
11
12 // Time: O(nlogn)
13 // Space: O(1)
14 class Solution2 {
15 public:
16 bool containsDuplicate(vector& nums) {
17 sort(nums.begin(), nums.end());
18 return unique(nums.begin(), nums.end()) != nums.end();
19 }
20 };
******************

65. Contains Duplicate(Python)


******************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 # @param {integer[]} nums
6 # @return {boolean}
7 def containsDuplicate(self, nums):
8 return len(nums) > len(set(nums))
9
*********************

66. Contains Duplicate II


*********************

Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i]
== nums[j] and abs(i - j) <= k .

Example 1:

Input: nums = [1,2,3,1], k = 3


Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1


Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2


Output: false

Constraints:

1 <= nums.length <= 10 5


-109 <= nums[i] <= 10 9
0 <= k <= 10 5
*********************

66. Contains Duplicate II(C++)


*********************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool containsNearbyDuplicate(vector& nums, int k) {
7 unordered_map lookup;
8 for (int i = 0; i < nums.size(); ++i) {
9 if (lookup.find(nums[i]) == lookup.end()) {
10 lookup[nums[i]] = i;
11 } else {
12 // If the value occurs before, check the difference.
13 if (i - lookup[nums[i]] <= k) {
14 return true;
15 }
16 // Update the index of the value.
17 lookup[nums[i]] = i;
18 }
19 }
20 return false;
21 }
22 };
*********************

66. Contains Duplicate II(Python)


*********************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 # @param {integer[]} nums
6 # @param {integer} k
7 # @return {boolean}
8 def containsNearbyDuplicate(self, nums, k):
9 lookup = {}
10 for i, num in enumerate(nums):
11 if num not in lookup:
12 lookup[num] = i
13 else:
14 # If the value occurs before, check the difference.
15 if i - lookup[num] <= k:
16 return True
17 # Update the index of the value.
18 lookup[num] = i
19 return False
20
**************

67. Rectangle Area


**************

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).

Example 1:

Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45

Example 2:

Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
Output: 16

Constraints:

-104 <= ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 <= 10 4
**************

67. Rectangle Area(C++)


**************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
7 return (D - B) * (C - A) +
8 (G - E) * (H - F) -
9 max(0, (min(C, G) - max(A, E))) *
10 max(0, (min(D, H) - max(B, F)));
11 }
12 };
**************

67. Rectangle Area(Python)


**************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param {integer} A
6 # @param {integer} B
7 # @param {integer} C
8 # @param {integer} D
9 # @param {integer} E
10 # @param {integer} F
11 # @param {integer} G
12 # @param {integer} H
13 # @return {integer}
14 def computeArea(self, A, B, C, D, E, F, G, H):
15 return (D - B) * (C - A) + \
16 (G - E) * (H - F) - \
17 max(0, (min(C, G) - max(A, E))) * \
18 max(0, (min(D, H) - max(B, F)))
19
****************************

68. Implement Stack using Queues


****************************

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a
normal stack (push, top, pop, and empty).

Implement the MyStack class:

void push(int x) Pushes element x to the top of the stack.


int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.

Notes:

You must use only standard operations of a queue, which means that onlypush to back, peek/pop from front, size and is empty
operations are valid.
Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or
deque (double-ended queue) as long as you use only a queue's standard operations.

Example 1:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

Constraints:

1 <= x <= 9
At most 100 calls will be made to push, pop, top, and empty.
All the calls to pop and top are valid.

Follow-up: Can you implement the stack using only one queue?
****************************

68. Implement Stack using Queues(C++)


****************************
1 // Time: push: O(n), pop: O(1), top: O(1)
2 // Space: O(n)
3
4 class Stack {
5 public:
6 queue q_;
7
8 // Push element x onto stack.
9 void push(int x) { // O(n)
10 q_.emplace(x);
11 for (int i = 0; i < q_.size() - 1; ++i) {
12 q_.emplace(q_.front());
13 q_.pop();
14 }
15 }
16
17 // Remove the element on top of the stack.
18 void pop() { // O(1)
19 q_.pop();
20 }
21
22 // Get the top element.
23 int top() { // O(1)
24 return q_.front();
25 }
26
27 // Return whether the stack is empty.
28 bool empty() { // O(1)
29 return q_.empty();
30 }
31 };
32
33 // Time: push: O(1), pop: O(n), top: O(1)
34 // Space: O(n)
35 class Stack2 {
36 public:
37 queue q_;
38 int top_;
39
40 // Push element x onto stack.
41 void push(int x) { // O(1)
42 q_.emplace(x);
43 top_ = x;
44 }
45
46 // Remove the element on top of the stack.
47 void pop() { // O(n)
48 for (int i = 0; i < q_.size() - 1; ++i) {
49 top_ = q_.front();
50 q_.emplace(top_);
51 q_.pop();
52 }
53 q_.pop();
54 }
55
56 // Get the top element.
57 int top() { // O(1)
58 return top_;
59 }
60
61 // Return whether the stack is empty.
62 bool empty() { // O(1)
63 return q_.empty();
64 }
65 };
66
****************************

68. Implement Stack using Queues(Python)


****************************

1 # Time: push: O(n), pop: O(1), top: O(1)


2 # Space: O(n)
3
4 import collections
5
6
7 class Queue(object):
8 def __init__(self):
9 self.data = collections.deque()
10
11 def push(self, x):
12 self.data.append(x)
13
14 def peek(self):
15 return self.data[0]
16
17 def pop(self):
18 return self.data.popleft()
19
20 def size(self):
21 return len(self.data)
22
23 def empty(self):
24 return len(self.data) == 0
25
26
27 class Stack(object):
28 # initialize your data structure here.
29 def __init__(self):
30 self.q_ = Queue()
31
32 # @param x, an integer
33 # @return nothing
34 def push(self, x):
35 self.q_.push(x)
36 for _ in xrange(self.q_.size() - 1):
37 self.q_.push(self.q_.pop())
38
39 # @return nothing
40 def pop(self):
41 self.q_.pop()
42
43 # @return an integer
44 def top(self):
45 return self.q_.peek()
46
47 # @return an boolean
48 def empty(self):
49 return self.q_.empty()
50
51
52 # Time: push: O(1), pop: O(n), top: O(1)
53 # Space: O(n)
54 class Stack2(object):
55 # initialize your data structure here.
56 def __init__(self):
57 self.q_ = Queue()
58 self.top_ = None
59
60 # @param x, an integer
61 # @return nothing
62 def push(self, x):
63 self.q_.push(x)
64 self.top_ = x
65
66 # @return nothing
67 def pop(self):
68 for _ in xrange(self.q_.size() - 1):
69 self.top_ = self.q_.pop()
70 self.q_.push(self.top_)
71 self.q_.pop()
72
73 # @return an integer
74 def top(self):
75 return self.top_
76
77 # @return an boolean
78 def empty(self):
79 return self.q_.empty()
80
******************

69. Invert Binary Tree


******************

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

Input: root = [4,2,7,1,3,6,9]


Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]


Output: [2,3,1]

Example 3:

Input: root = []
Output: []

Constraints:

The number of nodes in the tree is in the range[0, 100].


-100 <= Node.val <= 100
******************

69. Invert Binary Tree(C++)


******************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13
14 // Time: O(n)
15 // Space: O(w), w is the max number of nodes of the levels.
16 // BFS solution.
17 class Solution {
18 public:
19 TreeNode* invertTree(TreeNode* root) {
20 if (root != nullptr) {
21 queue nodes;
22 nodes.emplace(root);
23 while (!nodes.empty()) {
24 auto node = nodes.front();
25 nodes.pop();
26 swap(node->left, node->right);
27 if (node->left != nullptr) {
28 nodes.emplace(node->left);
29 }
30 if (node->right != nullptr) {
31 nodes.emplace(node->right);
32 }
33 }
34 }
35 return root;
36 }
37 };
38
39 // Time: O(n)
40 // Space: O(h)
41 // Stack solution.
42 class Solution2 {
43 public:
44 TreeNode* invertTree(TreeNode* root) {
45 if (root != nullptr) {
46 stack nodes;
47 nodes.emplace(root);
48 while (!nodes.empty()) {
49 auto node = nodes.top();
50 nodes.pop();
51 swap(node->left, node->right);
52 if (node->left != nullptr) {
53 nodes.emplace(node->left);
54 }
55 if (node->right != nullptr) {
56 nodes.emplace(node->right);
57 }
58 }
59 }
60 return root;
61 }
62 };
63
64 // Time: O(n)
65 // Space: O(h)
66 // DFS, Recursive solution.
67 class Solution3 {
68 public:
69 TreeNode* invertTree(TreeNode* root) {
70 if (root != nullptr) {
71 swap(root->left, root->right);
72 invertTree(root->left);
73 invertTree(root->right);
74 }
75 return root;
76 }
77 };
******************

69. Invert Binary Tree(Python)


******************

1 # Time: O(n)
2 # Space: O(h)
3
4 import collections
5
6
7 # BFS solution.
8 class Queue(object):
9 def __init__(self):
10 self.data = collections.deque()
11
12 def push(self, x):
13 self.data.append(x)
14
15 def peek(self):
16 return self.data[0]
17
18 def pop(self):
19 return self.data.popleft()
20
21 def size(self):
22 return len(self.data)
23
24 def empty(self):
25 return len(self.data) == 0
26
27 # Definition for a binary tree node.
28 # class TreeNode:
29 # def __init__(self, x):
30 # self.val = x
31 # self.left = None
32 # self.right = None
33
34 class Solution(object):
35 # @param {TreeNode} root
36 # @return {TreeNode}
37 def invertTree(self, root):
38 if root is not None:
39 nodes = Queue()
40 nodes.push(root)
41 while not nodes.empty():
42 node = nodes.pop()
43 node.left, node.right = node.right, node.left
44 if node.left is not None:
45 nodes.push(node.left)
46 if node.right is not None:
47 nodes.push(node.right)
48
49 return root
50
51 # Time: O(n)
52 # Space: O(h)
53 # Stack solution.
54 class Solution2(object):
55 # @param {TreeNode} root
56 # @return {TreeNode}
57 def invertTree(self, root):
58 if root is not None:
59 nodes = []
60 nodes.append(root)
61 while nodes:
62 node = nodes.pop()
63 node.left, node.right = node.right, node.left
64 if node.left is not None:
65 nodes.append(node.left)
66 if node.right is not None:
67 nodes.append(node.right)
68
69 return root
70
71 # Time: O(n)
72 # Space: O(h)
73 # DFS, Recursive solution.
74 class Solution3(object):
75 # @param {TreeNode} root
76 # @return {TreeNode}
77 def invertTree(self, root):
78 if root is not None:
79 root.left, root.right = self.invertTree(root.right), \
80 self.invertTree(root.left)
81
82 return root
83
************

70. Power of Two


************

Given an integer n, return true if it is a power of two. Otherwise, returnfalse.

An integer n is a power of two, if there exists an integerx such that n == 2x.

Example 1:

Input: n = 1
Output: true
Explanation: 20 = 1

Example 2:

Input: n = 16
Output: true
Explanation: 24 = 16

Example 3:

Input: n = 3
Output: false

Example 4:

Input: n = 4
Output: true

Example 5:

Input: n = 5
Output: false

Constraints:

-231 <= n <= 2 31 - 1

Follow up: Could you solve it without loops/recursion?


************

70. Power of Two(C++)


************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isPowerOfTwo(int n) {
7 return n > 0 && (n & (n - 1)) == 0;
8 }
9 };
10
11 class Solution2 {
12 public:
13 bool isPowerOfTwo(int n) {
14 return n > 0 && (n & ~-n) == 0;
15 }
16 };
************

70. Power of Two(Python)


************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param {integer} n
6 # @return {boolean}
7 def isPowerOfTwo(self, n):
8 return n > 0 and (n & (n - 1)) == 0
9
10
11 class Solution2(object):
12 # @param {integer} n
13 # @return {boolean}
14 def isPowerOfTwo(self, n):
15 return n > 0 and (n & ~-n) == 0
16
****************************

71. Implement Queue using Stacks


****************************

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of
a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

void push(int x) Pushes element x to the back of the queue.


int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

You must use only standard operations of a stack, which means only push to top , peek/pop from top, size, and is empty
operations are valid.
Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque
(double-ended queue) as long as you use only a stack's standard operations.

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words,
performing n operations will take overall O(n) time even if one of those operations may take longer.

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Constraints:

1 <= x <= 9
At most 100 calls will be made to push, pop, peek, and empty.
All the calls to pop and peek are valid.
****************************

71. Implement Queue using Stacks(C++)


****************************

1 // Time: O(1), amortized


2 // Space: O(n)
3
4 class Queue {
5 public:
6 // Push element x to the back of queue.
7 void push(int x) {
8 A_.emplace(x);
9 }
10
11 // Removes the element from in front of queue.
12 void pop(void) {
13 peek();
14 B_.pop();
15 }
16
17 // Get the front element.
18 int peek(void) {
19 if (B_.empty()) {
20 // Transfers the elements in A_ to B_.
21 while (!A_.empty()) {
22 B_.emplace(A_.top());
23 A_.pop();
24 }
25 }
26 if (B_.empty()) { // B_ is still empty!
27 throw length_error("empty queue");
28 }
29 return B_.top();
30 }
31
32 // Return whether the queue is empty.
33 bool empty(void) {
34 return A_.empty() && B_.empty();
35 }
36
37 private:
38 stack A_, B_;
39 };
****************************

71. Implement Queue using Stacks(Python)


****************************

1 # Time: O(1), amortized


2 # Space: O(n)
3
4 class Queue(object):
5 # initialize your data structure here.
6 def __init__(self):
7 self.A, self.B = [], []
8
9 # @param x, an integer
10 # @return nothing
11 def push(self, x):
12 self.A.append(x)
13
14 # @return an integer
15 def pop(self):
16 self.peek()
17 return self.B.pop()
18
19 # @return an integer
20 def peek(self):
21 if not self.B:
22 while self.A:
23 self.B.append(self.A.pop())
24 return self.B[-1]
25
26 # @return an boolean
27 def empty(self):
28 return not self.A and not self.B
29
**********************

72. Palindrome Linked List


**********************

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:

Input: head = [1,2,2,1]


Output: true

Example 2:

Input: head = [1,2]


Output: false

Constraints:

The number of nodes in the list is in the range[1, 105].


0 <= Node.val <= 9

Follow up: Could you do it in O(n) time and O(1) space?


**********************

72. Palindrome Linked List(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 bool isPalindrome(ListNode* head) {
15 // Reverse the first half list.
16 ListNode *reverse = nullptr, *fast = head;
17 while (fast && fast->next) {
18 fast = fast->next->next;
19 const auto head_next = head->next;
20 head->next = reverse;
21 reverse = head;
22 head = head_next;
23 }
24
25 // If the number of the nodes is odd,
26 // set the head of the tail list to the next of the median node.
27 ListNode *tail = fast ? head->next : head;
28
29 // Compare the reversed first half list with the second half list.
30 // And restore the reversed first half list.
31 bool is_palindrome = true;
32 while (reverse) {
33 is_palindrome = is_palindrome && reverse->val == tail->val;
34 const auto reverse_next = reverse->next;
35 reverse->next = head;
36 head = reverse;
37 reverse = reverse_next;
38 tail = tail->next;
39 }
40
41 return is_palindrome;
42 }
43 };
**********************

72. Palindrome Linked List(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param {ListNode} head
6 # @return {boolean}
7 def isPalindrome(self, head):
8 reverse, fast = None, head
9 # Reverse the first half part of the list.
10 while fast and fast.next:
11 fast = fast.next.next
12 head.next, reverse, head = reverse, head, head.next
13
14 # If the number of the nodes is odd,
15 # set the head of the tail list to the next of the median node.
16 tail = head.next if fast else head
17
18 # Compare the reversed first half list with the second half list.
19 # And restore the reversed first half list.
20 is_palindrome = True
21 while reverse:
22 is_palindrome = is_palindrome and reverse.val == tail.val
23 reverse.next, head, reverse = head, reverse, reverse.next
24 tail = tail.next
25
26 return is_palindrome
27
**********************************************

73. Lowest Common Ancestor of a Binary Search Tree


**********************************************

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodesp and q as the
lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8


Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4


Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [2,1], p = 2, q = 1


Output: 2

Constraints:

The number of nodes in the tree is in the range[2, 105].


-109 <= Node.val <= 10 9
All Node.val are unique.
p != q
p and q will exist in the BST.
**********************************************

73. Lowest Common Ancestor of a Binary Search


Tree(C++)
**********************************************

1 // Time: O(h)
2 // Space: O(1)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
16 auto s = min(p->val, q->val);
17 auto b = max(p->val, q->val);
18
19 while (root->val < s || root->val > b) {
20 // Keep searching since root is outside of [s, b].
21 root = s <= root->val ? root->left : root->right;
22 }
23
24 // s <= root->val && root->val <= b.
25 return root;
26 }
27 };
**********************************************

73. Lowest Common Ancestor of a Binary Search


Tree(Python)
**********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param {TreeNode} root
6 # @param {TreeNode} p
7 # @param {TreeNode} q
8 # @return {TreeNode}
9 def lowestCommonAncestor(self, root, p, q):
10 s, b = sorted([p.val, q.val])
11 while not s <= root.val <= b:
12 # Keep searching since root is outside of [s, b].
13 root = root.left if s <= root.val else root.right
14 # s <= root.val <= b.
15 return root
16
****************************

74. Delete Node in a Linked List


****************************

Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be
given access to the node to be deleted directly.

It is guaranteed that the node to be deleted is not a tail node in the list.

Example 1:

Input: head = [4,5,1,9], node = 5


Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1


Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Example 3:

Input: head = [1,2,3,4], node = 3


Output: [1,2,4]

Example 4:

Input: head = [0,1], node = 0


Output: [1]

Example 5:

Input: head = [-3,5,-99], node = -3


Output: [5,-99]

Constraints:

The number of the nodes in the given list is in the range[2, 1000].
-1000 <= Node.val <= 1000
The value of each node in the list is unique.
The node to be deleted is in the list and is not a tail node
****************************

74. Delete Node in a Linked List(C++)


****************************

1 // Time: O(1)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 void deleteNode(ListNode* node) {
15 if (!node || !node->next) {
16 return;
17 }
18 auto node_to_delete = node->next;
19 node->val = node->next->val;
20 node->next = node->next->next;
21 delete node_to_delete;
22 }
23 };
****************************

74. Delete Node in a Linked List(Python)


****************************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param {ListNode} node
6 # @return {void} Do not return anything, modify node in-place instead.
7 def deleteNode(self, node):
8 if node and node.next:
9 node_to_delete = node.next
10 node.val = node_to_delete.val
11 node.next = node_to_delete.next
12 del node_to_delete
13
*************

75. Valid Anagram


*************

Given two strings s and t, return true if t is an anagram of s , and false otherwise.

Example 1:

Input: s = "anagram", t = "nagaram"


Output: true

Example 2:

Input: s = "rat", t = "car"


Output: false

Constraints:

1 <= s.length, t.length <= 5 * 10 4


s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
*************

75. Valid Anagram(C++)


*************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isAnagram(string s, string t) {
7 if (size(s) != size(t)) {
8 return false;
9 }
10
11 unordered_map count;
12 for (const auto& c: s) {
13 ++count[c];
14 }
15 for (const auto& c: t) {
16 --count[c];
17 if (count[c] < 0) {
18 return false;
19 }
20 }
21 return true;
22 }
23 };
24
25 // Time: O(nlogn)
26 // Space: O(1)
27 class Solution2 {
28 public:
29 bool isAnagram(string s, string t) {
30 if (size(s) != size(t)) {
31 return false;
32 }
33
34 sort(begin(s), end(s));
35 sort(begin(t), end(t));
36 return s == t;
37 }
38 };
*************

75. Valid Anagram(Python)


*************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def isAnagram(self, s, t):
9 """
10 :type s: str
11 :type t: str
12 :rtype: bool
13 """
14 if len(s) != len(t):
15 return False
16 count = collections.defaultdict(int)
17 for c in s:
18 count[c] += 1
19 for c in t:
20 count[c] -= 1
21 if count[c] < 0:
22 return False
23 return True
24
25
26 # Time: O(n)
27 # Space: O(1)
28 class Solution2(object):
29 def isAnagram(self, s, t):
30 """
31 :type s: str
32 :type t: str
33 :rtype: bool
34 """
35 return collections.Counter(s) == collections.Counter(t)
36
37
38 # Time: O(nlogn)
39 # Space: O(n)
40 class Solution3(object):
41 def isAnagram(self, s, t):
42 """
43 :type s: str
44 :type t: str
45 :rtype: bool
46 """
47 return sorted(s) == sorted(t)
48
**********************

76. Shortest Word Distance


**********************

Given an array of strings wordsDict and two different strings that already exist in the arrayword1 and word2, return the shortest
distance between these two words in the list.

Example 1:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output: 3

Example 2:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1

Constraints:

1 <= wordsDict.length <= 3 * 10 4


1 <= wordsDict[i].length <= 10
wordsDict[i] consists of lowercase English letters.
word1 and word2 are in wordsDict.
word1 != word2
**********************

76. Shortest Word Distance(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int shortestDistance(vector& words, string word1, string word2) {
7 int dist = INT_MAX;
8 for (int i = 0, index1 = -1, index2 = -1; i < words.size(); ++i) {
9 if (words[i] == word1) {
10 index1 = i;
11 } else if (words[i] == word2) {
12 index2 = i;
13 }
14 if (index1 != -1 && index2 != -1) {
15 dist = min(dist, abs(index1 - index2));
16 }
17 }
18 return dist;
19 }
20 };
**********************

76. Shortest Word Distance(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 # @param {string[]} words
6 # @param {string} word1
7 # @param {string} word2
8 # @return {integer}
9 def shortestDistance(self, words, word1, word2):
10 dist = float("inf")
11 i, index1, index2 = 0, None, None
12 while i < len(words):
13 if words[i] == word1:
14 index1 = i
15 elif words[i] == word2:
16 index2 = i
17
18 if index1 is not None and index2 is not None:
19 dist = min(dist, abs(index1 - index2))
20 i += 1
21
22 return dist
23
**********************

77. Strobogrammatic Number


**********************

Given a string num which represents an integer, return true if num is a strobogrammatic number.

A strobogrammatic number is a number that looks the same when rotated180 degrees (looked at upside down).

Example 1:

Input: num = "69"


Output: true

Example 2:

Input: num = "88"


Output: true

Example 3:

Input: num = "962"


Output: false

Example 4:

Input: num = "1"


Output: true

Constraints:

1 <= num.length <= 50


num consists of only digits.
num does not contain any leading zeros except for zero itself.
**********************

77. Strobogrammatic Number(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isStrobogrammatic(string num) {
7 const int n = num.size();
8 for (int i = 0; i <= n - 1 - i; ++i) {
9 const auto it = lookup.find(num[n - 1 - i]);
10 if (it == lookup.end() || num[i] != it->second) {
11 return false;
12 }
13 }
14 return true;
15 }
16
17 private:
18 const unordered_map lookup{{'0', '0'}, {'1', '1'},
19 {'6', '9'}, {'8', '8'},
20 {'9', '6'}};
21 };
**********************

77. Strobogrammatic Number(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
6
7 # @param {string} num
8 # @return {boolean}
9 def isStrobogrammatic(self, num):
10 n = len(num)
11 for i in xrange((n+1) / 2):
12 if num[n-1-i] not in self.lookup or \
13 num[i] != self.lookup[num[n-1-i]]:
14 return False
15 return True
16
*********************

78. Group Shifted Strings


*********************

We can shift a string by shifting each of its letters to its successive letter.

For example, "abc" can be shifted to be "bcd".

We can keep shifting the string to form a sequence.

For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz" .

Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in
any order.

Example 1:

Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"]


Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]

Example 2:

Input: strings = ["a"]


Output: [["a"]]

Constraints:

1 <= strings.length <= 200


1 <= strings[i].length <= 50
strings[i] consists of lowercase English letters.
*********************

78. Group Shifted Strings(C++)


*********************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector> groupStrings(vector& strings) {
7 unordered_map> groups;
8 for (const auto& str : strings) { // Grouping.
9 groups[hashStr(str)].insert(str);
10 }
11
12 vector> result;
13 for (const auto& kvp : groups) {
14 vector group;
15 for (auto& str : kvp.second) { // Sorted in a group.
16 group.emplace_back(move(str));
17 }
18 result.emplace_back(move(group));
19 }
20
21 return result;
22 }
23
24 string hashStr(string str) {
25 const char base = str[0];
26 for (auto& c : str) {
27 c = 'a' + ((c - base) >= 0 ? c - base : c - base + 26);
28 }
29 return str;
30 }
31 };
*********************

78. Group Shifted Strings(Python)


*********************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 # @param {string[]} strings
9 # @return {string[][]}
10 def groupStrings(self, strings):
11 groups = collections.defaultdict(list)
12 for s in strings: # Grouping.
13 groups[self.hashStr(s)].append(s)
14
15 result = []
16 for key, val in groups.iteritems():
17 result.append(sorted(val))
18
19 return result
20
21 def hashStr(self, s):
22 base = ord(s[0])
23 hashcode = ""
24 for i in xrange(len(s)):
25 if ord(s[i]) - base >= 0:
26 hashcode += unichr(ord('a') + ord(s[i]) - base)
27 else:
28 hashcode += unichr(ord('a') + ord(s[i]) - base + 26)
29 return hashcode
30
*************

79. Meeting Rooms


*************

Given an array of meeting time intervals where intervals[i] = [start i, end i], determine if a person could attend all meetings.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]


Output: false

Example 2:

Input: intervals = [[7,10],[2,4]]


Output: true

Constraints:

0 <= intervals.length <= 104


intervals[i].length == 2
0 <= starti < end i <= 106
*************

79. Meeting Rooms(C++)


*************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool canAttendMeetings(vector>& intervals) {
7 sort(intervals.begin(), intervals.end());
8 for (int i = 1; i < intervals.size(); ++i) {
9 if (intervals[i][0] < intervals[i - 1][1]) {
10 return false;
11 }
12 }
13 return true;
14 }
15 };
*************

79. Meeting Rooms(Python)


*************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 class Solution(object):
5 def canAttendMeetings(self, intervals):
6 """
7 :type intervals: List[List[int]]
8 :rtype: bool
9 """
10 intervals.sort(key=lambda x: x[0])
11
12 for i in xrange(1, len(intervals)):
13 if intervals[i][0] < intervals[i-1][1]:
14 return False
15 return True
*****************

80. Binary Tree Paths


*****************

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Example 1:

Input: root = [1,2,3,null,5]


Output: ["1->2->5","1->3"]

Example 2:

Input: root = [1]


Output: ["1"]

Constraints:

The number of nodes in the tree is in the range[1, 100].


-100 <= Node.val <= 100
*****************

80. Binary Tree Paths(C++)


*****************

1 // Time: O(n * h)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 vector binaryTreePaths(TreeNode* root) {
16 vector result;
17 vector path;
18 binaryTreePathsRecu(root, &path, &result);
19 return result;
20 }
21
22 void binaryTreePathsRecu(TreeNode *node, vector *path, vector *result) {
23 if (!node) {
24 return;
25 }
26
27 if (!node->left && !node->right) {
28 string ans = "";
29 for (const auto& n : *path) {
30 ans.append(to_string(n->val).append("->"));
31 }
32 result->emplace_back(move(ans.append(to_string(node->val))));
33 }
34
35 if (node->left) {
36 path->emplace_back(node);
37 binaryTreePathsRecu(node->left, path, result);
38 path->pop_back();
39 }
40
41 if (node->right) {
42 path->emplace_back(node);
43 binaryTreePathsRecu(node->right, path, result);
44 path->pop_back();
45 }
46 }
47 };
*****************

80. Binary Tree Paths(Python)


*****************

1 # Time: O(n * h)
2 # Space: O(h)
3
4 class Solution(object):
5 # @param {TreeNode} root
6 # @return {string[]}
7 def binaryTreePaths(self, root):
8 result, path = [], []
9 self.binaryTreePathsRecu(root, path, result)
10 return result
11
12 def binaryTreePathsRecu(self, node, path, result):
13 if node is None:
14 return
15
16 if node.left is node.right is None:
17 ans = ""
18 for n in path:
19 ans += str(n.val) + "->"
20 result.append(ans + str(node.val))
21
22 if node.left:
23 path.append(node)
24 self.binaryTreePathsRecu(node.left, path, result)
25 path.pop()
26
27 if node.right:
28 path.append(node)
29 self.binaryTreePathsRecu(node.right, path, result)
30 path.pop()
31
**********

81. Add Digits


**********

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:

Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.

Example 2:

Input: num = 0
Output: 0

Constraints:

0 <= num <= 2 31 - 1

Follow up: Could you do it without any loop/recursion in O(1) runtime?


**********

81. Add Digits(C++)


**********

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int addDigits(int num) {
7 return (num - 1) % 9 + 1;
8 }
9 };
**********

81. Add Digits(Python)


**********

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 """
6 :type num: int
7 :rtype: int
8 """
9 def addDigits(self, num):
10 return (num - 1) % 9 + 1 if num > 0 else 0
11
***********

82. Ugly Number


***********

An ugly number is a positive integer whose prime factors are limited to2, 3, and 5.

Given an integer n, return true if n is an ugly number.

Example 1:

Input: n = 6
Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: n = 8
Output: true
Explanation: 8 = 2 × 2 × 2

Example 3:

Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.

Example 4:

Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

Constraints:

-231 <= n <= 2 31 - 1


***********

82. Ugly Number(C++)


***********

1 // Time: O(logn) = O(1)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isUgly(int num) {
7 if (num == 0) {
8 return false;
9 }
10 for (const auto& i : {2, 3, 5}) {
11 while (num % i == 0) {
12 num /= i;
13 }
14 }
15 return num == 1;
16 }
17 };
***********

82. Ugly Number(Python)


***********

1 # Time: O(logn) = O(1)


2 # Space: O(1)
3
4 class Solution(object):
5 # @param {integer} num
6 # @return {boolean}
7 def isUgly(self, num):
8 if num == 0:
9 return False
10 for i in [2, 3, 5]:
11 while num % i == 0:
12 num /= i
13 return num == 1
14
**********************

83. Palindrome Permutation


**********************

Given a string s , return true if a permutation of the string could form a palindrome.

Example 1:

Input: s = "code"
Output: false

Example 2:

Input: s = "aab"
Output: true

Example 3:

Input: s = "carerac"
Output: true

Constraints:

1 <= s.length <= 5000


s consists of only lowercase English letters.
**********************

83. Palindrome Permutation(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool canPermutePalindrome(string s) {
7 bitset<256> bits;
8 for (const auto& c : s) {
9 bits.flip(c);
10 }
11 return bits.count() < 2;
12 }
13 };
**********************

83. Palindrome Permutation(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def canPermutePalindrome(self, s):
9 """
10 :type s: str
11 :rtype: bool
12 """
13 return sum(v % 2 for v in collections.Counter(s).values()) < 2
14
********************************

84. Closest Binary Search Tree Value


********************************

Given the root of a binary search tree and a target value, return the value in the BST that is closest to thetarget.

Example 1:

Input: root = [4,2,5,1,3], target = 3.714286


Output: 4

Example 2:

Input: root = [1], target = 4.428571


Output: 1

Constraints:

The number of nodes in the tree is in the range[1, 104].


0 <= Node.val <= 10 9
-109 <= target <= 10 9
********************************

84. Closest Binary Search Tree Value(C++)


********************************

1 // Time: O(h)
2 // Space: O(1)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int closestValue(TreeNode* root, double target) {
16 double gap = numeric_limits::max();
17 int closest = numeric_limits::max();
18
19 while (root) {
20 if (abs(static_cast(root->val) - target) < gap) {
21 gap = abs(root->val - target);
22 closest = root->val;
23 }
24 if (target == root->val) {
25 break;
26 } else if (target < root->val) {
27 root = root->left;
28 } else {
29 root = root->right;
30 }
31 }
32 return closest;
33 }
34 };
********************************

84. Closest Binary Search Tree Value(Python)


********************************

1 # Time: O(h)
2 # Space: O(1)
3
4 class Solution(object):
5 def closestValue(self, root, target):
6 """
7 :type root: TreeNode
8 :type target: float
9 :rtype: int
10 """
11 gap = float("inf")
12 closest = float("inf")
13 while root:
14 if abs(root.val - target) < gap:
15 gap = abs(root.val - target)
16 closest = root.val
17 if target == root.val:
18 break
19 elif target < root.val:
20 root = root.left
21 else:
22 root = root.right
23 return closest
***********

85. Paint Fence


***********

You are painting a fence of n posts with k different colors. You must paint the posts following these rules:

Every post must be painted exactly one color.


There cannot be three or more consecutive posts with the same color.

Given the two integers n and k , return the number of ways you can paint the fence.

Example 1:

Input: n = 3, k = 2
Output: 6
Explanation: All the possibilities are shown.
Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color.

Example 2:

Input: n = 1, k = 1
Output: 1

Example 3:

Input: n = 7, k = 2
Output: 42

Constraints:

1 <= n <= 50
1 <= k <= 10 5
The testcases are generated such that the answer is in the range [0, 231 - 1] for the given n and k .
***********

85. Paint Fence(C++)


***********

1 // Time: O(n)
2 // Space: O(1)
3
4 // DP with rolling window.
5 class Solution {
6 public:
7 int numWays(int n, int k) {
8 if (n == 0) {
9 return 0;
10 } else if (n == 1) {
11 return k;
12 }
13 vector ways(3, 0);
14 ways[0] = k;
15 ways[1] = (k - 1) * ways[0] + k;
16 for (int i = 2; i < n; ++i) {
17 ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3]);
18 }
19 return ways[(n - 1) % 3];
20 }
21 };
22
23 // Time: O(n)
24 // Space: O(n)
25 // DP solution.
26 class Solution2 {
27 public:
28 int numWays(int n, int k) {
29 if (n == 0) {
30 return 0;
31 } else if (n == 1) {
32 return k;
33 }
34 vector ways(n, 0);
35 ways[0] = k;
36 ways[1] = (k - 1) * ways[0] + k;
37 for (int i = 2; i < n; ++i) {
38 ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]);
39 }
40 return ways[n - 1];
41 }
42 };
***********

85. Paint Fence(Python)


***********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def numWays(self, n, k):
6 """
7 :type n: int
8 :type k: int
9 :rtype: int
10 """
11 if n == 0:
12 return 0
13 elif n == 1:
14 return k
15 ways = [0] * 3
16 ways[0] = k
17 ways[1] = (k - 1) * ways[0] + k
18 for i in xrange(2, n):
19 ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3])
20 return ways[(n - 1) % 3]
21
22 # Time: O(n)
23 # Space: O(n)
24 # DP solution.
25 class Solution2(object):
26 def numWays(self, n, k):
27 """
28 :type n: int
29 :type k: int
30 :rtype: int
31 """
32 if n == 0:
33 return 0
34 elif n == 1:
35 return k
36 ways = [0] * n
37 ways[0] = k
38 ways[1] = (k - 1) * ways[0] + k
39 for i in xrange(2, n):
40 ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2])
41 return ways[n - 1]
42
*****************

86. First Bad Version


*****************

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your
product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad
version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be
bad.

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad
version. You should minimize the number of calls to the API.

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Constraints:

1 <= bad <= n <= 2 31 - 1


*****************

86. First Bad Version(C++)


*****************

1 // Time: O(logn)
2 // Space: O(1)
3
4 // Forward declaration of isBadVersion API.
5 bool isBadVersion(int version);
6
7 class Solution {
8 public:
9 int firstBadVersion(int n) {
10 int left = 1, right = n;
11 while (left <= right) {
12 int mid = left + (right - left) / 2;
13 if (isBadVersion(mid)) {
14 right = mid - 1;
15 } else {
16 left = mid + 1;
17 }
18 }
19 return left;
20 }
21 };
*****************

86. First Bad Version(Python)


*****************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def firstBadVersion(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 left, right = 1, n
11 while left <= right:
12 mid = left + (right - left) / 2
13 if isBadVersion(mid): # noqa
14 right = mid - 1
15 else:
16 left = mid + 1
17 return left
18
***********

87. Move Zeroes


***********

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]


Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]


Output: [0]

Constraints:

1 <= nums.length <= 10 4


-231 <= nums[i] <= 2 31 - 1

Follow up: Could you minimize the total number of operations done?
***********

87. Move Zeroes(C++)


***********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 void moveZeroes(vector& nums) {
7 int pos = 0;
8 for (auto& num : nums) {
9 if (num) {
10 swap(nums[pos++], num);
11 }
12 }
13 }
14 };
15
16 class Solution2 {
17 public:
18 void moveZeroes(vector& nums) {
19 int pos = 0;
20 for (const auto& num : nums) {
21 if (num) {
22 nums[pos++] = num;
23 }
24 }
25 fill(next(nums.begin(), pos), nums.end(), 0);
26 }
27 };
***********

87. Move Zeroes(Python)


***********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def moveZeroes(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: void Do not return anything, modify nums in-place instead.
9 """
10 pos = 0
11 for i in xrange(len(nums)):
12 if nums[i]:
13 nums[i], nums[pos] = nums[pos], nums[i]
14 pos += 1
15
16 def moveZeroes2(self, nums):
17 """
18 :type nums: List[int]
19 :rtype: void Do not return anything, modify nums in-place instead.
20 """
21 nums.sort(cmp=lambda a, b: 0 if b else -1)
22
23
24 class Solution2(object):
25 def moveZeroes(self, nums):
26 """
27 :type nums: List[int]
28 :rtype: void Do not return anything, modify nums in-place instead.
29 """
30 pos = 0
31 for i in xrange(len(nums)):
32 if nums[i]:
33 nums[pos] = nums[i]
34 pos += 1
35
36 for i in xrange(pos, len(nums)):
37 nums[i] = 0
38
39
************************

88. Unique Word Abbreviation


************************

The abbreviation of a word is a concatenation of its first letter, the number of characters between the first and last letter,
and its last letter. If a word has only two characters, then it is an abbreviation of itself.

For example:

dog --> d1g because there is one letter between the first letter 'd' and the last letter 'g'.
internationalization --> i18n because there are 18 letters between the first letter'i' and the last letter 'n'.
it --> it because any word with only two characters is an abbreviation of itself.

Implement the ValidWordAbbr class:

ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words.


boolean isUnique(string word) Returns true if either of the following conditions are met (otherwise returns false):
There is no word in dictionary whose abbreviation is equal to word's abbreviation.
For any word in dictionary whose abbreviation is equal to word's abbreviation, that word and word are the same.

Example 1:

Input
["ValidWordAbbr", "isUnique", "isUnique", "isUnique", "isUnique", "isUnique"]
[[["deer", "door", "cake", "card"]], ["dear"], ["cart"], ["cane"], ["make"], ["cake"]]
Output
[null, false, true, false, true, true]

Explanation
ValidWordAbbr validWordAbbr = new ValidWordAbbr(["deer", "door", "cake", "card"]);
validWordAbbr.isUnique("dear"); // return false, dictionary word "deer" and word "dear" have the same abbreviation "d2r" but are not the same
validWordAbbr.isUnique("cart"); // return true, no words in the dictionary have the abbreviation "c2t".
validWordAbbr.isUnique("cane"); // return false, dictionary word "cake" and word "cane" have the same abbreviation "c2e" but are not the sam
validWordAbbr.isUnique("make"); // return true, no words in the dictionary have the abbreviation "m2e".
validWordAbbr.isUnique("cake"); // return true, because "cake" is already in the dictionary and no other word in the dictionary has "c2e" abb

Constraints:

1 <= dictionary.length <= 3 * 10 4


1 <= dictionary[i].length <= 20
dictionary[i] consists of lowercase English letters.
1 <= word.length <= 20
word consists of lowercase English letters.
At most 5000 calls will be made to isUnique .
************************

88. Unique Word Abbreviation(C++)


************************

1 // Time: ctor: O(n), n is number of words in the dictionary.


2 // lookup: O(1)
3 // Space: O(k), k is number of unique words.
4
5 class ValidWordAbbr {
6 public:
7 ValidWordAbbr(vector &dictionary) {
8 for (string& word : dictionary) {
9 const string abbr = abbreviation(word);
10 lookup_[abbr].emplace(word);
11 }
12 }
13
14 bool isUnique(string word) {
15 const string abbr = abbreviation(word);
16 return lookup_[abbr].empty() ||
17 (lookup_[abbr].count(word) == lookup_[abbr].size());
18 }
19
20 private:
21 unordered_map> lookup_;
22
23 string abbreviation(const string& word) {
24 if (word.length() <= 2) {
25 return word;
26 }
27 return word.front() + to_string(word.length()) + word.back();
28 }
29 };
30
31
32 // Your ValidWordAbbr object will be instantiated and called as such:
33 // ValidWordAbbr vwa(dictionary);
34 // vwa.isUnique("hello");
35 // vwa.isUnique("anotherWord");
************************

88. Unique Word Abbreviation(Python)


************************

1 # Time: ctor: O(n), n is number of words in the dictionary.


2 # lookup: O(1)
3 # Space: O(k), k is number of unique words.
4
5 import collections
6
7
8 class ValidWordAbbr(object):
9 def __init__(self, dictionary):
10 """
11 initialize your data structure here.
12 :type dictionary: List[str]
13 """
14 self.lookup_ = collections.defaultdict(set)
15 for word in dictionary:
16 abbr = self.abbreviation(word)
17 self.lookup_[abbr].add(word)
18
19
20 def isUnique(self, word):
21 """
22 check if a word is unique.
23 :type word: str
24 :rtype: bool
25 """
26 abbr = self.abbreviation(word)
27 return self.lookup_[abbr] <= {word}
28
29
30 def abbreviation(self, word):
31 if len(word) <= 2:
32 return word
33 return word[0] + str(len(word)-2) + word[-1]
34
35
36
************

89. Word Pattern


************

Given a pattern and a string s , find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter inpattern and a non-empty word in s .

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"


Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"


Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"


Output: false

Example 4:

Input: pattern = "abba", s = "dog dog dog dog"


Output: false

Constraints:

1 <= pattern.length <= 300


pattern contains only lower-case English letters.
1 <= s.length <= 3000
s contains only lower-case English letters and spaces ' '.
s does not contain any leading or trailing spaces.
All the words in s are separated by a single space.
************

89. Word Pattern(C++)


************

1 // Time: O(n)
2 // Space: O(c), c is unique count of pattern
3
4 class Solution {
5 public:
6 bool wordPattern(string pattern, string str) {
7 // Count the words.
8 int cnt = str.empty() ? 0 : 1;
9 for (const auto& c : str) {
10 if (c == ' ') {
11 ++cnt;
12 }
13 }
14 if (pattern.size() != cnt) {
15 return false;
16 }
17
18 unordered_map w2p;
19 unordered_map p2w;
20 int i = 0, j = 0;
21 for (const auto& p : pattern) {
22 // Get a word at a time without saving all the words.
23 j = str.find(" ", i);
24 if (j == string::npos) {
25 j = str.length();
26 }
27 const string w = str.substr(i, j - i);
28
29 if (!w2p.count(w) && !p2w.count(p)) {
30 // Build mapping. Space: O(c)
31 w2p[w] = p;
32 p2w[p] = w;
33 } else if (!w2p.count(w) || w2p[w] != p) {
34 // Contradict mapping.
35 return false;
36 }
37 i = j + 1;
38 }
39 return true;
40 }
41 };
************

89. Word Pattern(Python)


************
1 # Time: O(n)
2 # Space: O(c), c is unique count of pattern
3
4 from itertools import izip # Generator version of zip.
5
6 class Solution(object):
7 def wordPattern(self, pattern, str):
8 """
9 :type pattern: str
10 :type str: str
11 :rtype: bool
12 """
13 if len(pattern) != self.wordCount(str):
14 return False
15
16 w2p, p2w = {}, {}
17 for p, w in izip(pattern, self.wordGenerator(str)):
18 if w not in w2p and p not in p2w:
19 # Build mapping. Space: O(c)
20 w2p[w] = p
21 p2w[p] = w
22 elif w not in w2p or w2p[w] != p:
23 # Contradict mapping.
24 return False
25 return True
26
27 def wordCount(self, str):
28 cnt = 1 if str else 0
29 for c in str:
30 if c == ' ':
31 cnt += 1
32 return cnt
33
34 # Generate a word at a time without saving all the words.
35 def wordGenerator(self, str):
36 w = ""
37 for c in str:
38 if c == ' ':
39 yield w
40 w = ""
41 else:
42 w += c
43 yield w
44
45
46 # Time: O(n)
47 # Space: O(n)
48 class Solution2(object):
49 def wordPattern(self, pattern, str):
50 """
51 :type pattern: str
52 :type str: str
53 :rtype: bool
54 """
55 words = str.split() # Space: O(n)
56 if len(pattern) != len(words):
57 return False
58
59 w2p, p2w = {}, {}
60 for p, w in izip(pattern, words):
61 if w not in w2p and p not in p2w:
62 # Build mapping. Space: O(c)
63 w2p[w] = p
64 p2w[p] = w
65 elif w not in w2p or w2p[w] != p:
66 # Contradict mapping.
67 return False
68 return True
69
********

90. Nim Game


********

You are playing the following Nim Game with your friend:

Initially, there is a heap of stones on the table.


You and your friend will alternate taking turns, and you go first.
On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
The one who removes the last stone is the winner.

Given n, the number of stones in the heap, returntrue if you can win the game assuming both you and your friend play
optimally, otherwise return false.

Example 1:

Input: n = 4
Output: false
Explanation: These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.

Example 2:

Input: n = 1
Output: true

Example 3:

Input: n = 2
Output: true

Constraints:

1 <= n <= 2 31 - 1
********

90. Nim Game(C++)


********

1 // Time: O(1)
2 // Soace: O(1)
3
4 class Solution {
5 public:
6 bool canWinNim(int n) {
7 return n % 4 != 0;
8 }
9 };
********

90. Nim Game(Python)


********

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def canWinNim(self, n):
6 """
7 :type n: int
8 :rtype: bool
9 """
10 return n % 4 != 0
11
*********

91. Flip Game


*********

You are playing a Flip Game with your friend.

You are given a string currentState that contains only '+' and '-'. You and your friend take turns to fliptwo consecutive "++" into
"--". The game ends when a person can no longer make a move, and therefore the other person will be the winner.

Return all possible states of the string currentState after one valid move. You may return the answer inany order. If there is
no valid move, return an empty list [].

Example 1:

Input: currentState = "++++"


Output: ["--++","+--+","++--"]

Example 2:

Input: currentState = "+"


Output: []

Constraints:

1 <= currentState.length <= 500


currentState[i] is either '+' or '-'.
*********

91. Flip Game(C++)


*********

1 // Time: O(c * n + n) = O(n * (c+1)), n is length of string, c is count of "++"


2 // Space: O(1), no extra space excluding the result which requires at most O(n^2) space
3
4 class Solution {
5 public:
6 vector generatePossibleNextMoves(string s) {
7 vector res;
8 int n = s.length();
9 for (int i = 0; i < n - 1; ++i) { // O(n) time
10 if (s[i] == '+') {
11 for (;i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time
12 s[i] = s[i + 1] = '-';
13 res.emplace_back(s); // O(n) to copy a string
14 s[i] = s[i + 1] = '+';
15 }
16 }
17 }
18 return res;
19 }
20 };
*********

91. Flip Game(Python)


*********

1 # Time: O(c * n + n) = O(n * (c+1))


2 # Space: O(n)
3
4 class Solution(object):
5 def generatePossibleNextMoves(self, s):
6 """
7 :type s: str
8 :rtype: List[str]
9 """
10 res = []
11 i, n = 0, len(s) - 1
12 while i < n: # O(n) time
13 if s[i] == '+':
14 while i < n and s[i+1] == '+': # O(c) time
15 res.append(s[:i] + '--' + s[i+2:]) # O(n) time and space
16 i += 1
17 i += 1
18 return res
19
20
21 # Time: O(c * m * n + n) = O(c * n + n), where m = 2 in this question
22 # Space: O(n)
23 # This solution compares O(m) = O(2) times for two consecutive "+", where m is length of the pattern
24 class Solution2(object):
25 def generatePossibleNextMoves(self, s):
26 """
27 :type s: str
28 :rtype: List[str]
29 """
30 return [s[:i] + "--" + s[i+2:] for i in xrange(len(s) - 1) if s[i:i+2] == "++"]
31
32
**************

92. Bulls and Cows


**************

You are playing the Bulls and Cows game with your friend.

You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you
provide a hint with the following info:

The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong
position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.

Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.

The hint should be formatted as "xAyB" , where x is the number of bulls and y is the number of cows. Note that both secret and
guess may contain duplicate digits.

Example 1:

Input: secret = "1807", guess = "7810"


Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"

Example 2:

Input: secret = "1123", guess = "0111"


Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.

Example 3:

Input: secret = "1", guess = "0"


Output: "0A0B"

Example 4:

Input: secret = "1", guess = "1"


Output: "1A0B"

Constraints:

1 <= secret.length, guess.length <= 1000


secret.length == guess.length
secret and guess consist of digits only.
**************

92. Bulls and Cows(C++)


**************

1 // Time: O(n)
2 // Space: O(10) = O(1)
3
4 // One pass solution.
5 class Solution {
6 public:
7 string getHint(string secret, string guess) {
8 unordered_map lookup;
9 int A = 0, B = 0;
10 for (int i = 0; i < size(secret); ++i) {
11 const char s = secret[i];
12 const char g = guess[i];
13 if (s == g) {
14 ++A;
15 } else {
16 B += int(lookup[s]++ < 0) + int(lookup[g]-- > 0);
17 }
18 }
19 return to_string(A).append("A").append(to_string(B)).append("B");
20 }
21 };
22
23 // Two pass solution.
24 class Solution2 {
25 public:
26 string getHint(string secret, string guess) {
27 unordered_map lookup;
28 int A = 0, B = 0;
29 for (const auto& s : secret) {
30 ++lookup[s];
31 }
32 for (const auto& g : guess) {
33 if (lookup[g]) {
34 --lookup[g];
35 ++B;
36 }
37 }
38 for (int i = 0; i < size(secret); ++i) {
39 if (secret[i] == guess[i]) {
40 ++A, --B;
41 }
42 }
43 return to_string(A).append("A").append(to_string(B)).append("B");
44 }
45 };
**************

92. Bulls and Cows(Python)


**************

1 # Time: O(n)
2 # Space: O(10) = O(1)
3
4 import operator
5
6
7 # One pass solution.
8 from collections import defaultdict, Counter
9 from itertools import izip, imap
10
11
12 class Solution(object):
13 def getHint(self, secret, guess):
14 """
15 :type secret: str
16 :type guess: str
17 :rtype: str
18 """
19 A, B = 0, 0
20 lookup = defaultdict(int)
21 for s, g in izip(secret, guess):
22 if s == g:
23 A += 1
24 else:
25 B += int(lookup[s] < 0) + int(lookup[g] > 0)
26 lookup[s] += 1
27 lookup[g] -= 1
28 return "%dA%dB" % (A, B)
29
30
31 # Two pass solution.
32 class Solution2(object):
33 def getHint(self, secret, guess):
34 """
35 :type secret: str
36 :type guess: str
37 :rtype: str
38 """
39 A = sum(imap(operator.eq, secret, guess))
40 B = sum((Counter(secret) & Counter(guess)).values()) - A
41 return "%dA%dB" % (A, B)
42
***************************

93. Range Sum Query - Immutable


***************************

Given an integer array nums, handle multiple queries of the following type:

1. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

Implement the NumArray class:

NumArray(int[] nums) Initializes the object with the integer array nums.
int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] +
nums[left + 1] + ... + nums[right]).

Example 1:

Input
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]

Explanation
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3

Constraints:

1 <= nums.length <= 10 4


-105 <= nums[i] <= 10 5
0 <= left <= right < nums.length
At most 104 calls will be made to sumRange.
***************************

93. Range Sum Query - Immutable(C++)


***************************

1 // Time: ctor: O(n),


2 // lookup: O(1)
3 // Space: O(n)
4
5 class NumArray {
6 public:
7 NumArray(vector &nums) {
8 accu.emplace_back(0);
9 for (const auto& num : nums) {
10 accu.emplace_back(accu.back() + num);
11 }
12 }
13
14 int sumRange(int i, int j) {
15 return accu[j + 1] - accu[i];
16 }
17
18 private:
19 vector accu;
20 };
21
22
23 // Your NumArray object will be instantiated and called as such:
24 // NumArray numArray(nums);
25 // numArray.sumRange(0, 1);
26 // numArray.sumRange(1, 2);
***************************

93. Range Sum Query - Immutable(Python)


***************************

1 # Time: ctor: O(n),


2 # lookup: O(1)
3 # Space: O(n)
4
5 class NumArray(object):
6 def __init__(self, nums):
7 """
8 initialize your data structure here.
9 :type nums: List[int]
10 """
11 self.accu = [0]
12 for num in nums:
13 self.accu.append(self.accu[-1] + num),
14
15 def sumRange(self, i, j):
16 """
17 sum of elements nums[i..j], inclusive.
18 :type i: int
19 :type j: int
20 :rtype: int
21 """
22 return self.accu[j + 1] - self.accu[i]
23
24
25
**************

94. Power of Three


**************

Given an integer n, return true if it is a power of three. Otherwise, return false.

An integer n is a power of three, if there exists an integer x such that n == 3x.

Example 1:

Input: n = 27
Output: true

Example 2:

Input: n = 0
Output: false

Example 3:

Input: n = 9
Output: true

Example 4:

Input: n = 45
Output: false

Constraints:

-231 <= n <= 2 31 - 1

Follow up: Could you solve it without loops/recursion?


**************

94. Power of Three(C++)


**************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 static const int max_log3 = log(numeric_limits::max()) / log(3);
7 static const int max_pow3 = pow(3, max_log3);
8
9 bool isPowerOfThree(int n) {
10 return n > 0 && max_pow3 % n == 0;
11 }
12 };
**************

94. Power of Three(Python)


**************

1 # Time: O(1)
2 # Space: O(1)
3
4 import math
5
6
7 class Solution(object):
8 def __init__(self):
9 self.__max_log3 = int(math.log(0x7fffffff) / math.log(3))
10 self.__max_pow3 = 3 ** self.__max_log3
11
12 def isPowerOfThree(self, n):
13 """
14 :type n: int
15 :rtype: bool
16 """
17 return n > 0 and self.__max_pow3 % n == 0
18
19
20 class Solution2(object):
21 def isPowerOfThree(self, n):
22 return n > 0 and (math.log10(n)/math.log10(3)).is_integer()
23
**********************

95. Nested List Weight Sum


**********************

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be
integers or other lists.

The depth of an integer is the number of lists that it is inside of. For example, the nested list[1,[2,2],[[3],2],1] has each integer's
value set to its depth.

Return the sum of each integer in nestedList multiplied by its depth.

Example 1:

Input: nestedList = [[1,1],2,[1,1]]


Output: 10
Explanation: Four 1's at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10.

Example 2:

Input: nestedList = [1,[4,[6]]]


Output: 27
Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.

Example 3:

Input: nestedList = [0]


Output: 0

Constraints:

1 <= nestedList.length <= 50


The values of the integers in the nested list is in the range[-100, 100].
The maximum depth of any integer is less than or equal to50.
**********************

95. Nested List Weight Sum(C++)


**********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * // This is the interface that allows for creating nested lists.
6 * // You should not implement it, or speculate about its implementation
7 * class NestedInteger {
8 * public:
9 * // Return true if this NestedInteger holds a single integer, rather than a nested list.
10 * bool isInteger() const;
11 *
12 * // Return the single integer that this NestedInteger holds, if it holds a single integer
13 * // The result is undefined if this NestedInteger holds a nested list
14 * int getInteger() const;
15 *
16 * // Return the nested list that this NestedInteger holds, if it holds a nested list
17 * // The result is undefined if this NestedInteger holds a single integer
18 * const vector &getList() const;
19 * };
20 */
21 class Solution {
22 public:
23 int depthSum(vector& nestedList) {
24 return depthSumHelper(nestedList, 1);
25 }
26
27 private:
28 int depthSumHelper(const vector& nestedList, int depth) {
29 int sum = 0;
30 for (const auto& list : nestedList) {
31 if (list.isInteger()) {
32 sum += list.getInteger() * depth;
33 } else {
34 sum += depthSumHelper(list.getList(), depth + 1);
35 }
36 }
37 return sum;
38 }
39 };
**********************

95. Nested List Weight Sum(Python)


**********************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def depthSum(self, nestedList):
6 """
7 :type nestedList: List[NestedInteger]
8 :rtype: int
9 """
10 def depthSumHelper(nestedList, depth):
11 res = 0
12 for l in nestedList:
13 if l.isInteger():
14 res += l.getInteger() * depth
15 else:
16 res += depthSumHelper(l.getList(), depth + 1)
17 return res
18 return depthSumHelper(nestedList, 1)
19
*************

96. Power of Four


*************

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integerx such that n == 4x.

Example 1:

Input: n = 16
Output: true

Example 2:

Input: n = 5
Output: false

Example 3:

Input: n = 1
Output: true

Constraints:

-231 <= n <= 2 31 - 1

Follow up: Could you solve it without loops/recursion?


*************

96. Power of Four(C++)


*************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isPowerOfFour(int num) {
7 return num > 0 && (num & (num - 1)) == 0 &&
8 ((num & 0b01010101010101010101010101010101) == num);
9 }
10 };
11
12 // Time: O(1)
13 // Space: O(1)
14 class Solution2 {
15 public:
16 bool isPowerOfFour(int num) {
17 while (num && !(num & 0b11)) {
18 num >>= 2;
19 }
20 return (num == 1);
21 }
22 };
*************

96. Power of Four(Python)


*************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def isPowerOfFour(self, num):
6 """
7 :type num: int
8 :rtype: bool
9 """
10 return num > 0 and (num & (num - 1)) == 0 and \
11 ((num & 0b01010101010101010101010101010101) == num)
12
13
14 # Time: O(1)
15 # Space: O(1)
16 class Solution2(object):
17 def isPowerOfFour(self, num):
18 """
19 :type num: int
20 :rtype: bool
21 """
22 while num and not (num & 0b11):
23 num >>= 2
24 return (num == 1)
25
26
27 class Solution3(object):
28 def isPowerOfFour(self, num):
29 """
30 :type num: int
31 :rtype: bool
32 """
33 num = bin(num)
34 return True if num[2:].startswith('1') and len(num[2:]) == num.count('0') and num.count('0') % 2 and '-' not in num else
35
**************

97. Reverse String


**************

Write a function that reverses a string. The input string is given as an array of characterss .

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints:

1 <= s.length <= 105


s[i] is a printable ascii character.

Follow up: Do not allocate extra space for another array. You must do this by modifying the input arrayin-place with O(1)
extra memory.
**************

97. Reverse String(C++)


**************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reverseString(string s) {
7 for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
8 swap(s[i], s[j]);
9 }
10 return s;
11 }
12 };
13
14 // Time: O(n)
15 // Space: O(1)
16 class Solution2 {
17 public:
18 string reverseString(string s) {
19 reverse(s.begin(), s.end());
20 return s;
21 }
22 };
**************

97. Reverse String(Python)


**************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def reverseString(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 string = list(s)
11 i, j = 0, len(string) - 1
12 while i < j:
13 string[i], string[j] = string[j], string[i]
14 i += 1
15 j -= 1
16 return "".join(string)
17
18
19 # Time: O(n)
20 # Space: O(n)
21 class Solution2(object):
22 def reverseString(self, s):
23 """
24 :type s: str
25 :rtype: str
26 """
27 return s[::-1]
28
**************************

98. Reverse Vowels of a String


**************************

Given a string s , reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

Constraints:

1 <= s.length <= 3 * 10 5


s consist of printable ASCII characters.
**************************

98. Reverse Vowels of a String(C++)


**************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reverseVowels(string s) {
7 for (int i = 0, j = s.length() - 1; i < j;) {
8 if (!is_vowel(tolower(s[i]))) {
9 ++i;
10 } else if (!is_vowel(tolower(s[j]))) {
11 --j;
12 } else {
13 swap(s[i++], s[j--]);
14 }
15 }
16 return s;
17 }
18
19 private:
20 const string vowels_ = "aeiou";
21 bool is_vowel(char a){
22 return vowels_.find(a) != string::npos;
23 }
24 };
**************************

98. Reverse Vowels of a String(Python)


**************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def reverseVowels(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 vowels = "aeiou"
11 string = list(s)
12 i, j = 0, len(s) - 1
13 while i < j:
14 if string[i].lower() not in vowels:
15 i += 1
16 elif string[j].lower() not in vowels:
17 j -= 1
18 else:
19 string[i], string[j] = string[j], string[i]
20 i += 1
21 j -= 1
22 return "".join(string)
23
*******************************

99. Moving Average from Data Stream


*******************************

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Implement the MovingAverage class:

MovingAverage(int size) Initializes the object with the size of the windowsize.
double next(int val) Returns the moving average of the last size values of the stream.

Example 1:

Input
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]

Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3

Constraints:

1 <= size <= 1000


-105 <= val <= 10 5
At most 104 calls will be made to next.
*******************************

99. Moving Average from Data Stream(C++)


*******************************

1 // Time: O(1)
2 // Space: O(w)
3
4 class MovingAverage {
5 public:
6 /** Initialize your data structure here. */
7 MovingAverage(int size) : size_(size), sum_(0) {
8 }
9
10 double next(int val) {
11 if (q_.size() == size_) {
12 sum_ -= q_.front();
13 q_.pop();
14 }
15 q_.emplace(val);
16 sum_ += val;
17 return 1.0 * sum_ / q_.size();
18 }
19
20 private:
21 int size_;
22 int sum_;
23 queue q_;
24 };
25
26 /**
27 * Your MovingAverage object will be instantiated and called as such:
28 * MovingAverage obj = new MovingAverage(size);
29 * double param_1 = obj.next(val);
30 */
31
*******************************

99. Moving Average from Data Stream(Python)


*******************************

1 # Time: O(1)
2 # Space: O(w)
3
4 from collections import deque
5
6 class MovingAverage(object):
7
8 def __init__(self, size):
9 """
10 Initialize your data structure here.
11 :type size: int
12 """
13 self.__size = size
14 self.__sum = 0
15 self.__q = deque()
16
17 def next(self, val):
18 """
19 :type val: int
20 :rtype: float
21 """
22 if len(self.__q) == self.__size:
23 self.__sum -= self.__q.popleft()
24 self.__sum += val
25 self.__q.append(val)
26 return 1.0 * self.__sum / len(self.__q)
27
28
29
**************************

100. Intersection of Two Arrays


**************************

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must beunique
and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]


Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]


Output: [9,4]
Explanation: [4,9] is also accepted.

Constraints:

1 <= nums1.length, nums2.length <= 1000


0 <= nums1[i], nums2[i] <= 1000
**************************

100. Intersection of Two Arrays(C++)


**************************

1 // Time: O(m + n)
2 // Space: O(min(m, n))
3
4 // Hash solution.
5 class Solution {
6 public:
7 vector intersection(vector& nums1, vector& nums2) {
8 if (nums1.size() > nums2.size()) {
9 return intersection(nums2, nums1);
10 }
11
12 unordered_set lookup{nums1.cbegin(), nums1.cend()};
13
14 vector result;
15 for (const auto& i : nums2) {
16 if (lookup.count(i)) {
17 result.emplace_back(i);
18 lookup.erase(i);
19 }
20 }
21
22 return result;
23 }
24 };
25
26
27 // Time: O(max(m, n) * log(max(m, n)))
28 // Space: O(1)
29 // Binary search solution.
30 class Solution2 {
31 public:
32 vector intersection(vector& nums1, vector& nums2) {
33 if (nums1.size() > nums2.size()) {
34 return intersection(nums2, nums1);
35 }
36
37 sort(nums1.begin(), nums1.end());
38 sort(nums2.begin(), nums2.end());
39
40 vector result;
41 auto it = nums2.cbegin();
42 for (const auto& i : nums1) {
43 it = lower_bound(it, nums2.cend(), i);
44 if (it != nums2.end() && *it == i) {
45 result.emplace_back(*it);
46 it = upper_bound(it, nums2.cend(), i);
47 }
48 }
49
50 return result;
51 }
52 };
53
54
55 // Time: O(max(m, n) * log(max(m, n)))
56 // Space: O(1)
57 // Two pointers solution.
58 class Solution3 {
59 public:
60 vector intersection(vector& nums1, vector& nums2) {
61 vector result;
62 sort(nums1.begin(), nums1.end());
63 sort(nums2.begin(), nums2.end());
64 auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
65 while (it1 != nums1.cend() && it2 != nums2.cend()) {
66 if (*it1 < *it2) {
67 ++it1;
68 } else if (*it1 > *it2) {
69 ++it2;
70 } else {
71 if (result.empty() || result.back() != *it1) {
72 result.emplace_back(*it1);
73 }
74 ++it1, ++it2;
75 }
76 }
77 return result;
78 }
79 };
80
81 // Time: O(mlogm + nlogn)
82 // Space: O(m + n)
83 class Solution4 {
84 public:
85 vector intersection(vector& nums1, vector& nums2) {
86 vector result;
87 sort(begin(nums1), end(nums1)); sort(begin(nums2), end(nums2));
88 set_intersection(cbegin(nums1), cend(nums1), cbegin(nums2), cend(nums2), back_inserter(result));
89 result.erase(unique(begin(result), end(result)), end(result));
90 return result;
91 }
92 };
**************************

100. Intersection of Two Arrays(Python)


**************************

1 # Time: O(m + n)
2 # Space: O(min(m, n))
3
4 class Solution(object):
5 def intersection(self, nums1, nums2):
6 """
7 :type nums1: List[int]
8 :type nums2: List[int]
9 :rtype: List[int]
10 """
11 if len(nums1) > len(nums2):
12 return self.intersection(nums2, nums1)
13
14 lookup = set()
15 for i in nums1:
16 lookup.add(i)
17
18 res = []
19 for i in nums2:
20 if i in lookup:
21 res += i,
22 lookup.discard(i)
23
24 return res
25
26 def intersection2(self, nums1, nums2):
27 """
28 :type nums1: List[int]
29 :type nums2: List[int]
30 :rtype: List[int]
31 """
32 return list(set(nums1) & set(nums2))
33
34
35 # Time: O(max(m, n) * log(max(m, n)))
36 # Space: O(1)
37 # Binary search solution.
38 class Solution2(object):
39 def intersection(self, nums1, nums2):
40 """
41 :type nums1: List[int]
42 :type nums2: List[int]
43 :rtype: List[int]
44 """
45 if len(nums1) > len(nums2):
46 return self.intersection(nums2, nums1)
47
48 def binary_search(compare, nums, left, right, target):
49 while left < right:
50 mid = left + (right - left) / 2
51 if compare(nums[mid], target):
52 right = mid
53 else:
54 left = mid + 1
55 return left
56
57 nums1.sort(), nums2.sort()
58
59 res = []
60 left = 0
61 for i in nums1:
62 left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i)
63 if left != len(nums2) and nums2[left] == i:
64 res += i,
65 left = binary_search(lambda x, y: x > y, nums2, left, len(nums2), i)
66
67 return res
68
69
70 # Time: O(max(m, n) * log(max(m, n)))
71 # Space: O(1)
72 # Two pointers solution.
73 class Solution3(object):
74 def intersection(self, nums1, nums2):
75 """
76 :type nums1: List[int]
77 :type nums2: List[int]
78 :rtype: List[int]
79 """
80 nums1.sort(), nums2.sort()
81 res = []
82
83 it1, it2 = 0, 0
84 while it1 < len(nums1) and it2 < len(nums2):
85 if nums1[it1] < nums2[it2]:
86 it1 += 1
87 elif nums1[it1] > nums2[it2]:
88 it2 += 1
89 else:
90 if not res or res[-1] != nums1[it1]:
91 res += nums1[it1],
92 it1 += 1
93 it2 += 1
94
95 return res
96
*****************************

101. Intersection of Two Arrays II


*****************************

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as
many times as it shows in both arrays and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]


Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]


Output: [4,9]
Explanation: [9,4] is also accepted.

Constraints:

1 <= nums1.length, nums2.length <= 1000


0 <= nums1[i], nums2[i] <= 1000

Follow up:

What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the
memory at once?
*****************************

101. Intersection of Two Arrays II(C++)


*****************************

1 // If the given array is not sorted and the memory is unlimited:


2 // - Time: O(m + n)
3 // - Space: O(min(m, n))
4 // elif the given array is already sorted:
5 // if m << n or m >> n:
6 // - Time: O(min(m, n) * log(max(m, n)))
7 // - Space: O(1)
8 // else:
9 // - Time: O(m + n)
10 // - Soace: O(1)
11 // else: (the given array is not sorted and the memory is limited)
12 // - Time: O(max(m, n) * log(max(m, n)))
13 // - Space: O(1)
14
15 // If the given array is not sorted and the memory is unlimited.
16 // Time: O(m + n)
17 // Space: O(min(m, n))
18 // Hash solution.
19 class Solution {
20 public:
21 vector intersect(vector& nums1, vector& nums2) {
22 if (nums1.size() > nums2.size()) {
23 return intersect(nums2, nums1);
24 }
25
26 unordered_map lookup;
27 for (const auto& i : nums1) {
28 ++lookup[i];
29 }
30
31 vector result;
32 for (const auto& i : nums2) {
33 if (lookup[i] > 0) {
34 result.emplace_back(i);
35 --lookup[i];
36 }
37 }
38
39 return result;
40 }
41 };
42
43
44 // If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
45 // Time: O(min(m, n) * log(max(m, n)))
46 // Space: O(1)
47 // Binary search solution.
48 class Solution {
49 public:
50 vector intersect(vector& nums1, vector& nums2) {
51 if (nums1.size() > nums2.size()) {
52 return intersect(nums2, nums1);
53 }
54
55 // Make sure it is sorted, doesn't count in time.
56 sort(nums1.begin(), nums1.end());
57 sort(nums2.begin(), nums2.end());
58
59 vector result;
60 auto it = nums2.cbegin();
61 for (const auto& i : nums1) {
62 it = lower_bound(it, nums2.cend(), i);
63 if (it != nums2.end() && *it == i) {
64 result.emplace_back(*it++);
65 }
66 }
67
68 return result;
69 }
70 };
71
72
73 // If the given array is already sorted, and the memory is limited or m ~ n.
74 // Time: O(m + n)
75 // Soace: O(1)
76 // Two pointers solution.
77 class Solution {
78 public:
79 vector intersect(vector& nums1, vector& nums2) {
80 vector result;
81 // Make sure it is sorted, doesn't count in time.
82 sort(nums1.begin(), nums1.end());
83 sort(nums2.begin(), nums2.end());
84 auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
85 while (it1 != nums1.cend() && it2 != nums2.cend()) {
86 if (*it1 < *it2) {
87 ++it1;
88 } else if (*it1 > *it2) {
89 ++it2;
90 } else {
91 result.emplace_back(*it1);
92 ++it1, ++it2;
93 }
94 }
95 return result;
96 }
97 };
98
99
100 // If the given array is not sorted, and the memory is limited.
101 // Time: O(max(m, n) * log(max(m, n)))
102 // Space: O(1)
103 // Two pointers solution.
104 class Solution {
105 public:
106 vector intersect(vector& nums1, vector& nums2) {
107 vector result;
108 // O(max(m, n) * log(max(m, n)))
109 sort(nums1.begin(), nums1.end());
110 sort(nums2.begin(), nums2.end());
111 auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
112 while (it1 != nums1.cend() && it2 != nums2.cend()) {
113 if (*it1 < *it2) {
114 ++it1;
115 } else if (*it1 > *it2) {
116 ++it2;
117 } else {
118 result.emplace_back(*it1);
119 ++it1, ++it2;
120 }
121 }
122 return result;
123 }
124 };
125
126 // Time: O(mlogm + nlogn)
127 // Space: O(m + n)
128 // simple solution
129 class Solution2 {
130 public:
131 vector intersect(vector& nums1, vector& nums2) {
132 vector result;
133 sort(begin(nums1), end(nums1)); sort(begin(nums2), end(nums2));
134 set_intersection(cbegin(nums1), cend(nums1), cbegin(nums2), cend(nums2), back_inserter(result));
135 return result;
135 return result;
136 }
137 };
*****************************

101. Intersection of Two Arrays II(Python)


*****************************

1 # If the given array is not sorted and the memory is unlimited:


2 # - Time: O(m + n)
3 # - Space: O(min(m, n))
4 # elif the given array is already sorted:
5 # if m << n or m >> n:
6 # - Time: O(min(m, n) * log(max(m, n)))
7 # - Space: O(1)
8 # else:
9 # - Time: O(m + n)
10 # - Soace: O(1)
11 # else: (the given array is not sorted and the memory is limited)
12 # - Time: O(max(m, n) * log(max(m, n)))
13 # - Space: O(1)
14
15 import collections
16
17
18 class Solution(object):
19 def intersect(self, nums1, nums2):
20 """
21 :type nums1: List[int]
22 :type nums2: List[int]
23 :rtype: List[int]
24 """
25 if len(nums1) > len(nums2):
26 return self.intersect(nums2, nums1)
27
28 lookup = collections.defaultdict(int)
29 for i in nums1:
30 lookup[i] += 1
31
32 res = []
33 for i in nums2:
34 if lookup[i] > 0:
35 res += i,
36 lookup[i] -= 1
37
38 return res
39
40 def intersect2(self, nums1, nums2):
41 """
42 :type nums1: List[int]
43 :type nums2: List[int]
44 :rtype: List[int]
45 """
46 c = collections.Counter(nums1) & collections.Counter(nums2)
47 intersect = []
48 for i in c:
49 intersect.extend([i] * c[i])
50 return intersect
51
52
53 # If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
54 # Time: O(min(m, n) * log(max(m, n)))
55 # Space: O(1)
56 # Binary search solution.
57 class Solution(object):
58 def intersect(self, nums1, nums2):
59 """
60 :type nums1: List[int]
61 :type nums2: List[int]
62 :rtype: List[int]
63 """
64 if len(nums1) > len(nums2):
65 return self.intersect(nums2, nums1)
66
67 def binary_search(compare, nums, left, right, target):
68 while left < right:
69 mid = left + (right - left) / 2
70 if compare(nums[mid], target):
71 right = mid
72 else:
73 left = mid + 1
74 return left
75
76 nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
77
78 res = []
79 left = 0
80 for i in nums1:
81 left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i)
82 if left != len(nums2) and nums2[left] == i:
83 res += i,
84 left += 1
85
86 return res
87
88
89 # If the given array is already sorted, and the memory is limited or m ~ n.
90 # Time: O(m + n)
91 # Space: O(1)
92 # Two pointers solution.
93 class Solution(object):
94 def intersect(self, nums1, nums2):
95 """
96 :type nums1: List[int]
97 :type nums2: List[int]
98 :rtype: List[int]
99 """
100 nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
101
102 res = []
103
104 it1, it2 = 0, 0
105 while it1 < len(nums1) and it2 < len(nums2):
106 if nums1[it1] < nums2[it2]:
107 it1 += 1
108 elif nums1[it1] > nums2[it2]:
109 it2 += 1
110 else:
111 res += nums1[it1],
112 it1 += 1
113 it2 += 1
114
115 return res
116
117
118 # If the given array is not sorted, and the memory is limited.
119 # Time: O(max(m, n) * log(max(m, n)))
120 # Space: O(1)
121 # Two pointers solution.
122 class Solution(object):
123 def intersect(self, nums1, nums2):
124 """
125 :type nums1: List[int]
126 :type nums2: List[int]
127 :rtype: List[int]
128 """
129 nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n)))
130
131 res = []
132
133 it1, it2 = 0, 0
134 while it1 < len(nums1) and it2 < len(nums2):
135 if nums1[it1] < nums2[it2]:
135 if nums1[it1] < nums2[it2]:
136 it1 += 1
137 elif nums1[it1] > nums2[it2]:
138 it2 += 1
139 else:
140 res += nums1[it1],
141 it1 += 1
142 it2 += 1
143
144 return res
145
*******************

102. Logger Rate Limiter


*******************

Design a logger system that receives a stream of messages along with their timestamps. Eachunique message should only
be printed at most every 10 seconds (i.e. a message printed at timestamp t will prevent other identical messages from
being printed until timestamp t + 10 ).

All messages will come in chronological order. Several messages may arrive at the same timestamp.

Implement the Logger class:

Logger() Initializes the logger object.


bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given timestamp,
otherwise returns false.

Example 1:

Input
["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"
[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
Output
[null, true, true, false, false, false, true]

Explanation
Logger logger = new Logger();
logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11
logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12
logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false
logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false
logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false
logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is
// 11 + 10 = 21

Constraints:

0 <= timestamp <= 10 9


Every timestamp will be passed in non-decreasing order (chronological order).
1 <= message.length <= 30
At most 104 calls will be made to shouldPrintMessage.
*******************

102. Logger Rate Limiter(C++)


*******************

1 // Time: O(1), amortized


2 // Space: O(k), k is the max number of printed messages in last 10 seconds
3
4 class Logger {
5 public:
6 /** Initialize your data structure here. */
7 Logger() {
8
9 }
10
11 /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granu
12 bool shouldPrintMessage(int timestamp, string message) {
13 while (!dq_.empty() && dq_.front().first <= timestamp - 10) {
14 printed_.erase(dq_.front().second);
15 dq_.pop_front();
16 }
17 if (printed_.count(message)) {
18 return false;
19 }
20 dq_.emplace_back(timestamp, message);
21 printed_.emplace(message);
22 return true;
23 }
24
25 private:
26 deque> dq_;
27 unordered_set printed_;
28 };
29
30 // Time: O(1)
31 // Space: O(n), n is the number of total unique messages
32 class Logger2 {
33 public:
34 /** Initialize your data structure here. */
35 Logger2() {
36
37 }
38
39 /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granu
40 bool shouldPrintMessage(int timestamp, string message) {
41 if (message_time_.count(message) &&
42 timestamp < message_time_[message] + 10) {
43 return false;
44 }
45 message_time_[message] = timestamp;
46 return true;
47 }
48
49 private:
50 unordered_map message_time_;
51 };
52
53 /**
54 * Your Logger object will be instantiated and called as such:
55 * Logger obj = new Logger();
56 * bool param_1 = obj.shouldPrintMessage(timestamp,message);
57 */
*******************

102. Logger Rate Limiter(Python)


*******************

1 # Time: O(1), amortized


2 # Space: O(k), k is the max number of printed messages in last 10 seconds
3
4 import collections
5
6
7 class Logger(object):
8
9 def __init__(self):
10 """
11 Initialize your data structure here.
12 """
13 self.__dq = collections.deque()
14 self.__printed = set()
15
16 def shouldPrintMessage(self, timestamp, message):
17 """
18 Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granu
19 :type timestamp: int
20 :type message: str
21 :rtype: bool
22 """
23 while self.__dq and self.__dq[0][0] <= timestamp - 10:
24 self.__printed.remove(self.__dq.popleft()[1])
25 if message in self.__printed:
26 return False
27 self.__dq.append((timestamp, message))
28 self.__printed.add(message)
29 return True
30
31
*******************

103. Sum of Two Integers


*******************

Given two integers a and b, return the sum of the two integers without using the operators+ and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = 2, b = 3
Output: 5

Constraints:

-1000 <= a, b <= 1000


*******************

103. Sum of Two Integers(C++)


*******************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int getSum(int a, int b) {
7 while (b) {
8 int carry = a & b;
9 a ^= b;
10 b = carry << 1;
11 }
12 return a;
13 }
14 };
*******************

103. Sum of Two Integers(Python)


*******************
1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def getSum(self, a, b):
6 """
7 :type a: int
8 :type b: int
9 :rtype: int
10 """
11 bit_length = 32
12 neg_bit, mask = (1 << bit_length) >> 1, ~(~0 << bit_length)
13
14 a = (a | ~mask) if (a & neg_bit) else (a & mask)
15 b = (b | ~mask) if (b & neg_bit) else (b & mask)
16
17 while b:
18 carry = a & b
19 a ^= b
20 a = (a | ~mask) if (a & neg_bit) else (a & mask)
21 b = carry << 1
22 b = (b | ~mask) if (b & neg_bit) else (b & mask)
23
24 return a
25
26 def getSum2(self, a, b):
27 """
28 :type a: int
29 :type b: int
30 :rtype: int
31 """
32 # 32 bits integer max
33 MAX = 0x7FFFFFFF
34 # 32 bits interger min
35 MIN = 0x80000000
36 # mask to get last 32 bits
37 mask = 0xFFFFFFFF
38 while b:
39 # ^ get different bits and & gets double 1s, << moves carry
40 a, b = (a ^ b) & mask, ((a & b) << 1) & mask
41 # if a is negative, get a's 32 bits complement positive first
42 # then get 32-bit positive's Python complement negative
43 return a if a <= MAX else ~(a ^ mask)
44
45 def minus(self, a, b):
46 b = self.getSum(~b, 1)
47 return self.getSum(a, b)
48
49 def multiply(self, a, b):
50 isNeg = (a > 0) ^ (b > 0)
51 x = a if a > 0 else self.getSum(~a, 1)
52 y = b if b > 0 else self.getSum(~b, 1)
53 ans = 0
54 while y & 0x01:
55 ans = self.getSum(ans, x)
56 y >>= 1
57 x <<= 1
58 return self.getSum(~ans, 1) if isNeg else ans
59
60 def divide(self, a, b):
61 isNeg = (a > 0) ^ (b > 0)
62 x = a if a > 0 else self.getSum(~a, 1)
63 y = b if b > 0 else self.getSum(~b, 1)
64 ans = 0
65 for i in range(31, -1, -1):
66 if (x >> i) >= y:
67 x = self.minus(x, y << i)
68 ans = self.getSum(ans, 1 << i)
69 return self.getSum(~ans, 1) if isNeg else ans
70
71
****************************

104. Guess Number Higher or Lower


****************************

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num) , which returns 3 possible results:

-1: The number I picked is lower than your guess (i.e.pick < num ).
1: The number I picked is higher than your guess (i.e.pick > num ).
0: The number I picked is equal to your guess (i.e.pick == num).

Return the number that I picked.

Example 1:

Input: n = 10, pick = 6


Output: 6

Example 2:

Input: n = 1, pick = 1
Output: 1

Example 3:

Input: n = 2, pick = 1
Output: 1

Example 4:

Input: n = 2, pick = 2
Output: 2

Constraints:

1 <= n <= 2 31 - 1
1 <= pick <= n
****************************

104. Guess Number Higher or Lower(C++)


****************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 // Forward declaration of guess API.
5 // @param num, your guess
6 // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
7 int guess(int num);
8
9 class Solution {
10 public:
11 int guessNumber(int n) {
12 int left = 1, right = n;
13 while (left <= right) {
14 const auto mid = left + (right - left) / 2;
15 if (guess(mid) <= 0) {
16 right = mid - 1;
17 } else {
18 left = mid + 1;
19 }
20 }
21 return left;
22 }
23 };
****************************

104. Guess Number Higher or Lower(Python)


****************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def guessNumber(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 left, right = 1, n
11 while left <= right:
12 mid = left + (right - left) / 2
13 if guess(mid) <= 0: # noqa
14 right = mid - 1
15 else:
16 left = mid + 1
17 return left
18
***********

105. Ransom Note


***********

Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Example 1:

Input: ransomNote = "a", magazine = "b"


Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"


Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"


Output: true

Constraints:

1 <= ransomNote.length, magazine.length <= 10 5


ransomNote and magazine consist of lowercase English letters.
***********

105. Ransom Note(C++)


***********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool canConstruct(string ransomNote, string magazine) {
7 vector counts(26);
8 int letters = 0;
9 for (const auto& c : ransomNote) {
10 if (counts[c - 'a']++ == 0) {
11 ++letters;
12 }
13 }
14 for (const auto& c : magazine) {
15 if (--counts[c - 'a'] == 0 && --letters == 0) {
16 // Break as soon as possible if letters have been enough.
17 break;
18 }
19 }
20 return letters == 0;
21 }
22 };
***********

105. Ransom Note(Python)


***********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def canConstruct(self, ransomNote, magazine):
6 """
7 :type ransomNote: str
8 :type magazine: str
9 :rtype: bool
10 """
11 counts = [0] * 26
12 letters = 0
13
14 for c in ransomNote:
15 if counts[ord(c) - ord('a')] == 0:
16 letters += 1
17 counts[ord(c) - ord('a')] += 1
18
19 for c in magazine:
20 counts[ord(c) - ord('a')] -= 1
21 if counts[ord(c) - ord('a')] == 0:
22 letters -= 1
23 if letters == 0:
24 break
25
26 return letters == 0
27
28 # Time: O(n)
29 # Space: O(1)
30 import collections
31
32 class Solution2(object):
33 def canConstruct(self, ransomNote, magazine):
34 """
35 :type ransomNote: str
36 :type magazine: str
37 :rtype: bool
38 """
39 return not collections.Counter(ransomNote) - collections.Counter(magazine)
40
**********************************

106. First Unique Character in a String


**********************************

Given a string s , find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

Constraints:

1 <= s.length <= 105


s consists of only lowercase English letters.
**********************************

106. First Unique Character in a String(C++)


**********************************

1 // Time: O(n)
2 // Space: O(n)
3
4 // One-pass solution.
5 class Solution {
6 public:
7 int firstUniqChar(string s) {
8 using IT = list::iterator;
9
10 list candidates;
11 unordered_map lookup;
12 for (int i = 0; i < s.length(); ++i) {
13 const auto c = s[i];
14 if (lookup.count(c)) {
15 if (lookup[c] != candidates.end()) {
16 candidates.erase(lookup[c]);
17 }
18 lookup[c] = candidates.end();
19 } else {
20 lookup[c] = candidates.emplace(candidates.end(), i);
21 }
22 }
23 return candidates.empty() ? -1 : candidates.front();
24 }
25 };
**********************************

106. First Unique Character in a String(Python)


**********************************

1 # Time: O(n)
2 # Space: O(n)
3
4 from collections import defaultdict
5
6 class Solution(object):
7 def firstUniqChar(self, s):
8 """
9 :type s: str
10 :rtype: int
11 """
12 lookup = defaultdict(int)
13 candidtates = set()
14 for i, c in enumerate(s):
15 if lookup[c]:
16 candidtates.discard(lookup[c])
17 else:
18 lookup[c] = i+1
19 candidtates.add(i+1)
20
21 return min(candidtates)-1 if candidtates else -1
22
*******************

107. Find the Difference


*******************

You are given two strings s and t.

String t is generated by random shuffling string s and then add one more letter at a random position.

Return the letter that was added to t.

Example 1:

Input: s = "abcd", t = "abcde"


Output: "e"
Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y"


Output: "y"

Example 3:

Input: s = "a", t = "aa"


Output: "a"

Example 4:

Input: s = "ae", t = "aea"


Output: "a"

Constraints:

0 <= s.length <= 1000


t.length == s.length + 1
s and t consist of lower-case English letters.
*******************

107. Find the Difference(C++)


*******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 char findTheDifference(string s, string t) {
7 return accumulate(s.cbegin(), s.cend(), 0, std::bit_xor()) ^
8 accumulate(t.cbegin(), t.cend(), 0, std::bit_xor());
9 }
10 };
*******************

107. Find the Difference(Python)


*******************

1 # Time: O(n)
2 # Space: O(1)
3
4 import operator
5 import collections
6 from functools import reduce
7
8
9 class Solution(object):
10 def findTheDifference(self, s, t):
11 """
12 :type s: str
13 :type t: str
14 :rtype: str
15 """
16 return chr(reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0))
17
18 def findTheDifference2(self, s, t):
19 """
20 :type s: str
21 :type t: str
22 :rtype: str
23 """
24 t = list(t)
25 s = list(s)
26 for i in s:
27 t.remove(i)
28 return t[0]
29
30 def findTheDifference3(self, s, t):
31 return chr(reduce(operator.xor, map(ord, s + t)))
32
33 def findTheDifference4(self, s, t):
34 return list((collections.Counter(t) - collections.Counter(s)))[0]
35
36 def findTheDifference5(self, s, t):
37 s, t = sorted(s), sorted(t)
38 return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0]
39
40
***************

108. Rotate Function


***************

You are given an integer array nums of length n.

Assume arrk to be an array obtained by rotatingnums by k positions clock-wise. We define the rotation function F on nums as
follow:

F(k) = 0 * arr k[0] + 1 * arr k[1] + ... + (n - 1) * arr k[n - 1].

Return the maximum value of F(0), F(1), ..., F(n-1) .

The test cases are generated so that the answer fits in a32-bit integer.

Example 1:

Input: nums = [4,3,2,6]


Output: 26
Explanation:
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

Example 2:

Input: nums = [100]


Output: 0

Constraints:

n == nums.length
1 <= n <= 10 5
-100 <= nums[i] <= 100
***************

108. Rotate Function(C++)


***************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxRotateFunction(vector& A) {
7 int sum = accumulate(A.begin(), A.end(), 0);
8 int fi = 0;
9 for (int i = 0; i < A.size(); ++i) {
10 fi += i * A[i];
11 }
12
13 int result = fi;
14 for (int i = 1; i <= A.size(); ++i) {
15 fi += sum - A.size() * A[A.size() - i];
16 result = max(result, fi);
17 }
18 return result;
19 }
20 };
***************

108. Rotate Function(Python)


***************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxRotateFunction(self, A):
6 """
7 :type A: List[int]
8 :rtype: int
9 """
10 s = sum(A)
11 fi = 0
12 for i in xrange(len(A)):
13 fi += i * A[i]
14
15 result = fi
16 for i in xrange(1, len(A)+1):
17 fi += s - len(A) * A[-i]
18 result = max(result, fi)
19 return result
20
*********

109. Nth Digit


*********

Given an integer n, return the nth digit of the infinite integer sequence[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] .

Example 1:

Input: n = 3
Output: 3

Example 2:

Input: n = 11
Output: 0
Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

Constraints:

1 <= n <= 2 31 - 1
*********

109. Nth Digit(C++)


*********

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findNthDigit(int n) {
7 int digit_len = 1;
8 while (n > digit_len * 9 * pow(10, digit_len - 1)) {
9 n -= digit_len * 9 * pow(10, digit_len - 1);
10 ++digit_len;
11 }
12
13 const int num = pow(10, digit_len - 1) + (n - 1) / digit_len;
14
15 int nth_digit = num / pow(10, (digit_len - 1) - (n - 1) % digit_len);
16 nth_digit %= 10;
17
18 return nth_digit;
19 }
20 };
*********

109. Nth Digit(Python)


*********

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def findNthDigit(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 digit_len = 1
11 while n > digit_len * 9 * (10 ** (digit_len-1)):
12 n -= digit_len * 9 * (10 ** (digit_len-1))
13 digit_len += 1
14
15 num = 10 ** (digit_len-1) + (n-1)/digit_len
16
17 nth_digit = num / (10 ** ((digit_len-1) - ((n-1)%digit_len)))
18 nth_digit %= 10
19
20 return nth_digit
21
************

110. Binary Watch


************

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the
minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

For example, the below binary watch reads "4:51".

Given an integer turnedOn which represents the number of LEDs that are currently on, returnall possible times the watch
could represent. You may return the answer inany order.

The hour must not contain a leading zero.

For example, "01:00" is not valid. It should be "1:00".

The minute must be consist of two digits and may contain a leading zero.

For example, "10:2" is not valid. It should be "10:02".

Example 1:

Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

Example 2:

Input: turnedOn = 9
Output: []

Constraints:
0 <= turnedOn <= 10
************

110. Binary Watch(C++)


************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector readBinaryWatch(int num) {
7 vector result;
8 for (int h = 0; h < 12; ++h) {
9 for (int m = 0; m < 60; ++m) {
10 if (bit_count(h) + bit_count(m) == num) {
11 const auto hour = to_string(h);
12 const auto minute = m < 10 ? "0" + to_string(m) : to_string(m);
13 result.emplace_back(hour + ":" + minute);
14 }
15 }
16 }
17 return result;
18 }
19
20 private:
21 int bit_count(int bits) {
22 int count = 0;
23 for (; bits; bits &= bits - 1) {
24 ++count;
25 }
26 return count;
27 }
28 };
************

110. Binary Watch(Python)


************

1 # Time: O(1)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def readBinaryWatch(self, num):
7 """
8 :type num: int
9 :rtype: List[str]
10 """
11 def bit_count(bits):
12 count = 0
13 while bits:
14 bits &= bits-1
15 count += 1
16 return count
17
18 return ['%d:%02d' % (h, m) for h in xrange(12) for m in xrange(60)
19 if bit_count(h) + bit_count(m) == num]
20
21 def readBinaryWatch2(self, num):
22 """
23 :type num: int
24 :rtype: List[str]
25 """
26 return ['{0}:{1}'.format(str(h), str(m).zfill(2))
27 for h in range(12) for m in range(60)
28 if (bin(h) + bin(m)).count('1') == num]
29
******************

111. Sum of Left Leaves


******************

Given the root of a binary tree, return the sum of all left leaves.

Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

Example 2:

Input: root = [1]


Output: 0

Constraints:

The number of nodes in the tree is in the range[1, 1000].


-1000 <= Node.val <= 1000
******************

111. Sum of Left Leaves(C++)


******************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int sumOfLeftLeaves(TreeNode* root) {
16 return sumOfLeftLeavesHelper(root, false);
17 }
18
19 private:
20 int sumOfLeftLeavesHelper(TreeNode* root, bool is_left) {
21 if (!root) {
22 return 0;
23 }
24 if (!root->left && !root->right) {
25 return is_left ? root->val : 0;
26 }
27 return sumOfLeftLeavesHelper(root->left, true) +
28 sumOfLeftLeavesHelper(root->right, false);
29 }
30 };
******************

111. Sum of Left Leaves(Python)


******************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def sumOfLeftLeaves(self, root):
6 """
7 :type root: TreeNode
8 :rtype: int
9 """
10 def sumOfLeftLeavesHelper(root, is_left):
11 if not root:
12 return 0
13 if not root.left and not root.right:
14 return root.val if is_left else 0
15 return sumOfLeftLeavesHelper(root.left, True) + \
16 sumOfLeftLeavesHelper(root.right, False)
17
18 return sumOfLeftLeavesHelper(root, False)
19
*******************************

112. Convert a Number to Hexadecimal


*******************************

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement
method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer
except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

Example 1:

Input: num = 26
Output: "1a"

Example 2:

Input: num = -1
Output: "ffffffff"

Constraints:

-231 <= num <= 2 31 - 1


*******************************

112. Convert a Number to Hexadecimal(C++)


*******************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string toHex(int num) {
7 if (!num) {
8 return "0";
9 }
10
11 string result;
12 while (num && result.length() != sizeof(int) * 2) {
13 int hex = num & 15;
14 if (hex < 10) {
15 result.push_back('0' + hex);
16 } else {
17 result.push_back('a' + hex - 10);
18 }
19 num >>= 4;
20 }
21 reverse(result.begin(), result.end());
22
23 return result;
24 }
25 };
*******************************

112. Convert a Number to Hexadecimal(Python)


*******************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def toHex(self, num):
6 """
7 :type num: int
8 :rtype: str
9 """
10 if not num:
11 return "0"
12
13 result = []
14 while num and len(result) != 8:
15 h = num & 15
16 if h < 10:
17 result.append(str(chr(ord('0') + h)))
18 else:
19 result.append(str(chr(ord('a') + h-10)))
20 num >>= 4
21 result.reverse()
22
23 return "".join(result)
24
***********************

113. Valid Word Abbreviation


***********************

A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string
such as "substitution" could be abbreviated as (but not limited to):

"s10n" ("s ubstitutio n" )


"sub4u4" ("sub stit u tion" )
"12" ("substitution" )
"su3i1u2on" ("su bst i t u ti on")
"substitution" (no substrings replaced)

Note that "s55n" ("s ubsti tutio n" ) is not a valid abbreviation of "substitution" because the replaced substrings are adjacent.

Given a string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

Example 1:

Input: word = "internationalization", abbr = "i12iz4n"


Output: true

Example 2:

Input: word = "apple", abbr = "a2e"


Output: false

Constraints:

1 <= word.length <= 20


word consists of only lowercase English letters.
1 <= abrr.length <= 10
abbr consists of lowercase English letters and digits.
All the integers in abrr will fit in a 32-bit integer.
***********************

113. Valid Word Abbreviation(C++)


***********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool validWordAbbreviation(string word, string abbr) {
7 int i = 0, digit = 0;
8 for (const auto& c : abbr) {
9 if (isdigit(c)) {
10 if (digit == 0 && c == '0') {
11 return false;
12 }
13 digit *= 10;
14 digit += c - '0';
15 } else {
16 if (digit) {
17 i += digit;
18 digit = 0;
19 }
20 if (i >= word.length() || word[i++] != c) {
21 return false;
22 }
23 }
24 }
25 if (digit) {
26 i += digit;
27 }
28 return i == word.length();
29 }
30 };
***********************

113. Valid Word Abbreviation(Python)


***********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def validWordAbbreviation(self, word, abbr):
6 """
7 :type word: str
8 :type abbr: str
9 :rtype: bool
10 """
11 i , digit = 0, 0
12 for c in abbr:
13 if c.isdigit():
14 if digit == 0 and c == '0':
15 return False
16 digit *= 10
17 digit += int(c)
18 else:
19 if digit:
20 i += digit
21 digit = 0
22 if i >= len(word) or word[i] != c:
23 return False
24 i += 1
25 if digit:
26 i += digit
27
28 return i == len(word)
29
******************

114. Longest Palindrome


******************

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be
built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1

Example 3:

Input: s = "bb"
Output: 2

Constraints:

1 <= s.length <= 2000


s consists of lowercase and/or uppercase English letters only.
******************

114. Longest Palindrome(C++)


******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int longestPalindrome(string s) {
7 int odds = 0;
8 for (auto c = 'A'; c <= 'z'; ++c) {
9 odds += count(s.cbegin(), s.cend(), c) & 1;
10 }
11 return s.length() - odds + (odds > 0);
12 }
13 };
******************

114. Longest Palindrome(Python)


******************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def longestPalindrome(self, s):
9 """
10 :type s: str
11 :rtype: int
12 """
13 odds = 0
14 for k, v in collections.Counter(s).iteritems():
15 odds += v & 1
16 return len(s) - odds + int(odds > 0)
17
18 def longestPalindrome2(self, s):
19 """
20 :type s: str
21 :rtype: int
22 """
23 odd = sum(map(lambda x: x & 1, collections.Counter(s).values()))
24 return len(s) - odd + int(odd > 0)
25
*********

115. Fizz Buzz


*********

Given an integer n, return a string array answer (1-indexed) where:

answer[i] == "FizzBuzz" if i is divisible by 3 and 5.


answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i if non of the above conditions are true.

Example 1:

Input: n = 3
Output: ["1","2","Fizz"]

Example 2:

Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 3:

Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

Constraints:

1 <= n <= 10 4
*********

115. Fizz Buzz(C++)


*********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector fizzBuzz(int n) {
7 vector result;
8
9 for (int i = 1; i <= n; ++i) {
10 if (i % 15 == 0) {
11 result.emplace_back("FizzBuzz");
12 } else if (i % 5 == 0) {
13 result.emplace_back("Buzz");
14 } else if (i % 3 == 0) {
15 result.emplace_back("Fizz");
16 } else {
17 result.emplace_back(to_string(i));
18 }
19 }
20
21 return result;
22 }
23 };
*********

115. Fizz Buzz(Python)


*********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def fizzBuzz(self, n):
6 """
7 :type n: int
8 :rtype: List[str]
9 """
10 result = []
11
12 for i in xrange(1, n+1):
13 if i % 15 == 0:
14 result.append("FizzBuzz")
15 elif i % 5 == 0:
16 result.append("Buzz")
17 elif i % 3 == 0:
18 result.append("Fizz")
19 else:
20 result.append(str(i))
21
22 return result
23
24 def fizzBuzz2(self, n):
25 """
26 :type n: int
27 :rtype: List[str]
28 """
29 l = [str(x) for x in range(n + 1)]
30 l3 = range(0, n + 1, 3)
31 l5 = range(0, n + 1, 5)
32 for i in l3:
33 l[i] = 'Fizz'
34 for i in l5:
35 if l[i] == 'Fizz':
36 l[i] += 'Buzz'
37 else:
38 l[i] = 'Buzz'
39 return l[1:]
40
41 def fizzBuzz3(self, n):
42 return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)]
43
44 def fizzBuzz4(self, n):
45 return ['FizzBuzz'[i % -3 & -4:i % -5 & 8 ^ 12] or repr(i) for i in range(1, n + 1)]
46
********************

116. Third Maximum Number


********************

Given integer array nums, return the third maximum number in this array. If the third maximum does not exist, return the
maximum number.

Example 1:

Input: nums = [3,2,1]


Output: 1
Explanation: The third maximum is 1.

Example 2:

Input: nums = [1,2]


Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: nums = [2,2,3,1]


Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

Constraints:

1 <= nums.length <= 10 4


-231 <= nums[i] <= 2 31 - 1

Follow up: Can you find an O(n) solution?


********************

116. Third Maximum Number(C++)


********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int thirdMax(vector& nums) {
7 int count = 0;
8 vector top(3, numeric_limits::min());
9
10 for (const auto& num : nums) {
11 if (num > top[0]) {
12 top[2] = top[1];
13 top[1] = top[0];
14 top[0] = num;
15 ++count;
16 } else if (num != top[0] && num > top[1]) {
17 top[2] = top[1];
18 top[1] = num;
19 ++count;
20 } else if (num != top[0] && num != top[1] && num >= top[2]) {
21 top[2] = num;
22 ++count;
23 }
24 }
25
26 if (count < 3) {
27 return top[0];
28 }
29 return top[2];
30 }
31 };
********************

116. Third Maximum Number(Python)


********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def thirdMax(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 count = 0
11 top = [float("-inf")] * 3
12 for num in nums:
13 if num > top[0]:
14 top[0], top[1], top[2] = num, top[0], top[1]
15 count += 1
16 elif num != top[0] and num > top[1]:
17 top[1], top[2] = num, top[1]
18 count += 1
19 elif num != top[0] and num != top[1] and num >= top[2]:
20 top[2] = num
21 count += 1
22
23 if count < 3:
24 return top[0]
25
26 return top[2]
27
***********

117. Add Strings


***********

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such asBigInteger). You must also
not convert the inputs to integers directly.

Example 1:

Input: num1 = "11", num2 = "123"


Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"


Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"


Output: "0"

Constraints:

1 <= num1.length, num2.length <= 10 4


num1 and num2 consist of only digits.
num1 and num2 don't have any leading zeros except for the zero itself.
***********

117. Add Strings(C++)


***********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string addStrings(string num1, string num2) {
7 string result;
8
9 for (int i = num1.size() - 1, j = num2.size() - 1, carry = 0;
10 i >= 0 || j >= 0 || carry;
11 carry /= 10) {
12
13 if (i >= 0) {
14 carry += num1[i--] - '0';
15 }
16 if (j >= 0) {
17 carry += num2[j--] - '0';
18 }
19 result += to_string(carry % 10);
20 }
21 reverse(result.begin(), result.end());
22
23 return result;
24 }
25 };
***********

117. Add Strings(Python)


***********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def addStrings(self, num1, num2):
6 """
7 :type num1: str
8 :type num2: str
9 :rtype: str
10 """
11 result = []
12 i, j, carry = len(num1) - 1, len(num2) - 1, 0
13
14 while i >= 0 or j >= 0 or carry:
15 if i >= 0:
16 carry += ord(num1[i]) - ord('0')
17 i -= 1
18 if j >= 0:
19 carry += ord(num2[j]) - ord('0')
20 j -= 1
21 result.append(str(carry % 10))
22 carry /= 10
23 result.reverse()
24
25 return "".join(result)
26
27 def addStrings2(self, num1, num2):
28 """
29 :type num1: str
30 :type num2: str
31 :rtype: str
32 """
33 length = max(len(num1), len(num2))
34 num1 = num1.zfill(length)[::-1]
35 num2 = num2.zfill(length)[::-1]
36 res, plus = '', 0
37 for index, num in enumerate(num1):
38 tmp = str(int(num) + int(num2[index]) + plus)
39 res += tmp[-1]
40 if int(tmp) > 9:
41 plus = 1
42 else:
43 plus = 0
44 if plus:
45 res += '1'
46 return res[::-1]
47
*****************

118. Valid Word Square


*****************

Given an array of strings words, return true if it forms a valid word square.

A sequence of strings forms a valid word square if the k th row and column read the same string, where 0 <= k < max(numRows,
numColumns).

Example 1:

Input: words = ["abcd","bnrt","crmy","dtye"]


Output: true
Explanation:
The 1st row and 1st column both read "abcd".
The 2nd row and 2nd column both read "bnrt".
The 3rd row and 3rd column both read "crmy".
The 4th row and 4th column both read "dtye".
Therefore, it is a valid word square.

Example 2:
Input: words = ["abcd","bnrt","crm","dt"]
Output: true
Explanation:
The 1st row and 1st column both read "abcd".
The 2nd row and 2nd column both read "bnrt".
The 3rd row and 3rd column both read "crm".
The 4th row and 4th column both read "dt".
Therefore, it is a valid word square.

Example 3:

Input: words = ["ball","area","read","lady"]


Output: false
Explanation:
The 3rd row reads "read" while the 3rd column reads "lead".
Therefore, it is NOT a valid word square.

Constraints:

1 <= words.length <= 500


1 <= words[i].length <= 500
words[i] consists of only lowercase English letters.
*****************

118. Valid Word Square(C++)


*****************

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool validWordSquare(vector& words) {
7 for (int i = 0; i < words.size(); ++i) {
8 for (int j = 0; j < words[i].size(); ++j) {
9 if (j >= words.size() || i >= words[j].size() ||
10 words[j][i] != words[i][j]) {
11 return false;
12 }
13 }
14 }
15 return true;
16 }
17 };
*****************

118. Valid Word Square(Python)


*****************

1 # Time: O(m * n)
2 # Space: O(1)
3
4 class Solution(object):
5 def validWordSquare(self, words):
6 """
7 :type words: List[str]
8 :rtype: bool
9 """
10 for i in xrange(len(words)):
11 for j in xrange(len(words[i])):
12 if j >= len(words) or i >= len(words[j]) or \
13 words[j][i] != words[i][j]:
14 return False
15 return True
16
******************************

119. Number of Segments in a String


******************************

You are given a string s , return the number of segments in the string.

A segment is defined to be a contiguous sequence ofnon-space characters.

Example 1:

Input: s = "Hello, my name is John"


Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

Example 3:

Input: s = "love live! mu'sic forever"


Output: 4

Example 4:

Input: s = ""
Output: 0

Constraints:

0 <= s.length <= 300


s consists of lower-case
and upper-case English letters, digits or one of the following characters"!@#$%^&*()_+-=',.:".
The only space character in s is ' '.
******************************

119. Number of Segments in a String(C++)


******************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countSegments(string s) {
7 int result = static_cast(!s.empty() && s.back() != ' ');
8 for (int i = 1; i < s.size(); ++i) {
9 if (s[i] == ' ' && s[i - 1] != ' ') {
10 ++result;
11 }
12 }
13 return result;
14 }
15 };
******************************

119. Number of Segments in a String(Python)


******************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countSegments(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result = int(len(s) and s[-1] != ' ')
11 for i in xrange(1, len(s)):
12 if s[i] == ' ' and s[i-1] != ' ':
13 result += 1
14 return result
15
16 def countSegments2(self, s):
17 """
18 :type s: str
19 :rtype: int
20 """
21 return len([i for i in s.strip().split(' ') if i])
22
************

120. Path Sum III


************

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the
path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes
to child nodes).

Example 1:

Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8


Output: 3
Explanation: The paths that sum to 8 are shown.

Example 2:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22


Output: 3

Constraints:

The number of nodes in the tree is in the range[0, 1000].


-109 <= Node.val <= 10 9
-1000 <= targetSum <= 1000
************

120. Path Sum III(C++)


************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int pathSum(TreeNode* root, int sum) {
16 unordered_map lookup;
17 lookup[0] = 1;
18 return pathSumHelper(root, 0, sum, &lookup);
19 }
20
21 private:
22 int pathSumHelper(TreeNode* root, int curr, int sum, unordered_map *lookup) {
23 if (!root) {
24 return 0;
25 }
26 curr += root->val;
27 int result = lookup->count(curr - sum) ? (*lookup)[curr - sum] : 0;
28 ++(*lookup)[curr];
29 result += pathSumHelper(root->left, curr, sum, lookup) + pathSumHelper(root->right, curr, sum, lookup);
30 --(*lookup)[curr];
31 if ((*lookup)[curr] == 0) {
32 lookup->erase(curr);
33 }
34 return result;
35 }
36 };
37
38
39 // Time: O(n^2)
40 // Space: O(h)
41 class Solution2 {
42 public:
43 int pathSum(TreeNode* root, int sum) {
44 if (!root) {
45 return 0;
46 }
47 return pathSumHelper(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
48 }
49
50 private:
51 int pathSumHelper(TreeNode* root, int prev, int sum) {
52 if (!root) {
53 return 0;
54 }
55 int curr = prev + root->val;
56 return (curr == sum) + pathSumHelper(root->left, curr, sum) + pathSumHelper(root->right, curr, sum);
57 }
58 };
************

120. Path Sum III(Python)


************

1 # Time: O(n)
2 # Space: O(h)
3
4 import collections
5
6
7 class Solution(object):
8 def pathSum(self, root, sum):
9 """
10 :type root: TreeNode
11 :type sum: int
12 :rtype: int
13 """
14 def pathSumHelper(root, curr, sum, lookup):
15 if root is None:
16 return 0
17 curr += root.val
18 result = lookup[curr-sum] if curr-sum in lookup else 0
19 lookup[curr] += 1
20 result += pathSumHelper(root.left, curr, sum, lookup) + \
21 pathSumHelper(root.right, curr, sum, lookup)
22 lookup[curr] -= 1
23 if lookup[curr] == 0:
24 del lookup[curr]
25 return result
26
27 lookup = collections.defaultdict(int)
28 lookup[0] = 1
29 return pathSumHelper(root, 0, sum, lookup)
30
31
32 # Time: O(n^2)
33 # Space: O(h)
34 class Solution2(object):
35 def pathSum(self, root, sum):
36 """
37 :type root: TreeNode
38 :type sum: int
39 :rtype: int
40 """
41 def pathSumHelper(root, prev, sum):
42 if root is None:
43 return 0
44
45 curr = prev + root.val
46 return int(curr == sum) + \
47 pathSumHelper(root.left, curr, sum) + \
48 pathSumHelper(root.right, curr, sum)
49
50 if root is None:
51 return 0
52
53 return pathSumHelper(root, 0, sum) + \
54 self.pathSum(root.left, sum) + \
55 self.pathSum(root.right, sum)
56
*****************************

121. Find All Anagrams in a String


*****************************

Given two strings s and p, return an array of all the start indices ofp's anagrams in s . You may return the answer inany
order.

Example 1:

Input: s = "cbaebabacd", p = "abc"


Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input: s = "abab", p = "ab"


Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

Constraints:

1 <= s.length, p.length <= 3 * 10 4


s and p consist of lowercase English letters.
*****************************

121. Find All Anagrams in a String(C++)


*****************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector findAnagrams(string s, string p) {
7 vector result;
8 if (p.empty() || s.empty()) {
9 return result;
10 }
11
12 vector cnts(26);
13 for (const auto& c : p) {
14 ++cnts[c - 'a'];
15 }
16
17 for (int left = 0, right = 0; right < s.length(); ++right) {
18 --cnts[s[right] - 'a'];
19 while (left <= right && cnts[s[right] - 'a'] < 0) {
20 ++cnts[s[left++] - 'a'];
21 }
22 if (right - left + 1 == p.length()) {
23 result.emplace_back(left);
24 }
25 }
26 return result;
27 }
28 };
*****************************

121. Find All Anagrams in a String(Python)


*****************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findAnagrams(self, s, p):
6 """
7 :type s: str
8 :type p: str
9 :rtype: List[int]
10 """
11 result = []
12
13 cnts = [0] * 26
14 for c in p:
15 cnts[ord(c) - ord('a')] += 1
16
17 left, right = 0, 0
18 while right < len(s):
19 cnts[ord(s[right]) - ord('a')] -= 1
20 while left <= right and cnts[ord(s[right]) - ord('a')] < 0:
21 cnts[ord(s[left]) - ord('a')] += 1
22 left += 1
23 if right - left + 1 == len(p):
24 result.append(left)
25 right += 1
26
27 return result
28
***************

122. Arranging Coins


***************

You have n coins and you want to build a staircase with these coins. The staircase consists ofk rows where the ith row has
exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

Example 1:

Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Example 2:

Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.

Constraints:

1 <= n <= 2 31 - 1
***************

122. Arranging Coins(C++)


***************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int arrangeCoins(int n) {
7 return static_cast((sqrt(8.0 * n + 1) - 1) / 2);
8 }
9 };
10
11 // Time: O(logn)
12 // Space: O(1)
13 class Solution2 {
14 public:
15 int arrangeCoins(int n) {
16 uint64_t left = 1, right = n;
17 while (left <= right) {
18 const auto mid = left + (right - left) / 2;
19 if (!check(mid, n)) {
20 right = mid - 1;
21 } else {
22 left = mid + 1;
23 }
24 }
25 return right;
26 }
27
28 private:
29 bool check(uint64_t mid, uint64_t n) {
30 return mid <= 2L * n / (mid + 1);
31 }
32 };
***************

122. Arranging Coins(Python)


***************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import math
5
6
7 class Solution(object):
8 def arrangeCoins(self, n):
9 """
10 :type n: int
11 :rtype: int
12 """
13 return int((math.sqrt(8*n+1)-1) / 2) # sqrt is O(logn) time.
14
15
16 # Time: O(logn)
17 # Space: O(1)
18 class Solution2(object):
19 def arrangeCoins(self, n):
20 """
21 :type n: int
22 :rtype: int
23 """
24 def check(mid, n):
25 return mid*(mid+1) <= 2*n
26
27 left, right = 1, n
28 while left <= right:
29 mid = left + (right-left)//2
30 if not check(mid, n):
31 right = mid-1
32 else:
33 left = mid+1
34 return right
******************

123. String Compression


******************

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s . For each group of consecutive repeating characters in chars:

If the group's length is 1, append the character to s .


Otherwise, append the character followed by the group's length.

The compressed string s should not be returned separately, but instead be stored in the input character array chars.
Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

You must write an algorithm that uses only constant extra space.

Example 1:

Input: chars = ["a","a","b","b","c","c","c"]


Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

Example 2:

Input: chars = ["a"]


Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since it's a single character.

Example 3:

Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]


Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".

Example 4:

Input: chars = ["a","a","a","b","b","a","a"]


Output: Return 6, and the first 6 characters of the input array should be: ["a","3","b","2","a","2"].
Explanation: The groups are "aaa", "bb", and "aa". This compresses to "a3b2a2". Note that each group is independent even if two groups have t

Constraints:

1 <= chars.length <= 2000


chars[i] is a lower-case English letter, upper-case English letter, digit, or symbol.
******************

123. String Compression(C++)


******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int compress(vector& chars) {
7 int write = 0, anchor = 0;
8 for (int read = 0; read < chars.size(); ++read) {
9 if (read + 1 == chars.size() || chars[read + 1] != chars[read]) {
10 chars[write++] = chars[read];
11 if (read - anchor > 0) {
12 auto n = read - anchor + 1, cnt = 0;
13 while (n > 0) {
14 chars[write++] = n % 10 + '0';
15 n /= 10;
16 ++cnt;
17 }
18 reverse(chars.begin() + write - cnt, chars.begin() + write);
19 }
20 anchor = read + 1;
21 }
22 }
23 return write;
24 }
25 };
******************

123. String Compression(Python)


******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def compress(self, chars):
6 """
7 :type chars: List[str]
8 :rtype: int
9 """
10 anchor, write = 0, 0
11 for read, c in enumerate(chars):
12 if read+1 == len(chars) or chars[read+1] != c:
13 chars[write] = chars[anchor]
14 write += 1
15 if read > anchor:
16 n, left = read-anchor+1, write
17 while n > 0:
18 chars[write] = chr(n%10+ord('0'))
19 write += 1
20 n /= 10
21 right = write-1
22 while left < right:
23 chars[left], chars[right] = chars[right], chars[left]
24 left += 1
25 right -= 1
26 anchor = read+1
27 return write
28
********************

124. Number of Boomerangs


********************

You are given n points in the plane that are all distinct, where points[i] = [x i, y i]. A boomerang is a tuple of points (i, j, k) such that
the distance between i and j equals the distance between i and k (the order of the tuple matters).

Return the number of boomerangs.

Example 1:

Input: points = [[0,0],[1,0],[2,0]]


Output: 2
Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].

Example 2:

Input: points = [[1,1],[2,2],[3,3]]


Output: 2

Example 3:

Input: points = [[1,1]]


Output: 0

Constraints:

n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= x i, y i <= 104
All the points are unique.
********************

124. Number of Boomerangs(C++)


********************

1 // Time: O(n^2)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int numberOfBoomerangs(vector>& points) {
7 int result = 0;
8
9 for (int i = 0; i < points.size(); ++i) {
10 unordered_map group;
11 for (int j = 0; j < points.size(); ++j) {
12 if (j == i) {
13 continue;
14 }
15 const auto dx = points[i].first - points[j].first;
16 const auto dy = points[i].second - points[j].second;
17 ++group[dx * dx + dy * dy];
18 }
19
20 for (const auto& p : group) {
21 if (p.second > 1) {
22 result += p.second * (p.second - 1);
23 }
24 }
25 }
26
27 return result;
28 }
29 };
********************

124. Number of Boomerangs(Python)


********************

1 # Time: O(n^2)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def numberOfBoomerangs(self, points):
9 """
10 :type points: List[List[int]]
11 :rtype: int
12 """
13 result = 0
14
15 for i in xrange(len(points)):
16 group = collections.defaultdict(int)
17 for j in xrange(len(points)):
18 if j == i:
19 continue
20 dx, dy = points[i][0] - points[j][0], points[i][1] - points[j][1]
21 group[dx**2 + dy**2] += 1
22
23 for _, v in group.iteritems():
24 if v > 1:
25 result += v * (v-1)
26
27 return result
28
29 def numberOfBoomerangs2(self, points):
30 """
31 :type points: List[List[int]]
32 :rtype: int
33 """
34 cnt = 0
35 for a, i in enumerate(points):
36 dis_list = []
37 for b, k in enumerate(points[:a] + points[a + 1:]):
38 dis_list.append((k[0] - i[0]) ** 2 + (k[1] - i[1]) ** 2)
39 for z in collections.Counter(dis_list).values():
40 if z > 1:
41 cnt += z * (z - 1)
42 return cnt
43
****************************************

125. Find All Numbers Disappeared in an Array


****************************************

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range[1, n] that do
not appear in nums.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]


Output: [5,6]

Example 2:

Input: nums = [1,1]


Output: [2]

Constraints:

n == nums.length
1 <= n <= 10 5
1 <= nums[i] <= n

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as
extra space.
****************************************

125. Find All Numbers Disappeared in an Array(C++)


****************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector findDisappearedNumbers(vector& nums) {
7 for (int i = 0; i < nums.size(); ++i) {
8 if (nums[abs(nums[i]) - 1] > 0) {
9 nums[abs(nums[i]) - 1] *= -1;
10 }
11 }
12
13 vector result;
14 for (int i = 0; i < nums.size(); ++i) {
15 if (nums[i] > 0) {
16 result.emplace_back(i + 1);
17 } else {
18 nums[i] *= -1;
19 }
20 }
21 return result;
22 }
23 };
****************************************

125. Find All Numbers Disappeared in an Array(Python)


****************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findDisappearedNumbers(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: List[int]
9 """
10 for i in xrange(len(nums)):
11 if nums[abs(nums[i]) - 1] > 0:
12 nums[abs(nums[i]) - 1] *= -1
13
14 result = []
15 for i in xrange(len(nums)):
16 if nums[i] > 0:
17 result.append(i+1)
18 else:
19 nums[i] *= -1
20 return result
21
22 def findDisappearedNumbers2(self, nums):
23 """
24 :type nums: List[int]
25 :rtype: List[int]
26 """
27 return list(set(range(1, len(nums) + 1)) - set(nums))
28
29 def findDisappearedNumbers3(self, nums):
30 for i in range(len(nums)):
31 index = abs(nums[i]) - 1
32 nums[index] = - abs(nums[index])
33
34 return [i + 1 for i in range(len(nums)) if nums[i] > 0]
35
36
*************************************

126. Minimum Moves to Equal Array Elements


*************************************

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment n - 1 elements of the array by 1.

Example 1:

Input: nums = [1,2,3]


Output: 3
Explanation: Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

Example 2:

Input: nums = [1,1,1]


Output: 0

Constraints:

n == nums.length
1 <= nums.length <= 10 5
-109 <= nums[i] <= 10 9
The answer is guaranteed to fit in a 32-bit integer.
*************************************

126. Minimum Moves to Equal Array Elements(C++)


*************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minMoves(vector& nums) {
7 return accumulate(nums.cbegin(), nums.cend(), 0) -
8 nums.size() * *min_element(nums.cbegin(), nums.cend());
9 }
10 };
*************************************

126. Minimum Moves to Equal Array Elements(Python)


*************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minMoves(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 return sum(nums) - len(nums) * min(nums)
11
**************

127. Assign Cookies


**************

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most
one cookie.

Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookiej
has a size s[j]. If s[j] >= g[i] , we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the
number of your content children and output the maximum number.

Example 1:

Input: g = [1,2,3], s = [1,1]


Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.

Example 2:

Input: g = [1,2], s = [1,2,3]


Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

Constraints:

1 <= g.length <= 3 * 10 4


0 <= s.length <= 3 * 10 4
1 <= g[i], s[j] <= 2 31 - 1
**************

127. Assign Cookies(C++)


**************

1 // Time: O(nlogn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findContentChildren(vector& g, vector& s) {
7 sort(g.begin(), g.end());
8 sort(s.begin(), s.end());
9
10 int result = 0;
11 for (int i = 0, j = 0; j < s.size(); ++j) {
12 if (i == g.size()) {
13 break;
14 }
15 if (s[j] >= g[i]) {
16 ++i;
17 ++result;
18 }
19 }
20 return result;
21 }
22 };
**************

127. Assign Cookies(Python)


**************

1 # Time: O(nlogn)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def findContentChildren(self, g, s):
7 """
8 :type g: List[int]
9 :type s: List[int]
10 :rtype: int
11 """
12 g.sort()
13 s.sort()
14
15 result, i = 0, 0
16 for j in xrange(len(s)):
17 if i == len(g):
18 break
19 if s[j] >= g[i]:
20 result += 1
21 i += 1
22 return result
23
*********

128. Poor Pigs


*********

There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous,
you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest
minutes to determine which bucket is poisonous.

You can feed the pigs according to these steps:

1. Choose some live pigs to feed.


2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will
take no time.
3. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
4. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will
survive.
5. Repeat this process until you run out of time.

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is
poisonous within the allotted time.

Example 1:

Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60


Output: 5

Example 2:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 15


Output: 2

Example 3:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 30


Output: 2

Constraints:

1 <= buckets <= 1000


1 <= minutesToDie <= minutesToTest <= 100
*********

128. Poor Pigs(C++)


*********

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
7 return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));
8 }
9 };
*********

128. Poor Pigs(Python)


*********

1 # Time: O(1)
2 # Space: O(1)
3
4 import math
5
6
7 class Solution(object):
8 def poorPigs(self, buckets, minutesToDie, minutesToTest):
9 """
10 :type buckets: int
11 :type minutesToDie: int
12 :type minutesToTest: int
13 :rtype: int
14 """
15 return int(math.ceil(math.log(buckets) / math.log(minutesToTest / minutesToDie + 1)))
16
**************************

129. Repeated Substring Pattern


**************************

Given a string s , check if it can be constructed by taking a substring of it and appending multiple copies of the substring
together.

Example 1:

Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.

Example 2:

Input: s = "aba"
Output: false

Example 3:

Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.

Constraints:

1 <= s.length <= 104


s consists of lowercase English letters.
**************************

129. Repeated Substring Pattern(C++)


**************************

1 // Time: O(n)
2 // Space: O(n)
3
4 // KMP solution.
5 class Solution {
6 public:
7 bool repeatedSubstringPattern(string str) {
8 vector prefix = getPrefix(str);
9 return prefix.back() != -1 &&
10 (prefix.back() + 1) % (str.length() - prefix.back() - 1) == 0;
11 }
12
13 private:
14 vector getPrefix(const string& pattern) {
15 vector prefix(pattern.length(), -1);
16 int j = -1;
17 for (int i = 1; i < pattern.length(); ++i) {
18 while (j > -1 && pattern[j + 1] != pattern[i]) {
19 j = prefix[j];
20 }
21 if (pattern[j + 1] == pattern[i]) {
22 ++j;
23 }
24 prefix[i] = j;
25 }
26 return prefix;
27 }
28 };
**************************

129. Repeated Substring Pattern(Python)


**************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def repeatedSubstringPattern(self, str):
6 """
7 :type str: str
8 :rtype: bool
9 """
10 def getPrefix(pattern):
11 prefix = [-1] * len(pattern)
12 j = -1
13 for i in xrange(1, len(pattern)):
14 while j > -1 and pattern[j + 1] != pattern[i]:
15 j = prefix[j]
16 if pattern[j + 1] == pattern[i]:
17 j += 1
18 prefix[i] = j
19 return prefix
20
21 prefix = getPrefix(str)
22 return prefix[-1] != -1 and \
23 (prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0
24
25 def repeatedSubstringPattern2(self, str):
26 """
27 :type str: str
28 :rtype: bool
29 """
30 if not str:
31 return False
32
33 ss = (str + str)[1:-1]
34 return ss.find(str) != -1
35
****************

130. Hamming Distance


****************

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y , return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

Constraints:

0 <= x, y <= 2 31 - 1
****************

130. Hamming Distance(C++)


****************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int hammingDistance(int x, int y) {
7 int distance = 0;
8 for (int z = x ^ y; z; z &= z - 1) {
9 ++distance;
10 }
11 return distance;
12 }
13 };
****************

130. Hamming Distance(Python)


****************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def hammingDistance(self, x, y):
6 """
7 :type x: int
8 :type y: int
9 :rtype: int
10 """
11 distance = 0
12 z = x ^ y
13 while z:
14 distance += 1
15 z &= z - 1
16 return distance
17
18 def hammingDistance2(self, x, y):
19 """
20 :type x: int
21 :type y: int
22 :rtype: int
23 """
24 return bin(x ^ y).count('1')
25
*******

131. Heaters
*******

Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the
houses.

Every house can be warmed, as long as the house is within the heater's warm radius range.

Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those
heaters could cover all houses.

Notice that all the heaters follow your radius standard, and the warm radius will the same.

Example 1:

Input: houses = [1,2,3], heaters = [2]


Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Example 2:

Input: houses = [1,2,3,4], heaters = [1,4]


Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

Example 3:

Input: houses = [1,5], heaters = [2]


Output: 3

Constraints:

1 <= houses.length, heaters.length <= 3 * 10 4


1 <= houses[i], heaters[i] <= 10 9
*******

131. Heaters(C++)
*******

1 // Time: O((m + n) * logn), m is the number of the houses, n is the number of the heaters.
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findRadius(vector& houses, vector& heaters) {
7 sort(heaters.begin(), heaters.end());
8 int min_radius = 0;
9 for (const auto& house : houses) {
10 auto equal_or_larger = lower_bound(heaters.cbegin(), heaters.cend(), house);
11 auto curr_radius = numeric_limits::max();
12 if (equal_or_larger != heaters.cend()) {
13 curr_radius = *equal_or_larger - house;
14 }
15 if (equal_or_larger != heaters.cbegin()) {
16 auto smaller = prev(equal_or_larger);
17 curr_radius = min(curr_radius, house - *smaller);
18 }
19 min_radius = max(min_radius, curr_radius);
20 }
21 return min_radius;
22 }
23 };
*******

131. Heaters(Python)
*******

1 # Time: O((m + n) * logn), m is the number of the houses, n is the number of the heaters.
2 # Space: O(1)
3
4 import bisect
5
6
7 class Solution(object):
8 def findRadius(self, houses, heaters):
9 """
10 :type houses: List[int]
11 :type heaters: List[int]
12 :rtype: int
13 """
14 heaters.sort()
15 min_radius = 0
16 for house in houses:
17 equal_or_larger = bisect.bisect_left(heaters, house)
18 curr_radius = float("inf")
19 if equal_or_larger != len(heaters):
20 curr_radius = heaters[equal_or_larger] - house
21 if equal_or_larger != 0:
22 smaller = equal_or_larger-1
23 curr_radius = min(curr_radius, house - heaters[smaller])
24 min_radius = max(min_radius, curr_radius)
25 return min_radius
26
**********************

132. License Key Formatting


**********************

You are given a license key represented as a strings that consists of only alphanumeric characters and dashes. The string
is separated into n + 1 groups by n dashes. You are also given an integerk .

We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could
be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two
groups, and you should convert all lowercase letters to uppercase.

Return the reformatted license key.

Example 1:

Input: s = "5F3Z-2e-9-w", k = 4
Output: "5F3Z-2E9W"
Explanation: The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.

Example 2:

Input: s = "2-5g-3-J", k = 2
Output: "2-5G-3J"
Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mention

Constraints:

1 <= s.length <= 105


s consists of English letters, digits, and dashes '-'.
1 <= k <= 10 4
**********************

132. License Key Formatting(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string licenseKeyFormatting(string S, int K) {
7 string result;
8 for (auto it = S.rbegin(); it < S.rend(); ++it) {
9 if (*it == '-') {
10 continue;
11 }
12 if (result.length() % (K + 1) == K) {
13 result += '-';
14 }
15 result += toupper(*it);
16 }
17 reverse(result.begin(), result.end());
18 return result;
19 }
20 };
**********************

132. License Key Formatting(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def licenseKeyFormatting(self, S, K):
6 """
7 :type S: str
8 :type K: int
9 :rtype: str
10 """
11 result = []
12 for i in reversed(xrange(len(S))):
13 if S[i] == '-':
14 continue
15 if len(result) % (K + 1) == K:
16 result += '-'
17 result += S[i].upper()
18 return "".join(reversed(result))
****************

133. Fibonacci Number


****************

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number
is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

Example 1:

Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints:

0 <= n <= 30
****************

133. Fibonacci Number(C++)


****************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int fib(int N) {
7 vector> T = {{1, 1},
8 {1, 0}};
9 return matrixMult({{1, 0}}, matrixExpo(T, N))[0][1]; // [a1, a0] * T^N
10 }
11
12 private:
13 vector> matrixExpo(const vector>& A, int pow) {
14 vector> result(A.size(), vector(A.size()));
15 vector> A_exp(A);
16 for (int i = 0; i < A.size(); ++i) {
17 result[i][i] = 1;
18 }
19 while (pow) {
20 if (pow % 2 == 1) {
21 result = matrixMult(result, A_exp);
22 }
23 A_exp = matrixMult(A_exp, A_exp);
24 pow /= 2;
25 }
26 return result;
27 }
28
29 vector> matrixMult(const vector>& A, const vector>& B) {
30 vector> result(A.size(), vector(B[0].size()));
31 for (int i = 0; i < A.size(); ++i) {
32 for (int j = 0; j < B[0].size(); ++j) {
33 int64_t entry = 0;
34 for (int k = 0; k < B.size(); ++k) {
35 entry = (static_cast(A[i][k]) * B[k][j] + entry);
36 }
37 result[i][j] = static_cast(entry);
38 }
39 }
40 return result;
41 }
42 };
43
44 // Time: O(n)
45 // Space: O(1)
46 class Solution2 {
47 public:
48 int fib(int N) {
49 vector dp(3, 0);
50 dp[0] = 0;
51 dp[1] = 1;
52 for (int i = 2; i <= N; ++i) {
53 dp[i % 3] = dp[(i - 1) % 3] + dp[(i - 2) % 3];
54 }
55 return dp[N % 3];
56 }
57 };
****************

133. Fibonacci Number(Python)


****************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def fib(self, N):
9 """
10 :type N: int
11 :rtype: int
12 """
13 def matrix_expo(A, K):
14 result = [[int(i==j) for j in xrange(len(A))] \
15 for i in xrange(len(A))]
16 while K:
17 if K % 2:
18 result = matrix_mult(result, A)
19 A = matrix_mult(A, A)
20 K /= 2
21 return result
22
23 def matrix_mult(A, B):
24 ZB = zip(*B)
25 return [[sum(a*b for a, b in itertools.izip(row, col)) \
26 for col in ZB] for row in A]
27
28 T = [[1, 1],
29 [1, 0]]
30 return matrix_mult([[1, 0]], matrix_expo(T, N))[0][1] # [a1, a0] * T^N
31
32
33 # Time: O(n)
34 # Space: O(1)
35 class Solution2(object):
36 def fib(self, N):
37 """
38 :type N: int
39 :rtype: int
40 """
41 prev, current = 0, 1
42 for i in xrange(N):
43 prev, current = current, prev + current,
44 return prev
********************

134. Game Play Analysis I


********************

Table: Activity

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
(player_id, event_date) is the primary key of this table.
This table shows the activity of players of some game.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.

Write an SQL query that reports the first login date for each player.

The query result format is in the following example:

Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-05-02 | 6 |
| 2 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+

Result table:
+-----------+-------------+
| player_id | first_login |
+-----------+-------------+
| 1 | 2016-03-01 |
| 2 | 2017-06-25 |
| 3 | 2016-03-02 |
+-----------+-------------+
********************

134. Game Play Analysis I(Shell)


********************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT player_id,
5 Min(event_date) first_login
6 FROM activity
7 GROUP BY player_id
8 ORDER BY NULL
*********************

135. Game Play Analysis II


*********************

Table: Activity

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
(player_id, event_date) is the primary key of this table.
This table shows the activity of players of some game.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.

Write a SQL query that reports the device that is first logged in for each player.

The query result format is in the following example:

Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-05-02 | 6 |
| 2 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+

Result table:
+-----------+-----------+
| player_id | device_id |
+-----------+-----------+
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
+-----------+-----------+
*********************

135. Game Play Analysis II(Shell)


*********************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT player_id,
5 device_id
6 FROM activity
7 WHERE ( player_id, event_date ) IN (SELECT player_id,
8 Min(event_date)
9 FROM activity
10 GROUP BY player_id
11 ORDER BY NULL)
**************

136. Detect Capital


**************

We define the usage of capitals in a word to be right when one of the following cases holds:

All letters in this word are capitals, like "USA".


All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

Example 1:

Input: word = "USA"


Output: true

Example 2:

Input: word = "FlaG"


Output: false

Constraints:

1 <= word.length <= 100


word consists of lowercase and uppercase English letters.
**************

136. Detect Capital(C++)


**************

1 // Time: O(l)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool detectCapitalUse(string word) {
7 int count = count_if(word.begin(), word.end(), [](char c){ return isupper(c); });
8 return count == word.length() || count == 0 || (count == 1 && isupper(word[0]));
9 }
10 };
**************

136. Detect Capital(Python)


**************

1 # Time: O(l)
2 # Space: O(1)
3
4 class Solution(object):
5 def detectCapitalUse(self, word):
6 """
7 :type word: str
8 :rtype: bool
9 """
10 return word.isupper() or word.islower() or word.istitle()
11
******************************

137. Longest Uncommon Subsequence I


******************************

Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest
uncommon subsequence does not exist, return -1.

An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.

A subsequence of a string s is a string that can be obtained after deleting any number of characters froms .

For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc".
Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).

Example 1:

Input: a = "aba", b = "cdc"


Output: 3
Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Note that "cdc" is also a longest uncommon subsequence.

Example 2:

Input: a = "aaa", b = "bbb"


Output: 3
Explanation: The longest uncommon subsequences are "aaa" and "bbb".

Example 3:

Input: a = "aaa", b = "aaa"


Output: -1
Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence

Constraints:

1 <= a.length, b.length <= 100


a and b consist of lower-case English letters.
******************************

137. Longest Uncommon Subsequence I(C++)


******************************

1 // Time: O(min(a, b))


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findLUSlength(string a, string b) {
7 if (a == b) {
8 return -1;
9 }
10 return max(a.length(), b.length());
11 }
12 };
******************************

137. Longest Uncommon Subsequence I(Python)


******************************

1 # Time: O(min(a, b))


2 # Space: O(1)
3
4 class Solution(object):
5 def findLUSlength(self, a, b):
6 """
7 :type a: str
8 :type b: str
9 :rtype: int
10 """
11 if a == b:
12 return -1
13 return max(len(a), len(b))
14
**********************************

138. Minimum Absolute Difference in BST


**********************************

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two
different nodes in the tree.

Example 1:

Input: root = [4,2,6,1,3]


Output: 1

Example 2:

Input: root = [1,0,48,null,null,12,49]


Output: 1

Constraints:

The number of nodes in the tree is in the range[2, 104].


0 <= Node.val <= 10 5
Note: This question is the same as 783:https://leetcode.com/problems/minimum-distance-between-bst-nodes/
**********************************

138. Minimum Absolute Difference in BST(C++)


**********************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int getMinimumDifference(TreeNode* root) {
16 int result = numeric_limits::max();
17 TreeNode *prev = nullptr;
18
19 inorderTraversal(root, &prev, &result);
20
21 return result;
22 }
23
24 private:
25 void inorderTraversal(TreeNode *root, TreeNode **prev, int *result) {
26 if (!root) {
27 return;
28 }
29
30 inorderTraversal(root->left, prev, result);
31
32 if (*prev) {
33 *result = min(*result, root->val - (*prev)->val);
34 }
35 *prev = root;
36
37 inorderTraversal(root->right, prev, result);
38 }
39 };
**********************************

138. Minimum Absolute Difference in BST(Python)


**********************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def getMinimumDifference(self, root):
6 """
7 :type root: TreeNode
8 :rtype: int
9 """
10 def inorderTraversal(root, prev, result):
11 if not root:
12 return (result, prev)
13
14 result, prev = inorderTraversal(root.left, prev, result)
15 if prev: result = min(result, root.val - prev.val)
16 return inorderTraversal(root.right, root, result)
17
18 return inorderTraversal(root, None, float("inf"))[0]
19
************************

139. K-diff Pairs in an Array


************************

Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array.

A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:

0 <= i < j < nums.length


|nums[i] - nums[j]| == k

Notice that |val| denotes the absolute value of val.

Example 1:

Input: nums = [3,1,4,1,5], k = 2


Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

Input: nums = [1,2,3,4,5], k = 1


Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: nums = [1,3,1,5,4], k = 0


Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Example 4:

Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3


Output: 2

Example 5:

Input: nums = [-1,-2,-3], k = 1


Output: 2

Constraints:

1 <= nums.length <= 10 4


-107 <= nums[i] <= 10 7
0 <= k <= 10 7
************************

139. K-diff Pairs in an Array(C++)


************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int findPairs(vector& nums, int k) {
7 if (k < 0) {
8 return 0;
9 }
10 unordered_set result, lookup;
11 for (const auto& num : nums) {
12 if (lookup.count(num - k)) {
13 result.emplace(num - k);
14 }
15 if (lookup.count(num + k)) {
16 result.emplace(num);
17 }
18 lookup.emplace(num);
19 }
20 return result.size();
21 }
22 };
************************

139. K-diff Pairs in an Array(Python)


************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def findPairs(self, nums, k):
6 """
7 :type nums: List[int]
8 :type k: int
9 :rtype: int
10 """
11 if k < 0: return 0
12 result, lookup = set(), set()
13 for num in nums:
14 if num-k in lookup:
15 result.add(num-k)
16 if num+k in lookup:
17 result.add(num)
18 lookup.add(num)
19 return len(result)
20
***************************

140. Convert BST to Greater Tree


***************************

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed
to the original key plus sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

The left subtree of a node contains only nodes with keysless than the node's key.
The right subtree of a node contains only nodes with keysgreater than the node's key.
Both the left and right subtrees must also be binary search trees.

Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/

Example 1:

Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]


Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

Example 2:

Input: root = [0,null,1]


Output: [1,null,1]

Example 3:

Input: root = [1,0,2]


Output: [3,3,2]

Example 4:

Input: root = [3,2,4,1]


Output: [7,9,4,10]
Constraints:

The number of nodes in the tree is in the range[0, 104].


-104 <= Node.val <= 10 4
All the values in the tree are unique.
root is guaranteed to be a valid binary search tree.
***************************

140. Convert BST to Greater Tree(C++)


***************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 TreeNode* convertBST(TreeNode* root) {
16 int cur_sum = 0;
17 convertBSTHelper(root, &cur_sum);
18 return root;
19 }
20
21 private:
22 void convertBSTHelper(TreeNode* root, int *cur_sum) {
23 if (!root) {
24 return;
25 }
26
27 if (root->right) {
28 convertBSTHelper(root->right, cur_sum);
29 }
30 root->val = (*cur_sum += root->val);
31 if (root->left) {
32 convertBSTHelper(root->left, cur_sum);
33 }
34 }
35 };
***************************

140. Convert BST to Greater Tree(Python)


***************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def convertBST(self, root):
6 """
7 :type root: TreeNode
8 :rtype: TreeNode
9 """
10 def convertBSTHelper(root, cur_sum):
11 if not root:
12 return cur_sum
13
14 if root.right:
15 cur_sum = convertBSTHelper(root.right, cur_sum)
16 cur_sum += root.val
17 root.val = cur_sum
18 if root.left:
19 cur_sum = convertBSTHelper(root.left, cur_sum)
20 return cur_sum
21
22 convertBSTHelper(root, 0)
23 return root
24
*****************

141. Reverse String II


*****************

Given a string s and an integer k , reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than2k but greater than or equal to k
characters, then reverse the first k characters and left the other as original.

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

Constraints:

1 <= s.length <= 104


s consists of only lowercase English letters.
1 <= k <= 10 4
*****************

141. Reverse String II(C++)


*****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reverseStr(string s, int k) {
7 for (int left = 0; left < s.size(); left += 2 * k) {
8 for (int i = left, j = min(left + k - 1, static_cast(s.size()) - 1);
9 i < j; ++i, --j) {
10 swap(s[i], s[j]);
11 }
12 }
13 return s;
14 }
15 };
*****************

141. Reverse String II(Python)


*****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def reverseStr(self, s, k):
6 """
7 :type s: str
8 :type k: int
9 :rtype: str
10 """
11 s = list(s)
12 for i in xrange(0, len(s), 2*k):
13 s[i:i+k] = reversed(s[i:i+k])
14 return "".join(s)
15
***********************

142. Diameter of Binary Tree


***********************

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not
pass through the root.

The length of a path between two nodes is represented by the number of edges between them.

Example 1:

Input: root = [1,2,3,4,5]


Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

Input: root = [1,2]


Output: 1

Constraints:

The number of nodes in the tree is in the range[1, 104].


-100 <= Node.val <= 100
***********************

142. Diameter of Binary Tree(C++)


***********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15 class Solution {
16 public:
17 int diameterOfBinaryTree(TreeNode* root) {
18 return iter_dfs(root);
19 }
20
21 private:
22 int iter_dfs(TreeNode *node) {
23 int result = 0;
24
25 vector> stk;
26 function divide;
27 function&, shared_ptr&, int *)> conquer;
28 divide = [&](TreeNode *node, int *ret) {
29 if (!node) {
30 return;
31 }
32 auto ret1 = make_shared(), ret2 = make_shared();
33 stk.emplace_back(bind(conquer, node, ret1, ret2, ret));
34 stk.emplace_back(bind(divide, node->right, ret2.get()));
35 stk.emplace_back(bind(divide, node->left, ret1.get()));
36 };
37 conquer = [&](TreeNode *node, shared_ptr ret1, shared_ptr ret2, int *ret) {
38 result = max(result, *ret1 + *ret2);
39 *ret = 1 + max(*ret1, *ret2);
40 };
41
42 int max_h = 0;
43 stk.emplace_back(bind(divide, node, &max_h));
44 while (!stk.empty()) {
45 auto cb = move(stk.back()); stk.pop_back();
46 cb();
47 }
48 return result;
49 }
50 };
51
52 // Time: O(n)
53 // Space: O(h)
54 class Solution2 {
55 public:
56 int diameterOfBinaryTree(TreeNode* root) {
57 return iter_dfs(root);
58 }
59
60 private:
61 int iter_dfs(TreeNode *node) {
62 int result = 0, max_h = 0;
63 vector, unique_ptr, int*>> stk;
64 stk.emplace_back(1, node, nullptr, nullptr, &max_h);
65 while (!stk.empty()) {
66 const auto [step, node, ret1, ret2, ret] = move(stk.back()); stk.pop_back();
67 if (step == 1) {
68 if (!node) {
69 continue;
70 }
71 auto ret1 = make_unique(), ret2 = make_unique();
72 auto p1 = ret1.get(), p2 = ret2.get();
73 stk.emplace_back(2, node, move(ret1), move(ret2), ret);
74 stk.emplace_back(1, node->right, nullptr, nullptr, p2);
75 stk.emplace_back(1, node->left, nullptr, nullptr, p1);
76 } else if (step == 2) {
77 result = max(result, *ret1 + *ret2);
78 *ret = 1 + max(*ret1, *ret2);
79 }
80 }
81 return result;
82 }
83 };
84
85 // Time: O(n)
86 // Space: O(h)
87 class Solution3 {
88 public:
89 int diameterOfBinaryTree(TreeNode* root) {
90 return dfs(root).first;
91 }
92
93 private:
94 pair dfs(TreeNode *root) {
95 if (!root) {
96 return {0, 0};
97 }
98 const auto& [left_d, left_h] = dfs(root->left);
99 const auto& [right_d, right_h] = dfs(root->right);
100 return {max({left_d, right_d, left_h + right_h}), 1 + max(left_h, right_h)};
101 }
102 };
***********************

142. Diameter of Binary Tree(Python)


***********************

1 # Time: O(n)
2 # Space: O(h)
3
4 class TreeNode(object):
5 def __init__(self, val=0, left=None, right=None):
6 self.val = val
7 self.left = left
8 self.right = right
9
10
11 class Solution(object):
12 def diameterOfBinaryTree(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 def iter_dfs(node):
18 result = 0
19 max_depth = [0]
20 stk = [(1, [node, max_depth])]
21 while stk:
22 step, params = stk.pop()
23 if step == 1:
24 node, ret = params
25 if not node:
26 continue
27 ret1, ret2 = [0], [0]
28 stk.append((2, [node, ret1, ret2, ret]))
29 stk.append((1, [node.right, ret2]))
30 stk.append((1, [node.left, ret1]))
31 elif step == 2:
32 node, ret1, ret2, ret = params
33 result = max(result, ret1[0]+ret2[0])
34 ret[0] = 1+max(ret1[0], ret2[0])
35 return result
36
37 return iter_dfs(root)
38
39
40 # Time: O(n)
41 # Space: O(h)
42 class Solution2(object):
43 def diameterOfBinaryTree(self, root):
44 """
45 :type root: TreeNode
46 :rtype: int
47 """
48 def dfs(root):
49 if not root:
50 return 0, 0
51 left_d, left_h = dfs(root.left)
52 right_d, right_h = dfs(root.right)
53 return max(left_d, right_d, left_h+right_h), 1+max(left_h, right_h)
54
55 return dfs(root)[0]
***************************

143. Student Attendance Record I


***************************

You are given a string s representing an attendance record for a student where each character signifies whether the student
was absent, late, or present on that day. The record only contains the following three characters:

'A' : Absent.
'L': Late.
'P' : Present.

The student is eligible for an attendance award if they meet both of the following criteria:

The student was absent ('A') for strictly fewer than 2 days total.
The student was never late ('L') for 3 or more consecutive days.

Return true if the student is eligible for an attendance award, orfalse otherwise.

Example 1:

Input: s = "PPALLP"
Output: true
Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.

Example 2:

Input: s = "PPALLL"
Output: false
Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.

Constraints:

1 <= s.length <= 1000


s[i] is either 'A' , 'L', or 'P' .
***************************

143. Student Attendance Record I(C++)


***************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool checkRecord(string s) {
7 int count_A = 0;
8 for (int i = 0; i < s.length(); ++i) {
9 if (s[i] == 'A') {
10 if (++count_A == 2) {
11 return false;
12 }
13 }
14 if (i + 2 < s.length() && s[i] == 'L' && s[i + 1] == 'L' && s[i + 2] == 'L') {
15 return false;
16 }
17 }
18 return true;
19 }
20 };
***************************

143. Student Attendance Record I(Python)


***************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def checkRecord(self, s):
6 """
7 :type s: str
8 :rtype: bool
9 """
10 count_A = 0
11 for i in xrange(len(s)):
12 if s[i] == 'A':
13 count_A += 1
14 if count_A == 2:
15 return False
16 if i < len(s) - 2 and s[i] == s[i+1] == s[i+2] == 'L':
17 return False
18 return True
19
20
*****************************

144. Reverse Words in a String III


*****************************

Given a string s , reverse the order of characters in each word within a sentence while still preserving whitespace and initial
word order.

Example 1:

Input: s = "Let's take LeetCode contest"


Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"


Output: "doG gniD"

Constraints:

1 <= s.length <= 5 * 10 4


s contains printable ASCII characters.
s does not contain any leading or trailing spaces.
There is at least one word in s .
All the words in s are separated by a single space.
*****************************

144. Reverse Words in a String III(C++)


*****************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reverseWords(string s) {
7 for (int i = 0, j = 0; j <= s.length(); ++j) {
8 if (j == s.length() || s[j] == ' ') {
9 reverse(s.begin() + i, s.begin() + j);
10 i = j + 1;
11 }
12 }
13 return s;
14 }
15 };
*****************************

144. Reverse Words in a String III(Python)


*****************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def reverseWords(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 def reverse(s, begin, end):
11 for i in xrange((end - begin) // 2):
12 s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]
13
14 s, i = list(s), 0
15 for j in xrange(len(s) + 1):
16 if j == len(s) or s[j] == ' ':
17 reverse(s, i, j)
18 i = j + 1
19 return "".join(s)
20
21
22 class Solution2(object):
23 def reverseWords(self, s):
24 reversed_words = [word[::-1] for word in s.split(' ')]
25 return ' '.join(reversed_words)
26
*****************

145. Array Partition I


*****************

Given an integer array nums of 2n integers, group these integers into n pairs (a 1, b 1), (a 2, b 2), ..., (a n, b n) such that the sum of
min(ai, b i) for all i is maximized. Return the maximized sum.

Example 1:

Input: nums = [1,4,3,2]


Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.

Example 2:

Input: nums = [6,2,6,5,1,2]


Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.

Constraints:

1 <= n <= 10 4
nums.length == 2 * n
-104 <= nums[i] <= 10 4
*****************

145. Array Partition I(C++)


*****************

1 // Time: O(r), r is the range size of the integers


2 // Space: O(r)
3
4 class Solution {
5 public:
6 int arrayPairSum(vector& nums) {
7 const auto LEFT = -10000;
8 const auto RIGHT = 10000;
9 vector lookup(RIGHT - LEFT + 1, 0);
10 for (const auto& num: nums) {
11 ++lookup[num - LEFT];
12 }
13 auto r = 0, result = 0;
14 for (int i = LEFT; i <= RIGHT; ++i) {
15 result += (lookup[i - LEFT] + 1 - r) / 2 * i;
16 r = (lookup[i - LEFT] + r) % 2;
17 }
18 return result;
19 }
20 };
21
22 // Time: O(nlogn)
23 // Space: O(1)
24 class Solution2 {
25 public:
26 int arrayPairSum(vector& nums) {
27 sort(nums.begin(), nums.end());
28 auto result = 0;
29 for (auto i = 0; i < nums.size(); i += 2) {
30 result += nums[i];
31 }
32 return result;
33 }
34 };
*****************

145. Array Partition I(Python)


*****************

1 # Time: O(r), r is the range size of the integers


2 # Space: O(r)
3
4
5 class Solution(object):
6 def arrayPairSum(self, nums):
7 """
8 :type nums: List[int]
9 :rtype: int
10 """
11 LEFT, RIGHT = -10000, 10000
12 lookup = [0] * (RIGHT-LEFT+1)
13 for num in nums:
14 lookup[num-LEFT] += 1
15 r, result = 0, 0
16 for i in xrange(LEFT, RIGHT+1):
17 result += (lookup[i-LEFT] + 1 - r) / 2 * i
18 r = (lookup[i-LEFT] + r) % 2
19 return result
20
21
22 # Time: O(nlogn)
23 # Space: O(1)
24 class Solution2(object):
25 def arrayPairSum(self, nums):
26 """
27 :type nums: List[int]
28 :rtype: int
29 """
30 nums.sort()
31 result = 0
32 for i in xrange(0, len(nums), 2):
33 result += nums[i]
34 return result
35
36
37 # Time: O(nlogn)
38 # Space: O(n)
39 class Solution3(object):
40 def arrayPairSum(self, nums):
41 """
42 :type nums: List[int]
43 :rtype: int
44 """
45 nums = sorted(nums)
46 return sum([nums[i] for i in range(0, len(nums), 2)])
47
****************

146. Binary Tree Tilt


****************

Given the root of a binary tree, return the sum of every tree node's tilt.

The tilt of a tree node is the absolute difference between the sum of all left subtree nodevalues and all right subtree node
values. If a node does not have a left child, then the sum of the left subtree nodevalues is treated as 0. The rule is similar if
there the node does not have a right child.

Example 1:

Input: root = [1,2,3]


Output: 1
Explanation:
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1

Example 2:

Input: root = [4,2,9,3,5,null,7]


Output: 15
Explanation:
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, whic
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15

Example 3:
Input: root = [21,7,14,1,1,2,2,3,3]
Output: 9

Constraints:

The number of nodes in the tree is in the range[0, 104].


-1000 <= Node.val <= 1000
****************

146. Binary Tree Tilt(C++)


****************

1 // Time: O(n)
2 // Space: O(n)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int findTilt(TreeNode* root) {
16 int tilt = 0;
17 postOrderTraverse(root, &tilt);
18 return tilt;
19 }
20 private:
21 int postOrderTraverse(TreeNode* root, int *tilt) {
22 if (!root) {
23 return 0;
24 }
25 auto left = postOrderTraverse(root->left, tilt);
26 auto right = postOrderTraverse(root->right, tilt);
27 *tilt += abs(left - right);
28 return left + right + root->val;
29 }
30 };
****************

146. Binary Tree Tilt(Python)


****************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def findTilt(self, root):
6 """
7 :type root: TreeNode
8 :rtype: int
9 """
10 def postOrderTraverse(root, tilt):
11 if not root:
12 return 0, tilt
13 left, tilt = postOrderTraverse(root.left, tilt)
14 right, tilt = postOrderTraverse(root.right, tilt)
15 tilt += abs(left-right)
16 return left+right+root.val, tilt
17
18 return postOrderTraverse(root, 0)[1]
19
******************

147. Reshape the Matrix


******************

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x
c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of
the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they
were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the
original matrix.

Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4


Output: [[1,2,3,4]]

Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4


Output: [[1,2],[3,4]]

Constraints:

m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
******************

147. Reshape the Matrix(C++)


******************

1 // Time: O(m * n)
2 // Space: O(m * n)
3
4 class Solution {
5 public:
6 vector> matrixReshape(vector>& nums, int r, int c) {
7 if (nums.empty() ||
8 r * c != nums.size() * nums[0].size()) {
9 return nums;
10 }
11
12 vector> result(r, vector(c));
13 int count = 0;
14 for (int i = 0; i < nums.size(); ++i) {
15 for (int j = 0; j < nums[0].size(); ++j) {
16 result[count / c][count % c] = nums[i][j];
17 ++count;
18 }
19 }
20 return result;
21 }
22 };
******************

147. Reshape the Matrix(Python)


******************

1 # Time: O(m * n)
2 # Space: O(m * n)
3
4 class Solution(object):
5 def matrixReshape(self, nums, r, c):
6 """
7 :type nums: List[List[int]]
8 :type r: int
9 :type c: int
10 :rtype: List[List[int]]
11 """
12 if not nums or \
13 r*c != len(nums) * len(nums[0]):
14 return nums
15
16 result = [[0 for _ in xrange(c)] for _ in xrange(r)]
17 count = 0
18 for i in xrange(len(nums)):
19 for j in xrange(len(nums[0])):
20 result[count/c][count%c] = nums[i][j]
21 count += 1
22 return result
23
***********************

148. Subtree of Another Tree


***********************

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node
values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could
also be considered as a subtree of itself.

Example 1:

Input: root = [3,4,5,1,2], subRoot = [4,1,2]


Output: true

Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false

Constraints:

The number of nodes in the root tree is in the range [1, 2000].
The number of nodes in the subRoot tree is in the range [1, 1000].
-104 <= root.val <= 10 4
-104 <= subRoot.val <= 10 4
***********************

148. Subtree of Another Tree(C++)


***********************

1 // Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t


2 // Space: O(h), h is the height of s
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 bool isSubtree(TreeNode* s, TreeNode* t) {
16 return preOrderTraverse(s, t);
17 }
18
19 private:
20 bool preOrderTraverse(TreeNode *s, TreeNode *t) {
21 return s && (isSame(s, t) ||
22 preOrderTraverse(s->left, t) ||
23 preOrderTraverse(s->right, t));
24 }
25
26 bool isSame(TreeNode *x,TreeNode *y) {
27 if (!x && !y) {
28 return true;
29 }
30 if (!x || !y) {
31 return false;
32 }
33 return x->val == y->val &&
34 isSame(x->left, y->left) &&
35 isSame(x->right, y->right);
36 }
37 };
***********************

148. Subtree of Another Tree(Python)


***********************

1 # Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t


2 # Space: O(h), h is the height of s
3
4 class Solution(object):
5 def isSubtree(self, s, t):
6 """
7 :type s: TreeNode
8 :type t: TreeNode
9 :rtype: bool
10 """
11 def isSame(x, y):
12 if not x and not y:
13 return True
14 if not x or not y:
15 return False
16 return x.val == y.val and \
17 isSame(x.left, y.left) and \
18 isSame(x.right, y.right)
19
20 def preOrderTraverse(s, t):
21 return s != None and \
22 (isSame(s, t) or \
23 preOrderTraverse(s.left, t) or \
24 preOrderTraverse(s.right, t))
25
26 return preOrderTraverse(s, t)
27
******************

149. Distribute Candies


******************

Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a
doctor.

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and
she wants to eat the maximum number of different types of candies while still following the doctor's advice.

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she
only eats n / 2 of them.

Example 1:

Input: candyType = [1,1,2,2,3,3]


Output: 3
Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.

Example 2:

Input: candyType = [1,1,2,3]


Output: 2
Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.

Example 3:

Input: candyType = [6,6,6,6]


Output: 1
Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.

Constraints:

n == candyType.length
2 <= n <= 10 4
n is even.
-105 <= candyType[i] <= 10 5
******************

149. Distribute Candies(C++)


******************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int distributeCandies(vector& candies) {
7 unordered_set lookup;
8 for (const auto& candy: candies) {
9 lookup.emplace(candy);
10 }
11 return min(lookup.size(), candies.size() / 2);
12 }
13 };
******************

149. Distribute Candies(Python)


******************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5
6 def distributeCandies(self, candies):
7 """
8 :type candies: List[int]
9 :rtype: int
10 """
11 lookup = set(candies)
12 return min(len(lookup), len(candies)/2)
13
*************************************

150. Shortest Unsorted Continuous Subarray


*************************************

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending
order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

Example 1:

Input: nums = [2,6,4,8,10,9,15]


Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

Input: nums = [1,2,3,4]


Output: 0

Example 3:

Input: nums = [1]


Output: 0

Constraints:

1 <= nums.length <= 10 4


-105 <= nums[i] <= 10 5

Follow up: Can you solve it in O(n) time complexity?


*************************************

150. Shortest Unsorted Continuous Subarray(C++)


*************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findUnsortedSubarray(vector& nums) {
7 const auto n = nums.size();
8 auto left = -1, right = -2;
9 auto max_from_left = nums[0], min_from_right = nums.back();
10 for (int i = 1; i < n; ++i) {
11 max_from_left = max(max_from_left, nums[i]);
12 min_from_right = min(min_from_right, nums[n - 1 - i]);
13 if (nums[i] < max_from_left) {
14 right = i;
15 }
16 if (nums[n - 1 - i] > min_from_right) {
17 left = n - 1 - i;
18 }
19 }
20 return right - left + 1;
21 }
22 };
*************************************

150. Shortest Unsorted Continuous Subarray(Python)


*************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findUnsortedSubarray(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 n = len(nums)
11 left, right = -1, -2
12 min_from_right, max_from_left = nums[-1], nums[0]
13 for i in xrange(1, n):
14 max_from_left = max(max_from_left, nums[i])
15 min_from_right = min(min_from_right, nums[n-1-i])
16 if nums[i] < max_from_left: right = i
17 if nums[n-1-i] > min_from_right: left = n-1-i
18
19
20 # Time: O(nlogn)
21 # Space: O(n)
22 class Solution2(object):
23 def findUnsortedSubarray(self, nums):
24 """
25 :type nums: List[int]
26 :rtype: int
27 """
28 a = sorted(nums) #sort the list
29 left, right = 0, len(nums) -1 #define left and right pointer
30 while (nums[left] == a[left] or nums[right] == a[right]):
31 if right - left <= 1:
32 return 0
33 if nums[left] == a[left]:
34 left += 1
35 if nums[right] == a[right]:
36 right -= 1
37 return right - left + 1
38
******************************

151. Longest Harmonious Subsequence


******************************

We define a harmonious array as an array where the difference between its maximum value and its minimum value is
exactly 1.

Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.

A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without
changing the order of the remaining elements.

Example 1:

Input: nums = [1,3,2,2,5,2,3,7]


Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Example 2:

Input: nums = [1,2,3,4]


Output: 2

Example 3:

Input: nums = [1,1,1,1]


Output: 0

Constraints:

1 <= nums.length <= 2 * 10 4


-109 <= nums[i] <= 10 9
******************************

151. Longest Harmonious Subsequence(C++)


******************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int findLHS(vector& nums) {
7 unordered_map lookup;
8 auto result = 0;
9 for (const auto& num : nums) {
10 ++lookup[num];
11 for (const auto& diff : {-1, 1}) {
12 if (lookup.count(num + diff)) {
13 result = max(result, lookup[num] + lookup[num + diff]);
14 }
15 }
16 }
17 return result;
18 }
19 };
******************************

151. Longest Harmonious Subsequence(Python)


******************************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def findLHS(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: int
12 """
13 lookup = collections.defaultdict(int)
14 result = 0
15 for num in nums:
16 lookup[num] += 1
17 for diff in [-1, 1]:
18 if (num + diff) in lookup:
19 result = max(result, lookup[num] + lookup[num + diff])
20 return result
21
*****************

152. Range Addition II


*****************

You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [a i, b i] means M[x][y] should
be incremented by one for all 0 <= x < a i and 0 <= y < b i.

Count and return the number of maximum integers in the matrix after performing all the operations.

Example 1:

Input: m = 3, n = 3, ops = [[2,2],[3,3]]


Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.

Example 2:

Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]


Output: 4

Example 3:

Input: m = 3, n = 3, ops = []
Output: 9

Constraints:

1 <= m, n <= 4 * 10 4
1 <= ops.length <= 10 4
ops[i].length == 2
1 <= ai <= m
1 <= bi <= n
*****************

152. Range Addition II(C++)


*****************

1 // Time: O(p), p is the number of ops


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxCount(int m, int n, vector>& ops) {
7 for (const auto& op : ops) {
8 m = min(m, op[0]);
9 n = min(n, op[1]);
10 }
11 return m * n;
12 }
13 };
*****************

152. Range Addition II(Python)


*****************

1 # Time: O(p), p is the number of ops


2 # Space: O(1)
3
4 class Solution(object):
5 def maxCount(self, m, n, ops):
6 """
7 :type m: int
8 :type n: int
9 :type ops: List[List[int]]
10 :rtype: int
11 """
12 for op in ops:
13 m = min(m, op[0])
14 n = min(n, op[1])
15 return m*n
16
******************************

153. Minimum Index Sum of Two Lists


******************************

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants
represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between
answers, output all of them with no order requirement. You could assume there always exists an answer.

Example 1:

Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Sh
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".

Example 2:

Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]


Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).

Example 3:

Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Burger King","Tapioca Express","Shogun"]


Output: ["KFC","Burger King","Tapioca Express","Shogun"]

Example 4:

Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KNN","KFC","Burger King","Tapioca Express","Shogun"]


Output: ["KFC","Burger King","Tapioca Express","Shogun"]

Example 5:

Input: list1 = ["KFC"], list2 = ["KFC"]


Output: ["KFC"]

Constraints:

1 <= list1.length, list2.length <= 1000


1 <= list1[i].length, list2[i].length <= 30
list1[i] and list2[i] consist of spaces ' ' and English letters.
All the stings of list1 are unique.
All the stings of list2 are unique.
******************************

153. Minimum Index Sum of Two Lists(C++)


******************************

1 // Time: O((m + n) * l), m is the size of list1, n is the size of list2


2 // Space: O(m * l), l is the average string length
3
4 class Solution {
5 public:
6 vector findRestaurant(vector& list1, vector& list2) {
7 unordered_map lookup;
8 for (int i = 0; i < list1.size(); ++i) {
9 lookup[list1[i]] = i;
10 }
11 vector result;
12 int min_sum = numeric_limits::max();
13 for (int j = 0; j < list2.size() && j <= min_sum; ++j) {
14 if (lookup.count(list2[j])) {
15 auto sum = j + lookup[list2[j]];
16 if (sum < min_sum) {
17 result.clear();
18 result.emplace_back(list2[j]);
19 min_sum = sum;
20 } else if (sum == min_sum)
21 result.emplace_back(list2[j]);
22 }
23 }
24 return result;
25 }
26 };
******************************

153. Minimum Index Sum of Two Lists(Python)


******************************

1 # Time: O((m + n) * l), m is the size of list1, n is the size of list2


2 # Space: O(m * l), l is the average length of string
3
4 class Solution(object):
5 def findRestaurant(self, list1, list2):
6 """
7 :type list1: List[str]
8 :type list2: List[str]
9 :rtype: List[str]
10 """
11 lookup = {}
12 for i, s in enumerate(list1):
13 lookup[s] = i
14
15 result = []
16 min_sum = float("inf")
17 for j, s in enumerate(list2):
18 if j > min_sum:
19 break
20 if s in lookup:
21 if j + lookup[s] < min_sum:
22 result = [s]
23 min_sum = j + lookup[s]
24 elif j + lookup[s] == min_sum:
25 result.append(s)
26 return result
27
*********************************

154. Design Compressed String Iterator


*********************************

Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of
each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.

Implement the StringIterator class:

Returns the next character if the original string still has uncompressed characters, otherwise returns awhite
next()
space.
hasNext() Returns true if there is any letter needs to be uncompressed in the original string, otherwise returnsfalse.

Example 1:

Input
["StringIterator", "next", "next", "next", "next", "next", "next", "hasNext", "next", "hasNext"]
[["L1e2t1C1o1d1e1"], [], [], [], [], [], [], [], [], []]
Output
[null, "L", "e", "e", "t", "C", "o", true, "d", true]

Explanation
StringIterator stringIterator = new StringIterator("L1e2t1C1o1d1e1");
stringIterator.next(); // return "L"
stringIterator.next(); // return "e"
stringIterator.next(); // return "e"
stringIterator.next(); // return "t"
stringIterator.next(); // return "C"
stringIterator.next(); // return "o"
stringIterator.hasNext(); // return True
stringIterator.next(); // return "d"
stringIterator.hasNext(); // return True

Constraints:

1 <= compressedString.length <= 1000


compressedString consists of lower-case an upper-case English letters and digits.
The number of a single character repetitions in compressedString is in the range [1, 10^9]
At most 100 calls will be made to next and hasNext.
*********************************

154. Design Compressed String Iterator(C++)


*********************************

1 // Time: O(1)
2 // Space: O(1)
3
4 class StringIterator {
5 public:
6 StringIterator(string compresult_sedString)
7 : result_(compresult_sedString),
8 num_(0),
9 ch_(' ') {
10
11 }
12
13 char next() {
14 if (!hasNext()) {
15 return ' ';
16 }
17 if (num_ == 0) {
18 result_ >> ch_ >> num_;
19 }
20 --num_;
21 return ch_;
22 }
23
24 bool hasNext() {
25 return !result_.eof() || num_ != 0;
26 }
27
28 private:
29 istringstream result_;
30 int num_;
31 char ch_;
32 };
33
34 /**
35 * Your StringIterator object will be instantiated and called as such_:
36 * StringIterator obj = new StringIterator(compresult_sedString);
37 * ch_ar param_1 = obj.next();
38 * bool param_2 = obj.hasNext();
39 */
*********************************

154. Design Compressed String Iterator(Python)


*********************************

1 # Time: O(1)
2 # Space: O(1)
3
4 import re
5
6
7 class StringIterator(object):
8
9 def __init__(self, compressedString):
10 """
11 :type compressedString: str
12 """
13 self.__result = re.findall(r"([a-zA-Z])(\d+)", compressedString)
14 self.__index, self.__num, self.__ch = 0, 0, ' '
15
16 def next(self):
17 """
18 :rtype: str
19 """
20 if not self.hasNext():
21 return ' '
22 if self.__num == 0:
23 self.__ch = self.__result[self.__index][0]
24 self.__num = int(self.__result[self.__index][1])
25 self.__index += 1
26 self.__num -= 1
27 return self.__ch
28
29
30 def hasNext(self):
31 """
32 :rtype: bool
33 """
34 return self.__index != len(self.__result) or self.__num != 0
35
36
37
38
*****************

155. Can Place Flowers


*****************

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in
adjacent plots.

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return
if n new flowers can be planted in theflowerbed without violating the no-adjacent-flowers rule.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1


Output: true

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2


Output: false

Constraints:

1 <= flowerbed.length <= 2 * 10 4


flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length
*****************

155. Can Place Flowers(C++)


*****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool canPlaceFlowers(vector& flowerbed, int n) {
7 for (int i = 0; i < flowerbed.size(); ++i) {
8 if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) &&
9 (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {
10 flowerbed[i] = 1;
11 --n;
12 }
13 if (n <= 0) {
14 return true;
15 }
16 }
17 return false;
18 }
19 };
20
*****************

155. Can Place Flowers(Python)


*****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def canPlaceFlowers(self, flowerbed, n):
6 """
7 :type flowerbed: List[int]
8 :type n: int
9 :rtype: bool
10 """
11 for i in xrange(len(flowerbed)):
12 if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \
13 (i == len(flowerbed)-1 or flowerbed[i+1] == 0):
14 flowerbed[i] = 1
15 n -= 1
16 if n <= 0:
17 return True
18 return False
19
*********************************

156. Construct String from Binary Tree


*********************************

Given the root of a binary tree, construct a string consists of parenthesis and integers from a binary tree with the preorder
traversing way, and return it.

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the
original binary tree.

Example 1:

Input: root = [1,2,3,4]


Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be

Example 2:

Input: root = [1,2,3,null,4]


Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relations
Constraints:

The number of nodes in the tree is in the range[1, 104].


-1000 <= Node.val <= 1000
*********************************

156. Construct String from Binary Tree(C++)


*********************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 string tree2str(TreeNode* t) {
16 if (!t) {
17 return "";
18 }
19
20 auto s = to_string(t->val);
21
22 if (t->left || t->right) {
23 s += "(" + tree2str(t->left) + ")";
24 }
25
26 if (t->right) {
27 s += "(" + tree2str(t->right) + ")";
28 }
29
30 return s;
31 }
32 };
*********************************

156. Construct String from Binary Tree(Python)


*********************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def tree2str(self, t):
6 """
7 :type t: TreeNode
8 :rtype: str
9 """
10 if not t: return ""
11 s = str(t.val)
12 if t.left or t.right:
13 s += "(" + self.tree2str(t.left) + ")"
14 if t.right:
15 s += "(" + self.tree2str(t.right) + ")"
16 return s
17
**********************

157. Merge Two Binary Trees


**********************

You are given two binary trees root1 and root2.

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are
not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node
values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

Example 1:

Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]


Output: [3,4,5,5,4,null,7]

Example 2:

Input: root1 = [1], root2 = [1,2]


Output: [2,2]

Constraints:

The number of nodes in both trees is in the range[0, 2000].


-104 <= Node.val <= 10 4
**********************

157. Merge Two Binary Trees(C++)


**********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
16 if (!t1) {
17 return t2;
18 }
19 if (!t2) {
20 return t1;
21 }
22 t1->val += t2->val;
23 t1->left = mergeTrees(t1->left, t2->left);
24 t1->right = mergeTrees(t1->right, t2->right);
25 return t1;
26 }
27 };
**********************

157. Merge Two Binary Trees(Python)


**********************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def mergeTrees(self, t1, t2):
6 """
7 :type t1: TreeNode
8 :type t2: TreeNode
9 :rtype: TreeNode
10 """
11 if t1 is None:
12 return t2
13 if t2 is None:
14 return t1
15 t1.val += t2.val
16 t1.left = self.mergeTrees(t1.left, t2.left)
17 t1.right = self.mergeTrees(t1.right, t2.right)
18 return t1
19
**************************

158. Maximum Distance in Arrays


**************************

You are given m arrays, where each array is sorted in ascending order.

You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the
distance between two integers a and b to be their absolute difference |a - b| .

Return the maximum distance.

Example 1:

Input: arrays = [[1,2,3],[4,5],[1,2,3]]


Output: 4
Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.

Example 2:

Input: arrays = [[1],[1]]


Output: 0

Example 3:

Input: arrays = [[1],[2]]


Output: 1

Example 4:

Input: arrays = [[1,4],[0,5]]


Output: 4

Constraints:

m == arrays.length
2 <= m <= 10 5
1 <= arrays[i].length <= 500
-104 <= arrays[i][j] <= 10 4
arrays[i] is sorted in ascending
order.
There will be at most 105 integers in all the arrays.
**************************

158. Maximum Distance in Arrays(C++)


**************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxDistance(vector>& arrays) {
7 int result = 0;
8 int min_val = arrays[0].front(), max_val = arrays[0].back();
9 for (int i = 1; i < arrays.size(); ++i) {
10 result = max(result,
11 max(max_val - arrays[i].front(),
12 arrays[i].back() - min_val));
13 min_val = min(min_val, arrays[i].front());
14 max_val = max(max_val, arrays[i].back());
15 }
16 return result;
17 }
18 };
19
**************************

158. Maximum Distance in Arrays(Python)


**************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxDistance(self, arrays):
6 """
7 :type arrays: List[List[int]]
8 :rtype: int
9 """
10 result, min_val, max_val = 0, arrays[0][0], arrays[0][-1]
11 for i in xrange(1, len(arrays)):
12 result = max(result, \
13 max(max_val - arrays[i][0], \
14 arrays[i][-1] - min_val))
15 min_val = min(min_val, arrays[i][0])
16 max_val = max(max_val, arrays[i][-1])
17 return result
18
********************************

159. Maximum Product of Three Numbers


********************************

Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

Example 1:

Input: nums = [1,2,3]


Output: 6

Example 2:

Input: nums = [1,2,3,4]


Output: 24

Example 3:

Input: nums = [-1,-2,-3]


Output: -6

Constraints:

3 <= nums.length <= 10 4


-1000 <= nums[i] <= 1000
********************************

159. Maximum Product of Three Numbers(C++)


********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maximumProduct(vector& nums) {
7 auto min1 = numeric_limits::max();
8 auto min2 = numeric_limits::max();
9 auto max1 = numeric_limits::min();
10 auto max2 = numeric_limits::min();
11 auto max3 = numeric_limits::min();
12 for (const auto& n: nums) {
13 if (n <= min1) {
14 min2 = min1;
15 min1 = n;
16 } else if (n <= min2) {
17 min2 = n;
18 }
19 if (n >= max1) {
20 max3 = max2;
21 max2 = max1;
22 max1 = n;
23 } else if (n >= max2) {
24 max3 = max2;
25 max2 = n;
26 } else if (n >= max3) {
27 max3 = n;
28 }
29 }
30 return max(min1 * min2 * max1, max1 * max2 * max3);
31 }
32 };
33
********************************

159. Maximum Product of Three Numbers(Python)


********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maximumProduct(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 min1, min2 = float("inf"), float("inf")
11 max1, max2, max3 = float("-inf"), float("-inf"), float("-inf")
12
13 for n in nums:
14 if n <= min1:
15 min2 = min1
16 min1 = n
17 elif n <= min2:
18 min2 = n
19
20 if n >= max1:
21 max3 = max2
22 max2 = max1
23 max1 = n
24 elif n >= max2:
25 max3 = max2
26 max2 = n
27 elif n >= max3:
28 max3 = n
29
30 return max(min1 * min2 * max1, max1 * max2 * max3)
31
*********************

160. Sum of Square Numbers


*********************

Given a non-negative integer c , decide whether there're two integers a and b such that a2 + b 2 = c .

Example 1:

Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: c = 3
Output: false

Example 3:

Input: c = 4
Output: true

Example 4:

Input: c = 2
Output: true

Example 5:

Input: c = 1
Output: true

Constraints:

0 <= c <= 2 31 - 1
*********************

160. Sum of Square Numbers(C++)


*********************

1 // Time: O(sqrt(c) * logc)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool judgeSquareSum(int c) {
7 for (long long a = 0; a * a <= c; ++a) {
8 auto b = static_cast(sqrt(c - a * a));
9 if (a * a + b * b == c) {
10 return true;
11 }
12 }
13 return false;
14 }
15 };
16
*********************

160. Sum of Square Numbers(Python)


*********************

1 # Time: O(sqrt(c) * logc)


2 # Space: O(1)
3
4 import math
5
6
7 class Solution(object):
8 def judgeSquareSum(self, c):
9 """
10 :type c: int
11 :rtype: bool
12 """
13 for a in xrange(int(math.sqrt(c))+1):
14 b = int(math.sqrt(c-a**2))
15 if a**2 + b**2 == c:
16 return True
17 return False
18
********************************

161. Average of Levels in Binary Tree


********************************

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-
5 of the actual answer will be accepted.

Example 1:

Input: root = [3,9,20,null,15,7]


Output: [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return [3, 14.5, 11].

Example 2:

Input: root = [3,9,20,15,7]


Output: [3.00000,14.50000,11.00000]

Constraints:

The number of nodes in the tree is in the range[1, 104].


-231 <= Node.val <= 2 31 - 1
********************************

161. Average of Levels in Binary Tree(C++)


********************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 vector averageOfLevels(TreeNode* root) {
16 vector result;
17 vector q;
18 q.emplace_back(root);
19 while (!q.empty()) {
20 long long sum = 0, count = 0;
21 vector next_q;
22 for (const auto& n : q) {
23 sum += n->val;
24 ++count;
25 if (n->left) {
26 next_q.emplace_back(n->left);
27 }
28 if (n->right) {
29 next_q.emplace_back(n->right);
30 }
31 }
32 swap(q, next_q);
33 result.emplace_back(sum * 1.0 / count);
34 }
35 return result;
36 }
37 };
38
********************************

161. Average of Levels in Binary Tree(Python)


********************************

1 # Time: O(n)
2 # Space: O(h)
3
4
5 class Solution(object):
6 def averageOfLevels(self, root):
7 """
8 :type root: TreeNode
9 :rtype: List[float]
10 """
11 result = []
12 q = [root]
13 while q:
14 total, count = 0, 0
15 next_q = []
16 for n in q:
17 total += n.val
18 count += 1
19 if n.left:
20 next_q.append(n.left)
21 if n.right:
22 next_q.append(n.right)
23 q = next_q
24 result.append(float(total) / count)
25 return result
26
**************************

162. Maximum Average Subarray I


**************************

You are given an integer array nums consisting of n elements, and an integer k .

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any
answer with a calculation error less than 10-5 will be accepted.

Example 1:

Input: nums = [1,12,-5,-6,50,3], k = 4


Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75

Example 2:

Input: nums = [5], k = 1


Output: 5.00000

Constraints:

n == nums.length
1 <= k <= n <= 10 5
-104 <= nums[i] <= 10 4
**************************

162. Maximum Average Subarray I(C++)


**************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 double findMaxAverage(vector& nums, int k) {
7 double sum = 0;
8 for (int i = 0; i < k; ++i) {
9 sum += nums[i];
10 }
11 double result = sum;
12 for (int i = k; i < nums.size(); ++i) {
13 sum += nums[i] - nums[i-k];
14 result = max(result, sum);
15 }
16 return result / k;
17 }
18 };
19
**************************

162. Maximum Average Subarray I(Python)


**************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findMaxAverage(self, nums, k):
6 """
7 :type nums: List[int]
8 :type k: int
9 :rtype: float
10 """
11 result = total = sum(nums[:k])
12 for i in xrange(k, len(nums)):
13 total += nums[i] - nums[i-k]
14 result = max(result, total)
15 return float(result) / k
16
************

163. Set Mismatch


************

You have a set of integers s , which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of
the numbers in s got duplicated to another number in the set, which results inrepetition of one number and loss of
another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and returnthem in the form of an array.

Example 1:

Input: nums = [1,2,2,4]


Output: [2,3]

Example 2:

Input: nums = [1,1]


Output: [1,2]

Constraints:

2 <= nums.length <= 10 4


1 <= nums[i] <= 10 4
************

163. Set Mismatch(C++)


************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector findErrorNums(vector& nums) {
7 int x_xor_y = 0;
8 for (int i = 0; i < nums.size(); ++i) {
9 x_xor_y ^= nums[i] ^ (i + 1);
10 }
11 int bit = x_xor_y & ~(x_xor_y - 1);
12 vector result(2);
13 for (int i = 0; i < nums.size(); ++i) {
14 result[static_cast(nums[i] & bit)] ^= nums[i];
15 result[static_cast((i + 1) & bit)] ^= i + 1;
16 }
17 if (find(nums.begin(), nums.end(), result[0]) == nums.end()) {
18 swap(result[0], result[1]);
19 }
20 return result;
21 }
22 };
23
24
25 // Time: O(n)
26 // Space: O(1)
27 class Solution2 {
28 public:
29 vector findErrorNums(vector& nums) {
30 vector result(2);
31 for (const auto& i : nums) {
32 if (nums[abs(i) - 1] < 0) { // twice
33 result[0] = abs(i);
34 } else {
35 nums[abs(i) - 1] *= -1;
36 }
37 }
38 for (int i = 0; i < nums.size(); ++i) {
39 if (nums[i] > 0) { // missing
40 result[1] = i + 1;
41 } else {
42 nums[i] *= -1;
43 }
44 }
45 return result;
46 }
47 };
************

163. Set Mismatch(Python)


************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findErrorNums(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: List[int]
9 """
10 x_xor_y = 0
11 for i in xrange(len(nums)):
12 x_xor_y ^= nums[i] ^ (i+1)
13 bit = x_xor_y & ~(x_xor_y-1)
14 result = [0] * 2
15 for i, num in enumerate(nums):
16 result[bool(num & bit)] ^= num
17 result[bool((i+1) & bit)] ^= i+1
18 if result[0] not in nums:
19 result[0], result[1] = result[1], result[0]
20 return result
21
22
23 # Time: O(n)
24 # Space: O(1)
25 class Solution2(object):
26 def findErrorNums(self, nums):
27 """
28 :type nums: List[int]
29 :rtype: List[int]
30 """
31 result = [0] * 2
32 for i in nums:
33 if nums[abs(i)-1] < 0:
34 result[0] = abs(i)
35 else:
36 nums[abs(i)-1] *= -1
37 for i in xrange(len(nums)):
38 if nums[i] > 0:
39 result[1] = i+1
40 else:
41 nums[i] *= -1
42 return result
43
44
45 # Time: O(n)
46 # Space: O(1)
47 class Solution3(object):
48 def findErrorNums(self, nums):
49 """
50 :type nums: List[int]
51 :rtype: List[int]
52 """
53 N = len(nums)
54 x_minus_y = sum(nums) - N*(N+1)//2
55 x_plus_y = (sum(x*x for x in nums) - N*(N+1)*(2*N+1)/6) // x_minus_y
56 return (x_plus_y+x_minus_y) // 2, (x_plus_y-x_minus_y) // 2
57
***************************

164. Two Sum IV - Input is a BST


***************************

Given the root of a Binary Search Tree and a target numberk , return true if there exist two elements in the BST such that their
sum is equal to the given target.

Example 1:

Input: root = [5,3,6,2,4,null,7], k = 9


Output: true

Example 2:

Input: root = [5,3,6,2,4,null,7], k = 28


Output: false

Example 3:
Input: root = [2,1,3], k = 4
Output: true

Example 4:

Input: root = [2,1,3], k = 1


Output: false

Example 5:

Input: root = [2,1,3], k = 3


Output: true

Constraints:

The number of nodes in the tree is in the range[1, 104].


-104 <= Node.val <= 10 4
root is guaranteed to be a valid binary search tree.
-105 <= k <= 10 5
***************************

164. Two Sum IV - Input is a BST(C++)


***************************
1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13
14 class Solution {
15 public:
16 bool findTarget(TreeNode* root, int k) {
17 if (!root) {
18 return false;
19 }
20 BSTIterator left(root, true), right(root, false);
21 while (*left < *right) {
22 if (*left + *right == k) {
23 return true;
24 } else if (*left + *right < k) {
25 ++left;
26 } else {
27 ++right;
28 }
29 }
30 return false;
31 }
32
33 private:
34 class BSTIterator {
35 public:
36 BSTIterator(TreeNode *root, bool forward) :
37 node_(root),
38 forward_(forward) {
39 ++(*this);
40 };
41
42 int operator*() {
43 return cur_;
44 }
45
46 void operator++() {
47 while (node_ || !s_.empty()) {
48 if (node_) {
49 s_.emplace(node_);
50 node_ = forward_ ? node_->left : node_->right;
51 } else {
52 node_ = s_.top();
53 s_.pop();
54 cur_ = node_->val;
55 node_ = forward_ ? node_->right : node_->left;
56 break;
57 }
58 }
59 }
60
61 private:
62 TreeNode* node_;
63 bool forward_;
64 stack s_;
65 int cur_;
66 };
67 };
***************************

164. Two Sum IV - Input is a BST(Python)


***************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def findTarget(self, root, k):
6 """
7 :type root: TreeNode
8 :type k: int
9 :rtype: bool
10 """
11 class BSTIterator(object):
12 def __init__(self, root, forward):
13 self.__node = root
14 self.__forward = forward
15 self.__s = []
16 self.__cur = None
17 self.next()
18
19 def val(self):
20 return self.__cur
21
22 def next(self):
23 while self.__node or self.__s:
24 if self.__node:
25 self.__s.append(self.__node)
26 self.__node = self.__node.left if self.__forward else self.__node.right
27 else:
28 self.__node = self.__s.pop()
29 self.__cur = self.__node.val
30 self.__node = self.__node.right if self.__forward else self.__node.left
31 break
32
33
34 if not root:
35 return False
36 left, right = BSTIterator(root, True), BSTIterator(root, False)
37 while left.val() < right.val():
38 if left.val() + right.val() == k:
39 return True
40 elif left.val() + right.val() < k:
41 left.next()
42 else:
43 right.next()
44 return False
45
**********************

165. Robot Return to Origin


**********************

There is a robot starting at the position(0, 0) , the origin, on a 2D plane. Given a sequence of its moves, judge if this robot
ends up at (0, 0) after it completes its moves.

You are given a string moves that represents the move sequence of the robot wheremoves[i] represents its ith move. Valid
moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).

Return true if the robot returns to the origin after it finishes all of its moves, orfalse otherwise.

Note: The way that the robot is "facing" is irrelevant.'R' will always make the robot move to the right once,'L' will always
make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

Input: moves = "UD"


Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. T

Example 2:

Input: moves = "LL"


Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at

Example 3:

Input: moves = "RRDD"


Output: false

Example 4:

Input: moves = "LDRRLRUULR"


Output: false

Constraints:

1 <= moves.length <= 2 * 10 4


moves only contains the characters 'U', 'D', 'L' and 'R'.
**********************

165. Robot Return to Origin(C++)


**********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool judgeCircle(string moves) {
7 unordered_map count;
8 for (const auto& m : moves) {
9 ++count[m];
10 }
11 return count['L'] == count['R'] && count['U'] == count['D'];
12 }
13 };
14
15 // Time: O(n)
16 // Space: O(1)
17 class Solution2 {
18 public:
19 bool judgeCircle(string moves) {
20 auto v = 0, h = 0;
21 for (const auto& move : moves) {
22 switch (move) {
23 case 'U': ++v; break;
24 case 'D': --v; break;
25 case 'R': ++h; break;
26 case 'L': --h; break;
27 }
28 }
29 return v == 0 && h == 0;
30 }
31 };
**********************

165. Robot Return to Origin(Python)


**********************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def judgeCircle(self, moves):
9 """
10 :type moves: str
11 :rtype: bool
12 """
13 count = collections.Counter(moves)
14 return count['L'] == count['R'] and count['U'] == count['D']
15
16
17 # Time: O(n)
18 # Space: O(1)
19 class Solution(object):
20 def judgeCircle(self, moves):
21 """
22 :type moves: str
23 :rtype: bool
24 """
25 v, h = 0, 0
26 for move in moves:
27 if move == 'U':
28 v += 1
29 elif move == 'D':
30 v -= 1
31 elif move == 'R':
32 h += 1
33 elif move == 'L':
34 h -= 1
35 return v == 0 and h == 0
**************

166. Image Smoother


**************

An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of
the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the
surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red
smoother).

Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on
each cell of it.

Example 1:
Input: img = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

Example 2:

Input: img = [[100,200,100],[200,50,200],[100,200,100]]


Output: [[137,141,137],[141,138,141],[137,141,137]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138

Constraints:

m == img.length
n == img[i].length
1 <= m, n <= 200
0 <= img[i][j] <= 255
**************

166. Image Smoother(C++)


**************

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> imageSmoother(vector>& M) {
7 const auto& m = M.size(), &n = M[0].size();
8 vector> result(M);
9 for (int i = 0; i < m; ++i) {
10 for (int j = 0; j < n; ++j) {
11 result[i][j] = getGray(M, i, j);
12 }
13 }
14 return result;
15 }
16
17 private:
18 int getGray(const vector>& M, int i, int j) {
19 const auto& m = M.size(), &n = M[0].size();
20 double total = 0.0;
21 int count = 0;
22 for (int r = -1; r < 2; ++r) {
23 for (int c = -1; c < 2; ++c) {
24 const auto& ii = i + r;
25 const auto& jj = j + c;
26 if (0 <= ii && ii < m && 0 <= jj && jj < n) {
27 total += M[ii][jj];
28 ++count;
29 }
30 }
31 }
32 return static_cast(total / count);
33 }
34 };
**************

166. Image Smoother(Python)


**************

1 # Time: O(m * n)
2 # Space: O(1)
3
4 class Solution(object):
5 def imageSmoother(self, M):
6 """
7 :type M: List[List[int]]
8 :rtype: List[List[int]]
9 """
10 def getGray(M, i, j):
11 total, count = 0, 0.0
12 for r in xrange(-1, 2):
13 for c in xrange(-1, 2):
14 ii, jj = i + r, j + c
15 if 0 <= ii < len(M) and 0 <= jj < len(M[0]):
16 total += M[ii][jj]
17 count += 1.0
18 return int(total / count)
19
20 result = [[0 for _ in xrange(len(M[0]))] for _ in xrange(len(M))]
21 for i in xrange(len(M)):
22 for j in xrange(len(M[0])):
23 result[i][j] = getGray(M, i, j)
24 return result
25
********************

167. Non-decreasing Array


********************

Given an array nums with n integers, your task is to check if it could become non-decreasing by modifyingat most one
element.

We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2 ).

Example 1:

Input: nums = [4,2,3]


Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: nums = [4,2,1]


Output: false
Explanation: You can't get a non-decreasing array by modify at most one element.

Constraints:

n == nums.length
1 <= n <= 10 4
-105 <= nums[i] <= 10 5
********************

167. Non-decreasing Array(C++)


********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool checkPossibility(vector& nums) {
7 int cnt = 0;
8 for (int i = 1, prev = nums[0]; i < nums.size(); ++i) {
9 if (prev > nums[i]) {
10 if (cnt++) {
11 return false;
12 }
13 if (i - 2 < 0 || nums[i - 2] <= nums[i]) {
14 prev = nums[i]; // nums[i - 1] = nums[i], prev = nums[i]
15 // } else {
16 // prev = nums[i - 1]; // nums[i] = nums[i - 1], prev = nums[i]
17 }
18 } else {
19 prev = nums[i];
20 }
21 }
22 return true;
23 }
24 };
********************

167. Non-decreasing Array(Python)


********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def checkPossibility(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: bool
9 """
10 modified, prev = False, nums[0]
11 for i in xrange(1, len(nums)):
12 if prev > nums[i]:
13 if modified:
14 return False
15 if i-2 < 0 or nums[i-2] <= nums[i]:
16 prev = nums[i] # nums[i-1] = nums[i], prev = nums[i]
17 # else:
18 # prev = nums[i-1] # nums[i] = nums[i-1], prev = nums[i]
19 modified = True
20 else:
21 prev = nums[i]
22 return True
23
24
*************************

168. Trim a Binary Search Tree


*************************

Given the root of a binary search tree and the lowest and highest boundaries aslow and high , trim the tree so that all its
elements lies in [low, high] . Trimming the tree should not change the relative structure of the elements that will remain in the
tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Example 1:

Input: root = [1,0,2], low = 1, high = 2


Output: [1,null,2]

Example 2:

Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3


Output: [3,2,null,1]

Example 3:

Input: root = [1], low = 1, high = 2


Output: [1]

Example 4:

Input: root = [1,null,2], low = 1, high = 3


Output: [1,null,2]

Example 5:
Input: root = [1,null,2], low = 2, high = 4
Output: [2]

Constraints:

The number of nodes in the tree in the range[1, 104].


0 <= Node.val <= 10 4
The value of each node in the tree is unique.
root is guaranteed to be a valid binary search tree.
0 <= low <= high <= 10 4
*************************

168. Trim a Binary Search Tree(C++)


*************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 TreeNode* trimBST(TreeNode* root, int L, int R) {
16 if (!root) {
17 return nullptr;
18 }
19 if (root->val < L) {
20 return trimBST(root->right, L, R);
21 }
22 if (root->val > R) {
23 return trimBST(root->left, L, R);
24 }
25 root->left = trimBST(root->left, L, R);
26 root->right = trimBST(root->right, L, R);
27 return root;
28 }
29 };
*************************

168. Trim a Binary Search Tree(Python)


*************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def trimBST(self, root, L, R):
6 """
7 :type root: TreeNode
8 :type L: int
9 :type R: int
10 :rtype: TreeNode
11 """
12 if not root:
13 return None
14 if root.val < L:
15 return self.trimBST(root.right, L, R)
16 if root.val > R:
17 return self.trimBST(root.left, L, R)
18 root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R)
19 return root
20
21
************************************

169. Second Minimum Node In a Binary Tree


************************************

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has
exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-
nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the
whole tree.

If no such second minimum value exists, output -1 instead.

Example 1:

Input: root = [2,2,5,null,null,5,7]


Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input: root = [2,2,2]


Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

Constraints:

The number of nodes in the tree is in the range[1, 25].


1 <= Node.val <= 2 31 - 1
root.val == min(root.left.val, root.right.val) for each internal node of the tree.
************************************

169. Second Minimum Node In a Binary Tree(C++)


************************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int findSecondMinimumValue(TreeNode* root) {
16 set bst;
17 findSecondMinimumValueHelper(root, &bst);
18 if (bst.size() < 2) {
19 return -1;
20 }
21 return *bst.rbegin();
22 }
23
24 private:
25 void findSecondMinimumValueHelper(TreeNode* root, set *bst) {
26 if (!root) {
27 return;
28 }
29 bst->emplace(root->val);
30 if (bst->size() > 2) {
31 bst->erase(prev(bst->end()));
32 }
33 findSecondMinimumValueHelper(root->left, bst);
34 findSecondMinimumValueHelper(root->right, bst);
35 }
36 };
************************************

169. Second Minimum Node In a Binary Tree(Python)


************************************

1 # Time: O(n)
2 # Space: O(h)
3
4 import heapq
5
6
7 class Solution(object):
8 def findSecondMinimumValue(self, root):
9 """
10 :type root: TreeNode
11 :rtype: int
12 """
13 def findSecondMinimumValueHelper(root, max_heap, lookup):
14 if not root:
15 return
16 if root.val not in lookup:
17 heapq.heappush(max_heap, -root.val)
18 lookup.add(root.val)
19 if len(max_heap) > 2:
20 lookup.remove(-heapq.heappop(max_heap))
21 findSecondMinimumValueHelper(root.left, max_heap, lookup)
22 findSecondMinimumValueHelper(root.right, max_heap, lookup)
23
24 max_heap, lookup = [], set()
25 findSecondMinimumValueHelper(root, max_heap, lookup)
26 if len(max_heap) < 2:
27 return -1
28 return -max_heap[0]
29
*****************************************

170. Longest Continuous Increasing Subsequence


*****************************************

Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e.
subarray). The subsequence must be strictly increasing.

A continuous increasing subsequence is defined by two indices l and r (l < r ) such that it is [nums[l], nums[l + 1], ..., nums[r - 1],
nums[r]] and for each l <= i < r , nums[i] < nums[i + 1] .

Example 1:

Input: nums = [1,3,5,4,7]


Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.

Example 2:

Input: nums = [2,2,2,2,2]


Output: 1
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.

Constraints:

1 <= nums.length <= 10 4


-109 <= nums[i] <= 10 9
*****************************************

170. Longest Continuous Increasing Subsequence(C++)


*****************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findLengthOfLCIS(vector& nums) {
7 int result = 0, count = 0;
8 for (int i = 0; i < nums.size(); ++i) {
9 if (i == 0 || nums[i - 1] < nums[i]) {
10 result = max(result, ++count);
11 } else {
12 count = 1;
13 }
14 }
15 return result;
16 }
17 };
*****************************************

170. Longest Continuous Increasing


Subsequence(Python)
*****************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findLengthOfLCIS(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 result, count = 0, 0
11 for i in xrange(len(nums)):
12 if i == 0 or nums[i-1] < nums[i]:
13 count += 1
14 result = max(result, count)
15 else:
16 count = 1
17 return result
18
*******************

171. Valid Palindrome II


*******************

Given a string s , return true if the s can be palindrome after deleting at most one character from it.

Example 1:

Input: s = "aba"
Output: true

Example 2:

Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.

Example 3:

Input: s = "abc"
Output: false

Constraints:

1 <= s.length <= 105


s consists of lowercase English letters.
*******************

171. Valid Palindrome II(C++)


*******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool validPalindrome(string s) {
7 int left = 0, right = s.length() - 1;
8 while (left < right) {
9 if (s[left] != s[right]) {
10 return validPalindrome(s, left, right - 1) || validPalindrome(s, left + 1, right);
11 }
12 ++left, --right;
13 }
14 return true;
15 }
16
17 private:
18 bool validPalindrome(const string& s, int left, int right) {
19 while (left < right) {
20 if (s[left] != s[right]) {
21 return false;
22 }
23 ++left, --right;
24 }
25 return true;
26 }
27 };
*******************

171. Valid Palindrome II(Python)


*******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def validPalindrome(self, s):
6 """
7 :type s: str
8 :rtype: bool
9 """
10 def validPalindrome(s, left, right):
11 while left < right:
12 if s[left] != s[right]:
13 return False
14 left, right = left+1, right-1
15 return True
16
17 left, right = 0, len(s)-1
18 while left < right:
19 if s[left] != s[right]:
20 return validPalindrome(s, left, right-1) or validPalindrome(s, left+1, right)
21 left, right = left+1, right-1
22 return True
23
*************

172. Baseball Game


*************

You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of
past rounds may affect future rounds' scores.

At the beginning of the game, you start with an empty record. You are given a list of stringsops, where ops[i] is the ith
operation you must apply to the record and is one of the following:

1. An integer x - Record a new score of x .


2. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous
scores.
3. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
4. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.

Return the sum of all the scores on the record.

Example 1:

Input: ops = ["5","2","C","D","+"]


Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.

Example 2:

Input: ops = ["5","-2","4","C","D","9","+","+"]


Output: 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.

Example 3:

Input: ops = ["1"]


Output: 1

Constraints:

1 <= ops.length <= 1000


is "C", "D", "+", or a string representing an integer in the range[-3 * 104, 3 * 10 4].
ops[i]
For operation "+", there will always be at least two previous scores on the record.
For operations "C" and "D", there will always be at least one previous score on the record.
*************

172. Baseball Game(C++)


*************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int calPoints(vector& ops) {
7 vector records;
8 for (const auto& op : ops) {
9 if (op == "+") {
10 records.emplace_back(records[records.size() - 2] + records.back());
11 } else if (op == "D") {
12 records.emplace_back(2 * records.back());
13 } else if (op == "C") {
14 records.pop_back();
15 } else {
16 records.emplace_back(stoi(op));
17 }
18 }
19 return accumulate(records.begin(), records.end(), 0);
20 }
21 };
*************

172. Baseball Game(Python)


*************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def calPoints(self, ops):
6 """
7 :type ops: List[str]
8 :rtype: int
9 """
10 history = []
11 for op in ops:
12 if op == '+':
13 history.append(history[-1] + history[-2])
14 elif op == 'D':
15 history.append(history[-1] * 2)
16 elif op == 'C':
17 history.pop()
18 else:
19 history.append(int(op))
20 return sum(history)
21
*********************

173. Repeated String Match


*********************

Given two strings a and b, return the minimum number of times you should repeat stringa so that string b is a substring of it.
If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.

Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".

Example 1:

Input: a = "abcd", b = "cdabcdab"


Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.

Example 2:

Input: a = "a", b = "aa"


Output: 2

Example 3:

Input: a = "a", b = "a"


Output: 1

Example 4:

Input: a = "abc", b = "wxyz"


Output: -1

Constraints:

1 <= a.length <= 10 4


1 <= b.length <= 10 4
a and b consist of lower-case English letters.
*********************

173. Repeated String Match(C++)


*********************
1 // Time: O(n + m)
2 // Space: O(1)
3
4 // Rabin-Karp Algorithm (rolling hash)
5 class Solution {
6 public:
7 int repeatedStringMatch(string A, string B) {
8 static const uint64_t M = 1000000007;
9 static const uint64_t p = 113;
10 static const uint64_t p_inv = pow(p, M - 2, M);
11
12 const auto q = (B.length() + A.length() - 1) / A.length();
13
14 uint64_t b_hash = 0, power = 1;
15 for (int i = 0; i < B.length(); ++i) {
16 b_hash += power * B[i];
17 b_hash %= M;
18 power = (power * p) % M;
19 }
20
21 uint64_t a_hash = 0; power = 1;
22 for (int i = 0; i < B.length(); ++i) {
23 a_hash += power * A[i % A.length()];
24 a_hash %= M;
25 power = (power * p) % M;
26 }
27 if (a_hash == b_hash && check(0, A, B)) {
28 return q;
29 }
30
31 power = (power * p_inv) % M;
32 for (int i = B.length(); i < (q + 1) * A.length(); ++i) {
33 a_hash -= A[(i - B.length()) % A.length()];
34 a_hash *= p_inv;
35 a_hash += power * A[i % A.length()];
36 a_hash %= M;
37 if (a_hash == b_hash && check(i - B.length() + 1, A, B)) {
38 return i < q * A.length() ? q : q + 1;
39 }
40 }
41 return -1;
42 }
43
44 private:
45 bool check(int index, const string& A, const string& B) {
46 for (int i = 0; i < B.length(); ++i) {
47 if (A[(i + index) % A.length()] != B[i]) {
48 return false;
49 }
50 }
51 return true;
52 }
53
54 uint64_t pow(uint64_t a,uint64_t b, uint64_t m) {
55 a %= m;
56 uint64_t result = 1;
57 while (b) {
58 if (b & 1) {
59 result = (result * a) % m;
60 }
61 a = (a * a) % m;
62 b >>= 1;
63 }
64 return result;
65 }
66 };
*********************

173. Repeated String Match(Python)


*********************

1 # Time: O(n + m)
2 # Space: O(1)
3
4 class Solution(object):
5 def repeatedStringMatch(self, A, B):
6 """
7 :type A: str
8 :type B: str
9 :rtype: int
10 """
11 def check(index):
12 return all(A[(i+index) % len(A)] == c
13 for i, c in enumerate(B))
14
15 M, p = 10**9+7, 113
16 p_inv = pow(p, M-2, M)
17 q = (len(B)+len(A)-1) // len(A)
18
19 b_hash, power = 0, 1
20 for c in B:
21 b_hash += power * ord(c)
22 b_hash %= M
23 power = (power*p) % M
24
25 a_hash, power = 0, 1
26 for i in xrange(len(B)):
27 a_hash += power * ord(A[i%len(A)])
28 a_hash %= M
29 power = (power*p) % M
30
31 if a_hash == b_hash and check(0): return q
32
33 power = (power*p_inv) % M
34 for i in xrange(len(B), (q+1)*len(A)):
35 a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv
36 a_hash += power * ord(A[i%len(A)])
37 a_hash %= M
38 if a_hash == b_hash and check(i-len(B)+1):
39 return q if i < q*len(A) else q+1
40
41 return -1
42
*********************

174. Longest Univalue Path


*********************

Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This
path may or may not pass through the root.

The length of the path between two nodes is represented by the number of edges between them.

Example 1:

Input: root = [5,4,5,1,1,5]


Output: 2

Example 2:

Input: root = [1,4,5,4,4,5]


Output: 2

Constraints:

The number of nodes in the tree is in the range[0, 104].


-1000 <= Node.val <= 1000
The depth of the tree will not exceed 1000.
*********************

174. Longest Univalue Path(C++)


*********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int longestUnivaluePath(TreeNode* root) {
16 auto result = 0;
17 dfs(root, &result);
18 return result;
19 }
20
21 private:
22 int dfs(TreeNode *node, int *result) {
23 if (!node) {
24 return 0;
25 }
26 auto left = dfs(node->left, result);
27 auto right = dfs(node->right, result);
28 left = node->left && node->val == node->left->val ? left + 1 : 0;
29 right = node->right && node->val == node->right->val ? right + 1 : 0;
30 *result = max(*result, left + right);
31 return max(left, right);
32 }
33 };
*********************

174. Longest Univalue Path(Python)


*********************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def longestUnivaluePath(self, root):
6 """
7 :type root: TreeNode
8 :rtype: int
9 """
10 result = [0]
11 def dfs(node):
12 if not node:
13 return 0
14 left, right = dfs(node.left), dfs(node.right)
15 left = (left+1) if node.left and node.left.val == node.val else 0
16 right = (right+1) if node.right and node.right.val == node.val else 0
17 result[0] = max(result[0], left+right)
18 return max(left, right)
19
20 dfs(root)
21 return result[0]
22
*******************

175. Employee Importance


*******************

You have a data structure of employee information, which includes the employee's unique id, their importance value, and
their direct subordinates' id.

You are given an array of employeesemployees where:

employees[i].idis the ID of the ith employee.


employees[i].importance is the importance value of the ith employee.
employees[i].subordinates is a list of the IDs of the subordinates of theith employee.

Given an integer id that represents the ID of an employee, return the total importance value of this employee and all their
subordinates.

Example 1:

Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1


Output: 11
Explanation: Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3.
They both have importance value 3.
So the total importance value of employee 1 is 5 + 3 + 3 = 11.

Example 2:
Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5
Output: -3

Constraints:

1 <= employees.length <= 2000


1 <= employees[i].id <= 2000
All employees[i].id are unique.
-100 <= employees[i].importance <= 100
One employee has at most one direct leader and may have several subordinates.
id is guaranteed to be a valid employee id.
*******************

175. Employee Importance(C++)


*******************

1 // Time: O(n)
2 // Space: O(h)
3
4 /*
5 // Employee info
6 class Employee {
7 public:
8 // It's the unique ID of each node.
9 // unique id of this employee
10 int id;
11 // the importance value of this employee
12 int importance;
13 // the id of direct subordinates
14 vector subordinates;
15 };
16 */
17 class Solution {
18 public:
19 int getImportance(vector employees, int id) {
20 return dfs(employees, id);
21 }
22
23 private:
24 int dfs(const vector& employees, const int id) {
25 if (!employees[id - 1]) {
26 return 0;
27 }
28 auto result = employees[id - 1]->importance;
29 for (const auto& id : employees[id - 1]->subordinates) {
30 result += getImportance(employees, id);
31 }
32 return result;
33 }
34 };
35
36 // Time: O(n)
37 // Space: O(w), w is the max number of nodes in the levels of the tree
38 class Solution2 {
39 public:
40 int getImportance(vector employees, int id) {
41 auto result = 0;
42 queue q;
43 q.emplace(id);
44 while (!q.empty()) {
45 const auto curr = q.front(); q.pop();
46 const auto& employee = employees[curr - 1];
47 result += employee->importance;
48 for (const auto& id : employee->subordinates) {
49 q.emplace(id);
50 }
51 }
52 return result;
53 }
54 };
*******************

175. Employee Importance(Python)


*******************

1 # Time: O(n)
2 # Space: O(h)
3
4 import collections
5
6
7 """
8 # Employee info
9 class Employee(object):
10 def __init__(self, id, importance, subordinates):
11 # It's the unique id of each node.
12 # unique id of this employee
13 self.id = id
14 # the importance value of this employee
15 self.importance = importance
16 # the id of direct subordinates
17 self.subordinates = subordinates
18 """
19 class Solution(object):
20 def getImportance(self, employees, id):
21 """
22 :type employees: Employee
23 :type id: int
24 :rtype: int
25 """
26 if employees[id-1] is None:
27 return 0
28 result = employees[id-1].importance
29 for id in employees[id-1].subordinates:
30 result += self.getImportance(employees, id)
31 return result
32
33
34 # Time: O(n)
35 # Space: O(w), w is the max number of nodes in the levels of the tree
36 class Solution2(object):
37 def getImportance(self, employees, id):
38 """
39 :type employees: Employee
40 :type id: int
41 :rtype: int
42 """
43 result, q = 0, collections.deque([id])
44 while q:
45 curr = q.popleft()
46 employee = employees[curr-1]
47 result += employee.importance
48 for id in employee.subordinates:
49 q.append(id)
50 return result
51
***********************************

176. Binary Number with Alternating Bits


***********************************

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101

Example 2:

Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.

Example 3:

Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.

Example 4:

Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010.

Example 5:

Input: n = 3
Output: false

Constraints:

1 <= n <= 2 31 - 1
***********************************

176. Binary Number with Alternating Bits(C++)


***********************************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool hasAlternatingBits(int n) {
7 auto curr = n % 2;
8 n /= 2;
9 while (n > 0) {
10 if (curr == n % 2) {
11 return false;
12 }
13 curr = n % 2;
14 n /= 2;
15 }
16 return true;
17 }
18 };
***********************************

176. Binary Number with Alternating Bits(Python)


***********************************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def hasAlternatingBits(self, n):
6 """
7 :type n: int
8 :rtype: bool
9 """
10 n, curr = divmod(n, 2)
11 while n > 0:
12 if curr == n % 2:
13 return False
14 n, curr = divmod(n, 2)
15 return True
16
******************

177. Max Area of Island


******************

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal
or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

Example 1:

Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0


Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

Example 2:

Input: grid = [[0,0,0,0,0,0,0,0]]


Output: 0

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is either 0 or 1.
******************

177. Max Area of Island(C++)


******************

1 // Time: O(m * n)
2 // Space: O(m * n), the max depth of dfs may be m * n
3
4 class Solution {
5 public:
6 int maxAreaOfIsland(vector>& grid) {
7 int result = 0;
8 for (int i = 0; i < grid.size(); ++i) {
9 for (int j = 0; j < grid[0].size(); ++j) {
10 int area = 0;
11 if (dfs(i, j, &grid, &area)) {
12 result = max(result, area);
13 }
14 }
15 }
16 return result;
17 }
18
19 private:
20 bool dfs(const int i, const int j, vector> *grid, int *area) {
21 static const vector> directions{{-1, 0}, { 1, 0},
22 { 0, 1}, { 0, -1}};
23 if (i < 0 || i >= grid->size() ||
24 j < 0 || j >= (*grid)[0].size() ||
25 (*grid)[i][j] <= 0) {
26 return false;
27 }
28 (*grid)[i][j] *= -1;
29 ++(*area);
30 for (const auto& d : directions) {
31 dfs(i + d.first, j + d.second, grid, area);
32 }
33 return true;
34 }
35 };
******************

177. Max Area of Island(Python)


******************

1 # Time: O(m * n)
2 # Space: O(m * n), the max depth of dfs may be m * n
3
4 class Solution(object):
5 def maxAreaOfIsland(self, grid):
6 """
7 :type grid: List[List[int]]
8 :rtype: int
9 """
10 directions = [[-1, 0], [ 1, 0], [ 0, 1], [ 0, -1]]
11
12 def dfs(i, j, grid, area):
13 if not (0 <= i < len(grid) and \
14 0 <= j < len(grid[0]) and \
15 grid[i][j] > 0):
16 return False
17 grid[i][j] *= -1
18 area[0] += 1
19 for d in directions:
20 dfs(i+d[0], j+d[1], grid, area)
21 return True
22
23 result = 0
24 for i in xrange(len(grid)):
25 for j in xrange(len(grid[0])):
26 area = [0]
27 if dfs(i, j, grid, area):
28 result = max(result, area[0])
29 return result
30
***********************

178. Count Binary Substrings


***********************

Give a binary string s , return the number of non-empty substrings that have the same number of0's and 1's, and all the 0's
and all the 1's in these substrings are grouped consecutively.

Substrings that occur multiple times are counted the number of times they occur.

Example 1:

Input: s = "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

Example 2:

Input: s = "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Constraints:

1 <= s.length <= 105


s[i] is either '0' or '1'.
***********************

178. Count Binary Substrings(C++)


***********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countBinarySubstrings(string s) {
7 auto result = 0, prev = 0, curr = 1;
8 for (int i = 1; i < s.length(); ++i) {
9 if (s[i - 1] != s[i]) {
10 result += min(prev, curr);
11 prev = curr, curr = 1;
12 } else {
13 ++curr;
14 }
15 }
16 result += min(prev, curr);
17 return result;
18 }
19 };
***********************

178. Count Binary Substrings(Python)


***********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countBinarySubstrings(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result, prev, curr = 0, 0, 1
11 for i in xrange(1, len(s)):
12 if s[i-1] != s[i]:
13 result += min(prev, curr)
14 prev, curr = curr, 1
15 else:
16 curr += 1
17 result += min(prev, curr)
18 return result
19
******************

179. Degree of an Array


******************

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any
one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray ofnums, that has the same degree as nums.

Example 1:

Input: nums = [1,2,2,3,1]


Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

Input: nums = [1,2,2,3,1,4,2]


Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.

Constraints:

nums.length will be between 1 and 50,000.


nums[i] will be an integer between 0 and 49,999.
******************

179. Degree of an Array(C++)


******************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int findShortestSubArray(vector& nums) {
7 unordered_map left, right;
8 unordered_map counts;
9 for (int i = 0; i < nums.size(); ++i) {
10 if (left.count(nums[i]) == 0) {
11 left[nums[i]] = i;
12 }
13 right[nums[i]] = i;
14 ++counts[nums[i]];
15 }
16 auto degree = max_element(counts.begin(), counts.end(),
17 [](const pair& a,
18 const pair& b) {
19 return a.second < b.second;
20 })->second;
21 auto result = numeric_limits::max();
22 for (const auto& kvp : counts) {
23 if (kvp.second == degree) {
24 result = min(result, right[kvp.first] - left[kvp.first] + 1);
25 }
26 }
27 return result;
28 }
29 };
******************

179. Degree of an Array(Python)


******************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def findShortestSubArray(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: int
12 """
13 counts = collections.Counter(nums)
14 left, right = {}, {}
15 for i, num in enumerate(nums):
16 left.setdefault(num, i)
17 right[num] = i
18 degree = max(counts.values())
19 return min(right[num]-left[num]+1 \
20 for num in counts.keys() \
21 if counts[num] == degree)
22
*******************************

180. Kth Largest Element in a Stream


*******************************

Design a class to find the k th largest element in a stream. Note that it is thek th largest element in the sorted order, not thek th
distinct element.

Implement KthLargest class:

KthLargest(int k, int[] nums)Initializes the object with the integer k and the stream of integers nums.
int add(int val) Returns the element representing the k th largest element in the stream.

Example 1:

Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]

Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8

Constraints:

1 <= k <= 10 4
0 <= nums.length <= 10 4
-104 <= nums[i] <= 10 4
-104 <= val <= 10 4
At most 104 calls will be made to add.
It is guaranteed that there will be at least k elements in the array when you search for thek th element.
*******************************

180. Kth Largest Element in a Stream(C++)


*******************************

1 // Time: O(nlogk)
2 // Space: O(k)
3
4 class KthLargest {
5 public:
6 KthLargest(int k, vector nums) :
7 k_(k) {
8 for (const auto& num : nums) {
9 add(num);
10 }
11 }
12
13 int add(int val) {
14 min_heap_.emplace(val);
15 if (min_heap_.size() > k_) {
16 min_heap_.pop();
17 }
18 return min_heap_.top();
19 }
20
21 private:
22 const int k_;
23 priority_queue, greater> min_heap_;
24 };
25
26 /**
27 * Your KthLargest object will be instantiated and called as such:
28 * KthLargest obj = new KthLargest(k, nums);
29 * int param_1 = obj.add(val);
30 */
31
*******************************

180. Kth Largest Element in a Stream(Python)


*******************************

1 # Time: O(nlogk)
2 # Space: O(k)
3
4 import heapq
5
6
7 class KthLargest(object):
8
9 def __init__(self, k, nums):
10 """
11 :type k: int
12 :type nums: List[int]
13 """
14 self.__k = k
15 self.__min_heap = []
16 for n in nums:
17 self.add(n)
18
19
20 def add(self, val):
21 """
22 :type val: int
23 :rtype: int
24 """
25 heapq.heappush(self.__min_heap, val)
26 if len(self.__min_heap) > self.__k:
27 heapq.heappop(self.__min_heap)
28 return self.__min_heap[0]
29
30
31
*********

181. Max Stack


*********

Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.

Implement the MaxStack class:

MaxStack() Initializes the stack object.


void push(int x) Pushes element x onto the stack.
int pop() Removes the element on top of the stack and returns it.
int top() Gets the element on the top of the stack without removing it.
int peekMax() Retrieves the maximum element in the stack without removing it.
int popMax() Retrieves the maximum element in the stack and removes it. If there is more than one maximum element,
only remove the top-most one.

Example 1:

Input
["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"]
[[], [5], [1], [5], [], [], [], [], [], []]
Output
[null, null, null, null, 5, 5, 1, 5, 1, 5]

Explanation
MaxStack stk = new MaxStack();
stk.push(5); // [5] the top of the stack and the maximum number is 5.
stk.push(1); // [5, 1] the top of the stack is 1, but the maximum is 5.
stk.push(5); // [5, 1, 5] the top of the stack is 5, which is also the maximum, because it is the top most one.
stk.top(); // return 5, [5, 1, 5] the stack did not change.
stk.popMax(); // return 5, [5, 1] the stack is changed now, and the top is different from the max.
stk.top(); // return 1, [5, 1] the stack did not change.
stk.peekMax(); // return 5, [5, 1] the stack did not change.
stk.pop(); // return 1, [5] the top of the stack and the max element is now 5.
stk.top(); // return 5, [5] the stack did not change.

Constraints:

-107 <= x <= 10 7


At most 104 calls will be made to push, pop, top, peekMax, and popMax.
There will be at least one element in the stack when pop, top, peekMax, or popMax is called.

Follow up: Could you come up with a solution that supportsO(1) for each top call and O(logn) for each other call?
*********

181. Max Stack(C++)


*********
1 // Time: push: O(logn)
2 // pop: O(logn)
3 // popMax: O(logn)
4 // top: O(1)
5 // peekMax: O(1)
6 // Space: O(n), n is the number of values in the current stack
7
8 class MaxStack {
9 public:
10 /** initialize your data structure here. */
11 MaxStack() {
12
13 }
14
15 void push(int x) {
16 const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.cbegin()->first + 1;
17 idx_to_val_[idx] = x;
18 val_to_idxs_[x].emplace_back(idx);
19 }
20
21 int pop() {
22 const auto val = idx_to_val_.cbegin()->second;
23 remove(val);
24 return val;
25 }
26
27 int top() {
28 return idx_to_val_.cbegin()->second;
29 }
30
31 int peekMax() {
32 return val_to_idxs_.cbegin()->first;
33 }
34
35 int popMax() {
36 const auto val = val_to_idxs_.cbegin()->first;
37 remove(val);
38 return val;
39 }
40
41 private:
42 void remove(const int val) {
43 const auto idx = val_to_idxs_[val].back();
44 val_to_idxs_[val].pop_back();
45 if (val_to_idxs_[val].empty()) {
46 val_to_idxs_.erase(val);
47 }
48 idx_to_val_.erase(idx);
49 }
50
51 map> idx_to_val_;
52 map, greater> val_to_idxs_;
53 };
54
55 /**
56 * Your MaxStack object will be instantiated and called as such:
57 * MaxStack obj = new MaxStack();
58 * obj.push(x);
59 * int param_2 = obj.pop();
60 * int param_3 = obj.top();
61 * int param_4 = obj.peekMax();
62 * int param_5 = obj.popMax();
63 */
*********

181. Max Stack(Python)


*********

1 # Time: push: O(1)


2 # pop: O(n), there is no built-in SortedDict in python. If applied, it could be reduced to O(logn)
3 # popMax: O(n)
4 # top: O(1)
5 # peekMax: O(1)
6 # Space: O(n), n is the number of values in the current stack
7
8 import collections
9
10
11 class MaxStack(object):
12
13 def __init__(self):
14 """
15 initialize your data structure here.
16 """
17 self.__idx_to_val = collections.defaultdict(int)
18 self.__val_to_idxs = collections.defaultdict(list)
19 self.__top = None
20 self.__max = None
21
22
23 def push(self, x):
24 """
25 :type x: int
26 :rtype: void
27 """
28 idx = self.__val_to_idxs[self.__top][-1]+1 if self.__val_to_idxs else 0
29 self.__idx_to_val[idx] = x
30 self.__val_to_idxs[x].append(idx)
31 self.__top = x
32 self.__max = max(self.__max, x)
33
34
35 def pop(self):
36 """
37 :rtype: int
38 """
39 val = self.__top
40 self.__remove(val)
41 return val
42
43
44 def top(self):
45 """
46 :rtype: int
47 """
48 return self.__top
49
50
51 def peekMax(self):
52 """
53 :rtype: int
54 """
55 return self.__max
56
57
58 def popMax(self):
59 """
60 :rtype: int
61 """
62 val = self.__max
63 self.__remove(val)
64 return val
65
66
67 def __remove(self, val):
68 idx = self.__val_to_idxs[val][-1]
69 self.__val_to_idxs[val].pop()
70 if not self.__val_to_idxs[val]:
71 del self.__val_to_idxs[val]
72 del self.__idx_to_val[idx]
73 if val == self.__top:
74 self.__top = self.__idx_to_val[max(self.__idx_to_val.keys())] if self.__idx_to_val else None
75 if val == self.__max:
76 self.__max = max(self.__val_to_idxs.keys()) if self.__val_to_idxs else None
77
78
79
**************************

182. 1-bit and 2-bit Characters


**************************

We have two special characters:

The first character can be represented by one bit 0.


The second character can be represented by two bits (10 or 11).

Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.

Example 1:

Input: bits = [1,0,0]


Output: true
Explanation: The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.

Example 2:

Input: bits = [1,1,1,0]


Output: false
Explanation: The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.

Constraints:

1 <= bits.length <= 1000


bits[i] is either 0 or 1.
**************************

182. 1-bit and 2-bit Characters(C++)


**************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isOneBitCharacter(vector& bits) {
7 auto parity = 0;
8 for (int i = static_cast(bits.size()) - 2;
9 i >= 0 && bits[i]; --i) {
10 parity ^= bits[i];
11 }
12 return parity == 0;
13 }
14 };
**************************

182. 1-bit and 2-bit Characters(Python)


**************************

1 # Time: O(n)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def isOneBitCharacter(self, bits):
7 """
8 :type bits: List[int]
9 :rtype: bool
10 """
11 parity = 0
12 for i in reversed(xrange(len(bits)-1)):
13 if bits[i] == 0:
14 break
15 parity ^= bits[i]
16 return parity == 0
17
**************************

183. Longest Word in Dictionary


**************************

Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one
character at a time by other words in words.

If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no
answer, return the empty string.

Example 1:

Input: words = ["w","wo","wor","worl","world"]


Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".

Example 2:

Input: words = ["a","banana","app","appl","ap","apply","apple"]


Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "ap

Constraints:

1 <= words.length <= 1000


1 <= words[i].length <= 30
words[i] consists of lowercase English letters.
**************************

183. Longest Word in Dictionary(C++)


**************************
1 // Time: O(n), n is the total sum of the lengths of words
2 // Space: O(t), t is the number of nodes in trie
3
4 class Solution {
5 public:
6 string longestWord(vector& words) {
7 TrieNode trie;
8 for (int i = 0; i < words.size(); ++i) {
9 trie.Insert(words[i], i);
10 }
11
12 // DFS
13 stack stk;
14 for (const auto& node : trie.leaves) {
15 if (node) {
16 stk.emplace(node);
17 }
18 }
19
20 string result;
21 while (!stk.empty()) {
22 const auto curr = stk.top(); stk.pop();
23 if (curr->isString) {
24 const auto& word = words[curr->val];
25 if (word.size() > result.size() || (word.size() == result.size() && word < result)) {
26 result = word;
27 }
28 for (const auto& node : curr->leaves) {
29 if (node) {
30 stk.emplace(node);
31 }
32 }
33 }
34 }
35 return result;
36 }
37
38 private:
39 struct TrieNode {
40 bool isString;
41 int val;
42 vector leaves;
43
44 TrieNode() : isString{false}, val{0}, leaves(26) {}
45
46 void Insert(const string& s, const int i) {
47 auto* p = this;
48 for (const auto& c : s) {
49 if (!p->leaves[c - 'a']) {
50 p->leaves[c - 'a'] = new TrieNode;
51 }
52 p = p->leaves[c - 'a'];
53 }
54 p->isString = true;
55 p->val = i;
56 }
57
58 ~TrieNode() {
59 for (auto& node : leaves) {
60 if (node) {
61 delete node;
62 }
63 }
64 }
65 };
66 };
**************************

183. Longest Word in Dictionary(Python)


**************************

1 # Time: O(n), n is the total sum of the lengths of words


2 # Space: O(t), t is the number of nodes in trie
3
4 from collections import defaultdict
5 from operator import getitem
6
7
8 class Solution(object):
9 def longestWord(self, words):
10 """
11 :type words: List[str]
12 :rtype: str
13 """
14 _trie = lambda: defaultdict(_trie)
15 trie = _trie()
16 for i, word in enumerate(words):
17 reduce(getitem, word, trie)["_end"] = i
18
19 # DFS
20 stack = trie.values()
21 result = ""
22 while stack:
23 curr = stack.pop()
24 if "_end" in curr:
25 word = words[curr["_end"]]
26 if len(word) > len(result) or (len(word) == len(result) and word < result):
27 result = word
28 stack += [curr[letter] for letter in curr if letter != "_end"]
29 return result
30
****************

184. Find Pivot Index


****************

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbersstrictly to the left of the index is equal to the sum of all the
numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is0 because there are no elements to the left. This also applies
to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = [1,7,3,6,5,6]


Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11

Example 2:

Input: nums = [1,2,3]


Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Example 3:

Input: nums = [2,1,-1]


Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0

Constraints:

1 <= nums.length <= 10 4


-1000 <= nums[i] <= 1000
****************

184. Find Pivot Index(C++)


****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int pivotIndex(vector& nums) {
7 const auto total = accumulate(nums.begin(), nums.end(), 0);
8 auto left_sum = 0;
9 for (int i = 0; i < nums.size(); ++i) {
10 if (left_sum == (total - left_sum - nums[i])) {
11 return i;
12 }
13 left_sum += nums[i];
14 }
15 return -1;
16 }
17 };
****************

184. Find Pivot Index(Python)


****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def pivotIndex(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 total = sum(nums)
11 left_sum = 0
12 for i, num in enumerate(nums):
13 if left_sum == (total-left_sum-num):
14 return i
15 left_sum += num
16 return -1
17
18
******************

185. Max Area of Island


******************

An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel
image[sr][sc].

To perform a flood fill, consider the starting pixel, plus any pixels connected4-directionally to the starting pixel of the same
color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on.
Replace the color of all of the aforementioned pixels with newColor.

Return the modified image after performing the flood fill.

Example 1:

Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2


Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same c
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.

Example 2:

Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2


Output: [[2,2,2],[2,2,2]]

Constraints:

m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], newColor < 2 16
0 <= sr < m
0 <= sc < n
******************

185. Max Area of Island(C++)


******************

1 // Time: O(m * n)
2 // Space: O(m * n)
3
4 class Solution {
5 public:
6 vector> floodFill(vector>& image, int sr, int sc, int newColor) {
7 int color = image[sr][sc];
8 if (color == newColor) return image;
9 dfs(&image, sr, sc, newColor, color);
10 return image;
11 }
12
13 private:
14 void dfs(vector> *image, int r, int c, int newColor, int color) {
15 static const vector> directions{{-1, 0}, { 1, 0},
16 { 0, 1}, { 0, -1}};
17 if (r < 0 || r >= image->size() ||
18 c < 0 || c >= (*image)[0].size() ||
19 (*image)[r][c] != color) {
20 return;
21 }
22 (*image)[r][c] = newColor;
23 for (const auto& d : directions) {
24 dfs(image, r + d.first, c + d.second, newColor, color);
25 }
26 }
27 };
******************

185. Max Area of Island(Python)


******************

1 # Time: O(m * n)
2 # Space: O(m * n)
3
4 class Solution(object):
5 def floodFill(self, image, sr, sc, newColor):
6 """
7 :type image: List[List[int]]
8 :type sr: int
9 :type sc: int
10 :type newColor: int
11 :rtype: List[List[int]]
12 """
13 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
14
15 def dfs(image, r, c, newColor, color):
16 if not (0 <= r < len(image) and \
17 0 <= c < len(image[0]) and \
18 image[r][c] == color):
19 return
20
21 image[r][c] = newColor
22 for d in directions:
23 dfs(image, r+d[0], c+d[1], newColor, color)
24
25 color = image[sr][sc]
26 if color == newColor: return image
27 dfs(image, sr, sc, newColor, color)
28 return image
29
*******************

186. Sentence Similarity


*******************

We can represent a sentence as an array of words, for example, the sentence"I am happy with leetcode" can be represented as
arr = ["I","am",happy","with","leetcode"] .

Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairssimilarPairs
where similarPairs[i] = [x i, y i] indicates that the two words x i and y i are similar.

Return true if sentence1 and sentence2 are similar, or false if they are not similar.

Two sentences are similar if:

They have the same length (i.e., the same number of words)
sentence1[i] and sentence2[i] are similar.

Notice that a word is always similar to itself, also notice that the similarity relation is not transitive. For example, if the words
a and b are similar, and the words b and c are similar, a and c are not necessarily similar.

Example 1:

Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["


Output: true
Explanation: The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.

Example 2:

Input: sentence1 = ["great"], sentence2 = ["great"], similarPairs = []


Output: true
Explanation: A word is similar to itself.

Example 3:

Input: sentence1 = ["great"], sentence2 = ["doubleplus","good"], similarPairs = [["great","doubleplus"]]


Output: false
Explanation: As they don't have the same length, we return false.

Constraints:

1 <= sentence1.length, sentence2.length <= 1000


1 <= sentence1[i].length, sentence2[i].length <= 20
sentence1[i] and sentence2[i] consist of English letters.
0 <= similarPairs.length <= 1000
similarPairs[i].length == 2
1 <= x i.length, y i.length <= 20
xiand y i consist of lower-case and upper-case English letters.
All the pairs (xi, y i) are distinct.
*******************

186. Sentence Similarity(C++)


*******************

1 // Time: O(n + p)
2 // Space: O(p)
3
4 class Solution {
5 public:
6 bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) {
7 if (words1.size() != words2.size()) {
8 return false;
9 }
10 unordered_set, PairHash> lookup;
11 for (const auto& pair : pairs) {
12 lookup.emplace(pair.first, pair.second);
13 lookup.emplace(pair.second, pair.first);
14 }
15 for (int i = 0; i < words1.size(); ++i) {
16 if (words1[i] != words2[i] &&
17 !lookup.count(make_pair(words1[i], words2[i]))) {
18 return false;
19 }
20 }
21 return true;
22 }
23
24 private:
25 template
26 struct PairHash {
27 size_t operator()(const pair& p) const {
28 size_t seed = 0;
29 seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
30 seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
31 return seed;
32 }
33 };
34 };
*******************

186. Sentence Similarity(Python)


*******************

1 # Time: O(n + p)
2 # Space: O(p)
3
4 import itertools
5
6
7 class Solution(object):
8 def areSentencesSimilar(self, words1, words2, pairs):
9 """
10 :type words1: List[str]
11 :type words2: List[str]
12 :type pairs: List[List[str]]
13 :rtype: bool
14 """
15 if len(words1) != len(words2): return False
16 lookup = set(map(tuple, pairs))
17 return all(w1 == w2 or (w1, w2) in lookup or (w2, w1) in lookup \
18 for w1, w2 in itertools.izip(words1, words2))
19
****************************************

187. Find Smallest Letter Greater Than Target


****************************************

Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in
the array that is larger than target.

Note that the letters wrap around.

For example, if target == 'z' and letters == ['a', 'b'] , the answer is 'a'.

Example 1:

Input: letters = ["c","f","j"], target = "a"


Output: "c"

Example 2:

Input: letters = ["c","f","j"], target = "c"


Output: "f"

Example 3:

Input: letters = ["c","f","j"], target = "d"


Output: "f"

Example 4:

Input: letters = ["c","f","j"], target = "g"


Output: "j"

Example 5:

Input: letters = ["c","f","j"], target = "j"


Output: "c"

Constraints:

2 <= letters.length <= 104


letters[i] is a lowercase English letter.
letters is sorted in non-decreasing order.
letters contains at least two different characters.
target is a lowercase English letter.
****************************************

187. Find Smallest Letter Greater Than Target(C++)


****************************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 char nextGreatestLetter(vector& letters, char target) {
7 const auto cit = upper_bound(letters.cbegin(), letters.cend(), target);
8 return cit != letters.cend() ? *cit : letters.front();
9 }
10 };
****************************************

187. Find Smallest Letter Greater Than Target(Python)


****************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import bisect
5
6
7 class Solution(object):
8 def nextGreatestLetter(self, letters, target):
9 """
10 :type letters: List[str]
11 :type target: str
12 :rtype: str
13 """
14 i = bisect.bisect_right(letters, target)
15 return letters[0] if i == len(letters) else letters[i]
16
************************

188. Min Cost Climbing Stairs


************************

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either
climb one or two steps.

You can either start from the step with index0, or the step with index1.

Return the minimum cost to reach the top of the floor.

Example 1:

Input: cost = [10,15,20]


Output: 15
Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top.

Example 2:

Input: cost = [1,100,1,1,1,100,1,1,100,1]


Output: 6
Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3].

Constraints:

2 <= cost.length <= 1000


0 <= cost[i] <= 999
************************

188. Min Cost Climbing Stairs(C++)


************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minCostClimbingStairs(vector& cost) {
7 vector dp(3);
8 for (int i = cost.size() - 1; i >= 0; --i) {
9 dp[i % 3] = cost[i] +
10 min(dp[(i + 1) % 3],
11 dp[(i + 2) % 3]);
12 }
13 return min(dp[0], dp[1]);
14 }
15 };
************************

188. Min Cost Climbing Stairs(Python)


************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minCostClimbingStairs(self, cost):
6 """
7 :type cost: List[int]
8 :rtype: int
9 """
10 dp = [0] * 3
11 for i in reversed(xrange(len(cost))):
12 dp[i%3] = cost[i] + min(dp[(i+1)%3], dp[(i+2)%3])
13 return min(dp[0], dp[1])
14
***************************************

189. Largest Number At Least Twice of Others


***************************************

You are given an integer array nums where the largest integer is unique.

Determine whether the largest element in the array isat least twice as much as every other number in the array. If it is,
return the index of the largest element, or return -1 otherwise.

Example 1:

Input: nums = [3,6,1,0]


Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]


Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.

Example 3:

Input: nums = [1]


Output: 0
Explanation: 1 is trivially at least twice the value as any other number because there are no other numbers.

Constraints:

1 <= nums.length <= 50


0 <= nums[i] <= 100
The largest element in nums is unique.
***************************************

189. Largest Number At Least Twice of Others(C++)


***************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int dominantIndex(vector& nums) {
7 const auto result = distance(nums.begin(), max_element(nums.begin(),nums.end()));
8 for (int i = 0; i < nums.size(); ++i) {
9 if (i != result && 2 * nums[i] > nums[result]) {
10 return -1;
11 }
12 }
13 return result;
14 }
15 };
***************************************

189. Largest Number At Least Twice of Others(Python)


***************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def dominantIndex(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 m = max(nums)
11 if all(m >= 2*x for x in nums if x != m):
12 return nums.index(m)
13 return -1
14
************************

190. Shortest Completing Word


************************

Given a string licensePlate and an array of strings words, find the shortest completing word in words.

A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and
treat letters as case insensitive. If a letter appears more than once inlicensePlate, then it must appear in the word the same
number of times or more.

For example, if licensePlate = "aBc 12c" , then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words
are "abccdef", "caaacab", and "cbca".

Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortestcompleting
words, return the first one that occurs in words.

Example 1:

Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]


Output: "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.

Example 2:

Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]


Output: "pest"
Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. T

Example 3:

Input: licensePlate = "Ah71752", words = ["suggest","letter","of","husband","easy","education","drug","prevent","writer","old"]


Output: "husband"

Example 4:

Input: licensePlate = "OgEu755", words = ["enough","these","play","wide","wonder","box","arrive","money","tax","thus"]


Output: "enough"

Example 5:

Input: licensePlate = "iMSlpe4", words = ["claim","consumer","student","camera","public","never","wonder","simple","thought","use"]


Output: "simple"

Constraints:
1 <= licensePlate.length <= 7
licensePlate contains digits, letters (uppercase or lowercase), or space ' '.
1 <= words.length <= 1000
1 <= words[i].length <= 15
words[i] consists of lower case English letters.
************************

190. Shortest Completing Word(C++)


************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string shortestCompletingWord(string licensePlate, vector& words) {
7 string result;
8 const auto& counter = counts(licensePlate);
9 for (const auto& word : words) {
10 if ((result.empty() || word.length() < result.length()) &&
11 contains(counter, word)) {
12 result = word;
13 }
14 }
15 return result;
16 }
17
18 private:
19 bool contains(const vector& counter1, const string& w2) const {
20 const auto& counter2 = counts(w2);
21 for (int i = 0; i < counter2.size(); ++i) {
22 if (counter1[i] > counter2[i]) {
23 return false;
24 }
25 }
26 return true;
27 }
28
29 vector counts(const string& s) const {
30 vector count(26);
31 for (const auto& c : s) {
32 if (isalpha(c)) {
33 ++count[tolower(c) - 'a'];
34 }
35 }
36 return count;
37 }
38 };
************************

190. Shortest Completing Word(Python)


************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def shortestCompletingWord(self, licensePlate, words):
9 """
10 :type licensePlate: str
11 :type words: List[str]
12 :rtype: str
13 """
14 def contains(counter1, w2):
15 c2 = collections.Counter(w2.lower())
16 c2.subtract(counter1)
17 return all(map(lambda x: x >= 0, c2.values()))
18
19 result = None
20 counter = collections.Counter(c.lower() for c in licensePlate if c.isalpha())
21 for word in words:
22 if (result is None or (len(word) < len(result))) and \
23 contains(counter, word):
24 result = word
25 return result
26
********************

191. Bold Words in String


********************

Given an array of keywords words and a string s , make all appearances of all keywords words[i] in s bold. Any letters between
<b> and </b> tags become bold.

Return s after adding the bold tags. The returned string should use the least number of tags possible, and the tags should
form a valid combination.

Example 1:

Input: words = ["ab","bc"], s = "aabcd"


Output: "a<b>abc</b>d"
Explanation: Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect.

Example 2:

Input: words = ["ab","cb"], s = "aabcd"


Output: "a<b>ab</b>cd"

Constraints:

1 <= s.length <= 500


0 <= words.length <= 50
1 <= words[i].length <= 10
s and words[i] consist of lowercase English letters.

Note: This question is the same as 616:https://leetcode.com/problems/add-bold-tag-in-string/


********************

191. Bold Words in String(C++)


********************

1 // Time: O(n * l), n is the length of S, l is the average length of words


2 // Space: O(t) , t is the size of trie
3
4 class Solution {
5 public:
6 string boldWords(vector& words, string S) {
7 TrieNode trie;
8 for (const auto& word : words) {
9 trie.Insert(word);
10 }
11
12 vector lookup(S.length());
13 for (int i = 0; i < S.length(); ++i) {
14 auto curr = ≜
15 int k = i - 1;
16 for (int j = i; j < S.length(); ++j) {
17 if (!curr->leaves[S[j] - 'a']) {
18 break;
19 }
20 curr = curr->leaves[S[j] - 'a'];
21 if (curr->isString) {
22 k = j;
23 }
24 }
25 fill(lookup.begin() + i, lookup.begin() + k + 1, true);
26 }
27
28 string result;
29 for (int i = 0; i < S.length(); ++i) {
30 if (lookup[i] && (i == 0 || !lookup[i - 1])) {
31 result += "";
32 }
33 result.push_back(S[i]);
34 if (lookup[i] && (i == (S.length() - 1) || !lookup[i + 1])) {
35 result += "";
36 }
37 }
38 return result;
39 }
40
41 private:
42 struct TrieNode {
43 bool isString;
44 vector leaves;
45
46 TrieNode() : isString{false}, leaves(26) {}
47
48 void Insert(const string& s) {
49 auto* p = this;
50 for (const auto& c : s) {
51 if (!p->leaves[c - 'a']) {
52 p->leaves[c - 'a'] = new TrieNode;
53 }
54 p = p->leaves[c - 'a'];
55 }
56 p->isString = true;
57 }
58
59 ~TrieNode() {
60 for (auto& node : leaves) {
61 if (node) {
62 delete node;
63 }
64 }
65 }
66 };
67 };
68
69
70 // Time: O(n * d * l), l is the average length of words
71 // Space: O(n)
72 class Solution2 {
73 public:
74 string boldWords(vector& words, string S) {
75 vector lookup(S.length());
76 for (const auto& d: words) {
77 auto pos = -1;
78 while ((pos = S.find(d, pos + 1)) != string::npos) {
79 fill(lookup.begin() + pos, lookup.begin() + pos + d.length(), true);
80 }
81 }
82 string result;
83 for (int i = 0; i < S.length(); ++i) {
84 if (lookup[i] && (i == 0 || !lookup[i - 1])) {
85 result += "";
86 }
87 result.push_back(S[i]);
88 if (lookup[i] && (i == (S.length() - 1) || !lookup[i + 1])) {
89 result += "";
90 }
91 }
92 return result;
93 }
94 };
********************

191. Bold Words in String(Python)


********************
1 # Time: O(n * l), n is the length of S, l is the average length of words
2 # Space: O(t) , t is the size of trie
3
4 import collections
5 import functools
6
7
8 class Solution(object):
9 def boldWords(self, words, S):
10 """
11 :type words: List[str]
12 :type S: str
13 :rtype: str
14 """
15 _trie = lambda: collections.defaultdict(_trie)
16 trie = _trie()
17 for i, word in enumerate(words):
18 functools.reduce(dict.__getitem__, word, trie).setdefault("_end")
19
20 lookup = [False] * len(S)
21 for i in xrange(len(S)):
22 curr = trie
23 k = -1
24 for j in xrange(i, len(S)):
25 if S[j] not in curr:
26 break
27 curr = curr[S[j]]
28 if "_end" in curr:
29 k = j
30 for j in xrange(i, k+1):
31 lookup[j] = True
32
33 result = []
34 for i in xrange(len(S)):
35 if lookup[i] and (i == 0 or not lookup[i-1]):
36 result.append("")
37 result.append(S[i])
38 if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
39 result.append("")
40 return "".join(result)
41
42
43 # Time: O(n * d * l), l is the average length of words
44 # Space: O(n)
45 class Solution2(object):
46 def boldWords(self, words, S):
47 """
48 :type words: List[str]
49 :type S: str
50 :rtype: str
51 """
52 lookup = [0] * len(S)
53 for d in words:
54 pos = S.find(d)
55 while pos != -1:
56 lookup[pos:pos+len(d)] = [1] * len(d)
57 pos = S.find(d, pos+1)
58
59 result = []
60 for i in xrange(len(S)):
61 if lookup[i] and (i == 0 or not lookup[i-1]):
62 result.append("")
63 result.append(S[i])
64 if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
65 result.append("")
66 return "".join(result)
67
*********************

192. Find Anagram Mappings


*********************

You are given two integer arrays nums1 and nums2 where nums2 is an anagram of nums1. Both arrays may contain duplicates.

Return an index mapping array mapping from nums1 to nums2 where mapping[i] = j means the ith element in nums1 appears in
nums2 at index j. If there are multiple answers, return any of them.

An array a is an anagram of an array b means b is made by randomizing the order of the elements ina.

Example 1:

Input: nums1 = [12,28,46,32,50], nums2 = [50,12,32,46,28]


Output: [1,4,3,2,0]
Explanation: As mapping[0] = 1 because the 0th element of nums1 appears at nums2[1], and mapping[1] = 4 because the 1st element of nums1 appe

Example 2:

Input: nums1 = [84,46], nums2 = [84,46]


Output: [0,1]

Constraints:

1 <= nums1.length <= 100


nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 10 5
nums2 is an anagram of nums1.
*********************

192. Find Anagram Mappings(C++)


*********************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector anagramMappings(vector& A, vector& B) {
7 unordered_map> lookup;
8 for (int i = 0; i < B.size(); ++i) {
9 lookup[B[i]].emplace(i);
10 }
11 vector result;
12 for (const auto& n : A) {
13 result.emplace_back(lookup[n].back());
14 lookup[n].pop();
15 }
16 return result;
17 }
18 };
*********************

192. Find Anagram Mappings(Python)


*********************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def anagramMappings(self, A, B):
9 """
10 :type A: List[int]
11 :type B: List[int]
12 :rtype: List[int]
13 """
14 lookup = collections.defaultdict(collections.deque)
15 for i, n in enumerate(B):
16 lookup[n].append(i)
17 result = []
18 for n in A:
19 result.append(lookup[n].popleft())
20 return result
21
*************************************************

193. Prime Number of Set Bits in Binary Representation


*************************************************

Given two integers left and right, return the count of numbers in the inclusive range[left, right] having a prime number of set bits
in their binary representation.

Recall that the number of set bits an integer has is the number of1's present when written in binary.

For example, 21 written in binary is 10101 which has 3 set bits.

Example 1:

Input: left = 6, right = 10


Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits , 2 is prime)
10->1010 (2 set bits , 2 is prime)

Example 2:

Input: left = 10, right = 15


Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)

Constraints:

1 <= left <= right <= 10 6


0 <= right - left <= 10 4
*************************************************

193. Prime Number of Set Bits in Binary


Representation(C++)
*************************************************

1 // Time: O(log(R - L)) = O(1)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countPrimeSetBits(int L, int R) {
7 static const unordered_set primes{2, 3, 5, 7, 11, 13, 17, 19};
8 int result = 0;
9 for (int i = L; i <= R; ++i) {
10 result += primes.count(bitCount(i));
11 }
12 return result;
13 }
14
15 private:
16 int bitCount(uint32_t n) {
17 int count = 0;
18 for (; n; n &= n - 1) {
19 ++count;
20 }
21 return count;
22 }
23 };
*************************************************

193. Prime Number of Set Bits in Binary


Representation(Python)
*************************************************

1 # Time: O(log(R - L)) = O(1)


2 # Space: O(1)
3
4 class Solution(object):
5 def countPrimeSetBits(self, L, R):
6 """
7 :type L: int
8 :type R: int
9 :rtype: int
10 """
11 def bitCount(n):
12 result = 0
13 while n:
14 n &= n-1
15 result += 1
16 return result
17
18 primes = {2, 3, 5, 7, 11, 13, 17, 19}
19 return sum(bitCount(i) in primes
20 for i in xrange(L, R+1))
21
***************

194. Toeplitz Matrix


***************

Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]


Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]


Output: false
Explanation:
The diagonal "[1, 2]" has different elements.

Constraints:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99

Follow up:
What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix
into the memory at once?
What if the matrix is so large that you can only load up a partial row into the memory at once?
***************

194. Toeplitz Matrix(C++)


***************

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isToeplitzMatrix(vector>& matrix) {
7 for (int i = 0; i < matrix.size(); ++i) {
8 for (int j = 0; j < matrix[i].size(); ++j) {
9 if (i != 0 && j != 0 &&
10 matrix[i - 1][j - 1] != matrix[i][j]) {
11 return false;
12 }
13 }
14 }
15 return true;
16 }
17 };
***************

194. Toeplitz Matrix(Python)


***************

1 # Time: O(m * n)
2 # Space: O(1)
3
4 class Solution(object):
5 def isToeplitzMatrix(self, matrix):
6 """
7 :type matrix: List[List[int]]
8 :rtype: bool
9 """
10 return all(i == 0 or j == 0 or matrix[i-1][j-1] == val
11 for i, row in enumerate(matrix)
12 for j, val in enumerate(row))
13
14
15 class Solution2(object):
16 def isToeplitzMatrix(self, matrix):
17 """
18 :type matrix: List[List[int]]
19 :rtype: bool
20 """
21 for row_index, row in enumerate(matrix):
22 for digit_index, digit in enumerate(row):
23 if not row_index or not digit_index:
24 continue
25 if matrix[row_index - 1][digit_index - 1] != digit:
26 return False
27 return True
28
*****************

195. Jewels and Stones


*****************

You're given strings jewels representing the types of stones that are jewels, andstones representing the stones you have.
Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"


Output: 3

Example 2:

Input: jewels = "z", stones = "ZZ"


Output: 0

Constraints:

1 <= jewels.length, stones.length <= 50


jewels and stones consist of only English letters.
All the characters of jewels are unique.
*****************

195. Jewels and Stones(C++)


*****************

1 // Time: O(m + n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int numJewelsInStones(string J, string S) {
7 unordered_set lookup;
8 for (const auto& j : J) {
9 lookup.emplace(j);
10 }
11 int result = 0;
12 for (const auto& s : S) {
13 result += lookup.count(s);
14 }
15 return result;
16 }
17 };
*****************

195. Jewels and Stones(Python)


*****************

1 # Time: O(m + n)
2 # Space: O(n)
3
4 class Solution(object):
5 def numJewelsInStones(self, J, S):
6 """
7 :type J: str
8 :type S: str
9 :rtype: int
10 """
11 lookup = set(J)
12 return sum(s in lookup for s in S)
13
14
**********************************

196. Minimum Distance Between BST Nodes


**********************************

Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes
in the tree.

Example 1:

Input: root = [4,2,6,1,3]


Output: 1

Example 2:

Input: root = [1,0,48,null,null,12,49]


Output: 1

Constraints:

The number of nodes in the tree is in the range[2, 100].


0 <= Node.val <= 10 5
Note: This question is the same as 530:https://leetcode.com/problems/minimum-absolute-difference-in-bst/
**********************************

196. Minimum Distance Between BST Nodes(C++)


**********************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int minDiffInBST(TreeNode* root) {
16 int prev = numeric_limits::min();
17 int result = numeric_limits::max();
18 dfs(root, &prev, &result);
19 return result;
20 }
21
22 private:
23 void dfs(TreeNode* node, int *prev, int *result) {
24 if (!node) {
25 return;
26 }
27 dfs(node->left, prev, result);
28 if (*prev != numeric_limits::min()) {
29 *result = min(*result, node->val - *prev);
30 }
31 *prev = node->val;
32 dfs(node->right, prev, result);
33 }
34 };
**********************************

196. Minimum Distance Between BST Nodes(Python)


**********************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class Solution(object):
5 def minDiffInBST(self, root):
6 """
7 :type root: TreeNode
8 :rtype: int
9 """
10 def dfs(node):
11 if not node:
12 return
13 dfs(node.left)
14 self.result = min(self.result, node.val-self.prev)
15 self.prev = node.val
16 dfs(node.right)
17
18 self.prev = float('-inf')
19 self.result = float('inf')
20 dfs(root)
21 return self.result
22
23
***********************

197. Letter Case Permutation


***********************

Given a string s , we can transform every letter individually to be lowercase or uppercase to create another string.

Return a list of all possible strings we could create. You can return the output in any order.

Example 1:

Input: s = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]

Example 2:

Input: s = "3z4"
Output: ["3z4","3Z4"]

Example 3:

Input: s = "12345"
Output: ["12345"]

Example 4:

Input: s = "0"
Output: ["0"]

Constraints:

s will be a string with length between 1 and 12.


s will consist only of letters or digits.
***********************

197. Letter Case Permutation(C++)


***********************

1 // Time: O(n * 2^n)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector letterCasePermutation(string S) {
7 vector result{""};
8 for (const auto& c : S) {
9 if (isalpha(c)) {
10 const auto& size = result.size();
11 for (int i = 0; i < size; ++i) {
12 result.emplace_back(result[i]);
13 result[i] += tolower(c);
14 result.back() += toupper(c);
15 }
16 } else {
17 for (auto &s : result) {
18 s += c;
19 }
20 }
21 }
22 return result;
23 }
24 };
***********************

197. Letter Case Permutation(Python)


***********************

1 # Time: O(n * 2^n)


2 # Space: O(n * 2^n)
3
4 class Solution(object):
5 def letterCasePermutation(self, S):
6 """
7 :type S: str
8 :rtype: List[str]
9 """
10 result = [[]]
11 for c in S:
12 if c.isalpha():
13 for i in xrange(len(result)):
14 result.append(result[i][:])
15 result[i].append(c.lower())
16 result[-1].append(c.upper())
17 else:
18 for s in result:
19 s.append(c)
20 return map("".join, result)
21
**************

198. Rotated Digits


**************

An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different fromx .
Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. For example:

0, 1, and 8 rotate to themselves,


2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words,2 or 5 gets mirrored),
6 and 9 rotate to each other, and
the rest of the numbers do not rotate to any other number and become invalid.

Given an integer n, return the number of good integers in the range [1, n].

Example 1:

Input: n = 10
Output: 4
Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

Example 2:

Input: n = 1
Output: 0

Example 3:

Input: n = 2
Output: 1

Constraints:

1 <= n <= 10 4
**************

198. Rotated Digits(C++)


**************

1 // Time: O(logn)
2 // Space: O(logn)
3
4 // memoization (top-down dp)
5 class Solution {
6 private:
7 template
8 struct TupleHash {
9 size_t operator()(const tuple& p) const {
10 size_t seed = 0;
11 A a; B b; C c;
12 tie(a, b, c) = p;
13 seed ^= std::hash{}(a) + 0x9e3779b9 + (seed<<6) + (seed>>2);
14 seed ^= std::hash{}(b) + 0x9e3779b9 + (seed<<6) + (seed>>2);
15 seed ^= std::hash{}(c) + 0x9e3779b9 + (seed<<6) + (seed>>2);
16 return seed;
17 }
18 };
19
20 public:
21 int rotatedDigits(int N) {
22 vector A;
23 for (; N; N /= 10) {
24 A.emplace_back(N % 10);
25 }
26 reverse(A.begin(), A.end());
27 unordered_map, int, TupleHash> lookup;
28 return dp(A, 0, true, false, &lookup);
29 }
30
31 private:
32 int dp(const vector& A, int i, bool is_prefix_equal, bool is_good,
33 unordered_map, int, TupleHash> *lookup) {
34 if (i == A.size()) {
35 return static_cast(is_good);
36 }
37 if (!lookup->count(make_tuple(i, is_prefix_equal, is_good))) {
38 const auto& ceil = is_prefix_equal ? A[i] + 1 : 10;
39 int result = 0;
40 for (int d = 0; d < ceil; ++d) {
41 if (invalid.count(d)) continue;
42 result += dp(A, i + 1,
43 is_prefix_equal && d == A[i],
44 is_good || diff.count(d),
45 lookup);
46 }
47 (*lookup)[make_tuple(i, is_prefix_equal, is_good)] = result;
48 }
49 return (*lookup)[make_tuple(i, is_prefix_equal, is_good)];
50 }
51
52 const unordered_set invalid = {3, 4, 7};
53 const unordered_set diff = {2, 5, 6, 9};
54 };
55
56 // Time: O(n)
57 // Space: O(n)
58 class Solution2 {
59 public:
60 int rotatedDigits(int N) {
61 enum State {INVALID, SAME, DIFF};
62 const vector same = {0, 1, 8};
63 const vector diff = {2, 5, 6, 9};
64 vector dp(N + 1);
65 dp[0] = SAME;
66 for (int i = 0; 10 * i <= N; ++i) {
67 if (dp[i] != INVALID) {
68 for (const auto& j : same) {
69 if (i * 10 + j <= N) {
70 dp[i * 10 + j] = max(SAME, dp[i]);
71 }
72 }
73 for (const auto& j : diff) {
74 if (i * 10 + j <= N) {
75 dp[i * 10 + j] = DIFF;
76 }
77 }
78 }
79 }
80 return count(dp.cbegin(), dp.cend(), DIFF);
81 }
82 };
83
84 // Time: O(nlogn) = O(n), because O(logn) = O(32) by this input
85 // Space: O(logn) = O(1)
86 class Solution3 {
87 public:
88 int rotatedDigits(int N) {
89 const unordered_set invalid = {'3', '4', '7'};
90 const unordered_set diff = {'2', '5', '6', '9'};
91 int result = 0;
92 for (int i = 0; i <= N; ++i){
93 string s(to_string(i));
94 unordered_set lookup(s.begin(),s.end());
95 if (intersect(invalid, lookup)) {
96 continue;
97 }
98 if (intersect(diff, lookup)) {
99 ++result;
100 }
101 }
102 return result;
103 }
104
105 private:
106 template
107 bool intersect(const unordered_set& a, const unordered_set& b) {
108 if (a.size() > b.size()) {
109 return intersect(b, a);
110 }
111 return any_of(a.cbegin(), a.cend(),
112 [&b](const T& e) {
113 return b.count(e);
114 });
115 }
116 };
**************

198. Rotated Digits(Python)


**************
1 # Time: O(logn)
2 # Space: O(logn)
3
4 class Solution(object):
5 def rotatedDigits(self, N):
6 """
7 :type N: int
8 :rtype: int
9 """
10 A = map(int, str(N))
11 invalid, diff = set([3, 4, 7]), set([2, 5, 6, 9])
12 def dp(A, i, is_prefix_equal, is_good, lookup):
13 if i == len(A): return int(is_good)
14 if (i, is_prefix_equal, is_good) not in lookup:
15 result = 0
16 for d in xrange(A[i]+1 if is_prefix_equal else 10):
17 if d in invalid: continue
18 result += dp(A, i+1,
19 is_prefix_equal and d == A[i],
20 is_good or d in diff,
21 lookup)
22 lookup[i, is_prefix_equal, is_good] = result
23 return lookup[i, is_prefix_equal, is_good]
24
25 lookup = {}
26 return dp(A, 0, True, False, lookup)
27
28
29 # Time: O(n)
30 # Space: O(n)
31 class Solution2(object):
32 def rotatedDigits(self, N):
33 """
34 :type N: int
35 :rtype: int
36 """
37 INVALID, SAME, DIFF = 0, 1, 2
38 same, diff = [0, 1, 8], [2, 5, 6, 9]
39 dp = [0] * (N+1)
40 dp[0] = SAME
41 for i in xrange(N//10+1):
42 if dp[i] != INVALID:
43 for j in same:
44 if i*10+j <= N:
45 dp[i*10+j] = max(SAME, dp[i])
46 for j in diff:
47 if i*10+j <= N:
48 dp[i*10+j] = DIFF
49 return dp.count(DIFF)
50
51
52 # Time: O(nlogn) = O(n), because O(logn) = O(32) by this input
53 # Space: O(logn) = O(1)
54 class Solution3(object):
55 def rotatedDigits(self, N):
56 """
57 :type N: int
58 :rtype: int
59 """
60 invalid, diff = set(['3', '4', '7']), set(['2', '5', '6', '9'])
61 result = 0
62 for i in xrange(N+1):
63 lookup = set(list(str(i)))
64 if invalid & lookup:
65 continue
66 if diff & lookup:
67 result += 1
68 return result
69
70
*************

199. Rotate String


*************

Given two strings s and goal , return true if and only if s can become goal after some number of shifts on s .

A shift on s consists of moving the leftmost character of s to the rightmost position.

For example, if s = "abcde" , then it will be "bcdea" after one shift.

Example 1:

Input: s = "abcde", goal = "cdeab"


Output: true

Example 2:

Input: s = "abcde", goal = "abced"


Output: false

Constraints:

1 <= s.length, goal.length <= 100


s and goal consist of lowercase English letters.
*************

199. Rotate String(C++)


*************

1 // Time: O(n)
2 // Space: O(1)
3
4 // Rabin-Karp Algorithm (rolling hash)
5 class Solution {
6 public:
7 bool rotateString(string A, string B) {
8 if (A.length() != B.length()) {
9 return false;
10 }
11 static const uint64_t M = 1000000007;
12 static const uint64_t p = 113;
13 static const uint64_t p_inv = pow(p, M - 2, M);
14
15 uint64_t b_hash = 0, power = 1;
16 for (int i = 0; i < B.length(); ++i) {
17 b_hash += power * B[i];
18 b_hash %= M;
19 power = (power * p) % M;
20 }
21
22 uint64_t a_hash = 0; power = 1;
23 for (int i = 0; i < B.length(); ++i) {
24 a_hash += power * A[i % A.length()];
25 a_hash %= M;
26 power = (power * p) % M;
27 }
28 if (a_hash == b_hash && check(0, A, B)) {
29 return true;
30 }
31
32 power = (power * p_inv) % M;
33 for (int i = B.length(); i < 2 * A.length(); ++i) {
34 a_hash -= A[(i - B.length()) % A.length()];
35 a_hash *= p_inv;
36 a_hash += power * A[i % A.length()];
37 a_hash %= M;
38 if (a_hash == b_hash && check(i - B.length() + 1, A, B)) {
39 return true;
40 }
41 }
42 return false;
43 }
44
45 private:
46 bool check(int index, const string& A, const string& B) {
47 for (int i = 0; i < B.length(); ++i) {
48 if (A[(i + index) % A.length()] != B[i]) {
49 return false;
50 }
51 }
52 return true;
53 }
54
55 uint64_t pow(uint64_t a,uint64_t b, uint64_t m) {
56 a %= m;
57 uint64_t result = 1;
58 while (b) {
59 if (b & 1) {
60 result = (result * a) % m;
61 }
62 a = (a * a) % m;
63 b >>= 1;
64 }
65 return result;
66 }
67 };
68
69 // Time: O(n)
70 // Space: O(n)
71 // KMP algorithm
72 class Solution2 {
73 public:
74 bool rotateString(string A, string B) {
75 if (A.length() != B.length()) {
76 return false;
77 }
78 return strStr(A + A, B) != -1;
79 }
80
81 private:
82 int strStr(string haystack, string needle) {
83 if (needle.empty()) {
84 return 0;
85 }
86
87 return KMP(haystack, needle);
88 }
89
90 int KMP(const string& text, const string& pattern) {
91 const vector prefix = getPrefix(pattern);
92 int j = -1;
93 for (int i = 0; i < text.length(); ++i) {
94 while (j > -1 && pattern[j + 1] != text[i]) {
95 j = prefix[j];
96 }
97 if (pattern[j + 1] == text[i]) {
98 ++j;
99 }
100 if (j == pattern.length() - 1) {
101 return i - j;
102 }
103 }
104 return -1;
105 }
106
107 vector getPrefix(const string& pattern) {
108 vector prefix(pattern.length(), -1);
109 int j = -1;
110 for (int i = 1; i < pattern.length(); ++i) {
111 while (j > -1 && pattern[j + 1] != pattern[i]) {
112 j = prefix[j];
113 }
114 if (pattern[j + 1] == pattern[i]) {
115 ++j;
116 }
117 prefix[i] = j;
118 }
119 return prefix;
120 }
121 };
122
123 // Time: O(n^2)
124 // Space: O(n)
125 class Solution3 {
126 public:
127 bool rotateString(string A, string B) {
128 return A.size() == B.size() && (A + A).find(B) != string::npos;
129 }
130 };
*************

199. Rotate String(Python)


*************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def rotateString(self, A, B):
6 """
7 :type A: str
8 :type B: str
9 :rtype: bool
10 """
11 def check(index):
12 return all(A[(i+index) % len(A)] == c
13 for i, c in enumerate(B))
14
15 if len(A) != len(B):
16 return False
17
18 M, p = 10**9+7, 113
19 p_inv = pow(p, M-2, M)
20
21 b_hash, power = 0, 1
22 for c in B:
23 b_hash += power * ord(c)
24 b_hash %= M
25 power = (power*p) % M
26
27 a_hash, power = 0, 1
28 for i in xrange(len(B)):
29 a_hash += power * ord(A[i%len(A)])
30 a_hash %= M
31 power = (power*p) % M
32
33 if a_hash == b_hash and check(0): return True
34
35 power = (power*p_inv) % M
36 for i in xrange(len(B), 2*len(A)):
37 a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv
38 a_hash += power * ord(A[i%len(A)])
39 a_hash %= M
40 if a_hash == b_hash and check(i-len(B)+1):
41 return True
42
43 return False
44
45
46 # Time: O(n)
47 # Space: O(n)
48 # KMP algorithm
49 class Solution2(object):
50 def rotateString(self, A, B):
51 """
52 :type A: str
53 :type B: str
54 :rtype: bool
55 """
56 def strStr(haystack, needle):
57 def KMP(text, pattern):
58 prefix = getPrefix(pattern)
59 j = -1
60 for i in xrange(len(text)):
61 while j > -1 and pattern[j + 1] != text[i]:
62 j = prefix[j]
63 if pattern[j + 1] == text[i]:
64 j += 1
65 if j == len(pattern) - 1:
66 return i - j
67 return -1
68
69 def getPrefix(pattern):
70 prefix = [-1] * len(pattern)
71 j = -1
72 for i in xrange(1, len(pattern)):
73 while j > -1 and pattern[j + 1] != pattern[i]:
74 j = prefix[j]
75 if pattern[j + 1] == pattern[i]:
76 j += 1
77 prefix[i] = j
78 return prefix
79
80 if not needle:
81 return 0
82 return KMP(haystack, needle)
83
84 if len(A) != len(B):
85 return False
86 return strStr(A*2, B) != -1
87
88
89 # Time: O(n^2)
90 # Space: O(n)
91 class Solution3(object):
92 def rotateString(self, A, B):
93 """
94 :type A: str
95 :type B: str
96 :rtype: bool
97 """
98 return len(A) == len(B) and B in A*2
99
*****************

200. Similar RGB Color


*****************

The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.

For example, "#15c" is shorthand for the color "#1155cc".

The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)2 - (CD - WX) 2 - (EF - YZ) 2.

Given a string color that follows the format "#ABCDEF", return a string represents the color that is most similar to the given
color and has a shorthand (i.e., it can be represented as some "#XYZ").

Any answer which has the same highest similarity as the best answer will be accepted.

Example 1:

Input: color = "#09f166"


Output: "#11ee66"
Explanation:
The similarity is -(0x09 - 0x11)2 -(0xf1 - 0xee)2 - (0x66 - 0x66)2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.

Example 2:

Input: color = "#4e3fe1"


Output: "#5544dd"

Constraints:

color.length == 7
color[0] == '#'
color[i] is either digit or character in the range['a', 'f'] for i > 0 .
*****************

200. Similar RGB Color(C++)


*****************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string similarRGB(string color) {
7 string result = "#";
8 result += round(color.substr(1, 2));
9 result += round(color.substr(3, 2));
10 result += round(color.substr(5, 2));
11 return result;
12 }
13
14 private:
15 string round(const string& color) {
16 std::stringstream in(color);
17 int decimal = 0;
18 in >> std::hex >> decimal;
19 decimal = decimal / 17 + (decimal % 17 > 8 ? 1 : 0);
20 std::stringstream out;
21 out << std::setfill('0') << std::setw(2) << std::hex << 17 * q;
22 return out.str();
23 }
24 };
*****************

200. Similar RGB Color(Python)


*****************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def similarRGB(self, color):
6 """
7 :type color: str
8 :rtype: str
9 """
10 def rounding(color):
11 q, r = divmod(int(color, 16), 17)
12 if r > 8: q += 1
13 return '{:02x}'.format(17*q)
14
15 return '#' + \
16 rounding(color[1:3]) + \
17 rounding(color[3:5]) + \
18 rounding(color[5:7])
19
***********************

201. Unique Morse Code Words


***********************

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as
follows:

'a' maps to ".-" ,


'b' maps to "-...",
'c' maps to "-.-.", and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","

Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.

For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-" , and "-...". We will call such a
concatenation the transformation of a word.

Return the number of different transformations among all words we have.

Example 1:

Input: words = ["gin","zen","gig","msg"]


Output: 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".

Example 2:

Input: words = ["a"]


Output: 1

Constraints:

1 <= words.length <= 100


1 <= words[i].length <= 12
words[i] consists of lowercase English letters.
***********************

201. Unique Morse Code Words(C++)


***********************

1 // Time: O(n), n is the sume of all word lengths


2 // Space: O(n)
3
4 class Solution {
5 public:
6 int uniqueMorseRepresentations(vector& words) {
7 static const vector MORSE =
8 { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
9 "....", "..", ".---", "-.-", ".-..", "--", "-.",
10 "---", ".--.", "--.-", ".-.", "...", "-", "..-",
11 "...-", ".--", "-..-", "-.--", "--.."};
12
13 unordered_set lookup;
14 for (const auto& word : words) {
15 string code;
16 for (const auto& c : word) {
17 code += MORSE[c - 'a'];
18 }
19 lookup.emplace(move(code));
20 }
21 return lookup.size();
22 }
23 };
***********************

201. Unique Morse Code Words(Python)


***********************

1 # Time: O(n), n is the sume of all word lengths


2 # Space: O(n)
3
4 class Solution(object):
5 def uniqueMorseRepresentations(self, words):
6 """
7 :type words: List[str]
8 :rtype: int
9 """
10 MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
11 "....", "..", ".---", "-.-", ".-..", "--", "-.",
12 "---", ".--.", "--.-", ".-.", "...", "-", "..-",
13 "...-", ".--", "-..-", "-.--", "--.."]
14
15 lookup = {"".join(MORSE[ord(c) - ord('a')] for c in word) \
16 for word in words}
17 return len(lookup)
18
*******************************

202. Number of Lines To Write String


*******************************

You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase
English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.

You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning ofs ,
write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s ,
continue writing as many letters as you can on the second line. Continue this process until you have written all of s .

Return an array result of length 2 where:

result[0] is the total number of lines.


result[1] is the width of the last line in pixels.

Example 1:

Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"


Output: [3,60]
Explanation: You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.

Example 2:

Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa"


Output: [2,4]
Explanation: You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.

Constraints:

widths.length == 26
2 <= widths[i] <= 10
1 <= s.length <= 1000
s contains only lowercase English letters.
*******************************

202. Number of Lines To Write String(C++)


*******************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector numberOfLines(vector& widths, string S) {
7 vector result(2);
8 result.front() = 1;
9 for (const auto& c : S) {
10 const auto& w = widths[c - 'a'];
11 result.back() += w;
12 if (result.back() > 100) {
13 ++result.front();
14 result.back() = w;
15 }
16 }
17 return result;
18 }
19 };
*******************************

202. Number of Lines To Write String(Python)


*******************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def numberOfLines(self, widths, S):
6 """
7 :type widths: List[int]
8 :type S: str
9 :rtype: List[int]
10 """
11 result = [1, 0]
12 for c in S:
13 w = widths[ord(c)-ord('a')]
14 result[1] += w
15 if result[1] > 100:
16 result[0] += 1
17 result[1] = w
18 return result
19
*********************

203. Subdomain Visit Count


*********************

A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have"com", at the next level, we
have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also
visit the parent domains "leetcode.com" and "com" implicitly.

A count-paired domain is a domain that has one of the two formats"rep d1.d2.d3" or "rep d1.d2" where rep is the number of
visits to the domain and d1.d2.d3 is the domain itself.

For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001
times.

Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the
input. You may return the answer inany order.

Example 1:

Input: cpdomains = ["9001 discuss.leetcode.com"]


Output: ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
Explanation: We only have one website domain: "discuss.leetcode.com".
As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.

Example 2:

Input: cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output: ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.
For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.

Constraints:

1 <= cpdomain.length <= 100


1 <= cpdomain[i].length <= 100
cpdomain[i] follows either the "repi d1i.d2i.d3i"
format or the "repi d1i.d2i" format.
repi is an integer in the range [1, 104].
d1i, d2i, and d3i consist of lowercase English letters.
*********************

203. Subdomain Visit Count(C++)


*********************

1 // Time: O(n), is the length of cpdomains (assuming the length of cpdomains[i] is fixed)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector subdomainVisits(vector& cpdomains) {
7 unordered_map counts;
8 for (const auto& cpdomain : cpdomains) {
9 int i = cpdomain.find(" ");
10 const int count = stoi(cpdomain.substr(0, i));
11 const auto& domain = cpdomain.substr(i + 1);
12 for (int i = -1; i < static_cast(domain.length()); ++i) {
13 if (i != -1 && domain[i] != '.') {
14 continue;
15 }
16 counts[domain.substr(i + 1)] += count;
17 }
18 }
19
20 vector result;
21 for (const auto& count : counts) {
22 result.emplace_back(to_string(count.second));
23 result.back() += " ";
24 result.back() += count.first;
25 }
26 return result;
27 }
28 };
*********************

203. Subdomain Visit Count(Python)


*********************

1 # Time: O(n), is the length of cpdomains (assuming the length of cpdomains[i] is fixed)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def subdomainVisits(self, cpdomains):
9 """
10 :type cpdomains: List[str]
11 :rtype: List[str]
12 """
13 result = collections.defaultdict(int)
14 for domain in cpdomains:
15 count, domain = domain.split()
16 count = int(count)
17 frags = domain.split('.')
18 curr = []
19 for i in reversed(xrange(len(frags))):
20 curr.append(frags[i])
21 result[".".join(reversed(curr))] += count
22
23 return ["{} {}".format(count, domain) \
24 for domain, count in result.iteritems()]
25
*********************

204. Largest Triangle Area


*********************

Given an array of points on the X-Y plane points where points[i] = [x i, y i], return the area of the largest triangle that can be formed
by any three different points. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]


Output: 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.

Example 2:

Input: points = [[1,0],[0,0],[0,1]]


Output: 0.50000

Constraints:

3 <= points.length <= 50


-50 <= x i, y i <= 50
All the given points are unique.
*********************

204. Largest Triangle Area(C++)


*********************

1 // Time: O(n^3)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 double largestTriangleArea(vector>& points) {
7 double result = 0.0;
8 for (int i = 0; i < points.size() - 2; ++i) {
9 for (int j = i + 1; j < points.size() - 1; ++j) {
10 for (int k = j + 1; k < points.size(); ++k) {
11 result = max(result,
12 0.5 * abs(points[i][0] * points[j][1] +
13 points[j][0] * points[k][1] +
14 points[k][0] * points[i][1] -
15 points[j][0] * points[i][1] -
16 points[k][0] * points[j][1] -
17 points[i][0] * points[k][1]));
18 }
19 }
20 }
21 return result;
22 }
23 };
*********************

204. Largest Triangle Area(Python)


*********************

1 # Time: O(n^3)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def largestTriangleArea(self, points):
7 """
8 :type points: List[List[int]]
9 :rtype: float
10 """
11 result = 0
12 for i in xrange(len(points)-2):
13 for j in xrange(i+1, len(points)-1):
14 for k in xrange(j+1, len(points)):
15 result = max(result,
16 0.5 * abs(points[i][0] * points[j][1] +
17 points[j][0] * points[k][1] +
18 points[k][0] * points[i][1] -
19 points[j][0] * points[i][1] -
20 points[k][0] * points[j][1] -
21 points[i][0] * points[k][1]))
22 return result
23
****************

205. Most Common Word


****************

Given a string paragraph and a string array of the banned wordsbanned, return the most frequent word that is not banned. It is
guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

Example 1:

Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.

Example 2:

Input: paragraph = "a.", banned = []


Output: "a"

Constraints:

1 <= paragraph.length <= 1000


paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i] consists of only lowercase English letters.
****************

205. Most Common Word(C++)


****************

1 // Time: O(m + n), m is the size of banned, n is the size of paragraph


2 // Space: O(m + n)
3
4 class Solution {
5 public:
6 string mostCommonWord(string paragraph, vector& banned) {
7 unordered_set lookup(banned.cbegin(), banned.cend());
8 unordered_map counts;
9 string word;
10 for (const auto& c : paragraph) {
11 if (isalpha(c)) {
12 word.push_back(tolower(c));
13 } else if (!word.empty()) {
14 ++counts[word];
15 word.clear();
16 }
17 }
18 if (!word.empty()) {
19 ++counts[word];
20 }
21 string result;
22 for (const auto& kvp : counts) {
23 if ((result.empty() || kvp.second > counts[result]) &&
24 !lookup.count(kvp.first)) {
25 result = kvp.first;
26 }
27 }
28 return result;
29 }
30 };
****************

205. Most Common Word(Python)


****************

1 # Time: O(m + n), m is the size of banned, n is the size of paragraph


2 # Space: O(m + n)
3
4 import collections
5
6
7 class Solution(object):
8 def mostCommonWord(self, paragraph, banned):
9 """
10 :type paragraph: str
11 :type banned: List[str]
12 :rtype: str
13 """
14 lookup = set(banned)
15 counts = collections.Counter(word.strip("!?',.")
16 for word in paragraph.lower().split())
17
18 result = ''
19 for word in counts:
20 if (not result or counts[word] > counts[result]) and \
21 word not in lookup:
22 result = word
23 return result
24
********************************

206. Shortest Distance to a Character


********************************

Given a string s and a character c that occurs in s , return an array of integers answer where answer.length == s.length and answer[i]
is the distance from index i to the closest occurrence of character c in s .

The distance between two indices i and j is abs(i - j), where abs is the absolute value function.

Example 1:

Input: s = "loveleetcode", c = "e"


Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) =
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.

Example 2:

Input: s = "aaab", c = "b"


Output: [3,2,1,0]

Constraints:

1 <= s.length <= 104


s[i] and c are lowercase English letters.
It is guaranteed that c occurs at least once in s .
********************************

206. Shortest Distance to a Character(C++)


********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector shortestToChar(string S, char C) {
7 vector result(S.length(), S.length());
8 int prev = -S.length();
9 for (int i = 0; i < S.length(); ++i) {
10 if (S[i] == C) {
11 prev = i;
12 }
13 result[i] = min(result[i], abs(i - prev));
14 }
15 for (int i = S.length() - 1; i >= 0; --i) {
16 if (S[i] == C) {
17 prev = i;
18 }
19 result[i] = min(result[i], abs(i - prev));
20 }
21 return result;
22 }
23 };
********************************

206. Shortest Distance to a Character(Python)


********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def shortestToChar(self, S, C):
9 """
10 :type S: str
11 :type C: str
12 :rtype: List[int]
13 """
14 result = [len(S)] * len(S)
15 prev = -len(S)
16 for i in itertools.chain(xrange(len(S)),
17 reversed(xrange(len(S)))):
18 if S[i] == C:
19 prev = i
20 result[i] = min(result[i], abs(i-prev))
21 return result
22
**********

207. Goat Latin


**********

You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase
letters only.

We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are
as follows:

If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word.
For example, the word "apple" becomes "applema".
If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add"ma".
For example, the word "goat" becomes "oatgma" .
Add one letter 'a' to the end of each word per its word index in the sentence, starting with1.
For example, the first word gets "a" added to the end, the second word gets"aa" added to the end, and so on.

Return the final sentence representing the conversion from sentence to Goat Latin.

Example 1:

Input: sentence = "I speak Goat Latin"


Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

Input: sentence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Constraints:

1 <= sentence.length <= 150


sentence consists of English letters and spaces.
sentence has no leading or trailing spaces.
All the words in sentence are separated by a single space.
**********

207. Goat Latin(C++)


**********

1 // Time: O(n + w^2), n = w * l,


2 // n is the length of S,
3 // w is the number of words,
4 // l is the average of word lengths
5 // Space: O(l)
6
7 class Solution {
8 public:
9 string toGoatLatin(string S) {
10 unordered_set vowel{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
11 string result, word;
12 int count = 0;
13 for (int i = 0; i < S.length(); ++i) {
14 if (S[i] != ' ') {
15 word.push_back(S[i]);
16 if (i != S.length() - 1) {
17 continue;
18 }
19 }
20 if (!vowel.count(word.front())) {
21 word.push_back(word.front());
22 word = word.substr(1);
23 }
24 word += "ma";
25 word += string(++count, 'a');
26 result += word;
27 result += " ";
28 word.clear();
29 }
30 result.pop_back();
31 return result;
32 }
33 };
**********

207. Goat Latin(Python)


**********

1 # Time: O(n + w^2), n = w * l,


2 # n is the length of S,
3 # w is the number of word,
4 # l is the average length of word
5 # Space: O(n)
6
7 class Solution(object):
8 def toGoatLatin(self, S):
9 """
10 :type S: str
11 :rtype: str
12 """
13 def convert(S):
14 vowel = set('aeiouAEIOU')
15 for i, word in enumerate(S.split(), 1):
16 if word[0] not in vowel:
17 word = word[1:] + word[:1]
18 yield word + 'ma' + 'a'*i
19 return " ".join(convert(S))
20
*************************

208. Positions of Large Groups


*************************

In a string s of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy".

A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In
the above example, "xxxx" has the interval [3,6].

A group is considered large if it has 3 or more characters.

Return the intervals of every large group sorted in increasing order by start index.

Example 1:

Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.

Example 2:

Input: s = "abc"
Output: []
Explanation: We have groups "a", "b", and "c", none of which are large groups.

Example 3:

Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Explanation: The large groups are "ddd", "eeee", and "bbb".

Example 4:

Input: s = "aba"
Output: []

Constraints:

1 <= s.length <= 1000


s contains lower-case English letters only.
*************************

208. Positions of Large Groups(C++)


*************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> largeGroupPositions(string S) {
7 vector> result;
8 for (int i = 0, j = 0; j < S.length(); ++j) {
9 if (j == S.length() - 1 || S[j] != S[j + 1]) {
10 if (j - i + 1 >= 3) {
11 result.emplace_back(vector{i, j});
12 }
13 i = j + 1;
14 }
15 }
16 return result;
17 }
18 };
*************************

208. Positions of Large Groups(Python)


*************************

1 # Time: O(n)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def largeGroupPositions(self, S):
7 """
8 :type S: str
9 :rtype: List[List[int]]
10 """
11 result = []
12 i = 0
13 for j in xrange(len(S)):
14 if j == len(S)-1 or S[j] != S[j+1]:
15 if j-i+1 >= 3:
16 result.append([i, j])
17 i = j+1
18 return result
19
*****************

209. Flipping an Image


*****************

Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed.

For example, flipping [1,1,0] horizontally results in [0,1,1].

To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

For example, inverting [0,1,1] results in [1,0,0].

Example 1:

Input: image = [[1,1,0],[1,0,1],[0,0,0]]


Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]

Example 2:

Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]


Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Constraints:

n == image.length
n == image[i].length
1 <= n <= 20
images[i][j] is either 0 or 1.
*****************

209. Flipping an Image(C++)


*****************

1 // Time: O(n^2)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> flipAndInvertImage(vector>& A) {
7 for (auto& row : A) {
8 for (int i = 0; i < (row.size() + 1) / 2; ++i) {
9 row[i] ^= 1;
10 if (i != row.size() + ~i) {
11 row[row.size() + ~i] ^= 1;
12 swap(row[i], row[row.size() + ~i]);
13 }
14 }
15 }
16 return A;
17 }
18 };
*****************

209. Flipping an Image(Python)


*****************

1 # Time: O(n^2)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def flipAndInvertImage(self, A):
7 """
8 :type A: List[List[int]]
9 :rtype: List[List[int]]
10 """
11 for row in A:
12 for i in xrange((len(row)+1) // 2):
13 row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1
14 return A
15
*****************

210. Rectangle Overlap


*****************

An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and
(x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges
are parallel to the Y-axis.

Two rectangles overlap if the area of their intersection ispositive. To be clear, two rectangles that only touch at the corner
or edges do not overlap.

Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.

Example 1:

Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]


Output: true

Example 2:

Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]


Output: false

Example 3:

Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]


Output: false

Constraints:

rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 10 9
rec1 and rec2 represent a valid rectangle with a non-zero area.
*****************

210. Rectangle Overlap(C++)


*****************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isRectangleOverlap(vector& rec1, vector& rec2) {
7 return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) &&
8 intersect(rec1[1], rec1[3], rec2[1], rec2[3]));
9 }
10
11 private:
12 bool intersect(int p_left, int p_right, int q_left, int q_right) {
13 return max(p_left, q_left) < min(p_right, q_right);
14 }
15 };
*****************

210. Rectangle Overlap(Python)


*****************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def isRectangleOverlap(self, rec1, rec2):
6 """
7 :type rec1: List[int]
8 :type rec2: List[int]
9 :rtype: bool
10 """
11 def intersect(p_left, p_right, q_left, q_right):
12 return max(p_left, q_left) < min(p_right, q_right)
13
14 return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and
15 intersect(rec1[1], rec1[3], rec2[1], rec2[3]))
16
*********************

211. Magic Squares In Grid


*********************

A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all
have the same sum.

Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).

Example 1:

Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]


Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:

while this one is not:

In total, there is only one magic square inside the given grid.

Example 2:

Input: grid = [[8]]


Output: 0

Example 3:

Input: grid = [[4,4],[3,3]]


Output: 0

Example 4:

Input: grid = [[4,7,8],[9,5,1],[2,3,6]]


Output: 0

Constraints:

row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
*********************

211. Magic Squares In Grid(C++)


*********************

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numMagicSquaresInside(vector>& grid) {
7 int result = 0;
8 for (int i = 0; i + k - 1 < grid.size(); ++i) {
9 for (int j = 0; j + k - 1 < grid[j].size(); ++j) {
10 if (magic(grid, i, j)) {
11 ++result;
12 }
13 }
14 }
15 return result;
16 }
17
18 private:
19 static const int k = 3;
20
21 bool magic(const vector>& grid, int r, int c) {
22 const int expect = k * (k * k + 1) / 2;
23 unordered_set nums;
24 int min_num = numeric_limits::max();
25 int sum_diag = 0, sum_anti = 0;
26 for (int i = 0; i < k; ++i) {
27 sum_diag += grid[r + i][c + i];
28 sum_anti += grid[r + i][c + k - 1 - i];
29 int sum_r = 0, sum_c = 0;
30 for (int j = 0; j < k; ++j) {
31 min_num = min(min_num, grid[r + i][c + j]);
32 nums.emplace(grid[r + i][c + j]);
33 sum_r += grid[r + i][c + j];
34 sum_c += grid[r + j][c + i];
35 }
36 if (!(sum_r == sum_c &&
37 sum_c == expect)) {
38 return false;
39 }
40 }
41 return sum_diag == sum_anti &&
42 sum_anti == expect &&
43 nums.size() == k * k &&
44 min_num == 1;
45 }
46 };
*********************

211. Magic Squares In Grid(Python)


*********************

1 # Time: O(m * n)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def numMagicSquaresInside(self, grid):
7 """
8 :type grid: List[List[int]]
9 :rtype: int
10 """
11 def magic(grid, r, c):
12 expect = k * (k**2+1) // 2
13 nums = set()
14 min_num = float("inf")
15 sum_diag, sum_anti = 0, 0
16 for i in xrange(k):
17 sum_diag += grid[r+i][c+i]
18 sum_anti += grid[r+i][c+k-1-i]
19 sum_r, sum_c = 0, 0
20 for j in xrange(k):
21 min_num = min(min_num, grid[r+i][c+j])
22 nums.add(grid[r+i][c+j])
23 sum_r += grid[r+i][c+j]
24 sum_c += grid[r+j][c+i]
25 if not (sum_r == sum_c == expect):
26 return False
27 return sum_diag == sum_anti == expect and \
28 len(nums) == k**2 and \
29 min_num == 1
30
31 k = 3
32 result = 0
33 for r in xrange(len(grid)-k+1):
34 for c in xrange(len(grid[r])-k+1):
35 if magic(grid, r, c):
36 result += 1
37 return result
38
************************

212. Backspace String Compare


************************

Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace
character.

Note that after backspacing an empty text, the text will continue empty.

Example 1:

Input: s = "ab#c", t = "ad#c"


Output: true
Explanation: Both s and t become "ac".

Example 2:

Input: s = "ab##", t = "c#d#"


Output: true
Explanation: Both s and t become "".

Example 3:

Input: s = "a##c", t = "#a#c"


Output: true
Explanation: Both s and t become "c".

Example 4:

Input: s = "a#c", t = "b"


Output: false
Explanation: s becomes "c" while t becomes "b".

Constraints:

1 <= s.length, t.length <= 200


s and t only contain lowercase letters and '#' characters.

Follow up: Can you solve it in O(n) time and O(1) space?
************************

212. Backspace String Compare(C++)


************************

1 // Time: O(m + n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool backspaceCompare(string S, string T) {
7 for (int i = S.length() - 1, j = T.length() - 1; i >= 0 || j >= 0; --i, --j) {
8 if (findNextChar(S, &i) != findNextChar(T, &j)) {
9 return false;
10 }
11 }
12 return true;
13 }
14
15 private:
16 char findNextChar(const string& s, int *i) {
17 int skip = 0;
18 for (; *i >= 0; --(*i)) {
19 if (s[*i] == '#') {
20 ++skip;
21 } else if (skip > 0) {
22 --skip;
23 } else {
24 return s[*i];
25 }
26 }
27 return '\0';
28 }
29 };
************************

212. Backspace String Compare(Python)


************************

1 # Time: O(m + n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def backspaceCompare(self, S, T):
9 """
10 :type S: str
11 :type T: str
12 :rtype: bool
13 """
14 def findNextChar(S):
15 skip = 0
16 for i in reversed(xrange(len(S))):
17 if S[i] == '#':
18 skip += 1
19 elif skip:
20 skip -= 1
21 else:
22 yield S[i]
23
24 return all(x == y for x, y in
25 itertools.izip_longest(findNextChar(S), findNextChar(T)))
26
***********************************

213. Maximize Distance to Closest Person


***********************************

You are given an array representing a row ofseats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0
represents that the ith seat is empty (0-indexed).

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return that maximum distance to the closest person.

Example 1:

Input: seats = [1,0,0,0,1,0,1]


Output: 2
Explanation:
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

Example 2:

Input: seats = [1,0,0,0]


Output: 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

Example 3:

Input: seats = [0,1]


Output: 1

Constraints:

2 <= seats.length <= 2 * 10 4


seats[i] is 0 or 1.
At least one seat is empty.
At least one seat is occupied.
***********************************

213. Maximize Distance to Closest Person(C++)


***********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxDistToClosest(vector& seats) {
7 int prev = -1, result = 1;
8 for (int i = 0; i < seats.size(); ++i) {
9 if (seats[i]) {
10 if (prev < 0) {
11 result = i;
12 } else {
13 result = max(result, (i - prev) / 2);
14 }
15 prev = i;
16 }
17 }
18 return max(result, static_cast(seats.size()) - 1 - prev);
19 }
20 };
***********************************

213. Maximize Distance to Closest Person(Python)


***********************************

1 # Time: O(n)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def maxDistToClosest(self, seats):
7 """
8 :type seats: List[int]
9 :rtype: int
10 """
11 prev, result = -1, 1
12 for i in xrange(len(seats)):
13 if seats[i]:
14 if prev < 0:
15 result = i
16 else:
17 result = max(result, (i-prev)//2)
18 prev = i
19 return max(result, len(seats)-1-prev)
20
******************************

214. Peak Index in a Mountain Array


******************************

Let's call an array arr a mountain if the following properties hold:

arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]

Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ...
> arr[arr.length - 1].

Example 1:

Input: arr = [0,1,0]


Output: 1

Example 2:

Input: arr = [0,2,1,0]


Output: 1

Example 3:

Input: arr = [0,10,5,2]


Output: 1

Example 4:

Input: arr = [3,4,5,1]


Output: 2

Example 5:

Input: arr = [24,69,100,99,79,78,67,36,26,19]


Output: 2

Constraints:

3 <= arr.length <= 10 4


0 <= arr[i] <= 10 6
arr is guaranteed to be a mountain array.

Follow up: Finding the O(n) is straightforward, could you find an O(log(n)) solution?
******************************

214. Peak Index in a Mountain Array(C++)


******************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int peakIndexInMountainArray(vector& arr) {
7 int left = 0, right = size(arr) - 1;
8 while (left <= right) {
9 const auto mid = left + (right - left) / 2;
10 if (arr[mid] > arr[mid + 1]) {
11 right = mid - 1;
12 } else {
13 left = mid + 1;
14 }
15 }
16 return left;
17 }
18 };
******************************

214. Peak Index in a Mountain Array(Python)


******************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def peakIndexInMountainArray(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: int
9 """
10 left, right = 0, len(arr)-1
11 while left <= right:
12 mid = left + (right-left)//2
13 if arr[mid] > arr[mid+1]:
14 right = mid-1
15 else:
16 left = mid+1
17 return left
18
*************

215. Buddy Strings


*************

Given two strings s and goal , return true if you can swap two letters in s so the result is equal to goal , otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

Example 1:

Input: s = "ab", goal = "ba"


Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.

Example 2:

Input: s = "ab", goal = "ab"


Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.

Example 3:

Input: s = "aa", goal = "aa"


Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.

Example 4:

Input: s = "aaaaaaabc", goal = "aaaaaaacb"


Output: true

Constraints:

1 <= s.length, goal.length <= 2 * 10 4


s and goal consist of lowercase letters.
*************

215. Buddy Strings(C++)


*************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool buddyStrings(string A, string B) {
7 if (A.length() != B.length()) {
8 return false;
9 }
10 vector diff;
11 for (int i = 0; i < A.length(); ++i) {
12 if (A[i] != B[i]) {
13 diff.emplace_back(i);
14 if (diff.size() > 2) {
15 return false;
16 }
17 }
18 }
19 return (diff.empty() && unordered_set(A.begin(), A.end()).size() < A.size()) ||
20 (diff.size() == 2 && A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]]);
21 }
22 };
*************

215. Buddy Strings(Python)


*************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def buddyStrings(self, A, B):
9 """
10 :type A: str
11 :type B: str
12 :rtype: bool
13 """
14 if len(A) != len(B):
15 return False
16 diff = []
17 for a, b in itertools.izip(A, B):
18 if a != b:
19 diff.append((a, b))
20 if len(diff) > 2:
21 return False
22 return (not diff and len(set(A)) < len(A)) or \
23 (len(diff) == 2 and diff[0] == diff[1][::-1])
24
***************

216. Lemonade Change


***************

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time
(in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must
provide the correct change to each customer so that the net transaction is that the customer pays $5.

Note that you don't have any change in hand at first.

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with
correct change, or false otherwise.

Example 1:

Input: bills = [5,5,5,10,20]


Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.

Example 2:

Input: bills = [5,5,10,10,20]


Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give change of $15 back because we only have two $10 bills.
Since not every customer received correct change, the answer is false.

Example 3:

Input: bills = [5,5,10]


Output: true

Example 4:

Input: bills = [10,10]


Output: false

Constraints:

1 <= bills.length <= 105


bills[i] is either 5, 10, or 20.
***************

216. Lemonade Change(C++)


***************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool lemonadeChange(vector& bills) {
7 static const vector coins = {20, 10, 5};
8 unordered_map counts;
9 for (const auto& bill : bills) {
10 ++counts[bill];
11 auto change = bill - coins.back();
12 for (const auto& coin : coins) {
13 if (change == 0) {
14 break;
15 }
16 if (change >= coin) {
17 const auto count = min(counts[coin], change / coin);
18 counts[coin] -= count;
19 change -= coin * count;
20 }
21 }
22 if (change != 0) {
23 return false;
24 }
25 }
26 return true;
27 }
28 };
29
30 class Solution2 {
31 public:
32 bool lemonadeChange(vector& bills) {
33 int five = 0, ten = 0;
34 for (const auto& bill : bills) {
35 if (bill == 5) {
36 ++five;
37 } else if (bill == 10) {
38 if (!five) {
39 return false;
40 }
41 --five;
42 ++ten;
43 } else {
44 if (five && ten) {
45 --five;
46 --ten;
47 } else if (five >= 3) {
48 five -= 3;
49 } else {
50 return false;
51 }
52 }
53 }
54 return true;
55 }
56 };
***************

216. Lemonade Change(Python)


***************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def lemonadeChange(self, bills):
9 """
10 :type bills: List[int]
11 :rtype: bool
12 """
13 coins = [20, 10, 5]
14 counts = collections.defaultdict(int)
15 for bill in bills:
16 counts[bill] += 1
17 change = bill - coins[-1]
18 for coin in coins:
19 if change == 0:
20 break
21 if change >= coin:
22 count = min(counts[coin], change//coin)
23 counts[coin] -= count
24 change -= coin * count
25 if change != 0:
26 return False
27 return True
28
29
30 class Solution2(object):
31 def lemonadeChange(self, bills):
32 """
33 :type bills: List[int]
34 :rtype: bool
35 """
36 five, ten = 0, 0
37 for bill in bills:
38 if bill == 5:
39 five += 1
40 elif bill == 10:
41 if not five:
42 return False
43 five -= 1
44 ten += 1
45 else:
46 if ten and five:
47 ten -= 1
48 five -= 1
49 elif five >= 3:
50 five -= 3
51 else:
52 return False
53 return True
54
****************

217. Transpose Matrix


****************

Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of
n. If there are no two adjacent 1's, return 0.

Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute
difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

Example 1:

Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.

Example 2:

Input: n = 5
Output: 2
Explanation: 5 in binary is "101".

Example 3:

Input: n = 6
Output: 1
Explanation: 6 in binary is "110".

Example 4:

Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.

Example 5:

Input: n = 1
Output: 0

Constraints:

1 <= n <= 10 9
****************

217. Transpose Matrix(C++)


****************

1 // Time: O(r * c)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> transpose(vector>& A) {
7 vector> result(A[0].size(), vector(A.size()));
8 for (int r = 0; r < A.size(); ++r) {
9 for (int c = 0; c < A[0].size(); ++c) {
10 result[c][r] = A[r][c];
11 }
12 }
13 return result;
14 }
15 };
****************

217. Transpose Matrix(Python)


****************

1 # Time: O(r * c)
2 # Space: O(1)
3
4
5 class Solution(object):
6 def transpose(self, A):
7 """
8 :type A: List[List[int]]
9 :rtype: List[List[int]]
10 """
11 result = [[None] * len(A) for _ in xrange(len(A[0]))]
12 for r, row in enumerate(A):
13 for c, val in enumerate(row):
14 result[c][r] = val
15 return result
16
17
18 # Time: O(r * c)
19 # Space: O(1)
20 class Solution2(object):
21 def transpose(self, A):
22 """
23 :type A: List[List[int]]
24 :rtype: List[List[int]]
25 """
26 return zip(*A)
27
**********

218. Binary Gap


**********

Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of
n. If there are no two adjacent 1's, return 0.

Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute
difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

Example 1:

Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.

Example 2:

Input: n = 5
Output: 2
Explanation: 5 in binary is "101".

Example 3:

Input: n = 6
Output: 1
Explanation: 6 in binary is "110".

Example 4:

Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.

Example 5:

Input: n = 1
Output: 0

Constraints:

1 <= n <= 10 9
**********

218. Binary Gap(C++)


**********

1 // Time: O(logn) = O(1) due to n is a 32-bit number


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int binaryGap(int N) {
7 int result = 0;
8 int last = -1;
9 for (int i = 0; i < 32; ++i) {
10 if ((N >> i) & 1) {
11 if (last != -1) {
12 result = max(result, i - last);
13 }
14 last = i;
15 }
16 }
17 return result;
18 }
19 };
**********

218. Binary Gap(Python)


**********

1 # Time: O(logn) = O(1) due to n is a 32-bit number


2 # Space: O(1)
3
4 class Solution(object):
5 def binaryGap(self, N):
6 """
7 :type N: int
8 :rtype: int
9 """
10 result = 0
11 last = None
12 for i in xrange(32):
13 if (N >> i) & 1:
14 if last is not None:
15 result = max(result, i-last)
16 last = i
17 return result
18
******************

219. Leaf-Similar Trees


******************

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form aleaf value sequence.

For example, in the given tree above, the leaf value sequence is(6, 7, 4, 9, 8) .

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodesroot1 and root2 are leaf-similar.

Example 1:

Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]


Output: true

Example 2:

Input: root1 = [1], root2 = [1]


Output: true

Example 3:
Input: root1 = [1], root2 = [2]
Output: false

Example 4:

Input: root1 = [1,2], root2 = [2,2]


Output: true

Example 5:

Input: root1 = [1,2,3], root2 = [1,3,2]


Output: false

Constraints:

The number of nodes in each tree will be in the range[1, 200].


Both of the given trees will have values in the range[0, 200].
******************

219. Leaf-Similar Trees(C++)


******************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 bool leafSimilar(TreeNode* root1, TreeNode* root2) {
16 vector s1{root1} , s2{root2};
17 while (!s1.empty() && !s2.empty()) {
18 if (dfs(s1) != dfs(s2)) {
19 return false;
20 }
21 }
22 return s1.empty() && s2.empty();
23 }
24
25 private:
26 int dfs(vector& s) {
27 while (true) {
28 const auto node = s.back(); s.pop_back();
29 if (node->right) {
30 s.emplace_back(node->right);
31 }
32 if (node->left) {
33 s.emplace_back(node->left);
34 }
35 if (!node->left && !node->right) {
36 return node->val;
37 }
38 }
39 }
40 };
******************

219. Leaf-Similar Trees(Python)


******************

1 # Time: O(n)
2 # Space: O(h)
3
4 import itertools
5
6
7 # Definition for a binary tree node.
8 class TreeNode(object):
9 def __init__(self, x):
10 self.val = x
11 self.left = None
12 self.right = None
13
14
15 class Solution(object):
16 def leafSimilar(self, root1, root2):
17 """
18 :type root1: TreeNode
19 :type root2: TreeNode
20 :rtype: bool
21 """
22 def dfs(node):
23 if not node:
24 return
25 if not node.left and not node.right:
26 yield node.val
27 for i in dfs(node.left):
28 yield i
29 for i in dfs(node.right):
30 yield i
31 return all(a == b for a, b in
32 itertools.izip_longest(dfs(root1), dfs(root2)))
33
************************

220. Walking Robot Simulation


************************

A robot on an infinite XY-plane starts at point (0, 0) and faces north. The robot can receive one of three possible types of
commands :

-2: turn left 90 degrees,


-1: turn right 90 degrees, or
1 <= k <= 9 : move forward k units.

Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (x i, y i).

If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the
rest of the route.)

Return the maximum Euclidean distance that the robot will be from the originsquared (i.e. if the distance is 5, return 25).

Note:

North means +Y direction.


East means +X direction.
South means -Y direction.
West means -X direction.

Example 1:

Input: commands = [4,-1,3], obstacles = []


Output: 25
Explanation: The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point away from the origin is (3, 4), which is 32 + 42 = 25 units away.

Example 2:

Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]


Output: 65
Explanation: The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point away from the origin is (1, 8), which is 12 + 82 = 65 units away.

Constraints:

1 <= commands.length <= 10 4


commands[i] is one of the values in the list[-2,-1,1,2,3,4,5,6,7,8,9].
0 <= obstacles.length <= 10 4
-3 * 104 <= x i, y i <= 3 * 10 4
The answer is guaranteed to be less than 231.
************************

220. Walking Robot Simulation(C++)


************************

1 // Time: O(n + k)
2 // Space: O(k)
3
4 class Solution {
5 private:
6 template
7 struct PairHash {
8 size_t operator()(const pair& p) const {
9 size_t seed = 0;
10 seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
11 seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
12 return seed;
13 }
14 };
15
16 public:
17 int robotSim(vector& commands, vector>& obstacles) {
18 static const vector> directions{{0, 1}, {1, 0},
19 {0, -1}, {-1, 0}};
20 unordered_set, PairHash> lookup;
21 for (const auto& obstacle: obstacles) {
22 lookup.emplace(obstacle[0], obstacle[1]);
23 }
24 int result = 0;
25 int x = 0, y = 0, i = 0;
26 for (const auto& cmd: commands) {
27 if (cmd == -2) {
28 i = (i - 1 + 4) % 4;
29 } else if (cmd == -1) {
30 i = (i + 1) % 4;
31 } else {
32 for (int k = 0; k < cmd; ++k) {
33 if (!lookup.count(make_pair(x + directions[i].first,
34 y + directions[i].second))) {
35 x += directions[i].first;
36 y += directions[i].second;
37 result = max(result, x * x + y * y);
38 }
39 }
40 }
41 }
42 return result;
43 }
44 };
************************

220. Walking Robot Simulation(Python)


************************

1 # Time: O(n + k)
2 # Space: O(k)
3
4 class Solution(object):
5 def robotSim(self, commands, obstacles):
6 """
7 :type commands: List[int]
8 :type obstacles: List[List[int]]
9 :rtype: int
10 """
11 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
12 x, y, i = 0, 0, 0
13 lookup = set(map(tuple, obstacles))
14 result = 0
15 for cmd in commands:
16 if cmd == -2:
17 i = (i-1) % 4
18 elif cmd == -1:
19 i = (i+1) % 4
20 else:
21 for k in xrange(cmd):
22 if (x+directions[i][0], y+directions[i][1]) not in lookup:
23 x += directions[i][0]
24 y += directions[i][1]
25 result = max(result, x*x + y*y)
26 return result
27
*************************

221. Middle of the Linked List


*************************

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]


Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]


Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

The number of nodes in the list is in the range[1, 100].


1 <= Node.val <= 100
*************************

221. Middle of the Linked List(C++)


*************************

1 // Time: O(n)
2 // Space: O(1)
3
4 /**
5 * Definition for singly-linked list.
6 * struct ListNode {
7 * int val;
8 * ListNode *next;
9 * ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12 class Solution {
13 public:
14 ListNode* middleNode(ListNode* head) {
15 auto slow = head, fast = head;
16 while (fast && fast->next) {
17 slow = slow->next;
18 fast = fast->next->next;
19 }
20 return slow;
21 }
22 };
*************************

221. Middle of the Linked List(Python)


*************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class ListNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.next = None
8
9 class Solution(object):
10 def middleNode(self, head):
11 """
12 :type head: ListNode
13 :rtype: ListNode
14 """
15 slow, fast = head, head
16 while fast and fast.next:
17 slow, fast = slow.next, fast.next.next
18 return slow
19
****************************

222. Projection Area of 3D Shapes


****************************

You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x , y , and z axes.

Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).

We view the projection of these cubes onto thexy, yz, and zx planes.

A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow"
when looking at the cubes from the top, the front, and the side.

Return the total area of all three projections.

Example 1:

Input: grid = [[1,2],[3,4]]


Output: 17
Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane.

Example 2:

Input: grid = [[2]]


Output: 5

Example 3:

Input: grid = [[1,0],[0,2]]


Output: 8

Example 4:

Input: grid = [[1,1,1],[1,0,1],[1,1,1]]


Output: 14

Example 5:

Input: grid = [[2,2,2],[2,1,2],[2,2,2]]


Output: 21
Constraints:

n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
****************************

222. Projection Area of 3D Shapes(C++)


****************************

1 // Time: O(n^2)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int projectionArea(vector>& grid) {
7 int result = 0;
8 for (int i = 0; i < grid.size(); ++i) {
9 int max_row = 0;
10 int max_col = 0;
11 for (int j = 0; j < grid.size(); ++j) {
12 if (grid[i][j] > 0) {
13 ++result;
14 }
15 max_row = max(max_row, grid[i][j]);
16 max_col = max(max_col, grid[j][i]);
17 }
18 result += max_row + max_col;
19 }
20 return result;
21 }
22 };
****************************

222. Projection Area of 3D Shapes(Python)


****************************

1 # Time: O(n^2)
2 # Space: O(1)
3
4 class Solution(object):
5 def projectionArea(self, grid):
6 """
7 :type grid: List[List[int]]
8 :rtype: int
9 """
10 result = 0
11 for i in xrange(len(grid)):
12 max_row, max_col = 0, 0
13 for j in xrange(len(grid)):
14 if grid[i][j]:
15 result += 1
16 max_row = max(max_row, grid[i][j])
17 max_col = max(max_col, grid[j][i])
18 result += max_row + max_col
19 return result
20
*********************************

223. Uncommon Words from Two Sentences


*********************************

A sentence is a string of single-space separated words where each word consists only of lowercase letters.

A word is uncommon if it appears exactly once in one of the sentences, anddoes not appear in the other sentence.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer inany order.

Example 1:

Input: s1 = "this apple is sweet", s2 = "this apple is sour"


Output: ["sweet","sour"]

Example 2:

Input: s1 = "apple apple", s2 = "banana"


Output: ["banana"]

Constraints:

1 <= s1.length, s2.length <= 200


s1 and s2 consist of lowercase English letters and spaces.
s1 and s2 do not have leading or trailing spaces.
All the words in s1 and s2 are separated by a single space.
*********************************

223. Uncommon Words from Two Sentences(C++)


*********************************

1 // Time: O(m + n)
2 // Space: O(m + n)
3
4 class Solution {
5 public:
6 vector uncommonFromSentences(string A, string B) {
7 unordered_map count;
8 istringstream iss(A + " " + B);
9 while (iss >> A) {
10 ++count[A];
11 }
12 vector result;
13 for (const auto& word : count) {
14 if (word.second == 1) {
15 result.emplace_back(word.first);
16 }
17 }
18 return result;
19 }
20 };
*********************************

223. Uncommon Words from Two Sentences(Python)


*********************************

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 import collections
5
6
7 class Solution(object):
8 def uncommonFromSentences(self, A, B):
9 """
10 :type A: str
11 :type B: str
12 :rtype: List[str]
13 """
14 count = collections.Counter(A.split())
15 count += collections.Counter(B.split())
16 return [word for word in count if count[word] == 1]
17
***************

224. Fair Candy Swap


***************

Alice and Bob have a different total number of candies. You are given two integer arraysaliceSizes and bobSizes where
aliceSizes[i] is the number of candies of theith box of candy that Alice has and bobSizes[j] is the number of candies of thejth box
of candy that Bob has.

Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the
same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they
have.

Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, andanswer[1] is
the number of candies in the box that Bob must exchange. If there are multiple answers, you mayreturn any one of them. It
is guaranteed that at least one answer exists.

Example 1:

Input: aliceSizes = [1,1], bobSizes = [2,2]


Output: [1,2]

Example 2:

Input: aliceSizes = [1,2], bobSizes = [2,3]


Output: [1,2]

Example 3:

Input: aliceSizes = [2], bobSizes = [1,3]


Output: [2,3]

Example 4:

Input: aliceSizes = [1,2,5], bobSizes = [2,4]


Output: [5,4]

Constraints:

1 <= aliceSizes.length, bobSizes.length <= 10 4


1 <= aliceSizes[i], bobSizes[j] <= 10 5
Alice and Bob have a different total number of candies.
There will be at least one valid answer for the given input.
***************

224. Fair Candy Swap(C++)


***************

1 // Time: O(m + n)
2 // Space: O(m + n)
3
4 class Solution {
5 public:
6 vector fairCandySwap(vector& A, vector& B) {
7 int diff = (accumulate(A.cbegin(), A.cend(), 0) -
8 accumulate(B.cbegin(), B.cend(), 0)) / 2;
9 unordered_set setA(A.begin(), A.end());
10 for (const auto& b: B) {
11 if (setA.count(b + diff)) {
12 return {b + diff, b};
13 }
14 }
15 return {};
16 }
17 };
***************

224. Fair Candy Swap(Python)


***************

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 class Solution(object):
5 def fairCandySwap(self, A, B):
6 """
7 :type A: List[int]
8 :type B: List[int]
9 :rtype: List[int]
10 """
11 diff = (sum(A)-sum(B))//2
12 setA = set(A)
13 for b in set(B):
14 if diff+b in setA:
15 return [diff+b, b]
16 return []
17
*************************

225. Surface Area of 3D Shapes


*************************

You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes
placed on top of cell (i, j).

After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D
shapes.

Return the total surface area of the resulting shapes.

Note: The bottom face of each shape counts toward its surface area.

Example 1:

Input: grid = [[2]]


Output: 10

Example 2:

Input: grid = [[1,2],[3,4]]


Output: 34

Example 3:

Input: grid = [[1,0],[0,2]]


Output: 16

Example 4:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 32

Example 5:

Input: grid = [[2,2,2],[2,1,2],[2,2,2]]


Output: 46

Constraints:

n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
*************************

225. Surface Area of 3D Shapes(C++)


*************************

1 // Time: O(n^2)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int surfaceArea(vector>& grid) {
7 int result = 0;
8 for (int i = 0; i < grid.size(); ++i) {
9 for (int j = 0; j < grid.size(); ++j) {
10 if (grid[i][j]) {
11 result += grid[i][j] * 4 + 2;
12 }
13 if (i) {
14 result -= min(grid[i][j], grid[i - 1][j]) * 2;
15 }
16 if (j) {
17 result -= min(grid[i][j], grid[i][j - 1]) * 2;
18 }
19 }
20 }
21 return result;
22 }
23 };
*************************

225. Surface Area of 3D Shapes(Python)


*************************

1 # Time: O(n^2)
2 # Space: O(1)
3
4 class Solution(object):
5 def surfaceArea(self, grid):
6 """
7 :type grid: List[List[int]]
8 :rtype: int
9 """
10 result = 0
11 for i in xrange(len(grid)):
12 for j in xrange(len(grid)):
13 if grid[i][j]:
14 result += 2 + grid[i][j]*4
15 if i:
16 result -= min(grid[i][j], grid[i-1][j])*2
17 if j:
18 result -= min(grid[i][j], grid[i][j-1])*2
19 return result
20
************************************

226. Groups of Special-Equivalent Strings


************************************

You are given an array of strings of the same lengthwords.

In one move, you can swap any two even indexed characters or any two odd indexed characters of a stringwords[i].

Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j] .

For example, words[i] = "zzxy" and words[j] = "xyzz" are special-equivalent because we may make the moves"zzxy" -> "xzzy"
-> "xyzz".

A group of special-equivalent strings from words is a non-empty subset of words such that:

Every pair of strings in the group are special equivalent, and


The group is the largest size possible (i.e., there is not a stringwords[i] not in the group such that words[i] is special-
equivalent to every string in the group).

Return the number of groups of special-equivalent strings from words.

Example 1:

Input: words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]


Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special
The other two groups are ["xyzz", "zzxy"] and ["zzyx"].
Note that in particular, "zzxy" is not special equivalent to "zzyx".

Example 2:

Input: words = ["abc","acb","bac","bca","cab","cba"]


Output: 3

Constraints:

1 <= words.length <= 1000


1 <= words[i].length <= 20
words[i] consist of lowercase English letters.
All the strings are of the same length.
************************************

226. Groups of Special-Equivalent Strings(C++)


************************************

1 // Time: O(n * l)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int numSpecialEquivGroups(vector& A) {
7 unordered_set lookup;
8 for (const auto& s: A) {
9 string count(52, 0);
10 for (int i = 0; i < s.length(); ++i) {
11 ++count[s[i] - 'a' + 26 * (i % 2)];
12 }
13 lookup.emplace(count);
14 }
15 return lookup.size();
16 }
17 };
************************************

226. Groups of Special-Equivalent Strings(Python)


************************************

1 # Time: O(n * l)
2 # Space: O(n)
3
4 class Solution(object):
5 def numSpecialEquivGroups(self, A):
6 """
7 :type A: List[str]
8 :rtype: int
9 """
10 def count(word):
11 result = [0]*52
12 for i, letter in enumerate(word):
13 result[ord(letter)-ord('a') + 26*(i%2)] += 1
14 return tuple(result)
15
16 return len({count(word) for word in A})
17
***************

227. Monotonic Array


***************

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array nums is monotone increasing if for all i <= j , nums[i] <= nums[j] . An array nums is monotone decreasing if for all i <= j ,
nums[i] >= nums[j] .

Given an integer array nums, return true if the given array is monotonic, orfalse otherwise.

Example 1:

Input: nums = [1,2,2,3]


Output: true

Example 2:

Input: nums = [6,5,4,4]


Output: true

Example 3:

Input: nums = [1,3,2]


Output: false

Example 4:

Input: nums = [1,2,4,5]


Output: true

Example 5:

Input: nums = [1,1,1]


Output: true

Constraints:

1 <= nums.length <= 10 5


-105 <= nums[i] <= 10 5
***************

227. Monotonic Array(C++)


***************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isMonotonic(vector& A) {
7 bool inc = false, dec = false;
8 for (int i = 0; i + 1 < A.size(); ++i) {
9 if (A[i] < A[i + 1]) {
10 inc = true;
11 } else if (A[i] > A[i + 1]) {
12 dec = true;
13 }
14 }
15 return !inc || !dec;
16 }
17 };
***************

227. Monotonic Array(Python)


***************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def isMonotonic(self, A):
6 """
7 :type A: List[int]
8 :rtype: bool
9 """
10 inc, dec = False, False
11 for i in xrange(len(A)-1):
12 if A[i] < A[i+1]:
13 inc = True
14 elif A[i] > A[i+1]:
15 dec = True
16 return not inc or not dec
17
****************************

228. Increasing Order Search Tree


****************************

Given the root of a binary search tree, rearrange the tree inin-order so that the leftmost node in the tree is now the root of
the tree, and every node has no left child and only one right child.

Example 1:

Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]


Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

Example 2:

Input: root = [5,1,7]


Output: [1,null,5,null,7]

Constraints:

The number of nodes in the given tree will be in the range[1, 100].
0 <= Node.val <= 1000
****************************

228. Increasing Order Search Tree(C++)


****************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 TreeNode* increasingBST(TreeNode* root) {
16 return increasingBSTHelper(root, nullptr);
17 }
18
19 private:
20 TreeNode* increasingBSTHelper(TreeNode* root, TreeNode* tail) {
21 if (!root) {
22 return tail;
23 }
24 auto result = increasingBSTHelper(root->left, root);
25 root->left = nullptr;
26 root->right = increasingBSTHelper(root->right, tail);
27 return result;
28 }
29 };
****************************

228. Increasing Order Search Tree(Python)


****************************

1 # Time: O(n)
2 # Space: O(h)
3
4 class TreeNode(object):
5 def __init__(self, x):
6 self.val = x
7 self.left = None
8 self.right = None
9
10
11 class Solution(object):
12 def increasingBST(self, root):
13 """
14 :type root: TreeNode
15 :rtype: TreeNode
16 """
17 def increasingBSTHelper(root, tail):
18 if not root:
19 return tail
20 result = increasingBSTHelper(root.left, root)
21 root.left = None
22 root.right = increasingBSTHelper(root.right, tail)
23 return result
24 return increasingBSTHelper(root, None)
25
********************

229. Sort Array By Parity


********************

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

Example 1:

Input: nums = [3,1,2,4]


Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:

Input: nums = [0]


Output: [0]

Constraints:

1 <= nums.length <= 5000


0 <= nums[i] <= 5000
********************

229. Sort Array By Parity(C++)


********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector sortArrayByParity(vector& A) {
7 for (int i = 0, j = 0; j < A.size(); ++j) {
8 if (A[j] % 2 == 0) {
9 swap(A[i++], A[j]);
10 }
11 }
12 return A;
13 }
14 };
********************

229. Sort Array By Parity(Python)


********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def sortArrayByParity(self, A):
6 """
7 :type A: List[int]
8 :rtype: List[int]
9 """
10 i = 0
11 for j in xrange(len(A)):
12 if A[j] % 2 == 0:
13 A[i], A[j] = A[j], A[i]
14 i += 1
15 return A
16
****************

230. Smallest Range I


****************

You are given an integer array nums and an integer k .

In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer
from the range [-k, k]. You can apply this operation at most once for each index i.

The score of nums is the difference between the maximum and minimum elements innums.

Return the minimum score of nums after applying the mentioned operation at most once for each index in it.

Example 1:

Input: nums = [1], k = 0


Output: 0
Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.

Example 2:

Input: nums = [0,10], k = 2


Output: 6
Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.

Example 3:

Input: nums = [1,3,6], k = 3


Output: 0
Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.

Constraints:

1 <= nums.length <= 10 4


0 <= nums[i] <= 10 4
0 <= k <= 10 4
****************

230. Smallest Range I(C++)


****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int smallestRangeI(vector& A, int K) {
7 return max(0, *max_element(A.cbegin(), A.cend()) -
8 *min_element(A.cbegin(), A.cend()) -
9 2 * K);
10 }
11 };
****************

230. Smallest Range I(Python)


****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def smallestRangeI(self, A, K):
6 """
7 :type A: List[int]
8 :type K: int
9 :rtype: int
10 """
11 return max(0, max(A) - min(A) - 2*K)
12
******************************

231. X of a Kind in a Deck of Cards


******************************

In a deck of cards, each card has an integer written on it.

Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards,
where:

Each group has exactly X cards.


All the cards in each group have the same integer.

Example 1:

Input: deck = [1,2,3,4,4,3,2,1]


Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Example 2:

Input: deck = [1,1,1,2,2,2,3,3]


Output: false
Explanation: No possible partition.

Example 3:

Input: deck = [1]


Output: false
Explanation: No possible partition.

Example 4:

Input: deck = [1,1]


Output: true
Explanation: Possible partition [1,1].

Example 5:

Input: deck = [1,1,2,2,2,2]


Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].

Constraints:

1 <= deck.length <= 104


0 <= deck[i] < 10 4
******************************

231. X of a Kind in a Deck of Cards(C++)


******************************

1 // Time: O(n * (logn)^2)


2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool hasGroupsSizeX(vector& deck) {
7 unordered_map count;
8 for (const auto& i : deck) {
9 ++count[i];
10 }
11 int result = 0;
12 for (const auto& kvp : count) {
13 result = gcd(result, kvp.second);
14 }
15 return result > 1;
16 }
17
18 private:
19 int gcd(int a, int b) {
20 while (b != 0) {
21 int tmp = b;
22 b = a % b;
23 a = tmp;
24 }
25 return a;
26 }
27 };
******************************

231. X of a Kind in a Deck of Cards(Python)


******************************

1 # Time: O(n * (logn)^2)


2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def hasGroupsSizeX(self, deck):
9 """
10 :type deck: List[int]
11 :rtype: bool
12 """
13 def gcd(a, b): # Time: O((logn)^2)
14 while b:
15 a, b = b, a % b
16 return a
17
18 vals = collections.Counter(deck).values()
19 return reduce(gcd, vals) >= 2
20
********************

232. Reverse Only Letters


********************

Given a string s , reverse the string according to the following rules:

All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.

Return s after reversing it.

Example 1:

Input: s = "ab-cd"
Output: "dc-ba"

Example 2:

Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Constraints:

1 <= s.length <= 100


s consists of characters with ASCII values in the range[33, 122] .
s does not contain '\"' or '\\'.
********************

232. Reverse Only Letters(C++)


********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reverseOnlyLetters(string S) {
7 string result;
8 int i = S.length() - 1;
9 for (const auto& c : S) {
10 if (isalpha(c)) {
11 while (!isalpha(S[i])) {
12 --i;
13 }
14 result.push_back(S[i]);
15 --i;
16 } else {
17 result.push_back(c);
18 }
19 }
20 return result;
21 }
22 };
********************

232. Reverse Only Letters(Python)


********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def reverseOnlyLetters(self, S):
6 """
7 :type S: str
8 :rtype: str
9 """
10 def getNext(S):
11 for i in reversed(xrange(len(S))):
12 if S[i].isalpha():
13 yield S[i]
14
15 result = []
16 letter = getNext(S)
17 for i in xrange(len(S)):
18 if S[i].isalpha():
19 result.append(letter.next())
20 else:
21 result.append(S[i])
22 return "".join(result)
23
***********************

233. Sort Array By Parity II


***********************

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.

Example 1:

Input: nums = [4,2,5,7]


Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Example 2:

Input: nums = [2,3]


Output: [2,3]

Constraints:

2 <= nums.length <= 2 * 10 4


nums.length is even.
Half of the integers in nums are even.
0 <= nums[i] <= 1000

Follow Up: Could you solve it in-place?


***********************

233. Sort Array By Parity II(C++)


***********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector sortArrayByParityII(vector& A) {
7 int j = 1;
8 for (int i = 0; i < A.size(); i += 2) {
9 if (A[i] % 2) {
10 while (A[j] % 2) {
11 j += 2;
12 }
13 swap(A[i], A[j]);
14 }
15 }
16 return A;
17 }
18 };
***********************

233. Sort Array By Parity II(Python)


***********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def sortArrayByParityII(self, A):
6 """
7 :type A: List[int]
8 :rtype: List[int]
9 """
10 j = 1
11 for i in xrange(0, len(A), 2):
12 if A[i] % 2:
13 while A[j] % 2:
14 j += 2
15 A[i], A[j] = A[j], A[i]
16 return A
*****************

234. Long Pressed Name


*****************

Your friend is typing his name into a keyboard. Sometimes, when typing a character c , the key might get long pressed, and
the character will be typed 1 or more times.

You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some
characters (possibly none) being long pressed.

Example 1:

Input: name = "alex", typed = "aaleex"


Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.

Example 2:

Input: name = "saeed", typed = "ssaaedd"


Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.

Example 3:

Input: name = "leelee", typed = "lleeelee"


Output: true

Example 4:

Input: name = "laiden", typed = "laiden"


Output: true
Explanation: It's not necessary to long press any character.

Constraints:

1 <= name.length <= 1000


1 <= typed.length <= 1000
name and typed contain only lowercase English letters.
*****************

234. Long Pressed Name(C++)


*****************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isLongPressedName(string name, string typed) {
7 int i = 0;
8 for (int j = 0; j < typed.length(); ++j) {
9 if (i < name.length() && name[i] == typed[j]) {
10 ++i;
11 } else if (j == 0 || typed[j] != typed[j - 1]) {
12 return false;
13 }
14 }
15 return i == name.length();
16 }
17 };
*****************

234. Long Pressed Name(Python)


*****************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def isLongPressedName(self, name, typed):
6 """
7 :type name: str
8 :type typed: str
9 :rtype: bool
10 """
11 i = 0
12 for j in xrange(len(typed)):
13 if i < len(name) and name[i] == typed[j]:
14 i += 1
15 elif j == 0 or typed[j] != typed[j-1]:
16 return False
17 return i == len(name)
**********************

235. Unique Email Addresses


**********************

Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the
email may contain one or more '.' or '+' .

For example, in "[email protected]", "alice" is the local name, and "leetcode.com" is the domain name.

If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded
to the same address without dots in the local name. Note that this rule does not apply to domain names.

For example, "[email protected]" and "[email protected]" forward to the same email address.

If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be
filtered. Note that this rule does not apply to domain names.

For example, "[email protected]" will be forwarded to "[email protected]".

It is possible to use both of these rules at the same time.

Given an array of strings emails where we send one email to each email[i], return the number of different addresses that
actually receive mails.

Example 1:

Input: emails = ["[email protected]","[email protected]","[email protected]"]


Output: 2
Explanation: "[email protected]" and "[email protected]" actually receive mails.

Example 2:

Input: emails = ["[email protected]","[email protected]","[email protected]"]


Output: 3

Constraints:

1 <= emails.length <= 100


1 <= emails[i].length <= 100
email[i] consist of lowercase English letters, '+' , '.' and '@'.
Each emails[i] contains exactly one '@' character.
All local and domain names are non-empty.
Local names do not start with a '+' character.
**********************

235. Unique Email Addresses(C++)


**********************

1 // Time: O(n * l)
2 // Space: O(n * l)
3
4 class Solution {
5 public:
6 int numUniqueEmails(vector& emails) {
7 unordered_set result;
8 for (const auto& email : emails) {
9 result.emplace(convert(email));
10 }
11 return result.size();
12 }
13
14 private:
15 string convert(const string& email) {
16 const auto& at_it = email.find('@');
17 const auto& domain = email.substr(at_it);
18 auto name = email.substr(0, at_it);
19 name = name.substr(0, name.find('+'));
20 name.erase(remove(name.begin(), name.end(), '.'), name.end());
21 auto new_email = move(name);
22 new_email += domain;
23 return new_email;
24 }
25 };
**********************

235. Unique Email Addresses(Python)


**********************

1 # Time: O(n * l)
2 # Space: O(n * l)
3
4 class Solution(object):
5 def numUniqueEmails(self, emails):
6 """
7 :type emails: List[str]
8 :rtype: int
9 """
10 def convert(email):
11 name, domain = email.split('@')
12 name = name[:name.index('+')]
13 return "".join(["".join(name.split(".")), '@', domain])
14
15 lookup = set()
16 for email in emails:
17 lookup.add(convert(email))
18 return len(lookup)
19
**********************

236. Number of Recent Calls


**********************

You have a RecentCounter class which counts the number of recent requests within a certain time frame.

Implement the RecentCounter class:

RecentCounter() Initializes the counter with zero recent requests.


int ping(int t) Adds a new request at timet , where t represents some time in milliseconds, and returns the number of
requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number
of requests that have happened in the inclusive range [t - 3000, t].

It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

Example 1:

Input
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output
[null, 1, 2, 3, 3]

Explanation
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1
recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2
recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3

Constraints:

1 <= t <= 10 9
Each test case will call ping with strictly increasing values of t.
At most 104 calls will be made to ping .
**********************

236. Number of Recent Calls(C++)


**********************

1 // Time: O(1) on average


2 // Space: O(w), w means the size of the last milliseconds
3
4 class RecentCounter {
5 public:
6 RecentCounter() {
7
8 }
9
10 int ping(int t) {
11 q_.emplace(t);
12 while (q_.front() < t - 3000) {
13 q_.pop();
14 }
15 return q_.size();
16 }
17
18 private:
19 queue q_;
20 };
21
22 /**
23 * Your RecentCounter object will be instantiated and called as such:
24 * RecentCounter* obj = new RecentCounter();
25 * int param_1 = obj->ping(t);
26 */
27
**********************

236. Number of Recent Calls(Python)


**********************

1 # Time: O(1) on average


2 # Space: O(w), w means the size of the last milliseconds.
3
4 import collections
5
6
7 class RecentCounter(object):
8
9 def __init__(self):
10 self.__q = collections.deque()
11
12 def ping(self, t):
13 """
14 :type t: int
15 :rtype: int
16 """
17 self.__q.append(t)
18 while self.__q[0] < t-3000:
19 self.__q.popleft()
20 return len(self.__q)
*****************

237. Reorder Log Files


*****************

You are given an array of logs. Each log is a space-delimited string of words, where the first word is theidentifier.

There are two types of logs:

Letter-logs: All words (except the identifier) consist of lowercase English letters.
Digit-logs: All words (except the identifier) consist of digits.

Reorder these logs so that:

1. The letter-logs come before all digit-logs.


2. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them
lexicographically by their identifiers.
3. The digit-logs maintain their relative ordering.

Return the final order of the logs.

Example 1:

Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Explanation:
The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".

Example 2:

Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]

Constraints:

1 <= logs.length <= 100


3 <= logs[i].length <= 100
All the tokens of logs[i] are separated by a single space.
logs[i] is guaranteed to have an identifier and at least one word after the identifier.
*****************

237. Reorder Log Files(C++)


*****************

1 // Time: O(nlogn * l), n is the length of files, l is the average length of strings
2 // Space: O(l)
3
4 class Solution {
5 public:
6 vector reorderLogFiles(vector& logs) {
7 auto pivot = stable_partition(logs.begin(), logs.end(),
8 []( const auto& log ) {
9 return isalpha(log.back());
10 });
11 sort(logs.begin(), pivot,
12 [](const auto& a, const auto& b) {
13 int i = a.find_first_of(' '), j = b.find_first_of(' ');
14 return a.substr(i) != b.substr(j) ?
15 a.substr(i) < b.substr(j) :
16 a.substr(0, i) < b.substr(0, j);
17 });
18 return logs;
19 }
20 };
*****************

237. Reorder Log Files(Python)


*****************

1 # Time: O(nlogn * l), n is the length of files, l is the average length of strings
2 # Space: O(l)
3
4 class Solution(object):
5 def reorderLogFiles(self, logs):
6 """
7 :type logs: List[str]
8 :rtype: List[str]
9 """
10 def f(log):
11 i, content = log.split(" ", 1)
12 return (0, content, i) if content[0].isalpha() else (1,)
13
14 logs.sort(key=f)
15 return logs
********************

238. Valid Mountain Array


********************

Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:

arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Example 1:

Input: arr = [2,1]


Output: false

Example 2:

Input: arr = [3,5,5]


Output: false

Example 3:

Input: arr = [0,3,2,1]


Output: true

Constraints:

1 <= arr.length <= 10 4


0 <= arr[i] <= 10 4
********************

238. Valid Mountain Array(C++)


********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool validMountainArray(vector& A) {
7 int i = 0;
8 while (i + 1 < A.size() && A[i] < A[i + 1]) {
9 ++i;
10 }
11 int j = A.size() - 1;
12 while (j - 1 >= 0 && A[j - 1] > A[j]) {
13 --j;
14 }
15 return 0 < i && i == j && j < A.size() - 1;
16 }
17 };
********************

238. Valid Mountain Array(Python)


********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def validMountainArray(self, A):
6 """
7 :type A: List[int]
8 :rtype: bool
9 """
10 i = 0
11 while i+1 < len(A) and A[i] < A[i+1]:
12 i += 1
13 j = len(A)-1
14 while j-1 >= 0 and A[j-1] > A[j]:
15 j -= 1
16 return 0 < i == j < len(A)-1
***************

239. DI String Match


***************

A permutation perm of n + 1 integers of all the integers in the range[0, n] can be represented as a string s of length n where:

s[i] == 'I' if perm[i] < perm[i + 1] , and


s[i] == 'D' if perm[i] > perm[i + 1] .

Given a string s , reconstruct the permutation perm and return it. If there are multiple valid permutations perm, returnany of
them.

Example 1:

Input: s = "IDID"
Output: [0,4,1,3,2]

Example 2:

Input: s = "III"
Output: [0,1,2,3]

Example 3:

Input: s = "DDI"
Output: [3,2,0,1]

Constraints:

1 <= s.length <= 105


s[i] is either 'I' or 'D'.
***************

239. DI String Match(C++)


***************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector diStringMatch(string S) {
7 vector result;
8 int left = 0, right = S.length();
9 for (const auto& c : S) {
10 if (c == 'I') {
11 result.emplace_back(left);
12 ++left;
13 } else {
14 result.emplace_back(right);
15 --right;
16 }
17 }
18 result.emplace_back(left);
19 return result;
20 }
21 };
***************

239. DI String Match(Python)


***************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def diStringMatch(self, S):
6 """
7 :type S: str
8 :rtype: List[int]
9 """
10 result = []
11 left, right = 0, len(S)
12 for c in S:
13 if c == 'I':
14 result.append(left)
15 left += 1
16 else:
17 result.append(right)
18 right -= 1
19 result.append(left)
20 return result
*****************************

240. Largest Time for Given Digits


*****************************

Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digitexactly once.

24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour
time is 00:00, and the latest is 23:59.

Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return an empty string.

Example 1:

Input: arr = [1,2,3,4]


Output: "23:41"
Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of the

Example 2:

Input: arr = [5,5,5,5]


Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.

Example 3:

Input: arr = [0,0,0,0]


Output: "00:00"

Example 4:

Input: arr = [0,0,1,0]


Output: "10:00"

Constraints:

arr.length == 4
0 <= arr[i] <= 9
*****************************

240. Largest Time for Given Digits(C++)


*****************************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string largestTimeFromDigits(vector& A) {
7 string result;
8 sort(A.begin(), A.end(), greater());
9 do {
10 if (A[0] * 10 + A[1] < 24 && A[2] < 6) {
11 for (const auto& i : A) {
12 if (result.length() == 2) {
13 result += ":";
14 }
15 result += to_string(i);
16 }
17 break;
18 }
19 } while (next_permutation(A.begin(), A.end(), greater()));
20 return result;
21 }
22 };
*****************************

240. Largest Time for Given Digits(Python)


*****************************

1 # Time: O(1)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def largestTimeFromDigits(self, A):
9 """
10 :type A: List[int]
11 :rtype: str
12 """
13 result = ""
14 for i in xrange(len(A)):
15 A[i] *= -1
16 A.sort()
17 for h1, h2, m1, m2 in itertools.permutations(A):
18 hours = -(10*h1 + h2)
19 mins = -(10*m1 + m2)
20 if 0 <= hours < 24 and 0 <= mins < 60:
21 result = "{:02}:{:02}".format(hours, mins)
22 break
23 return result
24
*****************************

241. Verifying an Alien Dictionary


*****************************

In an alien language, surprisingly they also use english lowercase letters, but possibly in a differentorder. The order of the
alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given
words are sorted lexicographicaly in this alien language.

Example 1:

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"


Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"


Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"


Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" >

Constraints:

1 <= words.length <= 100


1 <= words[i].length <= 20
order.length == 26
All characters in words[i] and order are English lowercase letters.
*****************************

241. Verifying an Alien Dictionary(C++)


*****************************

1 // Time: O(n * l), l is the average length of words


2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isAlienSorted(vector& words, string order) {
7 vector lookup(order.size());
8 for (int i = 0; i < order.size(); ++i) {
9 lookup[order[i] - 'a'] = i;
10 }
11 for (int i = 0; i < words.size() - 1; ++i) {
12 const auto& word1 = words[i];
13 const auto& word2 = words[i + 1];
14 int j = 0;
15 for (; j < min(word1.length(), word2.length()); ++j) {
16 if (word1[j] != word2[j]) {
17 if (lookup[word1[j] - 'a'] > lookup[word2[j] - 'a']) {
18 return false;
19 }
20 break;
21 }
22 }
23 if (j == min(word1.length(), word2.length()) &&
24 word1.length() > word2.length()) {
25 return false;
26 }
27 }
28 return true;
29 }
30 };
*****************************

241. Verifying an Alien Dictionary(Python)


*****************************

1 # Time: O(n * l), l is the average length of words


2 # Space: O(1)
3
4 class Solution(object):
5 def isAlienSorted(self, words, order):
6 """
7 :type words: List[str]
8 :type order: str
9 :rtype: bool
10 """
11 lookup = {c: i for i, c in enumerate(order)}
12 for i in xrange(len(words)-1):
13 word1 = words[i]
14 word2 = words[i+1]
15 for k in xrange(min(len(word1), len(word2))):
16 if word1[k] != word2[k]:
17 if lookup[word1[k]] > lookup[word2[k]]:
18 return False
19 break
20 else:
21 if len(word1) > len(word2):
22 return False
23 return True
***********************************

242. N-Repeated Element in Size 2N Array


***********************************

You are given an integer array nums with the following properties:

nums.length == 2 * n .
nums contains n + 1
unique elements.
Exactly one element of nums is repeated n times.

Return the element that is repeated n times.

Example 1:

Input: nums = [1,2,3,3]


Output: 3

Example 2:

Input: nums = [2,1,2,5,3,2]


Output: 2

Example 3:

Input: nums = [5,1,5,2,5,3,5,4]


Output: 5

Constraints:

2 <= n <= 5000


nums.length == 2 * n
0 <= nums[i] <= 10 4
nums contains n + 1 unique elements and one of them is repeated exactly n times.
***********************************

242. N-Repeated Element in Size 2N Array(C++)


***********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int repeatedNTimes(vector& A) {
7 for (int i = 2; i < A.size(); ++i) {
8 if (A[i - 1] == A[i] || A[i - 2] == A[i]) {
9 return A[i];
10 }
11 }
12 return A[0];
13 }
14 };
***********************************

242. N-Repeated Element in Size 2N Array(Python)


***********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def repeatedNTimes(self, A):
6 """
7 :type A: List[int]
8 :rtype: int
9 """
10 for i in xrange(2, len(A)):
11 if A[i-1] == A[i] or A[i-2] == A[i]:
12 return A[i]
13 return A[0]
*********************

243. Univalued Binary Tree


*********************

A binary tree is uni-valued if every node in the tree has the same value.

Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

Example 1:

Input: root = [1,1,1,1,1,null,1]


Output: true

Example 2:

Input: root = [2,2,2,5,2]


Output: false

Constraints:

The number of nodes in the tree is in the range[1, 100].


0 <= Node.val < 100
*********************

243. Univalued Binary Tree(C++)


*********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 bool isUnivalTree(TreeNode* root) {
16 vector s{root};
17 while (!s.empty()) {
18 auto node = s.back(); s.pop_back();
19 if (!node) {
20 continue;
21 }
22 if (node->val != root->val) {
23 return false;
24 }
25 s.emplace_back(node->left);
26 s.emplace_back(node->right);
27 }
28 return true;
29 }
30 };
31
32 // Time: O(n)
33 // Space: O(h)
34 class Solution2 {
35 public:
36 bool isUnivalTree(TreeNode* root) {
37 return (!root->left || (root->left->val == root->val & isUnivalTree(root->left))) &&
38 (!root->right || (root->right->val == root->val & isUnivalTree(root->right)));
39 }
40 };
*********************

243. Univalued Binary Tree(Python)


*********************

1 # Time: O(n)
2 # Space: O(h)
3
4 # Definition for a binary tree node.
5 class TreeNode(object):
6 def __init__(self, x):
7 self.val = x
8 self.left = None
9 self.right = None
10
11
12 class Solution(object):
13 def isUnivalTree(self, root):
14 """
15 :type root: TreeNode
16 :rtype: bool
17 """
18 s = [root]
19 while s:
20 node = s.pop()
21 if not node:
22 continue
23 if node.val != root.val:
24 return False
25 s.append(node.left)
26 s.append(node.right)
27 return True
28
29
30 # Time: O(n)
31 # Space: O(h)
32 class Solution2(object):
33 def isUnivalTree(self, root):
34 """
35 :type root: TreeNode
36 :rtype: bool
37 """
38 return (not root.left or (root.left.val == root.val and self.isUnivalTree(root.left))) and \
39 (not root.right or (root.right.val == root.val and self.isUnivalTree(root.right)))
*****************

244. Powerful Integers


*****************

Given three integers x , y , and bound, return a list of all the powerful integers that have a value less than or equal tobound.

An integer is powerful if it can be represented as x i + y j for some integers i >= 0 and j >= 0 .

You may return the answer in any order. In your answer, each value should occurat most once.

Example 1:

Input: x = 2, y = 3, bound = 10
Output: [2,3,4,5,7,9,10]
Explanation:
2 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32

Example 2:

Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]

Constraints:

1 <= x, y <= 100


0 <= bound <= 10 6
*****************

244. Powerful Integers(C++)


*****************

1 // Time: O((logn)^2), n is the bound


2 // Space: O(r), r is the size of the result
3
4 class Solution {
5 public:
6 vector powerfulIntegers(int x, int y, int bound) {
7 unordered_set result;
8 int log_x = (x != 1) ? int(floor(log(bound) / log(x))) + 1 : 1;
9 int log_y = (y != 1) ? int(floor(log(bound) / log(y))) + 1 : 1;
10 for (int i = 0, pow_x = 1; i < log_x; ++i, pow_x *= x) {
11 for (int j = 0, pow_y = 1; j < log_y; ++j, pow_y *= y) {
12 auto val = pow_x + pow_y;
13 if (val <= bound) {
14 result.emplace(val);
15 }
16 }
17 }
18 return vector(result.cbegin(), result.cend());
19 }
20 };
*****************

244. Powerful Integers(Python)


*****************

1 # Time: O((logn)^2), n is the bound


2 # Space: O(r), r is the size of the result
3
4 import math
5
6
7 class Solution(object):
8 def powerfulIntegers(self, x, y, bound):
9 """
10 :type x: int
11 :type y: int
12 :type bound: int
13 :rtype: List[int]
14 """
15 result = set()
16 log_x = int(math.floor(math.log(bound) / math.log(x)))+1 if x != 1 else 1
17 log_y = int(math.floor(math.log(bound) / math.log(y)))+1 if y != 1 else 1
18 pow_x = 1
19 for i in xrange(log_x):
20 pow_y = 1
21 for j in xrange(log_y):
22 val = pow_x + pow_y
23 if val <= bound:
24 result.add(val)
25 pow_y *= y
26 pow_x *= x
27 return list(result)
**************************

245. K Closest Points to Origin


**************************

Given an array of points where points[i] = [x i, y i] represents a point on the X-Y plane and an integer k , return the k closest points
to the origin (0, 0) .

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x 2)2 + (y 1 - y 2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

Example 1:

Input: points = [[1,3],[-2,2]], k = 1


Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], k = 2


Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.

Constraints:

1 <= k <= points.length <= 10 4


-104 < x i, y i < 10 4
**************************

245. K Closest Points to Origin(C++)


**************************

1 // Time: O(n) on average


2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> kClosest(vector>& points, int K) {
7 static const auto& dist = [](const vector& v) {
8 return v[0] * v[0] + v[1] * v[1];
9 };
10 nth_element(points.begin(), points.begin() + K - 1, points.end(),
11 [&](const vector& a, const vector& b) {
12 return dist(a) < dist(b);
13 });
14 return {points.cbegin(), points.cbegin() + K};
15 }
16 };
17
18 // Time: O(nlogk)
19 // Space: O(k)
20 class Solution2 {
21 public:
22 vector> kClosest(vector>& points, int K) {
23 static const auto& dist = [](const vector& v) {
24 return v[0] * v[0] + v[1] * v[1];
25 };
26
27 struct Compare {
28 bool operator()(const vector& a, const vector& b) {
29 return dist(a) < dist(b);
30 }
31 };
32 priority_queue, vector>, Compare> max_heap;
33 for (const auto& point : points) {
34 max_heap.emplace(point);
35 if (max_heap.size() > K) {
36 max_heap.pop();
37 }
38 }
39 vector> result;
40 while (!max_heap.empty()) {
41 result.emplace_back(max_heap.top()), max_heap.pop();
42 }
43 return result;
44 }
45 };
**************************

245. K Closest Points to Origin(Python)


**************************
1 # Time: O(n) on average
2 # Space: O(1)
3
4 # quick select solution
5 from random import randint
6
7
8 class Solution(object):
9 def kClosest(self, points, K):
10 """
11 :type points: List[List[int]]
12 :type K: int
13 :rtype: List[List[int]]
14 """
15 def dist(point):
16 return point[0]**2 + point[1]**2
17
18 def kthElement(nums, k, compare):
19 def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
20 new_pivot_idx = left
21 nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
22 for i in xrange(left, right):
23 if compare(nums[i], nums[right]):
24 nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
25 new_pivot_idx += 1
26
27 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
28 return new_pivot_idx
29
30 left, right = 0, len(nums) - 1
31 while left <= right:
32 pivot_idx = randint(left, right)
33 new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
34 if new_pivot_idx == k:
35 return
36 elif new_pivot_idx > k:
37 right = new_pivot_idx - 1
38 else: # new_pivot_idx < k.
39 left = new_pivot_idx + 1
40
41 kthElement(points, K-1, lambda a, b: dist(a) < dist(b))
42 return points[:K]
43
44
45 # Time: O(nlogk)
46 # Space: O(k)
47 import heapq
48
49
50 class Solution2(object):
51 def kClosest(self, points, K):
52 """
53 :type points: List[List[int]]
54 :type K: int
55 :rtype: List[List[int]]
56 """
57 def dist(point):
58 return point[0]**2 + point[1]**2
59
60 max_heap = []
61 for point in points:
62 heapq.heappush(max_heap, (-dist(point), point))
63 if len(max_heap) > K:
64 heapq.heappop(max_heap)
65 return [heapq.heappop(max_heap)[1] for _ in xrange(len(max_heap))]
**************************

246. Largest Perimeter Triangle


**************************

Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these
lengths. If it is impossible to form any triangle of a non-zero area, return0.

Example 1:

Input: nums = [2,1,2]


Output: 5

Example 2:

Input: nums = [1,2,1]


Output: 0

Example 3:

Input: nums = [3,2,3,4]


Output: 10

Example 4:

Input: nums = [3,6,2,3]


Output: 8

Constraints:

3 <= nums.length <= 10 4


1 <= nums[i] <= 10 6
**************************

246. Largest Perimeter Triangle(C++)


**************************

1 // Time: O(nlogn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int largestPerimeter(vector& A) {
7 sort(A.begin(), A.end());
8 for (int i = A.size() - 3; i >= 0; --i) {
9 if (A[i] + A[i + 1] > A[i + 2]) {
10 return A[i] + A[i + 1] + A[i + 2];
11 }
12 }
13 return 0;
14 }
15 };
**************************

246. Largest Perimeter Triangle(Python)


**************************

1 # Time: O(nlogn)
2 # Space: O(1)
3
4 class Solution(object):
5 def largestPerimeter(self, A):
6 """
7 :type A: List[int]
8 :rtype: int
9 """
10 A.sort()
11 for i in reversed(xrange(len(A) - 2)):
12 if A[i] + A[i+1] > A[i+2]:
13 return A[i] + A[i+1] + A[i+2]
14 return 0
*************************

247. Squares of a Sorted Array


*************************

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-
decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]


Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]


Output: [4,9,9,49,121]

Constraints:

1 <= nums.length <= 104


-104 <= nums[i] <= 10 4
nums is sorted in non-decreasing order.

Follow up: Squaring each element and sorting the new array is very trivial, could you find anO(n) solution using a different
approach?
*************************

247. Squares of a Sorted Array(C++)


*************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector sortedSquares(vector& A) {
7 int right = distance(A.cbegin(), lower_bound(A.cbegin(), A.cend(), 0));
8 int left = right - 1;
9 vector result;
10 while (0 <= left || right < A.size()) {
11 if (right == A.size() ||
12 (0 <= left && A[left] * A[left] < A[right] * A[right])) {
13 result.emplace_back(A[left] * A[left]);
14 --left;
15 } else {
16 result.emplace_back(A[right] * A[right]);
17 ++right;
18 }
19 }
20 return result;
21 }
22 };
*************************

247. Squares of a Sorted Array(Python)


*************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import bisect
5
6
7 class Solution(object):
8 def sortedSquares(self, A):
9 """
10 :type A: List[int]
11 :rtype: List[int]
12 """
13 right = bisect.bisect_left(A, 0)
14 left = right-1
15 result = []
16 while 0 <= left or right < len(A):
17 if right == len(A) or \
18 (0 <= left and A[left]**2 < A[right]**2):
19 result.append(A[left]**2)
20 left -= 1
21 else:
22 result.append(A[right]**2)
23 right += 1
24 return result
*************************

248. String Without AAA or BBB


*************************

Given two integers a and b, return any string s such that:

shas length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,
The substring 'aaa' does not occur in s , and
The substring 'bbb' does not occur in s .

Example 1:

Input: a = 1, b = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:

Input: a = 4, b = 1
Output: "aabaa"

Constraints:

0 <= a, b <= 100


It is guaranteed such an s exists for the given a and b.
*************************

248. String Without AAA or BBB(C++)


*************************

1 // Time: O(a + b)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string strWithout3a3b(int A, int B) {
7 string result;
8 bool put_A = false;
9 while (A || B) {
10 if (result.length() >= 2 &&
11 result.back() == result[result.length() - 2]) {
12 put_A = (result.back() == 'b');
13 } else {
14 put_A = (A >= B);
15 }
16 if (put_A) {
17 --A;
18 result.push_back('a');
19 } else {
20 --B;
21 result.push_back('b');
22 }
23 }
24 return result;
25 }
26 };
*************************

248. String Without AAA or BBB(Python)


*************************

1 # Time: O(a + b)
2 # Space: O(1)
3
4 class Solution(object):
5 def strWithout3a3b(self, A, B):
6 """
7 :type A: int
8 :type B: int
9 :rtype: str
10 """
11 result = []
12 put_A = None
13 while A or B:
14 if len(result) >= 2 and result[-1] == result[-2]:
15 put_A = result[-1] == 'b'
16 else:
17 put_A = A >= B
18
19 if put_A:
20 A -= 1
21 result.append('a')
22 else:
23 B -= 1
24 result.append('b')
25 return "".join(result)
*********************************

249. Sum of Even Numbers After Queries


*********************************

You are given an integer array nums and an array queries where queries[i] = [val i, index i].

For each query i, first, apply nums[indexi] = nums[index i] + val i, then print the sum of the even values ofnums.

Return an integer array answer where answer[i] is the answer to the ith query.

Example 1:

Input: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]


Output: [8,6,2,4]
Explanation: At the beginning, the array is [1,2,3,4].
After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.

Example 2:

Input: nums = [1], queries = [[4,0]]


Output: [0]

Constraints:

1 <= nums.length <= 10 4


-104 <= nums[i] <= 10 4
1 <= queries.length <= 10 4
-104 <= val i <= 104
0 <= index i < nums.length
*********************************

249. Sum of Even Numbers After Queries(C++)


*********************************

1 // Time: O(n + q)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector sumEvenAfterQueries(vector& A, vector>& queries) {
7 auto total = accumulate(A.cbegin(), A.cend(), 0,
8 [](int sum, int val) {
9 return sum + (val % 2 == 0 ? val : 0);
10 });
11
12 vector result;
13 for (const auto& q : queries) {
14 int v = q[0], i = q[1];
15 if (A[i] % 2 == 0) {
16 total -= A[i];
17 }
18 A[i] += v;
19 if (A[i] % 2 == 0) {
20 total += A[i];
21 }
22 result.emplace_back(total);
23 }
24 return result;
25 }
26 };
*********************************

249. Sum of Even Numbers After Queries(Python)


*********************************

1 # Time: O(n + q)
2 # Space: O(1)
3
4 class Solution(object):
5 def sumEvenAfterQueries(self, A, queries):
6 """
7 :type A: List[int]
8 :type queries: List[List[int]]
9 :rtype: List[int]
10 """
11 total = sum(v for v in A if v % 2 == 0)
12
13 result = []
14 for v, i in queries:
15 if A[i] % 2 == 0:
16 total -= A[i]
17 A[i] += v
18 if A[i] % 2 == 0:
19 total += A[i]
20 result.append(total)
21 return result
****************************

250. Add to Array-Form of Integer


****************************

The array-form of an integer num is an array representing its digits in left to right order.

For example, for num = 1321 , the array form is [1,3,2,1].

Given num, the array-form of an integer, and an integer k , return the array-form of the integer num + k .

Example 1:

Input: num = [1,2,0,0], k = 34


Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:

Input: num = [2,7,4], k = 181


Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:

Input: num = [2,1,5], k = 806


Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

Example 4:

Input: num = [9,9,9,9,9,9,9,9,9,9], k = 1


Output: [1,0,0,0,0,0,0,0,0,0,0]
Explanation: 9999999999 + 1 = 10000000000

Constraints:

1 <= num.length <= 10 4


0 <= num[i] <= 9
num does not contain any leading zeros except for the zero itself.
1 <= k <= 10 4
****************************

250. Add to Array-Form of Integer(C++)


****************************

1 // Time: O(n + logk)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector addToArrayForm(vector& A, int K) {
7 reverse(A.begin(), A.end());
8 int carry = K, i = 0;
9 A[i] += carry;
10 carry = A[i] / 10;
11 A[i] %= 10;
12 while (carry) {
13 ++i;
14 if (i < A.size()) {
15 A[i] += carry;
16 } else {
17 A.emplace_back(carry);
18 }
19 carry = A[i] / 10;
20 A[i] %= 10;
21 }
22 reverse(A.begin(), A.end());
23 return A;
24 }
25 };
****************************

250. Add to Array-Form of Integer(Python)


****************************

1 # Time: O(n + logk)


2 # Space: O(1)
3
4 class Solution(object):
5 def addToArrayForm(self, A, K):
6 """
7 :type A: List[int]
8 :type K: int
9 :rtype: List[int]
10 """
11 A.reverse()
12 carry, i = K, 0
13 A[i] += carry
14 carry, A[i] = divmod(A[i], 10)
15 while carry:
16 i += 1
17 if i < len(A):
18 A[i] += carry
19 else:
20 A.append(carry)
21 carry, A[i] = divmod(A[i], 10)
22 A.reverse()
23 return A
**********************

251. Cousins in Binary Tree


**********************

Given the root of a binary tree with unique values and the values of two different nodes of the treex and y , return true if the
nodes corresponding to the values x and y in the tree are cousins, or false otherwise.

Two nodes of a binary tree are cousins if they have the same depth with different parents.

Note that in a binary tree, the root node is at the depth0, and children of each depth k node are at the depth k + 1 .

Example 1:

Input: root = [1,2,3,4], x = 4, y = 3


Output: false

Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4


Output: true

Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

Constraints:

The number of nodes in the tree is in the range[2, 100].


1 <= Node.val <= 100
Each node has a unique value.
x != y
x and y are exist in the tree.
**********************

251. Cousins in Binary Tree(C++)


**********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 bool isCousins(TreeNode* root, int x, int y) {
16 int depth_x = 0, depth_y = 0;
17 TreeNode *parent_x = nullptr, *parent_y = nullptr;
18 return dfs(root, x, &depth_x, &parent_x) &&
19 dfs(root, y, &depth_y, &parent_y) &&
20 depth_x == depth_y &&
21 parent_x != parent_y;
22 }
23
24 private:
25 bool dfs(TreeNode *root, int x, int *depth, TreeNode **parent) {
26 if (!root) {
27 return false;
28 }
29 if (root->val == x) {
30 return true;
31 }
32 ++(*depth);
33 auto prev_parent = (*parent);
34 (*parent) = root;
35 if (dfs(root->left, x, depth, parent)) {
36 return true;
37 }
38 (*parent) = root;
39 if (dfs(root->right, x, depth, parent)) {
40 return true;
41 }
42 (*parent) = prev_parent;
43 --(*depth);
44 return false;
45 }
46 };
**********************

251. Cousins in Binary Tree(Python)


**********************

1 # Time: O(n)
2 # Space: O(h)
3
4 # Definition for a binary tree node.
5 class TreeNode(object):
6 def __init__(self, x):
7 self.val = x
8 self.left = None
9 self.right = None
10
11
12 class Solution(object):
13 def isCousins(self, root, x, y):
14 """
15 :type root: TreeNode
16 :type x: int
17 :type y: int
18 :rtype: bool
19 """
20 def dfs(root, x, depth, parent):
21 if not root:
22 return False
23 if root.val == x:
24 return True
25 depth[0] += 1
26 prev_parent, parent[0] = parent[0], root
27 if dfs(root.left, x, depth, parent):
28 return True
29 parent[0] = root
30 if dfs(root.right, x, depth, parent):
31 return True
32 parent[0] = prev_parent
33 depth[0] -= 1
34 return False
35
36 depth_x, depth_y = [0], [0]
37 parent_x, parent_y = [None], [None]
38 return dfs(root, x, depth_x, parent_x) and \
39 dfs(root, y, depth_y, parent_y) and \
40 depth_x[0] == depth_y[0] and \
41 parent_x[0] != parent_y[0]
42
43
***************

252. Rotting Oranges


***************

You are given an m x n grid where each cell can have one of three values:

0 representing an empty cell,


1 representing a fresh orange, or
2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Example 1:

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]


Output: 4

Example 2:

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]


Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.

Example 3:

Input: grid = [[0,2]]


Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j] is 0, 1, or 2.
***************

252. Rotting Oranges(C++)


***************

1 // Time: O(m * n)
2 // Space: O(m * n)
3
4 class Solution {
5 public:
6 int orangesRotting(vector>& grid) {
7 static const vector> directions{{0, 1}, {1, 0},
8 {0, -1}, {-1, 0}};
9
10 int count = 0;
11 queue> q;
12 for (int r = 0; r < grid.size(); ++r) {
13 for (int c = 0; c < grid[r].size(); ++c) {
14 if (grid[r][c] == 2) {
15 q.emplace(r, c, 0);
16 } else if (grid[r][c] == 1) {
17 ++count;
18 }
19 }
20 }
21
22 int result = 0;
23 while (!q.empty()) {
24 int r, c;
25 tie(r, c, result) = q.front(); q.pop();
26 for (const auto& d : directions) {
27 int nr = r + d.first, nc = c + d.second;
28 if (!(0 <= nr && nr < grid.size() &&
29 0 <= nc && nc < grid[r].size())) {
30 continue;
31 }
32 if (grid[nr][nc] == 1) {
33 --count;
34 grid[nr][nc] = 2;
35 q.emplace(nr, nc, result + 1);
36 }
37 }
38 }
39 return (count == 0) ? result : -1;
40 }
41 };
***************

252. Rotting Oranges(Python)


***************

1 # Time: O(m * n)
2 # Space: O(m * n)
3
4 import collections
5
6
7 class Solution(object):
8 def orangesRotting(self, grid):
9 """
10 :type grid: List[List[int]]
11 :rtype: int
12 """
13 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
14
15 count = 0
16 q = collections.deque()
17 for r, row in enumerate(grid):
18 for c, val in enumerate(row):
19 if val == 2:
20 q.append((r, c, 0))
21 elif val == 1:
22 count += 1
23
24 result = 0
25 while q:
26 r, c, result = q.popleft()
27 for d in directions:
28 nr, nc = r+d[0], c+d[1]
29 if not (0 <= nr < len(grid) and \
30 0 <= nc < len(grid[r])):
31 continue
32 if grid[nr][nc] == 1:
33 count -= 1
34 grid[nr][nc] = 2
35 q.append((nr, nc, result+1))
36 return result if count == 0 else -1
*******************

253. Find the Town Judge


*******************

In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

1. The town judge trusts nobody.


2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties 1 and 2.

You are given an array trust where trust[i] = [a i, b i] representing that the person labeled ai trusts the person labeled bi.

Return the label of the town judge if the town judge exists and can be identified, or return-1 otherwise.

Example 1:

Input: n = 2, trust = [[1,2]]


Output: 2

Example 2:

Input: n = 3, trust = [[1,3],[2,3]]


Output: 3

Example 3:

Input: n = 3, trust = [[1,3],[2,3],[3,1]]


Output: -1

Example 4:

Input: n = 3, trust = [[1,2],[2,3]]


Output: -1

Example 5:

Input: n = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]


Output: 3

Constraints:

1 <= n <= 1000


0 <= trust.length <= 10 4
trust[i].length == 2
All the pairs of trust are unique.
ai != b i
1 <= ai, b i <= n
*******************

253. Find the Town Judge(C++)


*******************

1 // Time: O(t + n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int findJudge(int N, vector>& trust) {
7 vector degrees(N);
8 for (const auto& t : trust) {
9 --degrees[t[0] - 1];
10 ++degrees[t[1] - 1];
11 }
12 for (int i = 0; i < degrees.size(); ++i) {
13 if (degrees[i] == N - 1) {
14 return i + 1;
15 }
16 }
17 return -1;
18 }
19 };
*******************

253. Find the Town Judge(Python)


*******************

1 # Time: O(t + n)
2 # Space: O(n)
3
4 class Solution(object):
5 def findJudge(self, N, trust):
6 """
7 :type N: int
8 :type trust: List[List[int]]
9 :rtype: int
10 """
11 degrees = [0]*N
12 for i, j in trust:
13 degrees[i-1] -= 1
14 degrees[j-1] += 1
15 for i in xrange(len(degrees)):
16 if degrees[i] == N-1:
17 return i+1
18 return -1
***************************

254. Available Captures for Rook


***************************

On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty
squares '.'.

When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction
until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is
considered attacking a pawn if the rook can capture the pawn on the rook's turn. Thenumber of available captures for
the white rook is the number of pawns that the rook is attacking.

Return the number of available captures for the white rook.

Example 1:

Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".


Output: 3
Explanation: In this example, the rook is attacking all the pawns.

Example 2:
Input: board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p
Output: 0
Explanation: The bishops are blocking the rook from attacking any of the pawns.

Example 3:

Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p


Output: 3
Explanation: The rook is attacking the pawns at positions b5, d6, and f5.

Constraints:

board.length == 8
board[i].length == 8
board[i][j] is either 'R', '.' , 'B' ,
or 'p'
There is exactly one cell with board[i][j] == 'R'
***************************

254. Available Captures for Rook(C++)


***************************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numRookCaptures(vector>& board) {
7 static vector> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
8
9 int r = -1, c = -1;
10 for (int i = 0; i < 8 && r == -1; ++i) {
11 for (int j = 0; j < 8; ++j) {
12 if (board[i][j] == 'R') {
13 tie(r, c) = make_pair(i, j);
14 break;
15 }
16 }
17 }
18
19 int result = 0;
20 for (const auto& d : directions) {
21 int nr, nc;
22 tie(nr, nc) = make_pair(r + d.first, c + d.second);
23 while (0 <= nr && nr < 8 && 0 <= nc && nc < 8) {
24 if (board[nr][nc] == 'p') {
25 ++result;
26 }
27 if (board[nr][nc] != '.') {
28 break;
29 }
30 tie(nr, nc) = make_pair(nr + d.first, nc + d.second);
31 }
32 }
33 return result;
34 }
35 };
***************************

254. Available Captures for Rook(Python)


***************************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def numRookCaptures(self, board):
6 """
7 :type board: List[List[str]]
8 :rtype: int
9 """
10 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
11
12 r, c = None, None
13 for i in xrange(8):
14 if r is not None:
15 break
16 for j in xrange(8):
17 if board[i][j] == 'R':
18 r, c = i, j
19 break
20
21 result = 0
22 for d in directions:
23 nr, nc = r+d[0], c+d[1]
24 while 0 <= nr < 8 and 0 <= nc < 8:
25 if board[nr][nc] == 'p':
26 result += 1
27 if board[nr][nc] != '.':
28 break
29 nr, nc= nr+d[0], nc+d[1]
30 return result
**********************

255. Find Common Characters


**********************

Given a string array words, return an array of all characters that show up in all strings within thewords (including duplicates).
You may return the answer in any order.

Example 1:

Input: words = ["bella","label","roller"]


Output: ["e","l","l"]

Example 2:

Input: words = ["cool","lock","cook"]


Output: ["c","o"]

Constraints:

1 <= words.length <= 100


1 <= words[i].length <= 100
words[i] consists of lowercase English letters.
**********************

255. Find Common Characters(C++)


**********************

1 // Time: O(n * l)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector commonChars(vector& A) {
7 vector count(26, numeric_limits::max());
8 vector result;
9 for (const auto& a : A) {
10 vector tmp_count(count.size());
11 for (const auto& c : a) {
12 ++tmp_count[c - 'a'];
13 }
14 for (int i = 0; i < count.size(); ++i) {
15 count[i] = min(count[i], tmp_count[i]);
16 }
17 }
18 for (int i = 0; i < count.size(); ++i) {
19 for (auto j = 0; j < count[i]; ++j) {
20 result.emplace_back(1, i + 'a');
21 }
22 }
23 return result;
24 }
25 };
**********************

255. Find Common Characters(Python)


**********************

1 # Time: O(n * l)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def commonChars(self, A):
9 """
10 :type A: List[str]
11 :rtype: List[str]
12 """
13 result = collections.Counter(A[0])
14 for a in A:
15 result &= collections.Counter(a)
16 return list(result.elements())
***************************************

256. Maximize Sum Of Array After K Negations


***************************************

Given an integer array nums and an integer k , modify the array in the following way:

choose an index i and replace nums[i] with -nums[i].

You should apply this process exactly k times. You may choose the same index i multiple times.

Return the largest possible sum of the array after modifying it in this way.

Example 1:

Input: nums = [4,2,3], k = 1


Output: 5
Explanation: Choose index 1 and nums becomes [4,-2,3].

Example 2:

Input: nums = [3,-1,0,2], k = 3


Output: 6
Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].

Example 3:

Input: nums = [2,-3,-1,5,-4], k = 2


Output: 13
Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].

Constraints:

1 <= nums.length <= 10 4


-100 <= nums[i] <= 100
1 <= k <= 10 4
***************************************

256. Maximize Sum Of Array After K Negations(C++)


***************************************

1 // Time: O(n) ~ O(n^2), O(n) on average.


2 // Space: O(1)
3
4 // quick select solution
5 class Solution {
6 public:
7 int largestSumAfterKNegations(vector& A, int K) {
8 nth_element(A.begin(), A.begin() + K, A.end());
9 int remain = K;
10 for (int i = 0; i < K; ++i) {
11 if (A[i] < 0) {
12 A[i] = -A[i];
13 --remain;
14 }
15 }
16 return accumulate(A.cbegin(), A.cend(), 0) -
17 (remain % 2) * *min_element(A.cbegin(), A.cend()) * 2;
18 }
19 };
20
21 // Time: O(nlogn)
22 // Space: O(1)
23 class Solution2 {
24 public:
25 int largestSumAfterKNegations(vector& A, int K) {
26 sort(A.begin(), A.end());
27 int remain = K;
28 for (int i = 0; i < K && A[i] < 0; ++i) {
29 A[i] = -A[i];
30 --remain;
31 }
32 return accumulate(A.cbegin(), A.cend(), 0) -
33 (remain % 2) * *min_element(A.cbegin(), A.cend()) * 2;
34 }
35 };
***************************************

256. Maximize Sum Of Array After K Negations(Python)


***************************************
1 # Time: O(n) ~ O(n^2), O(n) on average.
2 # Space: O(1)
3
4 import random
5
6
7 # quick select solution
8 class Solution(object):
9 def largestSumAfterKNegations(self, A, K):
10 """
11 :type A: List[int]
12 :type K: int
13 :rtype: int
14 """
15 def kthElement(nums, k, compare):
16 def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
17 new_pivot_idx = left
18 nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
19 for i in xrange(left, right):
20 if compare(nums[i], nums[right]):
21 nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
22 new_pivot_idx += 1
23
24 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
25 return new_pivot_idx
26
27 left, right = 0, len(nums) - 1
28 while left <= right:
29 pivot_idx = random.randint(left, right)
30 new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
31 if new_pivot_idx == k:
32 return
33 elif new_pivot_idx > k:
34 right = new_pivot_idx - 1
35 else: # new_pivot_idx < k.
36 left = new_pivot_idx + 1
37
38 kthElement(A, K, lambda a, b: a < b)
39 remain = K
40 for i in xrange(K):
41 if A[i] < 0:
42 A[i] = -A[i]
43 remain -= 1
44 return sum(A) - ((remain)%2)*min(A)*2
45
46
47 # Time: O(nlogn)
48 # Space: O(1)
49 class Solution2(object):
50 def largestSumAfterKNegations(self, A, K):
51 """
52 :type A: List[int]
53 :type K: int
54 :rtype: int
55 """
56 A.sort()
57 remain = K
58 for i in xrange(K):
59 if A[i] >= 0:
60 break
61 A[i] = -A[i]
62 remain -= 1
63 return sum(A) - (remain%2)*min(A)*2
*****************************

257. Complement of Base 10 Integer


*****************************

The complement of an integer is the integer you get when you flip all the0's to 1's and all the 1's to 0's in its binary
representation.

For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.

Given an integer n, return its complement.

Example 1:

Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.

Example 2:

Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.

Example 3:

Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.

Constraints:

0 <= n < 10 9

Note: This question is the same as 476:https://leetcode.com/problems/number-complement/


*****************************

257. Complement of Base 10 Integer(C++)


*****************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int bitwiseComplement(int N) {
7 int mask = 1;
8 while (N > mask) {
9 mask = mask * 2 + 1;
10 }
11 return mask - N;
12 }
13 };
*****************************

257. Complement of Base 10 Integer(Python)


*****************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def bitwiseComplement(self, N):
6 """
7 :type N: int
8 :rtype: int
9 """
10 mask = 1
11 while N > mask:
12 mask = mask*2+1
13 return mask-N
***************************************************

258. Pairs of Songs With Total Durations Divisible by 60


***************************************************

Given an array of integers arr, return true if we can partition the array into threenon-empty parts with equal sums.

Formally, we can partition the array if we can find indexesi + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] ==
arr[j] + arr[j + 1] + ... + arr[arr.length - 1])

Example 1:

Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1]


Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:

Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]


Output: false

Example 3:

Input: arr = [3,3,6,5,-2,2,5,1,-9,4]


Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Constraints:

3 <= arr.length <= 5 * 10 4


-104 <= arr[i] <= 10 4
***************************************************

258. Pairs of Songs With Total Durations Divisible by


60(C++)
***************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numPairsDivisibleBy60(vector& time) {
7 int result = 0;
8 vector counter(60);
9 for (const auto& t : time) {
10 result += counter[(60 - t % 60) % 60];
11 ++counter[t % 60];
12 }
13 return result;
14 }
15 };
***************************************************

258. Pairs of Songs With Total Durations Divisible by


60(Python)
***************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def numPairsDivisibleBy60(self, time):
9 """
10 :type time: List[int]
11 :rtype: int
12 """
13 result = 0
14 count = collections.Counter()
15 for t in time:
16 result += count[-t%60]
17 count[t%60] += 1
18 return result
****************************

259. Binary Prefix Divisible By 5


****************************

You are given a binary array nums (0-indexed).

We define x i as the number whose binary representation is the subarraynums[0..i] (from most-significant-bit to least-
significant-bit).

For example, if nums = [1,0,1] , then x 0 = 1 , x 1 = 2 , and x 2 = 5 .

Return an array of booleans answer where answer[i] is true if x i is divisible by 5.

Example 1:

Input: nums = [0,1,1]


Output: [true,false,false]
Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer[0] is true.

Example 2:

Input: nums = [1,1,1]


Output: [false,false,false]

Example 3:

Input: nums = [0,1,1,1,1,1]


Output: [true,false,false,false,true,false]

Example 4:

Input: nums = [1,1,1,0,1]


Output: [false,false,false,false,false]

Constraints:

1 <= nums.length <= 10 5


nums[i] is 0 or 1.
****************************

259. Binary Prefix Divisible By 5(C++)


****************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector prefixesDivBy5(vector& A) {
7 for (int i = 1; i < A.size(); ++i) {
8 A[i] += A[i - 1] * 2 % 5;
9 }
10 vector result(A.size());
11 transform(A.cbegin(), A.cend(), result.begin(),
12 [](int x) { return x % 5 == 0; });
13 return result;
14 }
15 };
****************************

259. Binary Prefix Divisible By 5(Python)


****************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def prefixesDivBy5(self, A):
6 """
7 :type A: List[int]
8 :rtype: List[bool]
9 """
10 for i in xrange(1, len(A)):
11 A[i] += A[i-1] * 2 % 5
12 return [x % 5 == 0 for x in A]
***********************************************

260. Partition Array Into Three Parts With Equal Sum


***********************************************

You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

A move consists of walking from one land cell to another adjacent 4( -directionally) land cell or walking off the boundary of
the grid.

Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number ofmoves.

Example 1:

Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]


Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.

Example 2:

Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]


Output: 0
Explanation: All 1s are either on the boundary or can reach the boundary.
Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j] is either 0 or 1.
***********************************************

260. Partition Array Into Three Parts With Equal Sum(C++)


***********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool canThreePartsEqualSum(vector& A) {
7 const auto& total = accumulate(A.cbegin(), A.cend(), 0);
8 if (total % 3 != 0) {
9 return false;
10 }
11 int curr = 0, parts = 0;
12 for (const auto& x : A) {
13 curr += x;
14 if (curr == total / 3) {
15 ++parts, curr = 0;
16 }
17 }
18 return parts >= 3;
19 }
20 };
***********************************************

260. Partition Array Into Three Parts With Equal


Sum(Python)
***********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def canThreePartsEqualSum(self, A):
6 """
7 :type A: List[int]
8 :rtype: bool
9 """
10 total = sum(A)
11 if total % 3 != 0:
12 return False
13 parts, curr = 0, 0
14 for x in A:
15 curr += x
16 if curr == total//3:
17 parts += 1
18 curr = 0
19 return parts >= 3
****************************

261. Remove Outermost Parentheses


****************************

A valid parentheses string is either empty "", "(" + A + ")" , or A + B , where A and B are valid parentheses strings, and +
represents string concatenation.

For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it intos = A + B , with A and B
nonempty valid parentheses strings.

Given a valid parentheses string s , consider its primitive decomposition: s = P 1 + P 2 + ... + P k, where Pi are primitive valid
parentheses strings.

Return s after removing the outermost parentheses of every primitive string in the primitive decomposition ofs .

Example 1:

Input: s = "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

Example 2:

Input: s = "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".

Example 3:

Input: s = "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

Constraints:

1 <= s.length <= 105


s[i] is either '(' or ')'.
s is a valid parentheses string.
****************************

261. Remove Outermost Parentheses(C++)


****************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string removeOuterParentheses(string S) {
7 static const int deep = 1;
8 string result;
9 int cnt = 0;
10 for (const auto& c : S) {
11 if (c == '(' && cnt++ >= deep) {
12 result += c;
13 }
14 if (c == ')' && cnt-- > deep) {
15 result += c;
16 }
17 }
18 return result;
19 }
20 };
****************************

261. Remove Outermost Parentheses(Python)


****************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def removeOuterParentheses(self, S):
6 """
7 :type S: str
8 :rtype: str
9 """
10 deep = 1
11 result, cnt = [], 0
12 for c in S:
13 if c == '(' and cnt >= deep:
14 result.append(c)
15 if c == ')' and cnt > deep:
16 result.append(c)
17 cnt += 1 if c == '(' else -1
18 return "".join(result)
**********************************

262. Sum of Root To Leaf Binary Numbers


**********************************

You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary
number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1 , then this could represent 01101 in
binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits integer.

Example 1:

Input: root = [1,0,1,0,1,0,1]


Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Example 2:

Input: root = [0]


Output: 0

Example 3:

Input: root = [1]


Output: 1

Example 4:

Input: root = [1,1]


Output: 3

Constraints:

The number of nodes in the tree is in the range[1, 1000].


Node.val is 0 or 1.
**********************************

262. Sum of Root To Leaf Binary Numbers(C++)


**********************************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 int sumRootToLeaf(TreeNode* root) {
16 return sumRootToLeafHelper(root, 0);
17 }
18
19 private:
20 int sumRootToLeafHelper(TreeNode* root, int val) {
21 static const int M = 1e9 + 7;
22 if (!root) {
23 return 0;
24 }
25 val = (val * 2 + root->val) % M;
26 if (!root->left && !root->right) {
27 return val;
28 }
29 return (sumRootToLeafHelper(root->left, val) +
30 sumRootToLeafHelper(root->right, val)) % M;
31 }
32 };
**********************************

262. Sum of Root To Leaf Binary Numbers(Python)


**********************************

1 # Time: O(n)
2 # Space: O(h)
3
4 # Definition for a binary tree node.
5 class TreeNode(object):
6 def __init__(self, x):
7 self.val = x
8 self.left = None
9 self.right = None
10
11
12 class Solution(object):
13 def sumRootToLeaf(self, root):
14 """
15 :type root: TreeNode
16 :rtype: int
17 """
18 M = 10**9 + 7
19 def sumRootToLeafHelper(root, val):
20 if not root:
21 return 0
22 val = (val*2 + root.val) % M
23 if not root.left and not root.right:
24 return val
25 return (sumRootToLeafHelper(root.left, val) +
26 sumRootToLeafHelper(root.right, val)) % M
27
28 return sumRootToLeafHelper(root, 0)
************

263. Divisor Game


************

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:

Choosing any x with 0 < x < n and n % x == 0 .


Replacing the number n on the chalkboard with n - x .

Also, if a player cannot make a move, they lose the game.

Return true if and only if Alice wins the game, assuming both players play optimally.

Example 1:

Input: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

Input: n = 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.

Constraints:

1 <= n <= 1000


************

263. Divisor Game(C++)


************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool divisorGame(int N) {
7 // 1. if we get an even, we can choose x = 1
8 // to make the opponent always get an odd
9 // 2. if the opponent gets an odd, he can only choose x = 1 or other odds
10 // and we can still get an even
11 // 3. at the end, the opponent can only choose x = 1 and we win
12 // 4. in summary, we win if only if we get an even and
13 // keeps even until the opponent loses
14 return N % 2 == 0;
15 }
16 };
17
18 // Time: O(n^3/2)
19 // Space: O(n)
20 // dp solution
21 class Solution2 {
22 public:
23 bool divisorGame(int N) {
24 unordered_map dp;
25 return memoization(N, &dp);
26 }
27
28 private:
29 bool memoization(int N, unordered_map *dp) {
30 if (N == 1) {
31 return false;
32 }
33 if (!dp->count(N)) {
34 bool result = false;
35 for (auto i = 1; i * i <= N; ++i) {
36 if (N % i == 0) {
37 if (!memoization(N - i, dp)) {
38 result = true;
39 break;
40 }
41 }
42 }
43 (*dp)[N] = result;
44 }
45 return (*dp)[N];
46 }
47 };
************

263. Divisor Game(Python)


************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def divisorGame(self, N):
6 """
7 :type N: int
8 :rtype: bool
9 """
10 # 1. if we get an even, we can choose x = 1
11 # to make the opponent always get an odd
12 # 2. if the opponent gets an odd, he can only choose x = 1 or other odds
13 # and we can still get an even
14 # 3. at the end, the opponent can only choose x = 1 and we win
15 # 4. in summary, we win if only if we get an even and
16 # keeps even until the opponent loses
17 return N % 2 == 0
18
19
20 # Time: O(n^3/2)
21 # Space: O(n)
22 # dp solution
23 class Solution2(object):
24 def divisorGame(self, N):
25 """
26 :type N: int
27 :rtype: bool
28 """
29 def memoization(N, dp):
30 if N == 1:
31 return False
32 if N not in dp:
33 result = False
34 for i in xrange(1, N+1):
35 if i*i > N:
36 break
37 if N % i == 0:
38 if not memoization(N-i, dp):
39 result = True
40 break
41 dp[N] = result
42 return dp[N]
43
44 return memoization(N, {})
*******************

264. Two City Scheduling


*******************

A company is planning to interview 2n people. Given the array costs where costs[i] = [aCost i, bCost i], the cost of flying the ith
person to city a is aCosti, and the cost of flying theith person to city b is bCosti.

Return the minimum cost to fly every person to a citysuch that exactly n people arrive in each city.

Example 1:

Input: costs = [[10,20],[30,200],[400,50],[30,20]]


Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

Example 2:

Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]


Output: 1859

Example 3:

Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]


Output: 3086

Constraints:

2 * n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCost i, bCost i <= 1000
*******************

264. Two City Scheduling(C++)


*******************

1 // Time: O(n) ~ O(n^2), O(n) on average.


2 // Space: O(1)
3
4 // quick select solution
5 class Solution {
6 public:
7 int twoCitySchedCost(vector>& costs) {
8 static auto cmp = [](auto &a, auto &b) {
9 return a[0] - a[1] < b[0] - b[1];
10 };
11
12 nth_element(costs.begin(),
13 costs.begin() + costs.size() / 2,
14 costs.end(),
15 cmp);
16
17 int result = 0;
18 for (int i = 0; i < costs.size(); ++i) {
19 result += (i < costs.size() / 2) ? costs[i][0] : costs[i][1];
20 }
21 return result;
22 }
23 };
*******************

264. Two City Scheduling(Python)


*******************

1 # Time: O(n) ~ O(n^2), O(n) on average.


2 # Space: O(1)
3
4 import random
5
6
7 # quick select solution
8 class Solution(object):
9 def twoCitySchedCost(self, costs):
10 """
11 :type costs: List[List[int]]
12 :rtype: int
13 """
14 def kthElement(nums, k, compare):
15 def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
16 new_pivot_idx = left
17 nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
18 for i in xrange(left, right):
19 if compare(nums[i], nums[right]):
20 nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
21 new_pivot_idx += 1
22
23 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
24 return new_pivot_idx
25
26 left, right = 0, len(nums) - 1
27 while left <= right:
28 pivot_idx = random.randint(left, right)
29 new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
30 if new_pivot_idx == k:
31 return
32 elif new_pivot_idx > k:
33 right = new_pivot_idx - 1
34 else: # new_pivot_idx < k.
35 left = new_pivot_idx + 1
36
37 kthElement(costs, len(costs)//2, lambda a, b: a[0]-a[1] < b[0]-b[1])
38 result = 0
39 for i in xrange(len(costs)):
40 result += costs[i][0] if i < len(costs)//2 else costs[i][1]
41 return result
******************************

265. Matrix Cells in Distance Order


******************************

You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the
coordinates (rCenter, cCenter).

Return the coordinates of all cells in the matrix, sorted by theirdistance from (rCenter, cCenter) from the smallest distance to
the largest distance. You may return the answer inany order that satisfies this condition.

The distance between two cells (r1, c 1) and (r2, c 2) is |r1 - r2| + |c 1 - c 2|.

Example 1:

Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0


Output: [[0,0],[0,1]]
Explanation: The distances from (0, 0) to other cells are: [0,1]

Example 2:

Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1


Output: [[0,1],[0,0],[1,1],[1,0]]
Explanation: The distances from (0, 1) to other cells are: [0,1,1,2]
The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.

Example 3:

Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2


Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]
There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].

Constraints:

1 <= rows, cols <= 100


0 <= rCenter < rows
0 <= cCenter < cols
******************************

265. Matrix Cells in Distance Order(C++)


******************************

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> allCellsDistOrder(int R, int C, int r0, int c0) {
7 vector> result{{r0, c0}};
8 for (auto d = 1; d < R + C; ++d) {
9 append(R, C, r0 - d, c0, &result);
10 for (int x = -d + 1; x < d; ++x) {
11 append(R, C, r0 + x, c0 + d - abs(x), &result);
12 append(R, C, r0 + x, c0 + abs(x) - d, &result);
13 }
14 append(R, C, r0 + d, c0, &result);
15 }
16 return result;
17 }
18
19 private:
20 void append(int R, int C, int r, int c,
21 vector> *result) {
22 if (0 <= r && r < R && 0 <= c && c < C) {
23 result->emplace_back(vector{r, c});
24 }
25 }
26 };
******************************

265. Matrix Cells in Distance Order(Python)


******************************

1 # Time: O(m * n)
2 # Space: O(1)
3
4 class Solution(object):
5 def allCellsDistOrder(self, R, C, r0, c0):
6 """
7 :type R: int
8 :type C: int
9 :type r0: int
10 :type c0: int
11 :rtype: List[List[int]]
12 """
13 def append(R, C, r, c, result):
14 if 0 <= r < R and 0 <= c < C:
15 result.append([r, c])
16
17 result = [[r0, c0]]
18 for d in xrange(1, R+C):
19 append(R, C, r0-d, c0, result)
20 for x in xrange(-d+1, d):
21 append(R, C, r0+x, c0+abs(x)-d, result)
22 append(R, C, r0+x, c0+d-abs(x), result)
23 append(R, C, r0+d, c0, result)
24 return result
*******************************

266. Moving Stones Until Consecutive


*******************************

There are three stones in different positions on the X-axis. You are given three integersa, b, and c , the positions of the
stones.

In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an
unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x , y , and z with x < y <
z . You pick up the stone at either positionx or position z , and move that stone to an integer position k , with x < k < z and k != y .

The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).

Return an integer array answer of length 2 where:

answer[0] is the minimum number of moves you can play, and


answer[1] is the maximum number of moves you can play.

Example 1:

Input: a = 1, b = 2, c = 5
Output: [1,2]
Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

Example 2:

Input: a = 4, b = 3, c = 2
Output: [0,0]
Explanation: We cannot make any moves.

Example 3:

Input: a = 3, b = 5, c = 1
Output: [1,2]
Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.

Constraints:

1 <= a, b, c <= 100


a, b, and c have different values.
*******************************

266. Moving Stones Until Consecutive(C++)


*******************************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector numMovesStones(int a, int b, int c) {
7 vector s = {a, b, c};
8 sort(s.begin(), s.end());
9 if (s[0] + 1 == s[1] && s[1] + 1 == s[2]) {
10 return {0, 0};
11 }
12 return {(s[0] + 2 >= s[1] || s[1] + 2 >= s[2]) ? 1 : 2,
13 s[2] - s[0] - 2};
14 }
15 };
16
17 // Time: O(1)
18 // Space: O(1)
19 class Solution2 {
20 public:
21 vector numMovesStones(int a, int b, int c) {
22 vector stones = {a, b, c};
23 sort(stones.begin(), stones.end());
24 int left = 0, min_moves = numeric_limits::max();
25 int max_moves = stones.back() - stones.front() - (stones.size() - 1);
26 for (int right = 0; right < stones.size(); ++right) {
27 while (stones[right] - stones[left] + 1 > stones.size()) { // find window size <= len(stones)
28 ++left;
29 }
30 min_moves = min(min_moves, static_cast(stones.size()) - (right - left + 1));
31 }
32 return {min_moves, max_moves};
33 }
34 };
*******************************

266. Moving Stones Until Consecutive(Python)


*******************************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def numMovesStones(self, a, b, c):
6 """
7 :type a: int
8 :type b: int
9 :type c: int
10 :rtype: List[int]
11 """
12 s = [a, b, c]
13 s.sort()
14 if s[0]+1 == s[1] and s[1]+1 == s[2]:
15 return [0, 0]
16 return [1 if s[0]+2 >= s[1] or s[1]+2 >= s[2] else 2, s[2]-s[0]-2]
17
18
19 # Time: O(1)
20 # Space: O(1)
21 class Solution2(object):
22 def numMovesStones(self, a, b, c):
23 """
24 :type a: int
25 :type b: int
26 :type c: int
27 :rtype: List[int]
28 """
29 stones = [a, b, c]
30 stones.sort()
31 left, min_moves = 0, float("inf")
32 max_moves = (stones[-1]-stones[0]) - (len(stones)-1)
33 for right in xrange(len(stones)):
34 while stones[right]-stones[left]+1 > len(stones): # find window size <= len(stones)
35 left += 1
36 min_moves = min(min_moves, len(stones)-(right-left+1)) # move stones not in this window
37 return [min_moves, max_moves]
***************

267. Valid Boomerang


***************

Given an array points where points[i] = [x i, y i] represents a point on the X-Y plane, return true if these points are a boomerang.

A boomerang is a set of three points that are all distinct and not in a straight line.

Example 1:

Input: points = [[1,1],[2,3],[3,2]]


Output: true

Example 2:

Input: points = [[1,1],[2,2],[3,3]]


Output: false

Constraints:

points.length == 3
points[i].length == 2
0 <= x i, y i <= 100
***************

267. Valid Boomerang(C++)


***************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isBoomerang(vector>& points) {
7 return (points[0][0] - points[1][0]) * (points[0][1] - points[2][1]) -
8 (points[0][0] - points[2][0]) * (points[0][1] - points[1][1]) != 0;
9 }
10 };
***************

267. Valid Boomerang(Python)


***************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def isBoomerang(self, points):
6 """
7 :type points: List[List[int]]
8 :rtype: bool
9 """
10 return (points[0][0] - points[1][0]) * (points[0][1] - points[2][1]) - \
11 (points[0][0] - points[2][0]) * (points[0][1] - points[1][1]) != 0
********************************

268. Flower Planting With No Adjacent


********************************

You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [x i, y i] describes a bidirectional path between
garden x i to garden y i. In each garden, you want to plant one of 4 types of flowers.

All gardens have at most 3 paths coming into or leaving it.

Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different
types of flowers.

Return any such a choice as an array answer, where answer[i] is the type of flower planted in the(i+1)th garden. The flower
types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.

Example 1:

Input: n = 3, paths = [[1,2],[2,3],[3,1]]


Output: [1,2,3]
Explanation:
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].

Example 2:

Input: n = 4, paths = [[1,2],[3,4]]


Output: [1,2,1,2]

Example 3:

Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]


Output: [1,2,3,4]

Constraints:

1 <= n <= 10 4
0 <= paths.length <= 2 * 10 4
paths[i].length == 2
1 <= x i, y i <= n
x i != y i
Every garden has at most 3 paths coming into or leaving it.
********************************

268. Flower Planting With No Adjacent(C++)


********************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector gardenNoAdj(int N, vector>& paths) {
7 vector result(N);
8 vector> G(N);
9 for (const auto& path : paths) {
10 int x = path[0], y = path[1];
11 G[x - 1].emplace_back(y - 1);
12 G[y - 1].emplace_back(x - 1);
13 }
14 for (int i = 0; i < N; ++i) {
15 unordered_set candidates = {1, 2, 3, 4};
16 for (const auto& j : G[i]) {
17 candidates.erase(result[j]);
18 }
19 result[i] = *(candidates.cbegin());
20 }
21 return result;
22 }
23 };
********************************

268. Flower Planting With No Adjacent(Python)


********************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def gardenNoAdj(self, N, paths):
6 """
7 :type N: int
8 :type paths: List[List[int]]
9 :rtype: List[int]
10 """
11 result = [0]*N
12 G = [[] for i in xrange(N)]
13 for x, y in paths:
14 G[x-1].append(y-1)
15 G[y-1].append(x-1)
16 for i in xrange(N):
17 result[i] = ({1, 2, 3, 4} - {result[j] for j in G[i]}).pop()
18 return result
*****************

269. Last Stone Weight


*****************

You are given an array of integersstones where stones[i] is the weight of the ith stone.

We are playing a game with the stones. On each turn, we choose theheaviest two stones and smash them together.
Suppose the heaviest two stones have weights x and y with x <= y . The result of this smash is:

If x == y , both stones are destroyed, and


If x != y , the stone of weight x is destroyed, and the stone of weight y has new weight y - x .

At the end of the game, there isat most one stone left.

Return the smallest possible weight of the left stone. If there are no stones left, return 0.

Example 1:

Input: stones = [2,7,4,1,8,1]


Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.

Example 2:

Input: stones = [1]


Output: 1

Constraints:

1 <= stones.length <= 30


1 <= stones[i] <= 1000
*****************

269. Last Stone Weight(C++)


*****************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int lastStoneWeight(vector& stones) {
7 priority_queue max_heap;
8 for (const auto& x : stones) {
9 max_heap.emplace(x);
10 }
11 for (int i = 0; i + 1 < stones.size(); ++i) {
12 auto x = max_heap.top(); max_heap.pop();
13 auto y = max_heap.top(); max_heap.pop();
14 max_heap.emplace(abs(x - y));
15 }
16 return max_heap.top();
17 }
18 };
*****************

269. Last Stone Weight(Python)


*****************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 import heapq
5
6
7 class Solution(object):
8 def lastStoneWeight(self, stones):
9 """
10 :type stones: List[int]
11 :rtype: int
12 """
13 max_heap = [-x for x in stones]
14 heapq.heapify(max_heap)
15 for i in xrange(len(stones)-1):
16 x, y = -heapq.heappop(max_heap), -heapq.heappop(max_heap)
17 heapq.heappush(max_heap, -abs(x-y))
18 return -max_heap[0]
****************************************

270. Remove All Adjacent Duplicates In String


****************************************

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and
equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of th

Example 2:

Input: s = "azxxzy"
Output: "ay"

Constraints:

1 <= s.length <= 105


s consists of lowercase English letters.
****************************************

270. Remove All Adjacent Duplicates In String(C++)


****************************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 string removeDuplicates(string S) {
7 string result;
8 for (const auto& c : S) {
9 if (!result.empty() && result.back() == c) {
10 result.pop_back();
11 } else {
12 result.push_back(c);
13 }
14 }
15 return result;
16 }
17 };
****************************************

270. Remove All Adjacent Duplicates In String(Python)


****************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def removeDuplicates(self, S):
6 """
7 :type S: str
8 :rtype: str
9 """
10 result = []
11 for c in S:
12 if result and result[-1] == c:
13 result.pop()
14 else:
15 result.append(c)
16 return "".join(result)
********************************************************

271. Actors and Directors Who Cooperated At Least


Three Times
********************************************************

Table: ActorDirector

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| actor_id | int |
| director_id | int |
| timestamp | int |
+-------------+---------+
timestamp is the primary key column for this table.

Write a SQL query for a report that provides the pairs(actor_id, director_id) where the actor have cooperated with the director at
least 3 times.

Example:

ActorDirector table:
+-------------+-------------+-------------+
| actor_id | director_id | timestamp |
+-------------+-------------+-------------+
| 1 | 1 | 0 |
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 3 |
| 1 | 2 | 4 |
| 2 | 1 | 5 |
| 2 | 1 | 6 |
+-------------+-------------+-------------+

Result table:
+-------------+-------------+
| actor_id | director_id |
+-------------+-------------+
| 1 | 1 |
+-------------+-------------+
The only pair is (1, 1) where they cooperated exactly 3 times.
********************************************************

271. Actors and Directors Who Cooperated At Least


Three Times(Shell)
********************************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT actor_id, director_id
5 FROM ActorDirector
6 GROUP BY actor_id, director_id
7 HAVING COUNT(1) >= 3
8 ORDER BY NULL
**************

272. Height Checker


**************

A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line innon-
decreasing order by height. Let this ordering be represented by the integer arrayexpected where expected[i] is the expected
height of the ith student in line.

You are given an integer array heights representing the current order that the students are standing in. Eachheights[i] is the
height of the ith student in line (0-indexed).

Return the number of indices where heights[i] != expected[i] .

Example 1:

Input: heights = [1,1,4,2,1,3]


Output: 3
Explanation:
heights: [1,1,4,2,1,3]
expected: [1,1,1,2,3,4]
Indices 2, 4, and 5 do not match.

Example 2:

Input: heights = [5,1,2,3,4]


Output: 5
Explanation:
heights: [5,1,2,3,4]
expected: [1,2,3,4,5]
All indices do not match.

Example 3:

Input: heights = [1,2,3,4,5]


Output: 0
Explanation:
heights: [1,2,3,4,5]
expected: [1,2,3,4,5]
All indices match.

Constraints:

1 <= heights.length <= 100


1 <= heights[i] <= 100
**************

272. Height Checker(C++)


**************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int heightChecker(vector& heights) {
7 vector sorted_heights{heights};
8 sort(sorted_heights.begin(), sorted_heights.end());
9 int result = 0;
10 for (int i = 0; i < heights.size(); ++i) {
11 result += static_cast(heights[i] != sorted_heights[i]);
12 }
13 return result;
14 }
15 };
**************

272. Height Checker(Python)


**************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 import itertools
5
6
7 class Solution(object):
8 def heightChecker(self, heights):
9 """
10 :type heights: List[int]
11 :rtype: int
12 """
13 return sum(i != j for i, j in itertools.izip(heights, sorted(heights)))
****************

273. Confusing Number


****************

A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.

We can rotate digits of a number by 180 degrees to form new digits.

When 0, 1, 6, 8, and 9 are rotated 180 degrees, they become 0, 1, 9, 8, and 6 respectively.
When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid.

Note that after rotating a number, we can ignore leading zeros.

For example, after rotating 8000, we have 0008 which is considered as just 8.

Given an integer n, return true if it is a confusing number, or false otherwise.

Example 1:

Input: n = 6
Output: true
Explanation: We get 9 after rotating 6, 9 is a valid number, and 9 != 6.

Example 2:

Input: n = 89
Output: true
Explanation: We get 68 after rotating 89, 86 is a valid number and 86 != 89.

Example 3:

Input: n = 11
Output: false
Explanation: We get 11 after rotating 11, 11 is a valid number but the value remains the same, thus 11 is not a confusing number

Example 4:
Input: n = 25
Output: false
Explanation: We get an invalid number after rotating 25.

Constraints:

0 <= n <= 10 9
****************

273. Confusing Number(C++)


****************

1 // Time: O(logn)
2 // Space: O(logn)
3
4 class Solution {
5 public:
6 bool confusingNumber(int N) {
7 static const unordered_map lookup =
8 {{'0', '0'}, {'1', '1'}, {'6', '9'},
9 {'8', '8'}, {'9', '6'}};
10
11 const auto& S = to_string(N);
12 for (int i = 0; i < S.length(); ++i) {
13 if (!lookup.count(S[i])) {
14 return false;
15 }
16 }
17 for (int i = 0; i < (S.length() + 1) / 2; ++i) {
18 if (S[i] != lookup.at(S[S.length() - 1 - i])) {
19 return true;
20 }
21 }
22 return false;
23 }
24 };
****************

273. Confusing Number(Python)


****************

1 # Time: O(logn)
2 # Space: O(logn)
3
4 class Solution(object):
5 def confusingNumber(self, N):
6 """
7 :type N: int
8 :rtype: bool
9 """
10 lookup = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"}
11
12 S = str(N)
13 result = []
14 for i in xrange(len(S)):
15 if S[i] not in lookup:
16 return False
17 for i in xrange((len(S)+1)//2):
18 if S[i] != lookup[S[-(i+1)]]:
19 return True
20 return False
***********

274. Fixed Point


***********

Given an array of distinct integers arr, where arr is sorted in ascending order, return the smallest index i that satisfies arr[i] ==
i. If there is no such index, return -1.

Example 1:

Input: arr = [-10,-5,0,3,7]


Output: 3
Explanation: For the given array, arr[0] = -10, arr[1] = -5, arr[2] = 0, arr[3] = 3, thus the output is 3.

Example 2:

Input: arr = [0,2,5,8,17]


Output: 0
Explanation: arr[0] = 0, thus the output is 0.

Example 3:

Input: arr = [-10,-5,3,4,7,9]


Output: -1
Explanation: There is no such i that arr[i] == i, thus the output is -1.

Constraints:

1 <= arr.length < 10 4


-109 <= arr[i] <= 10 9

Follow up: The O(n) solution is very straightforward. Can we do better?


***********

274. Fixed Point(C++)


***********

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int fixedPoint(vector& A) {
7 int left = 0, right = A.size() - 1;
8 while (left <= right) {
9 const auto& mid = left + (right - left) / 2;
10 if (A[mid] >= mid) {
11 right = mid - 1;
12 } else {
13 left = mid + 1;
14 }
15 }
16 return A[left] == left ? left : -1;
17 }
18 };
***********

274. Fixed Point(Python)


***********

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def fixedPoint(self, A):
6 """
7 :type A: List[int]
8 :rtype: int
9 """
10 left, right = 0, len(A)-1
11 while left <= right:
12 mid = left + (right-left)//2
13 if A[mid] >= mid:
14 right = mid-1
15 else:
16 left = mid+1
17 return left if A[left] == left else -1
***********************

275. Index Pairs of a String


***********************

Given a string text and an array of strings words, return an array of all index pairs [i, j] so that the substring text[i...j] is in words.

Return the pairs [i, j] in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second
coordinate).

Example 1:

Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]


Output: [[3,7],[9,13],[10,17]]

Example 2:

Input: text = "ababa", words = ["aba","ab"]


Output: [[0,1],[0,2],[2,3],[2,4]]
Explanation: Notice that matches can overlap, see "aba" is found in [0,2] and [2,4].

Constraints:

1 <= text.length <= 100


1 <= words.length <= 20
1 <= words[i].length <= 50
text and words[i] consist of lowercase English letters.
All the strings of words are unique.
***********************

275. Index Pairs of a String(C++)


***********************

1 // Time: O(n + m + z), n is the total size of patterns


2 // , m is the total size of query string
3 // , z is the number of all matched strings
4 // Space: O(t), t is the total size of ac automata trie
5
6 struct AhoNode {
7 vector children;
8 vector indices;
9 AhoNode *suffix;
10 AhoNode *output;
11 AhoNode() :
12 children(26, nullptr),
13 suffix(nullptr),
14 output(nullptr) {}
15 };
16
17 class AhoTrie {
18 public:
19 AhoTrie(const vector& patterns) : root_(createACTrie(patterns)) {
20 node_ = createACSuffixAndOutputLinks(root_);
21 }
22
23 vector step(char letter) {
24 while (node_ && !node_->children[letter - 'a']) {
25 node_ = node_->suffix;
26 }
27 node_ = node_ ? node_->children[letter - 'a'] : root_;
28 return getACNodeOutputs(node_);
29 }
30
31 private:
32 AhoNode *createACTrie(const vector& patterns) { // Time: O(n), Space: O(t)
33 auto root = new AhoNode();
34 for (int i = 0; i < patterns.size(); ++i) {
35 auto node = root;
36 for (const auto& c : patterns[i]) {
37 if (!node->children[c - 'a']) {
38 node->children[c - 'a'] = new AhoNode();
39 }
40 node = node->children[c - 'a'];
41 }
42 node->indices.emplace_back(i);
43 }
44 return root;
45 }
46
47 AhoNode *createACSuffixAndOutputLinks(AhoNode *root) { // Time: O(n), Space: O(t)
48 queue q;
49 for (auto node : root->children) {
50 if (!node) {
51 continue;
52 }
53 q.emplace(node);
54 node->suffix = root;
55 }
56
57 while (!q.empty()) {
58 auto node = q.front(); q.pop();
59 for (int c = 0; c < node->children.size(); ++c) {
60 if (!node->children[c]) {
61 continue;
62 }
63 auto child = node->children[c];
64 q.emplace(child);
65 auto suffix = node->suffix;
66 while (suffix && !suffix->children[c]) {
67 suffix = suffix->suffix;
68 }
69 child->suffix = suffix ? suffix->children[c] : root;
70 child->output = !child->suffix->indices.empty() ?
71 child->suffix : child->suffix->output;
72 }
73 }
74
75 return root;
76 }
77
78 vector getACNodeOutputs(AhoNode *node) { // Time: O(z)
79 vector result;
80 for (const auto& i : node_->indices) {
81 result.emplace_back(i);
82 // return result;
83 }
84 auto output = node_->output;
85 while (output) {
86 for (const auto& i : output->indices) {
87 result.emplace_back(i);
88 // return result;
89 }
90 output = output->output;
91 }
92 return result;
93 }
94
95 AhoNode * const root_;
96 AhoNode *node_;
97 };
98
99 class Solution {
100 public:
101 vector> indexPairs(string text, vector& words) {
102 for (auto& word : words) {
103 reverse(word.begin(), word.end());
104 }
105 AhoTrie trie(words);
106 vector> result;
107 for (int i = text.length() - 1; i >= 0; --i) {
108 for (const auto& j : trie.step(text[i])) {
109 result.push_back({i, i + words[j].length() - 1});
110 }
111 }
112 reverse(result.begin(), result.end());
113 return result;
114 }
115 };
***********************

275. Index Pairs of a String(Python)


***********************

1 # Time: O(n + m + z), n is the total size of patterns


2 # , m is the total size of query string
3 # , z is the number of all matched strings
4 # Space: O(t), t is the total size of ac automata trie
5
6 import collections
7
8
9 class AhoNode(object):
10 def __init__(self):
11 self.children = collections.defaultdict(AhoNode)
12 self.indices = []
13 self.suffix = None
14 self.output = None
15
16
17 class AhoTrie(object):
18
19 def step(self, letter):
20 while self.__node and letter not in self.__node.children:
21 self.__node = self.__node.suffix
22 self.__node = self.__node.children[letter] if self.__node else self.__root
23 return self.__get_ac_node_outputs(self.__node)
24
25 def __init__(self, patterns):
26 self.__root = self.__create_ac_trie(patterns)
27 self.__node = self.__create_ac_suffix_and_output_links(self.__root)
28
29 def __create_ac_trie(self, patterns): # Time: O(n), Space: O(t)
30 root = AhoNode()
31 for i, pattern in enumerate(patterns):
32 node = root
33 for c in pattern:
34 node = node.children[c]
35 node.indices.append(i)
36 return root
37
38 def __create_ac_suffix_and_output_links(self, root): # Time: O(n), Space: O(t)
39 queue = collections.deque()
40 for node in root.children.itervalues():
41 queue.append(node)
42 node.suffix = root
43
44 while queue:
45 node = queue.popleft()
46 for c, child in node.children.iteritems():
47 queue.append(child)
48 suffix = node.suffix
49 while suffix and c not in suffix.children:
50 suffix = suffix.suffix
51 child.suffix = suffix.children[c] if suffix else root
52 child.output = child.suffix if child.suffix.indices else child.suffix.output
53
54 return root
55
56 def __get_ac_node_outputs(self, node): # Time: O(z)
57 result = []
58 for i in node.indices:
59 result.append(i)
60 output = node.output
61 while output:
62 for i in output.indices:
63 result.append(i)
64 output = output.output
65 return result
66
67
68 class Solution(object):
69 def indexPairs(self, text, words):
70 """
71 :type text: str
72 :type words: List[str]
73 :rtype: List[List[int]]
74 """
75 result = []
76 reversed_words = [w[::-1] for w in words]
77 trie = AhoTrie(reversed_words)
78 for i in reversed(xrange(len(text))):
79 for j in trie.step(text[i]):
80 result.append([i, i+len(reversed_words[j])-1])
81 result.reverse()
82 return result
************************

276. Product Sales Analysis I


************************

Table: Sales

+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
(sale_id, year) is the primary key of this table.
product_id is a foreign key to Product table.
Note that the price is per unit.

Table: Product

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
+--------------+---------+
product_id is the primary key of this table.

Write an SQL query that reports the product_name, year, and price for each sale_id in the Sales table.

Return the resulting table in any order.

The query result format is in the following example:


Sales table:
+---------+------------+------+----------+-------+
| sale_id | product_id | year | quantity | price |
+---------+------------+------+----------+-------+
| 1 | 100 | 2008 | 10 | 5000 |
| 2 | 100 | 2009 | 12 | 5000 |
| 7 | 200 | 2011 | 15 | 9000 |
+---------+------------+------+----------+-------+

Product table:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
+------------+--------------+

Result table:
+--------------+-------+-------+
| product_name | year | price |
+--------------+-------+-------+
| Nokia | 2008 | 5000 |
| Nokia | 2009 | 5000 |
| Apple | 2011 | 9000 |
+--------------+-------+-------+
From sale_id = 1, we can conclude that Nokia was sold for 5000 in the year 2008.
From sale_id = 2, we can conclude that Nokia was sold for 5000 in the year 2009.
From sale_id = 7, we can conclude that Apple was sold for 9000 in the year 2011.
************************

276. Product Sales Analysis I(Shell)


************************

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 SELECT p.product_name,
5 s.year,
6 s.price
7 FROM sales AS s
8 INNER JOIN product AS p
9 ON s.product_id = p.product_id
*************************

277. Product Sales Analysis II


*************************

Table: Sales

+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
sale_id is the primary key of this table.
product_id is a foreign key to Product table.
Note that the price is per unit.

Table: Product

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
+--------------+---------+
product_id is the primary key of this table.

Write an SQL query that reports the total quantity sold for every product id.

The query result format is in the following example:


Sales table:
+---------+------------+------+----------+-------+
| sale_id | product_id | year | quantity | price |
+---------+------------+------+----------+-------+
| 1 | 100 | 2008 | 10 | 5000 |
| 2 | 100 | 2009 | 12 | 5000 |
| 7 | 200 | 2011 | 15 | 9000 |
+---------+------------+------+----------+-------+

Product table:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
+------------+--------------+

Result table:
+--------------+----------------+
| product_id | total_quantity |
+--------------+----------------+
| 100 | 22 |
| 200 | 15 |
+--------------+----------------+
*************************

277. Product Sales Analysis II(Shell)


*************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT product_id,
5 Sum(quantity) AS total_quantity
6 FROM sales
7 GROUP BY product_id
8 ORDER BY NULL
**********************************

278. Greatest Common Divisor of Strings


**********************************

For two strings s and t, we say "t divides s " if and only if s = t + ... + t (t concatenated with itself 1 or more times)

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"


Output: "ABC"

Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"


Output: "AB"

Example 3:

Input: str1 = "LEET", str2 = "CODE"


Output: ""

Example 4:

Input: str1 = "ABCDEF", str2 = "ABC"


Output: ""

Constraints:

1 <= str1.length <= 1000


1 <= str2.length <= 1000
str1 and str2 consist of English uppercase letters.
**********************************

278. Greatest Common Divisor of Strings(C++)


**********************************

1 // Time: O(m + n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string gcdOfStrings(string str1, string str2) {
7 if (str1.empty() || str2.empty()) {
8 return "";
9 }
10 int c = gcd(str1.length(), str2.length());
11 const auto& result = str1.substr(0, c);
12 return check(str1, result) && check(str2, result) ? result : "";
13 }
14
15 private:
16 bool check(const string& s, const string& common) {
17 int i = 0;
18 for (const auto& c : s) {
19 if (c != common[i]) {
20 return false;
21 }
22 i = (i + 1) % common.length();
23 }
24 return true;
25 }
26
27 int gcd(int a, int b) {
28 while (b != 0) {
29 int tmp = b;
30 b = a % b;
31 a = tmp;
32 }
33 return a;
34 }
35 };
**********************************

278. Greatest Common Divisor of Strings(Python)


**********************************

1 # Time: O(m + n)
2 # Space: O(1)
3
4 class Solution(object):
5 def gcdOfStrings(self, str1, str2):
6 """
7 :type str1: str
8 :type str2: str
9 :rtype: str
10 """
11 def check(s, common):
12 i = 0
13 for c in s:
14 if c != common[i]:
15 return False
16 i = (i+1)%len(common)
17 return True
18
19 def gcd(a, b): # Time: O((logn)^2)
20 while b:
21 a, b = b, a % b
22 return a
23
24 if not str1 or not str2:
25 return ""
26 c = gcd(len(str1), len(str2))
27 result = str1[:c]
28 return result if check(str1, result) and check(str2, result) else ""
*******************

279. Project Employees I


*******************

Table: Project

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
+-------------+---------+
(project_id, employee_id) is the primary key of this table.
employee_id is a foreign key to Employee table.

Table: Employee

+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| experience_years | int |
+------------------+---------+
employee_id is the primary key of this table.

Write an SQL query that reports the average experience years of all the employees for each project,rounded to 2 digits.

The query result format is in the following example:


Project table:
+-------------+-------------+
| project_id | employee_id |
+-------------+-------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 4 |
+-------------+-------------+

Employee table:
+-------------+--------+------------------+
| employee_id | name | experience_years |
+-------------+--------+------------------+
| 1 | Khaled | 3 |
| 2 | Ali | 2 |
| 3 | John | 1 |
| 4 | Doe | 2 |
+-------------+--------+------------------+

Result table:
+-------------+---------------+
| project_id | average_years |
+-------------+---------------+
| 1 | 2.00 |
| 2 | 2.50 |
+-------------+---------------+
The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00 and for the second project is (3 + 2) / 2 = 2.50
*******************

279. Project Employees I(Shell)


*******************

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 SELECT project_id,
5 Round(Avg(experience_years), 2) AS average_years
6 FROM project AS p
7 INNER JOIN employee AS e
8 ON p.employee_id = e.employee_id
9 GROUP BY project_id
10 ORDER BY NULL
********************

280. Project Employees II


********************

Table: Project

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
+-------------+---------+
(project_id, employee_id) is the primary key of this table.
employee_id is a foreign key to Employee table.

Table: Employee

+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| experience_years | int |
+------------------+---------+
employee_id is the primary key of this table.

Write an SQL query that reports all the projects that have the most employees.

The query result format is in the following example:


Project table:
+-------------+-------------+
| project_id | employee_id |
+-------------+-------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 4 |
+-------------+-------------+

Employee table:
+-------------+--------+------------------+
| employee_id | name | experience_years |
+-------------+--------+------------------+
| 1 | Khaled | 3 |
| 2 | Ali | 2 |
| 3 | John | 1 |
| 4 | Doe | 2 |
+-------------+--------+------------------+

Result table:
+-------------+
| project_id |
+-------------+
| 1 |
+-------------+
The first project has 3 employees while the second one has 2.
********************

280. Project Employees II(Shell)


********************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT project_id
5 FROM project
6 GROUP BY project_id
7 HAVING Count(employee_id) = (SELECT Count(employee_id)
8 FROM project
9 GROUP BY project_id
10 ORDER BY Count(employee_id) DESC
11 LIMIT 1)
12 ORDER BY NULL
************************

281. Occurrences After Bigram


************************

Given two strings first and second, consider occurrences in some text of the form"first second third" , where second comes
immediately after first, and third comes immediately after second.

Return an array of all the words third for each occurrence of "first second third" .

Example 1:

Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl","student"]

Example 2:

Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]

Constraints:

1 <= text.length <= 1000


text consists of lowercase English letters and spaces.
All the words in text a separated by a single space.
1 <= first.length, second.length <= 10
first and second consist of lowercase English letters.
************************

281. Occurrences After Bigram(C++)


************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector findOcurrences(string text, string first, string second) {
7 vector result;
8 first.push_back(' ');
9 second.push_back(' ');
10 string third;
11 int i = 0, j = 0, k = 0;
12 while (k < text.length()) {
13 auto c = text[k++];
14 if (i != first.length()) {
15 if (c == first[i]) {
16 ++i;
17 } else {
18 i = 0;
19 }
20 continue;
21 }
22 if (j != second.length()) {
23 if (c == second[j]) {
24 ++j;
25 } else {
26 k -= j + 1;
27 i = 0, j = 0;
28 }
29 continue;
30 }
31 if (c != ' ') {
32 third.push_back(c);
33 continue;
34 }
35 k -= second.length() + third.length() + 1;
36 i = 0, j = 0;
37 result.emplace_back(move(third));
38 }
39 if (!third.empty()) {
40 result.emplace_back(move(third));
41 }
42 return result;
43 }
44 };
************************

281. Occurrences After Bigram(Python)


************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findOcurrences(self, text, first, second):
6 """
7 :type text: str
8 :type first: str
9 :type second: str
10 :rtype: List[str]
11 """
12 result = []
13 first += ' '
14 second += ' '
15 third = []
16 i, j, k = 0, 0, 0
17 while k < len(text):
18 c = text[k]
19 k += 1
20 if i != len(first):
21 if c == first[i]:
22 i += 1
23 else:
24 i = 0
25 continue
26 if j != len(second):
27 if c == second[j]:
28 j += 1
29 else:
30 k -= j+1
31 i, j = 0, 0
32 continue
33 if c != ' ':
34 third.append(c)
35 continue
36 k -= len(second) + len(third) + 1
37 i, j = 0, 0
38 result.append("".join(third))
39 third = []
40 if third:
41 result.append("".join(third))
42 return result
****************

282. Sales Analysis I


****************

Table: Product

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
| unit_price | int |
+--------------+---------+
product_id is the primary key of this table.

Table: Sales

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| seller_id | int |
| product_id | int |
| buyer_id | int |
| sale_date | date |
| quantity | int |
| price | int |
+------ ------+---------+
This table has no primary key, it can have repeated rows.
product_id is a foreign key to Product table.

Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.

The query result format is in the following example:


Product table:
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1 | S8 | 1000 |
| 2 | G4 | 800 |
| 3 | iPhone | 1400 |
+------------+--------------+------------+

Sales table:
+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |
| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |
| 2 | 2 | 3 | 2019-06-02 | 1 | 800 |
| 3 | 3 | 4 | 2019-05-13 | 2 | 2800 |
+-----------+------------+----------+------------+----------+-------+

Result table:
+-------------+
| seller_id |
+-------------+
| 1 |
| 3 |
+-------------+
Both sellers with id 1 and 3 sold products with the most total price of 2800.
****************

282. Sales Analysis I(Shell)


****************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT seller_id
5 FROM sales
6 GROUP BY seller_id
7 HAVING Sum(price) = (SELECT Sum(price)
8 FROM sales
9 GROUP BY seller_id
10 ORDER BY Sum(price) DESC
11 LIMIT 1)
12 ORDER BY NULL
*****************

283. Sales Analysis II


*****************

Table: Product

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
| unit_price | int |
+--------------+---------+
product_id is the primary key of this table.

Table: Sales

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| seller_id | int |
| product_id | int |
| buyer_id | int |
| sale_date | date |
| quantity | int |
| price | int |
+------ ------+---------+
This table has no primary key, it can have repeated rows.
product_id is a foreign key to Product table.

Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products
present in the Product table.

The query result format is in the following example:


Product table:
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1 | S8 | 1000 |
| 2 | G4 | 800 |
| 3 | iPhone | 1400 |
+------------+--------------+------------+

Sales table:
+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |
| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |
| 2 | 1 | 3 | 2019-06-02 | 1 | 800 |
| 3 | 3 | 3 | 2019-05-13 | 2 | 2800 |
+-----------+------------+----------+------------+----------+-------+

Result table:
+-------------+
| buyer_id |
+-------------+
| 1 |
+-------------+
The buyer with id 1 bought an S8 but didn't buy an iPhone. The buyer with id 3 bought both.
*****************

283. Sales Analysis II(Shell)


*****************

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 SELECT DISTINCT buyer_id
5 FROM sales
6 INNER JOIN product
7 ON sales.product_id = product.product_id
8 WHERE product.product_name = "s8"
9 AND buyer_id NOT IN (SELECT DISTINCT buyer_id
10 FROM sales
11 INNER JOIN product
12 ON sales.product_id = product.product_id
13 WHERE product.product_name = "iphone");
******************

284. Sales Analysis III


******************

Table: Product

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
| unit_price | int |
+--------------+---------+
product_id is the primary key of this table.

Table: Sales

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| seller_id | int |
| product_id | int |
| buyer_id | int |
| sale_date | date |
| quantity | int |
| price | int |
+------ ------+---------+
This table has no primary key, it can have repeated rows.
product_id is a foreign key to Product table.

Write an SQL query that reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-
31 inclusive.

The query result format is in the following example:


Product table:
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1 | S8 | 1000 |
| 2 | G4 | 800 |
| 3 | iPhone | 1400 |
+------------+--------------+------------+

Sales table:
+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |
| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |
| 2 | 2 | 3 | 2019-06-02 | 1 | 800 |
| 3 | 3 | 4 | 2019-05-13 | 2 | 2800 |
+-----------+------------+----------+------------+----------+-------+

Result table:
+-------------+--------------+
| product_id | product_name |
+-------------+--------------+
| 1 | S8 |
+-------------+--------------+
The product with id 1 was only sold in spring 2019 while the other two were sold after.
******************

284. Sales Analysis III(Shell)


******************

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 SELECT product_id,
5 product_name
6 FROM product
7 WHERE product_id NOT IN (SELECT product_id
8 FROM sales
9 WHERE sale_date NOT BETWEEN
10 '2019-01-01' AND '2019-03-31');
***********************************

285. Sum of Digits in the Minimum Number


***********************************

Given an integer array nums, return 0 if the sum of the digits of the minimum integer innums is odd, or 1 otherwise.

Example 1:

Input: nums = [34,23,1,24,75,33,54,8]


Output: 0
Explanation: The minimal element is 1, and the sum of those digits is 1 which is odd, so the answer is 0.

Example 2:

Input: nums = [99,77,33,66,55]


Output: 1
Explanation: The minimal element is 33, and the sum of those digits is 3 + 3 = 6 which is even, so the answer is 1.

Constraints:

1 <= nums.length <= 100


1 <= nums[i] <= 100
***********************************

285. Sum of Digits in the Minimum Number(C++)


***********************************

1 // Time: O(n * l), l is the max length of numbers


2 // Space: O(l)
3
4 class Solution {
5 public:
6 int sumOfDigits(vector& A) {
7 int min_num = *min_element(A.begin(),A.end());
8 int total = 0;
9 while (min_num) {
10 total += min_num % 10;
11 min_num /= 10;
12 }
13 return total % 2 == 0;
14 }
15 };
***********************************

285. Sum of Digits in the Minimum Number(Python)


***********************************

1 # Time: O(n * l)
2 # Space: O(l)
3
4 class Solution(object):
5 def sumOfDigits(self, A):
6 """
7 :type A: List[int]
8 :rtype: int
9 """
10 total = sum([int(c) for c in str(min(A))])
11 return 1 if total % 2 == 0 else 0
*********

286. High Five


*********

Given a list of the scores of different students, items, where items[i] = [ID i, score i] represents one score from a student with IDi,
calculate each student's top five average.

Return the answer as an array of pairs result, where result[j] = [ID j, topFiveAverage j] represents the student with IDj and their top
five average. Sort result by IDj in increasing order.

A student's top five average is calculated by taking the sum of their top five scores and dividing it by5 using integer
division.

Example 1:

Input: items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]


Output: [[1,87],[2,88]]
Explanation:
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer

Example 2:

Input: items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]


Output: [[1,100],[7,100]]

Constraints:

1 <= items.length <= 1000


items[i].length == 2
1 <= ID i <= 1000
0 <= score i <= 100
For each IDi, there will be at least five scores.
*********

286. High Five(C++)


*********

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector> highFive(vector>& items) {
7 map, greater>> min_heaps;
8 for (const auto& item: items) {
9 min_heaps[item[0]].emplace(item[1]);
10 if (min_heaps[item[0]].size() > 5) {
11 min_heaps[item[0]].pop();
12 }
13 }
14
15 vector> result;
16 for (auto& [i, min_heap] : min_heaps) {
17 int total = 0, count = min_heap.size();
18 while (!min_heap.empty()) {
19 total += min_heap.top(); min_heap.pop();
20 }
21 result.push_back({i, total / count});
22 }
23 return result;
24 }
25 };
26
27 // Time: O(nlogn)
28 // Space: O(n)
29 class Solution2 {
30 public:
31 vector> highFive(vector>& items) {
32 vector> result;
33 map> students;
34 for (const auto& item : items) {
35 students[item[0]].push_back(item[1]);
36 }
37 for (auto& [i, scores] : students) {
38 partial_sort(scores.begin(), scores.begin() + 5, scores.end(), greater());
39 result.push_back({i, accumulate(scores.cbegin(), scores.cbegin() + 5, 0) / 5});
40 }
41 return result;
42 }
43 };
*********

286. High Five(Python)


*********

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 import collections
5 import heapq
6
7
8 class Solution(object):
9 def highFive(self, items):
10 """
11 :type items: List[List[int]]
12 :rtype: List[List[int]]
13 """
14 min_heaps = collections.defaultdict(list)
15 for i, val in items:
16 heapq.heappush(min_heaps[i], val)
17 if len(min_heaps[i]) > 5:
18 heapq.heappop(min_heaps[i])
19 return [[i, sum(min_heaps[i]) // len(min_heaps[i])] for i in sorted(min_heaps)]
***************

287. Duplicate Zeros


***************

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in
place and do not return anything.

Example 1:

Input: arr = [1,0,2,3,0,4,5,0]


Output: [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: arr = [1,2,3]


Output: [1,2,3]
Explanation: After calling your function, the input array is modified to: [1,2,3]

Constraints:

1 <= arr.length <= 10 4


0 <= arr[i] <= 9
***************

287. Duplicate Zeros(C++)


***************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 void duplicateZeros(vector& arr) {
7 int shift = 0, i;
8 for (i = 0; i + shift < arr.size(); ++i) {
9 shift += int(arr[i] == 0);
10 }
11 for (i = i - 1; shift > 0; --i) {
12 if (i + shift < arr.size()) {
13 arr[i + shift] = arr[i];
14 }
15 if (arr[i] == 0) {
16 --shift;
17 arr[i + shift] = arr[i];
18 }
19 }
20 }
21 };
***************

287. Duplicate Zeros(Python)


***************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def duplicateZeros(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: None Do not return anything, modify arr in-place instead.
9 """
10 shift, i = 0, 0
11 while i+shift < len(arr):
12 shift += int(arr[i] == 0)
13 i += 1
14 i -= 1
15 while shift:
16 if i+shift < len(arr):
17 arr[i+shift] = arr[i]
18 if arr[i] == 0:
19 shift -= 1
20 arr[i+shift] = arr[i]
21 i -= 1
*******************

288. Two Sum Less Than K


*******************

Given an array nums of integers and integer k , return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and
sum < k . If no i, j exist satisfying this equation, return -1.

Example 1:

Input: nums = [34,23,1,24,75,33,54,8], k = 60


Output: 58
Explanation: We can use 34 and 24 to sum 58 which is less than 60.

Example 2:

Input: nums = [10,20,30], k = 15


Output: -1
Explanation: In this case it is not possible to get a pair sum less that 15.

Constraints:

1 <= nums.length <= 100


1 <= nums[i] <= 1000
1 <= k <= 2000
*******************

288. Two Sum Less Than K(C++)


*******************

1 // Time: O(nlogn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int twoSumLessThanK(vector& A, int K) {
7 sort(A.begin(), A.end());
8 int result = -1;
9 int left = 0, right = A.size() - 1;
10 while (left < right) {
11 if (A[left] + A[right] >= K) {
12 --right;
13 } else {
14 result = max(result, A[left] + A[right]);
15 ++left;
16 }
17 }
18 return result;
19 }
20 };
*******************

288. Two Sum Less Than K(Python)


*******************

1 # Time: O(nlogn)
2 # Space: O(1)
3
4 class Solution(object):
5 def twoSumLessThanK(self, A, K):
6 """
7 :type A: List[int]
8 :type K: int
9 :rtype: int
10 """
11 A.sort()
12 result = -1
13 left, right = 0, len(A)-1
14 while left < right:
15 if A[left]+A[right] >= K:
16 right -= 1
17 else:
18 result = max(result, A[left]+A[right])
19 left += 1
20 return result
****************************

289. Distribute Candies to People


****************************

We distribute some number of candies, to a row of n = num_people people in the following way:

We then give 1 candy to the first person, 2 candies to the second person, and so on until we given candies to the last
person.

Then, we go back to the start of the row, givingn + 1 candies to the first person, n + 2 candies to the second person, and so
on until we give 2 * n candies to the last person.

This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end)
until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the
previous gift).

Return an array (of length num_people and sum candies) that represents the final distribution of candies.

Example 1:

Input: candies = 7, num_people = 4


Output: [1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].

Example 2:

Input: candies = 10, num_people = 3


Output: [5,2,3]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0].
On the third turn, ans[2] += 3, and the array is [1,2,3].
On the fourth turn, ans[0] += 4, and the final array is [5,2,3].

Constraints:

1 <= candies <= 10^9


1 <= num_people <= 1000
****************************

289. Distribute Candies to People(C++)


****************************
1 // Time: O(n + logc), c is the number of candies
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector distributeCandies(int candies, int num_people) {
7 // find max integer p s.t. sum(1 + 2 + ... + p) <= C
8 // => remaining : 0 <= C-(1+p)*p/2 < p+1
9 // => -2p-2 < p^2+p-2C <= 0
10 // => 2C+1/4 < (p+3/2)^2 and (p+1/2)^2 <= 2C+1/4
11 // => sqrt(2C+1/4)-3/2 < p <= sqrt(2C+1/4)-1/2
12 // => p = floor(sqrt(2C+1/4)-1/2)
13 int p = int(sqrt(2 * candies + 0.25) - 0.5);
14 int remaining = candies - (p + 1) * p / 2;
15 int rows = p / num_people, cols = p % num_people;
16
17 vector result(num_people);
18 for (int i = 0; i < num_people; ++i) {
19 result[i] = (i < cols) ? (i + 1) * (rows + 1) + (rows * (rows + 1) / 2) * num_people
20 : (i + 1) * rows + ((rows - 1) * rows / 2) * num_people;
21 }
22 result[cols] += remaining;
23 return result;
24 }
25 };
26
27 // Time: O(n + logc), c is the number of candies
28 // Space: O(1)
29 class Solution2 {
30 public:
31 vector distributeCandies(int candies, int num_people) {
32 // find max integer p s.t. sum(1 + 2 + ... + p) <= C
33 int left = 1, right = candies;
34 while (left <= right) {
35 const auto& mid = left + (right - left) / 2;
36 if (!(mid <= candies * 2 / (mid + 1))) {
37 right = mid - 1;
38 } else {
39 left = mid + 1;
40 }
41 }
42 int p = right;
43 int remaining = candies - (p + 1) * p / 2;
44 int rows = p / num_people, cols = p % num_people;
45
46 vector result(num_people);
47 for (int i = 0; i < num_people; ++i) {
48 result[i] = (i < cols) ? (i + 1) * (rows + 1) + (rows * (rows + 1) / 2) * num_people
49 : (i + 1) * rows + ((rows - 1) * rows / 2) * num_people;
50 }
51 result[cols] += remaining;
52 return result;
53 }
54 };
55
56 // Time: O(sqrt(c)), c is the number of candies
57 // Space: O(1)
58 class Solution3 {
59 public:
60 vector distributeCandies(int candies, int num_people) {
61 vector result(num_people);
62 for (int i = 0; candies; ++i) {
63 result[i % num_people] += min(candies, i + 1);
64 candies -= min(candies, i + 1);
65 }
66 return result;
67 }
68 };
****************************

289. Distribute Candies to People(Python)


****************************

1 # Time: O(n + logc), c is the number of candies


2 # Space: O(1)
3
4 class Solution(object):
5 def distributeCandies(self, candies, num_people):
6 """
7 :type candies: int
8 :type num_people: int
9 :rtype: List[int]
10 """
11 # find max integer p s.t. sum(1 + 2 + ... + p) <= C
12 # => remaining : 0 <= C-(1+p)*p/2 < p+1
13 # => -2p-2 < p^2+p-2C <= 0
14 # => 2C+1/4 < (p+3/2)^2 and (p+1/2)^2 <= 2C+1/4
15 # => sqrt(2C+1/4)-3/2 < p <= sqrt(2C+1/4)-1/2
16 # => p = floor(sqrt(2C+1/4)-1/2)
17 p = int((2*candies + 0.25)**0.5 - 0.5)
18 remaining = candies - (p+1)*p//2
19 rows, cols = divmod(p, num_people)
20
21 result = [0]*num_people
22 for i in xrange(num_people):
23 result[i] = (i+1)*(rows+1) + (rows*(rows+1)//2)*num_people if i < cols else \
24 (i+1)*rows + ((rows-1)*rows//2)*num_people
25 result[cols] += remaining
26 return result
27
28
29 # Time: O(n + logc), c is the number of candies
30 # Space: O(1)
31 class Solution2(object):
32 def distributeCandies(self, candies, num_people):
33 """
34 :type candies: int
35 :type num_people: int
36 :rtype: List[int]
37 """
38 # find max integer p s.t. sum(1 + 2 + ... + p) <= C
39 left, right = 1, candies
40 while left <= right:
41 mid = left + (right-left)//2
42 if not ((mid <= candies*2 // (mid+1))):
43 right = mid-1
44 else:
45 left = mid+1
46 p = right
47 remaining = candies - (p+1)*p//2
48 rows, cols = divmod(p, num_people)
49
50 result = [0]*num_people
51 for i in xrange(num_people):
52 result[i] = (i+1)*(rows+1) + (rows*(rows+1)//2)*num_people if i < cols else \
53 (i+1)*rows + ((rows-1)*rows//2)*num_people
54 result[cols] += remaining
55 return result
56
57
58 # Time: O(sqrt(c)), c is the number of candies
59 # Space: O(1)
60 class Solution3(object):
61 def distributeCandies(self, candies, num_people):
62 """
63 :type candies: int
64 :type num_people: int
65 :rtype: List[int]
66 """
67 result = [0]*num_people
68 i = 0
69 while candies != 0:
70 result[i % num_people] += min(candies, i+1)
71 candies -= min(candies, i+1)
72 i += 1
73 return result
***********************************

290. Path In Zigzag Labelled Binary Tree


***********************************

In an infinite binary tree where every node has two children, the nodes are labelled in row order.

In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second,
fourth, sixth,...), the labelling is right to left.

Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with thatlabel.

Example 1:

Input: label = 14
Output: [1,3,4,14]

Example 2:

Input: label = 26
Output: [1,2,6,10,26]

Constraints:

1 <= label <= 10^6


***********************************

290. Path In Zigzag Labelled Binary Tree(C++)


***********************************

1 // Time: O(logn)
2 // Space: O(logn)
3
4 class Solution {
5 public:
6 vector pathInZigZagTree(int label) {
7 int count = 1;
8 while (count <= label) {
9 count *= 2;
10 }
11 vector result;
12 for (; label >= 1; label /= 2, count /= 2) {
13 result.emplace_back(label);
14 label = (count / 2) + ((count - 1) - label);
15 }
16 reverse(result.begin(), result.end());
17 return result;
18 }
19 };
***********************************

290. Path In Zigzag Labelled Binary Tree(Python)


***********************************

1 # Time: O(logn)
2 # Space: O(logn)
3
4 class Solution(object):
5 def pathInZigZagTree(self, label):
6 """
7 :type label: int
8 :rtype: List[int]
9 """
10 count = 2**label.bit_length()
11 result = []
12 while label >= 1:
13 result.append(label)
14 label = ((count//2) + ((count-1)-label)) // 2
15 count //= 2
16 result.reverse()
17 return result
***********************

291. Defanging an IP Address


***********************

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period "." with "[.]".

Example 1:

Input: address = "1.1.1.1"


Output: "1[.]1[.]1[.]1"

Example 2:

Input: address = "255.100.50.0"


Output: "255[.]100[.]50[.]0"

Constraints:

The given address is a valid IPv4 address.


***********************

291. Defanging an IP Address(C++)


***********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string defangIPaddr(string address) {
7 string result;
8 for (const auto& c : address) {
9 if (c == '.') {
10 result += "[.]";
11 } else {
12 result.push_back(c);
13 }
14 }
15 return result;
16 }
17 };
***********************

291. Defanging an IP Address(Python)


***********************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def defangIPaddr(self, address):
6 """
7 :type address: str
8 :rtype: str
9 """
10 result = []
11 for c in address:
12 if c == '.':
13 result.append("[.]")
14 else:
15 result.append(c)
16 return "".join(result)
**************

292. Reported Posts


**************

Table: Actions

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| post_id | int |
| action_date | date |
| action | enum |
| extra | varchar |
+---------------+---------+
There is no primary key for this table, it may have duplicate rows.
The action column is an ENUM type of ('view', 'like', 'reaction', 'comment', 'report', 'share').
The extra column has optional information about the action such as a reason for report or a type of reaction.

Write an SQL query that reports the number of posts reported yesterday for each report reason. Assume today is2019-07-
05.

The query result format is in the following example:

Actions table:
+---------+---------+-------------+--------+--------+
| user_id | post_id | action_date | action | extra |
+---------+---------+-------------+--------+--------+
| 1 | 1 | 2019-07-01 | view | null |
| 1 | 1 | 2019-07-01 | like | null |
| 1 | 1 | 2019-07-01 | share | null |
| 2 | 4 | 2019-07-04 | view | null |
| 2 | 4 | 2019-07-04 | report | spam |
| 3 | 4 | 2019-07-04 | view | null |
| 3 | 4 | 2019-07-04 | report | spam |
| 4 | 3 | 2019-07-02 | view | null |
| 4 | 3 | 2019-07-02 | report | spam |
| 5 | 2 | 2019-07-04 | view | null |
| 5 | 2 | 2019-07-04 | report | racism |
| 5 | 5 | 2019-07-04 | view | null |
| 5 | 5 | 2019-07-04 | report | racism |
+---------+---------+-------------+--------+--------+

Result table:
+---------------+--------------+
| report_reason | report_count |
+---------------+--------------+
| spam | 1 |
| racism | 2 |
+---------------+--------------+
Note that we only care about report reasons with non zero number of reports.
**************

292. Reported Posts(Shell)


**************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT extra AS report_reason,
5 Count(DISTINCT post_id) AS report_count
6 FROM actions
7 WHERE action = 'report'
8 AND action_date = '2019-07-04'
9 GROUP BY extra
10 ORDER BY NULL
**************

293. Print in Order


**************

Suppose we have a class:

public class Foo {


public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will callfirst(), thread B will call second() , and
thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third()
is executed after second() .

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to
imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

Example 1:

Input: nums = [1,2,3]


Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and

Example 2:

Input: nums = [1,3,2]


Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the c
**************

293. Print in Order(C++)


**************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Foo {
5 public:
6 Foo() {
7 }
8
9 void first(function printFirst) {
10 // printFirst() outputs "first". Do not change or remove this line.
11 printFirst();
12 p1_.set_value();
13 }
14
15 void second(function printSecond) {
16 p1_.get_future().wait();
17 // printSecond() outputs "second". Do not change or remove this line.
18 printSecond();
19 p2_.set_value();
20 }
21
22 void third(function printThird) {
23 p2_.get_future().wait();
24 // printThird() outputs "third". Do not change or remove this line.
25 printThird();
26 }
27
28 private:
29 promise p1_;
30 promise p2_;
31 };
32
33 // Time: O(n)
34 // Space: O(1)
35 class Foo2 {
36 public:
37 Foo2() {
38 }
39
40 void first(function printFirst) {
41 {
42 unique_lock l(m_);
43 has_first_ = true;
44 // printFirst() outputs "first". Do not change or remove this line.
45 printFirst();
46 }
47 cv_.notify_all();
48 }
49
50 void second(function printSecond) {
51 {
52 unique_lock l(m_);
53 cv_.wait(l, [this]() { return has_first_; });
54 has_second_ = true;
55 // printSecond() outputs "second". Do not change or remove this line.
56 printSecond();
57 }
58 cv_.notify_all();
59 }
60
61 void third(function printThird) {
62 {
63 unique_lock l(m_);
64 cv_.wait(l, [this]() { return has_second_; });
65 // printThird() outputs "third". Do not change or remove this line.
66 printThird();
67 }
68 cv_.notify_all();
69 }
70
71 private:
72 bool has_first_ = false;
73 bool has_second_ = false;
74 mutex m_;
75 condition_variable cv_;
76 };
77
78 // Time: O(n)
79 // Space: O(1)
80 class Foo3 {
81 public:
82 Foo3() {
83 m1_.lock();
84 m2_.lock();
85 }
86
87 void first(function printFirst) {
88 // printFirst() outputs "first". Do not change or remove this line.
89 printFirst();
90 m1_.unlock();
91 }
92
93 void second(function printSecond) {
94 m1_.lock();
95 // printSecond() outputs "second". Do not change or remove this line.
96 printSecond();
97 m1_.unlock();
98 m2_.unlock();
99 }
100
101 void third(function printThird) {
102 m2_.lock();
103 // printThird() outputs "third". Do not change or remove this line.
104 printThird();
105 m2_.unlock();
106 }
107
108 private:
109 mutex m1_, m2_;
110 };
**************

293. Print in Order(Python)


**************

1 # Time: O(n)
2 # Space: O(1)
3
4 import threading
5
6
7 class Foo(object):
8 def __init__(self):
9 self.__cv = threading.Condition()
10 self.__has_first = False
11 self.__has_second = False
12
13 def first(self, printFirst):
14 """
15 :type printFirst: method
16 :rtype: void
17 """
18 with self.__cv:
19 # printFirst() outputs "first". Do not change or remove this line.
20 printFirst()
21 self.__has_first = True
22 self.__cv.notifyAll()
23
24 def second(self, printSecond):
25 """
26 :type printSecond: method
27 :rtype: void
28 """
29 with self.__cv:
30 while not self.__has_first:
31 self.__cv.wait()
32 # printSecond() outputs "second". Do not change or remove this line.
33 printSecond()
34 self.__has_second = True
35 self.__cv.notifyAll()
36
37 def third(self, printThird):
38 """
39 :type printThird: method
40 :rtype: void
41 """
42 with self.__cv:
43 while not self.__has_second:
44 self.__cv.wait()
45 # printThird() outputs "third". Do not change or remove this line.
46 printThird()
47 self.__cv.notifyAll()
48
*************************

294. Number of Days in a Month


*************************

Given a year year and a month month, return the number of days of that month.

Example 1:

Input: year = 1992, month = 7


Output: 31

Example 2:

Input: year = 2000, month = 2


Output: 29

Example 3:

Input: year = 1900, month = 2


Output: 28

Constraints:

1583 <= year <= 2100


1 <= month <= 12
*************************

294. Number of Days in a Month(C++)


*************************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numberOfDays(int Y, int M) {
7 const auto& leap = (((Y % 4 == 0) && (Y % 100 != 0)) || (Y % 400 == 0)) ? 1 : 0;
8 return (M == 2) ? 28 + leap : 31 - (M - 1) % 7 % 2;
9 }
10 };
*************************

294. Number of Days in a Month(Python)


*************************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def numberOfDays(self, Y, M):
6 """
7 :type Y: int
8 :type M: int
9 :rtype: int
10 """
11 leap = 1 if ((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0) else 0
12 return (28+leap if (M == 2) else 31-(M-1)%7%2)
13
***************************

295. Remove Vowels from a String


***************************

Given a string s , remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.

Example 1:

Input: s = "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"

Example 2:

Input: s = "aeiou"
Output: ""

Constraints:

1 <= s.length <= 1000


s consists of only lowercase English letters.
***************************

295. Remove Vowels from a String(C++)


***************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string removeVowels(string S) {
7 return accumulate(S.cbegin(), S.cend(), string{},
8 [](const auto &a, const auto &b) {
9 static const unordered_set lookup = {'a', 'e', 'i', 'o', 'u'};
10 if (!lookup.count(b)) {
11 return a + b;
12 }
13 return a;
14 });
15 }
16 };
***************************

295. Remove Vowels from a String(Python)


***************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def removeVowels(self, S):
6 """
7 :type S: str
8 :rtype: str
9 """
10 lookup = set("aeiou")
11 return "".join(c for c in S if c not in lookup)
***********************

296. Maximum Average Subtree


***********************

Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual
answer will be accepted.

A subtree of a tree is any node of that tree plus all its descendants.

The average value of a tree is the sum of its values, divided by the number of nodes.

Example 1:

Input: root = [5,6,1]


Output: 6.00000
Explanation:
For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
For the node with value = 6 we have an average of 6 / 1 = 6.
For the node with value = 1 we have an average of 1 / 1 = 1.
So the answer is 6 which is the maximum.

Example 2:

Input: root = [0,null,1]


Output: 1.00000

Constraints:

The number of nodes in the tree is in the range[1, 104].


0 <= Node.val <= 10 5
***********************

296. Maximum Average Subtree(C++)


***********************

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 double maximumAverageSubtree(TreeNode* root) {
16 double result = 0.0;
17 maximumAverageSubtreeHelper(root, &result);
18 return result;
19 }
20
21 private:
22 pair maximumAverageSubtreeHelper(TreeNode *root, double *result) {
23 if (!root) {
24 return {0, 0};
25 }
26 const auto& [s1, n1] = maximumAverageSubtreeHelper(root->left, result);
27 const auto& [s2, n2] = maximumAverageSubtreeHelper(root->right, result);
28 const auto& s = s1 + s2 + root->val;
29 const auto& n = n1 + n2 + 1;
30 *result = max(*result, s / n);
31 return {s, n};
32 }
33 };
***********************

296. Maximum Average Subtree(Python)


***********************

1 # Time: O(n)
2 # Space: O(h)
3
4 # Definition for a binary tree node.
5 class TreeNode(object):
6 def __init__(self, x):
7 self.val = x
8 self.left = None
9 self.right = None
10
11
12 class Solution(object):
13 def maximumAverageSubtree(self, root):
14 """
15 :type root: TreeNode
16 :rtype: float
17 """
18 def maximumAverageSubtreeHelper(root, result):
19 if not root:
20 return [0.0, 0]
21 s1, n1 = maximumAverageSubtreeHelper(root.left, result)
22 s2, n2 = maximumAverageSubtreeHelper(root.right, result)
23 s = s1+s2+root.val
24 n = n1+n2+1
25 result[0] = max(result[0], s / n)
26 return [s, n]
27
28 result = [0]
29 maximumAverageSubtreeHelper(root, result)
30 return result[0]
*******************

297. Relative Sort Array


*******************

Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in
arr2 should be placed at the end of arr1 in ascending order.

Example 1:

Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]


Output: [2,2,2,1,4,3,3,9,6,7,19]

Constraints:

1 <= arr1.length, arr2.length <= 1000


0 <= arr1[i], arr2[i] <= 1000
All the elements of arr2 are distinct.
Each arr2[i] is in arr1.
*******************

297. Relative Sort Array(C++)


*******************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector relativeSortArray(vector& arr1, vector& arr2) {
7 unordered_map lookup;
8 for (int i = 0; i < arr2.size(); ++i) {
9 lookup[arr2[i]] = i;
10 }
11 sort(arr1.begin(), arr1.end(),
12 [&lookup, l = arr2.size()](const auto& a, const auto& b) {
13 int i = lookup.count(a) ? lookup[a] : l + a;
14 int j = lookup.count(b) ? lookup[b] : l + b;
15 return i < j;
16 });
17 return arr1;
18 }
19 };
*******************

297. Relative Sort Array(Python)


*******************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 class Solution(object):
5 def relativeSortArray(self, arr1, arr2):
6 """
7 :type arr1: List[int]
8 :type arr2: List[int]
9 :rtype: List[int]
10 """
11 lookup = {v: i for i, v in enumerate(arr2)}
12 return sorted(arr1, key=lambda i: lookup.get(i, len(arr2)+i))
*********************************

298. Number of Equivalent Domino Pairs


*********************************

Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c)
- that is, one domino can be rotated to be equal to another domino.

Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length , and dominoes[i] is equivalent to dominoes[j].

Example 1:

Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]


Output: 1

Constraints:

1 <= dominoes.length <= 40000


1 <= dominoes[i][j] <= 9
*********************************

298. Number of Equivalent Domino Pairs(C++)


*********************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 template
7 struct PairHash {
8 size_t operator()(const pair& p) const {
9 size_t seed = 0;
10 seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
11 seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
12 return seed;
13 }
14 };
15
16 int numEquivDominoPairs(vector>& dominoes) {
17 unordered_map, int, PairHash> count;
18 for (const auto& domino : dominoes) {
19 ++count[make_pair(*min_element(domino.cbegin(), domino.cend()),
20 *max_element(domino.cbegin(), domino.cend()))];
21 }
22 int result = 0;
23 for (const auto& [k, v] : count) {
24 result += v * (v - 1) / 2;
25 }
26 return result;
27 }
28 };
*********************************

298. Number of Equivalent Domino Pairs(Python)


*********************************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def numEquivDominoPairs(self, dominoes):
9 """
10 :type dominoes: List[List[int]]
11 :rtype: int
12 """
13 counter = collections.Counter((min(x), max(x)) for x in dominoes)
14 return sum(v*(v-1)//2 for v in counter.itervalues())
*********************

299. Largest Unique Number


*********************

Given an integer array nums, return the largest integer that only occurs once. If no integer occurs once, return -1.

Example 1:

Input: nums = [5,7,3,9,4,9,8,3,1]


Output: 8
Explanation: The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it is the answer.

Example 2:

Input: nums = [9,9,8,8]


Output: -1
Explanation: There is no number that occurs only once.

Constraints:

1 <= nums.length <= 2000


0 <= nums[i] <= 1000
*********************

299. Largest Unique Number(C++)


*********************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int largestUniqueNumber(vector& A) {
7 unordered_map lookup;
8 for (const auto& x : A) {
9 ++lookup[x];
10 }
11 int result = -1;
12 for (const auto& [k, v] : lookup) {
13 if (v == 1) {
14 result = max(result, k);
15 }
16 }
17 return result;
18 }
19 };
*********************

299. Largest Unique Number(Python)


*********************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def largestUniqueNumber(self, A):
9 """
10 :type A: List[int]
11 :rtype: int
12 """
13 A.append(-1)
14 return max(k for k,v in collections.Counter(A).items() if v == 1)
****************

300. Armstrong Number


****************

Given an integer n, return true if and only if it is an Armstrong number.

The k -digit number n is an Armstrong number if and only if the k th power of each digit sums to n.

Example 1:

Input: n = 153
Output: true
Explanation: 153 is a 3-digit number, and 153 = 13 + 53 + 33.

Example 2:

Input: n = 123
Output: false
Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36.

Constraints:

1 <= n <= 10 8
****************

300. Armstrong Number(C++)


****************

1 // Time: O(klogk)
2 // Space: O(k)
3
4 class Solution {
5 public:
6 bool isArmstrong(int N) {
7 const auto& n_str = to_string(N);
8 return accumulate(n_str.cbegin(), n_str.cend(), 0,
9 [&](const auto& x, const auto& y) {
10 return x + pow(y - '0', n_str.length());
11 }) == N;
12 }
13 };
****************

300. Armstrong Number(Python)


****************

1 # Time: O(klogk)
2 # Space: O(k)
3
4 class Solution(object):
5 def isArmstrong(self, N):
6 """
7 :type N: int
8 :rtype: bool
9 """
10 n_str = str(N)
11 return sum(int(i)**len(n_str) for i in n_str) == N
**********************

301. N-th Tribonacci Number


**********************

The Tribonacci sequence Tn is defined as follows:

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Given n, return the value of Tn.

Example 1:

Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

Example 2:

Input: n = 25
Output: 1389537

Constraints:

0 <= n <= 37
The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 .
**********************

301. N-th Tribonacci Number(C++)


**********************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int tribonacci(int n) {
7 vector> T = {{1, 1, 0},
8 {1, 0, 1},
9 {1, 0, 0}};
10 return matrixMult({{1, 0, 0}}, matrixExpo(T, n))[0][1]; // [a1, a0, a(-1)] * T^n
11 }
12
13 private:
14 vector> matrixExpo(const vector>& A, int pow) {
15 vector> result(A.size(), vector(A.size()));
16 vector> A_exp(A);
17 for (int i = 0; i < A.size(); ++i) {
18 result[i][i] = 1;
19 }
20 while (pow) {
21 if (pow % 2 == 1) {
22 result = matrixMult(result, A_exp);
23 }
24 A_exp = matrixMult(A_exp, A_exp);
25 pow /= 2;
26 }
27 return result;
28 }
29
30 vector> matrixMult(const vector>& A, const vector>& B) {
31 vector> result(A.size(), vector(B[0].size()));
32 for (int i = 0; i < A.size(); ++i) {
33 for (int j = 0; j < B[0].size(); ++j) {
34 int64_t entry = 0;
35 for (int k = 0; k < B.size(); ++k) {
36 entry = (static_cast(A[i][k]) * B[k][j] + entry);
37 }
38 result[i][j] = static_cast(entry);
39 }
40 }
41 return result;
42 }
43 };
44
45 // Time: O(n)
46 // Space: O(1)
47 class Solution2 {
48 public:
49 int tribonacci(int n) {
50 vector dp = {0, 1, 1, 0};
51 for (int i = 3; i <= n; ++i) {
52 dp[i % 4] = dp[(i - 1) % 4] + dp[(i - 2) % 4] + dp[(i - 3) % 4];
53 }
54 return dp[n % 4];
55 }
56 };
**********************

301. N-th Tribonacci Number(Python)


**********************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def tribonacci(self, n):
9 """
10 :type n: int
11 :rtype: int
12 """
13 def matrix_expo(A, K):
14 result = [[int(i==j) for j in xrange(len(A))] \
15 for i in xrange(len(A))]
16 while K:
17 if K % 2:
18 result = matrix_mult(result, A)
19 A = matrix_mult(A, A)
20 K /= 2
21 return result
22
23 def matrix_mult(A, B):
24 ZB = zip(*B)
25 return [[sum(a*b for a, b in itertools.izip(row, col)) \
26 for col in ZB] for row in A]
27
28 T = [[1, 1, 0],
29 [1, 0, 1],
30 [1, 0, 0]]
31 return matrix_mult([[1, 0, 0]], matrix_expo(T, n))[0][1] # [a1, a0, a(-1)] * T^n
32
33
34 # Time: O(n)
35 # Space: O(1)
36 class Solution2(object):
37 def tribonacci(self, n):
38 """
39 :type n: int
40 :rtype: int
41 """
42 a, b, c = 0, 1, 1
43 for _ in xrange(n):
44 a, b, c = b, c, a+b+c
45 return a
************************************

302. User Activity for the Past 30 Days I


************************************

Table: Activity

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| session_id | int |
| activity_date | date |
| activity_type | enum |
+---------------+---------+
There is no primary key for this table, it may have duplicate rows.
The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message').
The table shows the user activities for a social media website.
Note that each session belongs to exactly one user.

Write an SQL query to find the daily active user count for a period of 30 days ending2019-07-27 inclusively. A user was
active on some day if he/she made at least one activity on that day.

The query result format is in the following example:

Activity table:
+---------+------------+---------------+---------------+
| user_id | session_id | activity_date | activity_type |
+---------+------------+---------------+---------------+
| 1 | 1 | 2019-07-20 | open_session |
| 1 | 1 | 2019-07-20 | scroll_down |
| 1 | 1 | 2019-07-20 | end_session |
| 2 | 4 | 2019-07-20 | open_session |
| 2 | 4 | 2019-07-21 | send_message |
| 2 | 4 | 2019-07-21 | end_session |
| 3 | 2 | 2019-07-21 | open_session |
| 3 | 2 | 2019-07-21 | send_message |
| 3 | 2 | 2019-07-21 | end_session |
| 4 | 3 | 2019-06-25 | open_session |
| 4 | 3 | 2019-06-25 | end_session |
+---------+------------+---------------+---------------+

Result table:
+------------+--------------+
| day | active_users |
+------------+--------------+
| 2019-07-20 | 2 |
| 2019-07-21 | 2 |
+------------+--------------+
Note that we do not care about days with zero active users.
************************************

302. User Activity for the Past 30 Days I(Shell)


************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT activity_date AS day,
5 Count(DISTINCT user_id) AS active_users
6 FROM activity
7 GROUP BY activity_date
8 HAVING Datediff("2019-07-27", activity_date) < 30
9 ORDER BY NULL
*************************************

303. User Activity for the Past 30 Days II


*************************************

Table: Activity

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| session_id | int |
| activity_date | date |
| activity_type | enum |
+---------------+---------+
There is no primary key for this table, it may have duplicate rows.
The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message').
The table shows the user activities for a social media website.
Note that each session belongs to exactly one user.

Write an SQL query to find the average number of sessions per user for a period of 30 days ending2019-07-27 inclusively,
rounded to 2 decimal places. The sessions we want to count for a user are those with at least one activity in that time
period.

The query result format is in the following example:

Activity table:
+---------+------------+---------------+---------------+
| user_id | session_id | activity_date | activity_type |
+---------+------------+---------------+---------------+
| 1 | 1 | 2019-07-20 | open_session |
| 1 | 1 | 2019-07-20 | scroll_down |
| 1 | 1 | 2019-07-20 | end_session |
| 2 | 4 | 2019-07-20 | open_session |
| 2 | 4 | 2019-07-21 | send_message |
| 2 | 4 | 2019-07-21 | end_session |
| 3 | 2 | 2019-07-21 | open_session |
| 3 | 2 | 2019-07-21 | send_message |
| 3 | 2 | 2019-07-21 | end_session |
| 3 | 5 | 2019-07-21 | open_session |
| 3 | 5 | 2019-07-21 | scroll_down |
| 3 | 5 | 2019-07-21 | end_session |
| 4 | 3 | 2019-06-25 | open_session |
| 4 | 3 | 2019-06-25 | end_session |
+---------+------------+---------------+---------------+

Result table:
+---------------------------+
| average_sessions_per_user |
+---------------------------+
| 1.33 |
+---------------------------+
User 1 and 2 each had 1 session in the past 30 days while user 3 had 2 sessions so the average is (1 + 1 + 2) / 3 = 1.33.
*************************************

303. User Activity for the Past 30 Days II(Shell)


*************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT Round(Ifnull(Count(DISTINCT session_id) / Count(DISTINCT user_id), 0), 2)
5 AS
6 average_sessions_per_user
7 FROM activity
8 WHERE Datediff("2019-07-27", activity_date) < 30
***************

304. Article Views I


***************

Table: Views

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| article_id | int |
| author_id | int |
| viewer_id | int |
| view_date | date |
+---------------+---------+
There is no primary key for this table, it may have duplicate rows.
Each row of this table indicates that some viewer viewed an article (written by some author) on some date.
Note that equal author_id and viewer_id indicate the same person.

Write an SQL query to find all the authors that viewed at least one of their own articles, sorted in ascending order by their id.

The query result format is in the following example:

Views table:
+------------+-----------+-----------+------------+
| article_id | author_id | viewer_id | view_date |
+------------+-----------+-----------+------------+
| 1 | 3 | 5 | 2019-08-01 |
| 1 | 3 | 6 | 2019-08-02 |
| 2 | 7 | 7 | 2019-08-01 |
| 2 | 7 | 6 | 2019-08-02 |
| 4 | 7 | 1 | 2019-07-22 |
| 3 | 4 | 4 | 2019-07-21 |
| 3 | 4 | 4 | 2019-07-21 |
+------------+-----------+-----------+------------+

Result table:
+------+
| id |
+------+
| 4 |
| 7 |
+------+
***************

304. Article Views I(Shell)


***************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT DISTINCT author_id AS id
5 FROM views
6 WHERE author_id = viewer_id
7 ORDER BY id
*******************************************************

305. Check If a Number Is Majority Element in a Sorted


Array
*******************************************************

Given an integer array nums sorted in non-decreasing order and an integertarget, return true if target is a majority element, or
false otherwise.

A majority element in an array nums is an element that appears more than nums.length / 2 times in the array.

Example 1:

Input: nums = [2,4,5,5,5,5,5,6,6], target = 5


Output: true
Explanation: The value 5 appears 5 times and the length of the array is 9.
Thus, 5 is a majority element because 5 > 9/2 is true.

Example 2:

Input: nums = [10,100,101,101], target = 101


Output: false
Explanation: The value 101 appears 2 times and the length of the array is 4.
Thus, 101 is not a majority element because 2 > 4/2 is false.

Constraints:

1 <= nums.length <= 1000


1 <= nums[i], target <= 109
nums is sorted in non-decreasing order.
*******************************************************

305. Check If a Number Is Majority Element in a Sorted


Array(C++)
*******************************************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isMajorityElement(vector& nums, int target) {
7 if (nums.size() % 2) {
8 if (nums[nums.size() / 2] != target) {
9 return false;
10 }
11 } else {
12 if (nums[nums.size() / 2 - 1] != nums[nums.size() / 2] ||
13 nums[nums.size() / 2] != target) {
14 return false;
15 }
16 }
17 const auto& l = lower_bound(nums.cbegin(), nums.cend(), target);
18 const auto& r = upper_bound(nums.cbegin(), nums.cend(), target);
19 return (r - l) * 2 > nums.size();
20 }
21 };
*******************************************************

305. Check If a Number Is Majority Element in a Sorted


Array(Python)
*******************************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import bisect
5
6
7 class Solution(object):
8 def isMajorityElement(self, nums, target):
9 """
10 :type nums: List[int]
11 :type target: int
12 :rtype: bool
13 """
14 if len(nums) % 2:
15 if nums[len(nums)//2] != target:
16 return False
17 else:
18 if not (nums[len(nums)//2-1] == nums[len(nums)//2] == target):
19 return False
20
21 left = bisect.bisect_left(nums, target)
22 right= bisect.bisect_right(nums, target)
23 return (right-left)*2 > len(nums)
***************

306. Day of the Year


***************

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

Example 1:

Input: date = "2019-01-09"


Output: 9
Explanation: Given date is the 9th day of the year in 2019.

Example 2:

Input: date = "2019-02-10"


Output: 41

Example 3:

Input: date = "2003-03-01"


Output: 60

Example 4:

Input: date = "2004-03-01"


Output: 61

Constraints:

date.length == 10
date[4] == date[7] == '-' , and all other date[i]'s are digits
date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.
***************

306. Day of the Year(C++)


***************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 Solution() : lookup_(12) {
7 for (int M = 1; M < lookup_.size(); ++M) {
8 lookup_[M] = lookup_[M - 1] + dayOfMonth(M);
9 }
10 }
11
12 int dayOfYear(string date) {
13 const auto& result = split(date, '-');
14 const auto& Y = stoi(result[0]), &M = stoi(result[1]), &D = stoi(result[2]);
15 const auto& leap = (M > 2 && (((Y % 4 == 0) && (Y % 100 != 0)) || (Y % 400 == 0))) ? 1 : 0;
16 return lookup_[M - 1] + D + leap;
17 }
18
19 private:
20 int dayOfMonth(int M) {
21 return (M == 2) ? 28 : 31 - (M - 1) % 7 % 2;
22 }
23
24 vector split(const string& s, const char delim) {
25 vector result;
26 auto end = string::npos;
27 do {
28 const auto& start = end + 1;
29 end = s.find(delim, start);
30 result.emplace_back(s.substr(start, end - start));
31 } while (end != string::npos);
32 return result;
33 }
34
35 vector lookup_;
36 };
***************

306. Day of the Year(Python)


***************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def __init__(self):
6 def dayOfMonth(M):
7 return (28 if (M == 2) else 31-(M-1)%7%2)
8
9 self.__lookup = [0]*12
10 for M in xrange(1, len(self.__lookup)):
11 self.__lookup[M] += self.__lookup[M-1]+dayOfMonth(M)
12
13 def dayOfYear(self, date):
14 """
15 :type date: str
16 :rtype: int
17 """
18 Y, M, D = map(int, date.split("-"))
19 leap = 1 if M > 2 and (((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0)) else 0
20 return self.__lookup[M-1]+D+leap
21
22
23 # Time: O(1)
24 # Space: O(1)
25 class Solution2(object):
26 def dayOfYear(self, date):
27 """
28 :type date: str
29 :rtype: int
30 """
31 def numberOfDays(Y, M):
32 leap = 1 if ((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0) else 0
33 return (28+leap if (M == 2) else 31-(M-1)%7%2)
34
35 Y, M, result = map(int, date.split("-"))
36 for i in xrange(1, M):
37 result += numberOfDays(Y, i)
38 return result
*******************************************

307. Find Words That Can Be Formed by Characters


*******************************************

You are given an array of stringswords and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"


Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"


Output: 10
Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Constraints:

1 <= words.length <= 1000


1 <= words[i].length, chars.length <= 100
words[i] and chars consist of lowercase English letters.
*******************************************

307. Find Words That Can Be Formed by Characters(C++)


*******************************************

1 // Time: O(m * n), m is the length of chars, n is the number of words


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countCharacters(vector& words, string chars) {
7 const auto& count = counter(chars);
8 int result = 0;
9 for (const auto& word : words) {
10 if (check(word, chars, count)) {
11 result += word.length();
12 }
13 }
14 return result;
15 }
16
17 private:
18 unordered_map counter(const string& s) {
19 unordered_map result;
20 for (const auto& c : s) {
21 ++result[c];
22 }
23 return result;
24 }
25
26 bool check(const string& word, const string& chars,
27 const unordered_map& count) {
28 if (word.length() > chars.length()) {
29 return false;
30 }
31 unordered_map curr_count;
32 for (const auto& c : word) {
33 ++curr_count[c];
34 if (!count.count(c) || count.at(c) < curr_count[c]) {
35 return false;
36 }
37 }
38 return true;
39 }
40 };
*******************************************

307. Find Words That Can Be Formed by


Characters(Python)
*******************************************

1 # Time: O(m * n), m is the length of chars, n is the number of words


2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def countCharacters(self, words, chars):
9 """
10 :type words: List[str]
11 :type chars: str
12 :rtype: int
13 """
14 def check(word, chars, count):
15 if len(word) > len(chars):
16 return False
17 curr_count = collections.Counter()
18 for c in word:
19 curr_count[c] += 1
20 if c not in count or count[c] < curr_count[c]:
21 return False
22 return True
23
24 count = collections.Counter(chars)
25 return sum(len(word) for word in words if check(word, chars, count))
26
*******************

308. Single-Row Keyboard


*******************

There is a special keyboard with all keys in a single row.

Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index
0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your
finger from index i to index j is |i - j|.

You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.

Example 1:

Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"


Output: 4
Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
Total time = 2 + 1 + 1 = 4.

Example 2:

Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"


Output: 73

Constraints:

keyboard.length == 26
keyboard contains each English lowercase letter exactly once in some order.
1 <= word.length <= 10 4
word[i] is an English lowercase letter.
*******************

308. Single-Row Keyboard(C++)


*******************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int calculateTime(string keyboard, string word) {
7 unordered_map lookup;
8 for (int i = 0; i < keyboard.length(); ++i) {
9 lookup[keyboard[i]] = i;
10 }
11 int result = 0, prev = 0;
12 for (const auto& c : word) {
13 result += abs(lookup[c] - prev);
14 prev = lookup[c];
15 }
16 return result;
17 }
18 };
*******************

308. Single-Row Keyboard(Python)


*******************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def calculateTime(self, keyboard, word):
6 """
7 :type keyboard: str
8 :type word: str
9 :rtype: int
10 """
11 lookup = {c:i for i, c in enumerate(keyboard)}
12 result, prev = 0, 0
13 for c in word:
14 result += abs(lookup[c]-prev)
15 prev = lookup[c]
16 return result
******************************************************

309. Compare Strings by Frequency of the Smallest


Character
******************************************************

Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s . For example, if s
= "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.

You are given an array of stringswords and another array of query strings queries. For each query queries[i], count the number
of words in words such that f(queries[i]) < f(W) for each W in words.

Return an integer array answer, where each answer[i] is the answer to the ith query.

Example 1:

Input: queries = ["cbd"], words = ["zaaaz"]


Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").

Example 2:

Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]


Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").

Constraints:

1 <= queries.length <= 2000


1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j], words[i][j] consist of lowercase English letters.
******************************************************

309. Compare Strings by Frequency of the Smallest


Character(C++)
******************************************************

1 // Time: O((m + n)logn), m is the number of queries, n is the number of words


2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector numSmallerByFrequency(vector& queries, vector& words) {
7 vector words_freq;
8 for (const auto& word : words) {
9 words_freq.emplace_back(f(word));
10 }
11 sort(words_freq.begin(), words_freq.end());
12 vector result;
13 for (const auto& query : queries) {
14 const auto& it = upper_bound(words_freq.cbegin(), words_freq.cend(), f(query));
15 result.emplace_back(distance(it, words_freq.cend()));
16 }
17 return result;
18 }
19
20 private:
21 int f(const string& word) {
22 const auto& smallest = *min_element(word.cbegin(), word.cend());
23 return count(word.cbegin(), word.cend(), smallest);
24 }
25 };
******************************************************

309. Compare Strings by Frequency of the Smallest


Character(Python)
******************************************************

1 # Time: O((m + n)logn), m is the number of queries, n is the number of words


2 # Space: O(n)
3
4 import bisect
5
6
7 class Solution(object):
8 def numSmallerByFrequency(self, queries, words):
9 """
10 :type queries: List[str]
11 :type words: List[str]
12 :rtype: List[int]
13 """
14 words_freq = sorted(word.count(min(word)) for word in words)
15 return [len(words)-bisect.bisect_right(words_freq, query.count(min(query))) \
16 for query in queries]
*************************

310. Immediate Food Delivery I


*************************

Table: Delivery

+-----------------------------+---------+
| Column Name | Type |
+-----------------------------+---------+
| delivery_id | int |
| customer_id | int |
| order_date | date |
| customer_pref_delivery_date | date |
+-----------------------------+---------+
delivery_id is the primary key of this table.
The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same

If the preferred delivery date of the customer is the same as the order date then the order is calledimmediate otherwise it's
called scheduled.

Write an SQL query to find the percentage of immediate orders in the table,rounded to 2 decimal places.

The query result format is in the following example:

Delivery table:
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1 | 1 | 2019-08-01 | 2019-08-02 |
| 2 | 5 | 2019-08-02 | 2019-08-02 |
| 3 | 1 | 2019-08-11 | 2019-08-11 |
| 4 | 3 | 2019-08-24 | 2019-08-26 |
| 5 | 4 | 2019-08-21 | 2019-08-22 |
| 6 | 2 | 2019-08-11 | 2019-08-13 |
+-------------+-------------+------------+-----------------------------+

Result table:
+----------------------+
| immediate_percentage |
+----------------------+
| 33.33 |
+----------------------+
The orders with delivery id 2 and 3 are immediate while the others are scheduled.
*************************

310. Immediate Food Delivery I(Shell)


*************************

1 # Time: O(n)
2 # Space: O(1)
3
4 SELECT Round(100 * Sum(order_date = customer_pref_delivery_date) / Count(*), 2)
5 AS
6 immediate_percentage
7 FROM delivery;
******************

311. Prime Arrangements


******************

Return the number of permutations of 1 ton so that prime numbers are at prime indices (1-indexed.)

(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive
integers both smaller than it.)

Since the answer may be large, return the answer modulo 10^9 + 7 .

Example 1:

Input: n = 5
Output: 12
Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.

Example 2:

Input: n = 100
Output: 682289015

Constraints:

1 <= n <= 100


******************

311. Prime Arrangements(C++)


******************

1 // Time: O(n/2 + n/3 + ... + n/p) = O(nlog(logn)), see https://mathoverflow.net/questions/4596/on-the-series-1-2-1-3-1-5-1-7-1-11


2 // Space: O(n)
3
4 class Solution {
5 public:
6 int numPrimeArrangements(int n) {
7 int cnt = count_primes(n);
8 return static_cast(factorial(cnt)) * factorial(n - cnt) % MOD;
9 }
10
11 private:
12 int count_primes(int n) {
13 if (n <= 1) {
14 return 0;
15 }
16 vector is_primes((n + 1) / 2, true);
17 int cnt = is_primes.size();
18 for (int i = 3; i * i <= n; i += 2) {
19 if (!is_primes[i / 2]) {
20 continue;
21 }
22 for (int j = i * i; j <= n; j += 2 * i) {
23 if (!is_primes[j / 2]) {
24 continue;
25 }
26 --cnt;
27 is_primes[j / 2] = false;
28 }
29 }
30 return cnt;
31 }
32
33 int factorial(int n) {
34 int result = 1ull;
35 for (int i = 2; i <= n; ++i) {
36 result = (static_cast(result) * i) % MOD;
37 }
38 return result;
39 }
40
41 static const int MOD = 1e9 + 7;
42 };
******************

311. Prime Arrangements(Python)


******************

1 # Time: O(n/2 + n/3 + ... + n/p) = O(nlog(logn)), see https://mathoverflow.net/questions/4596/on-the-series-1-2-1-3-1-5-1-7-1-11


2 # Space: O(n)
3
4 class Solution(object):
5 def numPrimeArrangements(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 def count_primes(n):
11 if n <= 1:
12 return 0
13 is_prime = [True]*((n+1)//2)
14 cnt = len(is_prime)
15 for i in xrange(3, n+1, 2):
16 if i*i > n:
17 break
18 if not is_prime[i//2]:
19 continue
20 for j in xrange(i*i, n+1, 2*i):
21 if not is_prime[j//2]:
22 continue
23 cnt -= 1
24 is_prime[j//2] = False
25 return cnt
26
27 def factorial(n):
28 result = 1
29 for i in xrange(2, n+1):
30 result = (result*i)%MOD
31 return result
32
33 MOD = 10**9+7
34 cnt = count_primes(n)
35 return factorial(cnt) * factorial(n-cnt) % MOD
*********************

312. Diet Plan Performance


*********************

A dieter consumes calories[i] calories on the i-th day.

Given an integer k , for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k ), they look
at T, the total calories consumed during that sequence ofk days (calories[i] + calories[i+1] + ... + calories[i+k-1] ):

If T < lower , they performed poorly on their diet and lose 1 point;
If T > upper , they performed well on their diet and gain 1 point;
Otherwise, they performed normally and there is no change in points.

Initially, the dieter has zero points. Return the total number of points the dieter has after dieting forcalories.length days.

Note that the total points can be negative.

Example 1:

Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3


Output: 0
Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
calories[0] and calories[1] are less than lower so 2 points are lost.
calories[3] and calories[4] are greater than upper so 2 points are gained.

Example 2:

Input: calories = [3,2], k = 2, lower = 0, upper = 1


Output: 1
Explanation: Since k = 2, we consider subarrays of length 2.
calories[0] + calories[1] > upper so 1 point is gained.

Example 3:

Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5


Output: 0
Explanation:
calories[0] + calories[1] > upper so 1 point is gained.
lower <= calories[1] + calories[2] <= upper so no change in points.
calories[2] + calories[3] < lower so 1 point is lost.

Constraints:

1 <= k <= calories.length <= 10^5


0 <= calories[i] <= 20000
0 <= lower <= upper
*********************

312. Diet Plan Performance(C++)


*********************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int dietPlanPerformance(vector& calories, int k, int lower, int upper) {
7 int total = accumulate(calories.cbegin(), calories.cbegin() + k, 0);
8 int result = int(total > upper) - int(total < lower);
9 for (int i = k; i < calories.size(); ++i) {
10 total += calories[i] - calories[i - k];
11 result += int(total > upper) - int(total < lower);
12 }
13 return result;
14 }
15 };
*********************

312. Diet Plan Performance(Python)


*********************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def dietPlanPerformance(self, calories, k, lower, upper):
9 """
10 :type calories: List[int]
11 :type k: int
12 :type lower: int
13 :type upper: int
14 :rtype: int
15 """
16 total = sum(itertools.islice(calories, 0, k))
17 result = int(total > upper)-int(total < lower)
18 for i in xrange(k, len(calories)):
19 total += calories[i]-calories[i-k]
20 result += int(total > upper)-int(total < lower)
21 return result
*************************

313. Reformat Department Table


*************************

Table: Department

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| revenue | int |
| month | varchar |
+---------------+---------+
(id, month) is the primary key of this table.
The table has information about the revenue of each department per month.
The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].

Write an SQL query to reformat the table such that there is a department id column and a revenue columnfor each month.

The query result format is in the following example:

Department table:
+------+---------+-------+
| id | revenue | month |
+------+---------+-------+
| 1 | 8000 | Jan |
| 2 | 9000 | Jan |
| 3 | 10000 | Feb |
| 1 | 7000 | Feb |
| 1 | 6000 | Mar |
+------+---------+-------+

Result table:
+------+-------------+-------------+-------------+-----+-------------+
| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1 | 8000 | 7000 | 6000 | ... | null |
| 2 | 9000 | null | null | ... | null |
| 3 | null | 10000 | null | ... | null |
+------+-------------+-------------+-------------+-----+-------------+

Note that the result table has 13 columns (1 for the department id + 12 for the months).
*************************

313. Reformat Department Table(Shell)


*************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT id,
5 SUM(IF(month = 'Jan', revenue, NULL)) AS Jan_Revenue,
6 SUM(IF(month = 'Feb', revenue, NULL)) AS Feb_Revenue,
7 SUM(IF(month = 'Mar', revenue, NULL)) AS Mar_Revenue,
8 SUM(IF(month = 'Apr', revenue, NULL)) AS Apr_Revenue,
9 SUM(IF(month = 'May', revenue, NULL)) AS May_Revenue,
10 SUM(IF(month = 'Jun', revenue, NULL)) AS Jun_Revenue,
11 SUM(IF(month = 'Jul', revenue, NULL)) AS Jul_Revenue,
12 SUM(IF(month = 'Aug', revenue, NULL)) AS Aug_Revenue,
13 SUM(IF(month = 'Sep', revenue, NULL)) AS Sep_Revenue,
14 SUM(IF(month = 'Oct', revenue, NULL)) AS Oct_Revenue,
15 SUM(IF(month = 'Nov', revenue, NULL)) AS Nov_Revenue,
16 SUM(IF(month = 'Dec', revenue, NULL)) AS Dec_Revenue
17 FROM department
18 GROUP BY id;
**********************************************

314. Count Substrings with Only One Distinct Letter


**********************************************

Given a string s , return the number of substrings that have only one distinct letter.

Example 1:

Input: s = "aaaba"
Output: 8
Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
"aaa" occurs 1 time.
"aa" occurs 2 times.
"a" occurs 4 times.
"b" occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.

Example 2:

Input: s = "aaaaaaaaaa"
Output: 55

Constraints:

1 <= s.length <= 1000


s[i] consists of only lowercase English letters.
**********************************************

314. Count Substrings with Only One Distinct Letter(C++)


**********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countLetters(string S) {
7 int result = S.length();
8 int left = 0;
9 for (int right = 1; right < S.length(); ++right) {
10 if (S[right] == S[left]) {
11 result += right - left;
12 } else {
13 left = right;
14 }
15 }
16 return result;
17 }
18 };
**********************************************

314. Count Substrings with Only One Distinct


Letter(Python)
**********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countLetters(self, S):
6 """
7 :type S: str
8 :rtype: int
9 """
10 result = len(S)
11 left = 0
12 for right in xrange(1, len(S)):
13 if S[right] == S[left]:
14 result += right-left
15 else:
16 left = right
17 return result
**************************

315. Distance Between Bus Stops


**************************

A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops
where distance[i] is the distance between the stops number i and (i + 1) % n .

The bus goes along both directions i.e. clockwise and counterclockwise.

Return the shortest distance between the given start and destination stops.

Example 1:

Input: distance = [1,2,3,4], start = 0, destination = 1


Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.

Example 2:

Input: distance = [1,2,3,4], start = 0, destination = 2


Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.

Example 3:
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.

Constraints:

1 <= n <= 10^4


distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
**************************

315. Distance Between Bus Stops(C++)


**************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int distanceBetweenBusStops(vector& distance, int start, int destination) {
7 if (start > destination) {
8 swap(start, destination);
9 }
10 const auto& s_to_d = accumulate(distance.cbegin() + start,
11 distance.cbegin() + destination, 0);
12 const auto& d_to_s = accumulate(distance.cbegin(),
13 distance.cbegin() + start, 0) +
14 accumulate(distance.cbegin() + destination,
15 distance.cend(), 0);
16 return min(s_to_d, d_to_s);
17 }
18 };
**************************

315. Distance Between Bus Stops(Python)


**************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def distanceBetweenBusStops(self, distance, start, destination):
9 """
10 :type distance: List[int]
11 :type start: int
12 :type destination: int
13 :rtype: int
14 """
15 if start > destination:
16 start, destination = destination, start
17 s_to_d = sum(itertools.islice(distance, start, destination))
18 d_to_s = sum(itertools.islice(distance, 0, start)) + \
19 sum(itertools.islice(distance, destination, len(distance)))
20 return min(s_to_d, d_to_s)
***************

316. Day of the Week


***************

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} .

Example 1:

Input: day = 31, month = 8, year = 2019


Output: "Saturday"

Example 2:

Input: day = 18, month = 7, year = 1999


Output: "Sunday"

Example 3:

Input: day = 15, month = 8, year = 1993


Output: "Sunday"

Constraints:

The given dates are valid dates between the years1971 and 2100.
***************

316. Day of the Week(C++)


***************

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string dayOfTheWeek(int day, int month, int year) {
7 static const vector DAYS = {"Sunday", "Monday", "Tuesday", "Wednesday",
8 "Thursday", "Friday", "Saturday"};
9
10 // Zeller Formula
11 if (month < 3) {
12 month += 12;
13 --year;
14 }
15 int c = year / 100, y = year % 100;
16 const auto& w = ((c / 4 - 2 * c + y + y / 4 + 13 * (month + 1) / 5 + day - 1) % 7 + 7) % 7;
17 return DAYS[w];
18 }
19 };
***************

316. Day of the Week(Python)


***************

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def dayOfTheWeek(self, day, month, year):
6 """
7 :type day: int
8 :type month: int
9 :type year: int
10 :rtype: str
11 """
12 DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", \
13 "Thursday", "Friday", "Saturday"]
14
15 # Zeller Formula
16 if month < 3:
17 month += 12
18 year -= 1
19 c, y = divmod(year, 100)
20 w = (c//4 - 2*c + y + y//4 + 13*(month+1)//5 + day - 1) % 7
21 return DAYS[w]
**************************

317. Maximum Number of Balloons


**************************

Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.

You can use each character in text at most once. Return the maximum number of instances that can be formed.

Example 1:

Input: text = "nlaebolko"


Output: 1

Example 2:

Input: text = "loonbalxballpoon"


Output: 2

Example 3:

Input: text = "leetcode"


Output: 0

Constraints:

1 <= text.length <= 10 4


text consists of lower case English letters only.
**************************

317. Maximum Number of Balloons(C++)


**************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxNumberOfBalloons(string text) {
7 static const string TARGET = "balloon";
8 unordered_map source_count, target_count;
9 for (const auto& c : text) {
10 ++source_count[c];
11 }
12 for (const auto& c : TARGET) {
13 ++target_count[c];
14 }
15 int result = numeric_limits::max();
16 for (const auto& [c, count] : target_count) {
17 result = min(result, source_count[c] / count);
18 }
19 return result;
20 }
21 };
**************************

317. Maximum Number of Balloons(Python)


**************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def maxNumberOfBalloons(self, text):
9 """
10 :type text: str
11 :rtype: int
12 """
13 TARGET = "balloon"
14 source_count = collections.Counter(text)
15 target_count = collections.Counter(TARGET)
16 return min(source_count[c]//target_count[c] for c in target_count.iterkeys())
*******************************************

318. How Many Apples Can You Put into the Basket
*******************************************

You have some apples, where arr[i] is the weight of the i-th apple. You also have a basket that can carry up to5000 units of
weight.

Return the maximum number of apples you can put in the basket.

Example 1:

Input: arr = [100,200,150,1000]


Output: 4
Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.

Example 2:

Input: arr = [900,950,800,1000,700,800]


Output: 5
Explanation: The sum of weights of the 6 apples exceeds 5000 so we choose any 5 of them.

Constraints:

1 <= arr.length <= 10^3


1 <= arr[i] <= 10^3
*******************************************

318. How Many Apples Can You Put into the Basket(C++)
*******************************************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int maxNumberOfApples(vector& arr) {
7 static int LIMIT = 5000;
8 sort(arr.begin(), arr.end());
9 int result = 0, total = 0;
10 for (const auto& x : arr) {
11 if (total + x > LIMIT) {
12 break;
13 }
14 total += x;
15 ++result;
16 }
17 return result;
18 }
19 };
*******************************************

318. How Many Apples Can You Put into the


Basket(Python)
*******************************************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 class Solution(object):
5 def maxNumberOfApples(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: int
9 """
10 LIMIT = 5000
11 arr.sort()
12 result, total = 0, 0
13 for x in arr:
14 if total+x > LIMIT:
15 break
16 total += x
17 result += 1
18 return result
***************************

319. Minimum Absolute Difference


***************************

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair[a, b] follows

a, b are from arr


a<b
b - a equals to the minimum absolute difference of any two elements inarr

Example 1:

Input: arr = [4,2,1,3]


Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

Example 2:

Input: arr = [1,3,6,10,15]


Output: [[1,3]]

Example 3:

Input: arr = [3,8,-10,23,19,-4,-14,27]


Output: [[-14,-10],[19,23],[23,27]]

Constraints:

2 <= arr.length <= 10^5


-10^6 <= arr[i] <= 10^6
***************************

319. Minimum Absolute Difference(C++)


***************************

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector> minimumAbsDifference(vector& arr) {
7 vector> result;
8 int min_diff = numeric_limits::max();
9 sort(arr.begin(),arr.end());
10 for (int i = 0; i < arr.size() - 1; ++i) {
11 const auto diff = arr[i + 1] - arr[i];
12 if (diff < min_diff) {
13 min_diff = diff;
14 result = {{arr[i], arr[i + 1]}};
15 } else if (diff == min_diff) {
16 result.push_back({arr[i], arr[i + 1]});
17 }
18 }
19 return result;
20 }
21 };
***************************

319. Minimum Absolute Difference(Python)


***************************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 class Solution(object):
5 def minimumAbsDifference(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: List[List[int]]
9 """
10 result = []
11 min_diff = float("inf")
12 arr.sort()
13 for i in xrange(len(arr)-1):
14 diff = arr[i+1]-arr[i]
15 if diff < min_diff:
16 min_diff = diff
17 result = [[arr[i], arr[i+1]]]
18 elif diff == min_diff:
19 result.append([arr[i], arr[i+1]])
20 return result
****************************

320. Unique Number of Occurrences


****************************

Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the
array is unique.

Example 1:

Input: arr = [1,2,2,1,1,3]


Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2:

Input: arr = [1,2]


Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]


Output: true

Constraints:

1 <= arr.length <= 1000


-1000 <= arr[i] <= 1000
****************************

320. Unique Number of Occurrences(C++)


****************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool uniqueOccurrences(vector& arr) {
7 unordered_map count;
8 for (const auto& a : arr) {
9 ++count[a];
10 }
11 unordered_set lookup;
12 for (const auto& [k, v] : count) {
13 if (lookup.count(v)) {
14 return false;
15 }
16 lookup.emplace(v);
17 }
18 return true;
19 }
20 };
****************************

320. Unique Number of Occurrences(Python)


****************************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def uniqueOccurrences(self, arr):
9 """
10 :type arr: List[int]
11 :rtype: bool
12 """
13 count = collections.Counter(arr)
14 lookup = set()
15 for v in count.itervalues():
16 if v in lookup:
17 return False
18 lookup.add(v)
19 return True
20
21
22 # Time: O(n)
23 # Space: O(n)
24 class Solution2(object):
25 def uniqueOccurrences(self, arr):
26 """
27 :type arr: List[int]
28 :rtype: bool
29 """
30 count = collections.Counter(arr)
31 return len(count) == len(set(count.itervalues()))
******************************

321. Queries Quality and Percentage


******************************

Table: Queries

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| query_name | varchar |
| result | varchar |
| position | int |
| rating | int |
+-------------+---------+
There is no primary key for this table, it may have duplicate rows.
This table contains information collected from some queries on a database.
The position column has a value from 1 to 500.
The rating column has a value from 1 to 5. Query with rating less than 3 is a poor query.

We define query quality as:

The average of the ratio between query rating and its position.

We also define poor query percentage as:

The percentage of all queries with rating less than 3.

Write an SQL query to find each query_name, the quality and poor_query_percentage.

Both quality and poor_query_percentage should be rounded to 2 decimal places.

The query result format is in the following example:

Queries table:
+------------+-------------------+----------+--------+
| query_name | result | position | rating |
+------------+-------------------+----------+--------+
| Dog | Golden Retriever | 1 | 5 |
| Dog | German Shepherd | 2 | 5 |
| Dog | Mule | 200 | 1 |
| Cat | Shirazi | 5 | 2 |
| Cat | Siamese | 3 | 3 |
| Cat | Sphynx | 7 | 4 |
+------------+-------------------+----------+--------+

Result table:
+------------+---------+-----------------------+
| query_name | quality | poor_query_percentage |
+------------+---------+-----------------------+
| Dog | 2.50 | 33.33 |
| Cat | 0.66 | 33.33 |
+------------+---------+-----------------------+

Dog queries quality is ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50


Dog queries poor_ query_percentage is (1 / 3) * 100 = 33.33

Cat queries quality equals ((2 / 5) + (3 / 3) + (4 / 7)) / 3 = 0.66


Cat queries poor_ query_percentage is (1 / 3) * 100 = 33.33
******************************

321. Queries Quality and Percentage(Shell)


******************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT query_name,
5 ROUND(AVG(rating * 100 / POSITION)) / 100 AS quality,
6 ROUND(SUM(rating < 3) * 100 / COUNT(*), 2) AS poor_query_percentage
7 FROM Queries
8 GROUP BY query_name
9 ORDER BY NULL;
***********************************

322. Intersection of Three Sorted Arrays


***********************************

Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that
appeared in all three arrays.

Example 1:

Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]


Output: [1,5]
Explanation: Only 1 and 5 appeared in the three arrays.

Example 2:

Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]


Output: []

Constraints:

1 <= arr1.length, arr2.length, arr3.length <= 1000


1 <= arr1[i], arr2[i], arr3[i] <= 2000
***********************************

322. Intersection of Three Sorted Arrays(C++)


***********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) {
7 vector result;
8 int i = 0, j = 0, k = 0;
9 while (i != arr1.size() && j != arr2.size() && k != arr3.size()) {
10 if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
11 result.emplace_back(arr1[i]);
12 ++i, ++j, ++k;
13 } else {
14 int curr = max(max(arr1[i], arr2[j]), arr3[k]);
15 for (; i != arr1.size() && arr1[i] < curr; ++i);
16 for (; j != arr2.size() && arr2[j] < curr; ++j);
17 for (; k != arr3.size() && arr3[k] < curr; ++k);
18 }
19 }
20 return result;
21 }
22 };
***********************************

322. Intersection of Three Sorted Arrays(Python)


***********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def arraysIntersection(self, arr1, arr2, arr3):
6 """
7 :type arr1: List[int]
8 :type arr2: List[int]
9 :type arr3: List[int]
10 :rtype: List[int]
11 """
12 result = []
13 i, j, k = 0, 0, 0
14 while i != len(arr1) and j != len(arr2) and k != len(arr3):
15 if arr1[i] == arr2[j] == arr3[k]:
16 result.append(arr1[i])
17 i += 1
18 j += 1
19 k += 1
20 else:
21 curr = max(arr1[i], arr2[j], arr3[k])
22 while i != len(arr1) and arr1[i] < curr:
23 i += 1
24 while j != len(arr2) and arr2[j] < curr:
25 j += 1
26 while k != len(arr3) and arr3[k] < curr:
27 k += 1
28 return result
29
30
31 # Time: O(n)
32 # Space: O(n)
33 class Solution2(object):
34 def arraysIntersection(self, arr1, arr2, arr3):
35 """
36 :type arr1: List[int]
37 :type arr2: List[int]
38 :type arr3: List[int]
39 :rtype: List[int]
40 """
41 intersect = reduce(set.intersection, map(set, [arr2, arr3]))
42 return [x for x in arr1 if x in intersect]
**********************************

323. Split a String in Balanced Strings


**********************************

Balanced strings are those that have an equal quantity of'L' and 'R' characters.

Given a balanced string s , split it in the maximum amount of balanced strings.

Return the maximum amount of split balanced strings.

Example 1:

Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:

Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

Example 4:

Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

Constraints:

1 <= s.length <= 1000


s[i] is either 'L' or 'R'.
s is a balanced string.
**********************************

323. Split a String in Balanced Strings(C++)


**********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int balancedStringSplit(string s) {
7 int result = 0, count = 0;
8 for (const auto& c : s) {
9 count += (c == 'L') ? 1 : -1;
10 if (count == 0) {
11 ++result;
12 }
13 }
14 return result;
15 }
16 };
**********************************

323. Split a String in Balanced Strings(Python)


**********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def balancedStringSplit(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result, count = 0, 0
11 for c in s:
12 count += 1 if c == 'L' else -1
13 if count == 0:
14 result += 1
15 return result
****************************************

324. Missing Number In Arithmetic Progression


****************************************

In some array arr, the values were in arithmetic progression: the valuesarr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1 .

A value from arr was removed that was not the first or last value in the array.

Given arr, return the removed value.

Example 1:

Input: arr = [5,7,11,13]


Output: 9
Explanation: The previous array was [5,7,9,11,13].

Example 2:

Input: arr = [15,13,12]


Output: 14
Explanation: The previous array was [15,14,13,12].

Constraints:

3 <= arr.length <= 1000


0 <= arr[i] <= 10 5
The given array is guaranteed to be a valid array.
****************************************

324. Missing Number In Arithmetic Progression(C++)


****************************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int missingNumber(vector& arr) {
7 const auto& d = (arr.back() - arr[0]) / static_cast(arr.size());
8 int left = 0, right = arr.size() - 1;
9 while (left <= right) {
10 const auto& mid = left + (right - left) / 2;
11 if (check(arr, d, mid)) {
12 right = mid - 1;
13 } else {
14 left = mid + 1;
15 }
16 }
17 return arr[0] + d * left;
18 }
19
20 private:
21 bool check(const vector& arr, int d, int x) {
22 return arr[x] != arr[0] + d * x;
23 }
24 };
25
26 // Time: O(logn)
27 // Space: O(1)
28 class Solution2 {
29 public:
30 int missingNumber(vector& arr) {
31 return (*min_element(arr.cbegin(), arr.cend()) +
32 *max_element(arr.cbegin(), arr.cend())) *
33 (arr.size() + 1) / 2 -
34 accumulate(arr.cbegin(), arr.cend(), 0);
35 }
36 };
****************************************

324. Missing Number In Arithmetic Progression(Python)


****************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def missingNumber(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: int
9 """
10 def check(arr, d, x):
11 return arr[x] != arr[0] + d*x
12
13 d = (arr[-1]-arr[0])//len(arr)
14 left, right = 0, len(arr)-1
15 while left <= right:
16 mid = left + (right-left)//2
17 if check(arr, d, mid):
18 right = mid-1
19 else:
20 left = mid+1
21 return arr[0] + d*left
22
23
24 # Time: O(n)
25 # Space: O(1)
26 class Solution2(object):
27 def missingNumber(self, arr):
28 """
29 :type arr: List[int]
30 :rtype: int
31 """
32 return (min(arr)+max(arr))*(len(arr)+1)//2 - sum(arr)
******************************

325. Check If It Is a Straight Line


******************************

You are given an array coordinates, coordinates[i] = [x, y] , where [x, y] represents the coordinate of a point. Check if these
points make a straight line in the XY plane.

Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]


Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]


Output: false
Constraints:

2 <= coordinates.length <= 1000


coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.
******************************

325. Check If It Is a Straight Line(C++)


******************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool checkStraightLine(vector>& coordinates) {
7 const auto& i = coordinates[0], &j = coordinates[1];
8 return all_of(coordinates.cbegin() + 2,
9 coordinates.cend(),
10 [&](const auto& k) {
11 return i[0] * j[1] - j[0] * i[1] +
12 j[0] * k[1] - k[0] * j[1] +
13 k[0] * i[1] - i[0] * k[1] == 0;
14 }
15 );
16 }
17 };
******************************

325. Check If It Is a Straight Line(Python)


******************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def checkStraightLine(self, coordinates):
6 """
7 :type coordinates: List[List[int]]
8 :rtype: bool
9 """
10 i, j = coordinates[:2]
11 return all(i[0] * j[1] - j[0] * i[1] +
12 j[0] * k[1] - k[0] * j[1] +
13 k[0] * i[1] - i[0] * k[1] == 0
14 for k in coordinates)
***************************************************

326. Find Positive Integer Solution for a Given Equation


***************************************************

Given a callable function f(x, y) with a hidden formula and a value z , reverse engineer the formula and return all positive
integer pairs x and y where f(x,y) == z . You may return the pairs in any order.

While the exact formula is hidden, the function is monotonically increasing, i.e.:

f(x, y) < f(x + 1, y)


f(x, y) < f(x, y + 1)

The function interface is defined like this:

interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};

We will judge your solution as follows:

The judge has a list of 9 hidden implementations of CustomFunction , along with a way to generate ananswer key of all
valid pairs for a specific z .
The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the
target z .
The judge will call your findSolution and compare your results with the answer key.
If your results match the answer key, your solution will be Accepted.

Example 1:

Input: function_id = 1, z = 5
Output: [[1,4],[2,3],[3,2],[4,1]]
Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.

Example 2:

Input: function_id = 2, z = 5
Output: [[1,5],[5,1]]
Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 * 5 = 5.
x=5, y=1 -> f(5, 1) = 5 * 1 = 5.

Constraints:

1 <= function_id <= 9


1 <= z <= 100
It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000 .
It is also guaranteed that f(x, y) will fit in 32 bit signed integer if1 <= x, y <= 1000 .
***************************************************

326. Find Positive Integer Solution for a Given


Equation(C++)
***************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 /*
5 * // This is the custom function interface.
6 * // You should not implement it, or speculate about its implementation
7 * class CustomFunction {
8 * public:
9 * // Returns f(x, y) for any given positive integers x and y.
10 * // Note that f(x, y) is increasing with respect to both x and y.
11 * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
12 * int f(int x, int y);
13 * };
14 */
15
16 class Solution {
17 public:
18 vector> findSolution(CustomFunction& customfunction, int z) {
19 vector> result;
20 int x = 1, y = 1;
21 while (customfunction.f(x, y) < z) {
22 ++y;
23 }
24 while (y > 0) {
25 while (y > 0 && customfunction.f(x, y) > z) {
26 --y;
27 }
28 if (y > 0 && customfunction.f(x, y) == z) {
29 result.push_back({x, y});
30 }
31 ++x;
32 }
33 return result;
34 }
35 };
***************************************************

326. Find Positive Integer Solution for a Given


Equation(Python)
***************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 """
5 This is the custom function interface.
6 You should not implement it, or speculate about its implementation
7 class CustomFunction:
8 # Returns f(x, y) for any given positive integers x and y.
9 # Note that f(x, y) is increasing with respect to both x and y.
10 # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
11 def f(self, x, y):
12
13 """
14 class Solution(object):
15 def findSolution(self, customfunction, z):
16 """
17 :type num: int
18 :type z: int
19 :rtype: List[List[int]]
20 """
21 result = []
22 x, y = 1, 1
23 while customfunction.f(x, y) < z:
24 y += 1
25 while y > 0:
26 while y > 0 and customfunction.f(x, y) > z:
27 y -= 1
28 if y > 0 and customfunction.f(x, y) == z:
29 result.append([x, y])
30 x += 1
31 return result
***************************

327. Number of Comments per Post


***************************

Table: Submissions

+---------------+----------+
| Column Name | Type |
+---------------+----------+
| sub_id | int |
| parent_id | int |
+---------------+----------+
There is no primary key for this table, it may have duplicate rows.
Each row can be a post or comment on the post.
parent_id is null for posts.
parent_id for comments is sub_id for another post in the table.

Write an SQL query to find number of comments per each post.

Result table should contain post_id and its corresponding number_of_comments, and must be sorted by post_id in ascending order.

Submissions may contain duplicate comments. You should count the number ofunique comments per post.

Submissions may contain duplicate posts. You should treat them as one post.

The query result format is in the following example:

Submissions table:
+---------+------------+
| sub_id | parent_id |
+---------+------------+
| 1 | Null |
| 2 | Null |
| 1 | Null |
| 12 | Null |
| 3 | 1 |
| 5 | 2 |
| 3 | 1 |
| 4 | 1 |
| 9 | 1 |
| 10 | 2 |
| 6 | 7 |
+---------+------------+

Result table:
+---------+--------------------+
| post_id | number_of_comments |
+---------+--------------------+
| 1 | 3 |
| 2 | 2 |
| 12 | 0 |
+---------+--------------------+

The post with id 1 has three comments in the table with id 3, 4 and 9. The comment with id 3 is repeated in the table, we counted it only onc
The post with id 2 has two comments in the table with id 5 and 10.
The post with id 12 has no comments in the table.
The comment with id 6 is a comment on a deleted post with id 7 so we ignored it.
***************************

327. Number of Comments per Post(Shell)


***************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT a.sub_id AS post_id,
5 Count(DISTINCT b.sub_id) AS number_of_comments
6 FROM submissions a
7 LEFT JOIN submissions b
8 ON a.sub_id = b.parent_id
9 WHERE a.parent_id IS NULL
10 GROUP BY a.sub_id
11 ORDER BY NULL
********************

328. Array Transformation


********************

Given an initial array arr, every day you produce a new array using the array of the previous day.

On the i-th day, you do the following operations on the array of dayi-1 to produce the array of day i:

1. If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
2. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented.
3. The first and last elements never change.

After some days, the array does not change. Return that final array.

Example 1:

Input: arr = [6,2,3,4]


Output: [6,3,3,4]
Explanation:
On the first day, the array is changed from [6,2,3,4] to [6,3,3,4].
No more operations can be done to this array.

Example 2:

Input: arr = [1,6,3,4,3,5]


Output: [1,4,4,4,4,5]
Explanation:
On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5].
On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5].
No more operations can be done to this array.

Constraints:

3 <= arr.length <= 100


1 <= arr[i] <= 100
********************

328. Array Transformation(C++)


********************

1 // Time: O(n^2)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector transformArray(vector& arr) {
7 while (is_changable(arr)) {
8 auto new_arr = arr;
9 for (int i = 1; i + 1 < arr.size(); ++i) {
10 new_arr[i] += int(arr[i - 1] > arr[i] && arr[i] < arr[i + 1]);
11 new_arr[i] -= int(arr[i - 1] < arr[i] && arr[i] > arr[i + 1]);
12 }
13 arr = move(new_arr);
14 }
15 return arr;
16 }
17
18 private:
19 bool is_changable(const vector& arr) {
20 for (int i = 1; i + 1 < arr.size(); ++i) {
21 if ((arr[i - 1] > arr[i] && arr[i] < arr[i + 1]) ||
22 (arr[i - 1] < arr[i] && arr[i] > arr[i + 1])) {
23 return true;
24 }
25 }
26 return false;
27 }
28 };
********************

328. Array Transformation(Python)


********************

1 # Time: O(n^2)
2 # Space: O(n)
3
4 class Solution(object):
5 def transformArray(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: List[int]
9 """
10 def is_changable(arr):
11 return any(arr[i-1] > arr[i] < arr[i+1] or
12 arr[i-1] < arr[i] > arr[i+1]
13 for i in xrange(1, len(arr)-1))
14
15 while is_changable(arr):
16 new_arr = arr[:]
17 for i in xrange(1, len(arr)-1):
18 new_arr[i] += arr[i-1] > arr[i] < arr[i+1]
19 new_arr[i] -= arr[i-1] < arr[i] > arr[i+1]
20 arr = new_arr
21 return arr
***********************************

329. Minimum Swaps to Make Strings Equal


***********************************

You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two
strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and
s2[j].

Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

Example 1:

Input: s1 = "xx", s2 = "yy"


Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".

Example 2:

Input: s1 = "xy", s2 = "yx"


Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.

Example 3:

Input: s1 = "xx", s2 = "xy"


Output: -1

Example 4:

Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"


Output: 4

Constraints:

1 <= s1.length, s2.length <= 1000


s1, s2 only contain 'x' or 'y'.
***********************************

329. Minimum Swaps to Make Strings Equal(C++)


***********************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minimumSwap(string s1, string s2) {
7 int x1 = 0, y1 = 0;
8 for (int i = 0; i < s1.length(); ++i) {
9 if (s1[i] == s2[i]) {
10 continue;
11 }
12 x1 += int(s1[i] == 'x');
13 y1 += int(s1[i] == 'y');
14 }
15 if (x1 % 2 != y1 % 2) { // impossible
16 return -1;
17 }
18 // case1: per xx or yy needs one swap, (x1 / 2 + y1 / 2)
19 // case2: per xy or yx needs two swaps, (x1 % 2 + y1 % 2)
20 return x1 / 2 + y1 / 2 + x1 % 2 + y1 % 2;
21 }
22 };
***********************************

329. Minimum Swaps to Make Strings Equal(Python)


***********************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minimumSwap(self, s1, s2):
6 """
7 :type s1: str
8 :type s2: str
9 :rtype: int
10 """
11 x1, y1 = 0, 0
12 for i in xrange(len(s1)):
13 if s1[i] == s2[i]:
14 continue
15 x1 += int(s1[i] == 'x')
16 y1 += int(s1[i] == 'y')
17 if x1%2 != y1%2: # impossible
18 return -1
19 # case1: per xx or yy needs one swap, (x1//2 + y1//2)
20 # case2: per xy or yx needs two swaps, (x1%2 + y1%2)
21 return (x1//2 + y1//2) + (x1%2 + y1%2)
*********************

330. Average Selling Price


*********************

Table: Prices

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| start_date | date |
| end_date | date |
| price | int |
+---------------+---------+
(product_id, start_date, end_date) is the primary key for this table.
Each row of this table indicates the price of the product_id in the period from start_date to end_date.
For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.

Table: UnitsSold

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| purchase_date | date |
| units | int |
+---------------+---------+
There is no primary key for this table, it may contain duplicates.
Each row of this table indicates the date, units and product_id of each product sold.

Write an SQL query to find the average selling price for each product.

average_price should be rounded to 2 decimal places.

The query result format is in the following example:


Prices table:
+------------+------------+------------+--------+
| product_id | start_date | end_date | price |
+------------+------------+------------+--------+
| 1 | 2019-02-17 | 2019-02-28 | 5 |
| 1 | 2019-03-01 | 2019-03-22 | 20 |
| 2 | 2019-02-01 | 2019-02-20 | 15 |
| 2 | 2019-02-21 | 2019-03-31 | 30 |
+------------+------------+------------+--------+

UnitsSold table:
+------------+---------------+-------+
| product_id | purchase_date | units |
+------------+---------------+-------+
| 1 | 2019-02-25 | 100 |
| 1 | 2019-03-01 | 15 |
| 2 | 2019-02-10 | 200 |
| 2 | 2019-03-22 | 30 |
+------------+---------------+-------+

Result table:
+------------+---------------+
| product_id | average_price |
+------------+---------------+
| 1 | 6.96 |
| 2 | 16.96 |
+------------+---------------+
Average selling price = Total Price of Product / Number of products sold.
Average selling price for product 1 = ((100 * 5) + (15 * 20)) / 115 = 6.96
Average selling price for product 2 = ((200 * 15) + (30 * 30)) / 230 = 16.96
*********************

330. Average Selling Price(Shell)


*********************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT b.product_id,
5 ROUND(SUM(a.units * b.price) / SUM(a.units), 2) AS average_price
6 FROM UnitsSold AS a
7 INNER JOIN Prices AS b
8 ON a.product_id = b.product_id
9 WHERE a.purchase_date BETWEEN b.start_date AND b.end_date
10 GROUP BY product_id;
*********************************

331. Cells with Odd Values in a Matrix


*********************************

There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [r i, c i] represents a 0-
indexed location to perform some increment operations on the matrix.

For each location indices[i] , do both of the following:

1. Increment all the cells on row ri.


2. Increment all the cells on column c i.

Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in
indices.

Example 1:

Input: m = 2, n = 3, indices = [[0,1],[1,1]]


Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.

Example 2:

Input: m = 2, n = 2, indices = [[1,1],[0,0]]


Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.

Constraints:

1 <= m, n <= 50
1 <= indices.length <= 100
0 <= ri < m
0 <= c i < n

Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?
*********************************

331. Cells with Odd Values in a Matrix(C++)


*********************************

1 // Time: O(n + m)
2 // Space: O(n + m)
3
4 class Solution {
5 public:
6 int oddCells(int n, int m, vector>& indices) {
7 vector row(n), col(m);
8 for (const auto& idx : indices) {
9 row[idx[0]] ^= 1;
10 col[idx[1]] ^= 1;
11 }
12 int row_sum = accumulate(row.cbegin(), row.cend(), 0);
13 int col_sum = accumulate(col.cbegin(), col.cend(), 0);
14 return row_sum * m + col_sum * n - 2 * row_sum * col_sum;
15 }
16 };
*********************************

331. Cells with Odd Values in a Matrix(Python)


*********************************

1 # Time: O(n + m)
2 # Space: O(n + m)
3
4 class Solution(object):
5 def oddCells(self, n, m, indices):
6 """
7 :type n: int
8 :type m: int
9 :type indices: List[List[int]]
10 :rtype: int
11 """
12 row, col = [0]*n, [0]*m
13 for r, c in indices:
14 row[r] ^= 1
15 col[c] ^= 1
16 row_sum, col_sum = sum(row), sum(col)
17 return row_sum*m+col_sum*n-2*row_sum*col_sum
18
19
20 # Time: O(n + m)
21 # Space: O(n + m)
22 import collections
23 import itertools
24
25
26 class Solution2(object):
27 def oddCells(self, n, m, indices):
28 """
29 :type n: int
30 :type m: int
31 :type indices: List[List[int]]
32 :rtype: int
33 """
34 fn = lambda x: sum(count&1 for count in collections.Counter(x).itervalues())
35 row_sum, col_sum = map(fn, itertools.izip(*indices))
36 return row_sum*m+col_sum*n-2*row_sum*col_sum

You might also like