Leetcode Easy1
Leetcode Easy1
Leetcode Easy1
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.
Example 1:
Example 2:
Example 3:
Constraints:
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
Write the code that will take a string and make this conversion given a number of rows:
Example 1:
Example 2:
Example 3:
Constraints:
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:
3. Reverse Integer(C++)
***************
3. Reverse Integer(Python)
***************
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'satoi function).
Note:
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:
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:
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:
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 };
************************
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
*****************
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:
Follow up: Could you solve it without converting the integer to a string?
*****************
5. Palindrome Number(C++)
*****************
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
****************
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:
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:
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
*********************
Write a function to find the longest common prefix string amongst an array of strings.
Example 1:
Example 2:
Constraints:
8. Valid Parentheses
*****************
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
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:
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
**********************
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:
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Constraints:
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 };
**********************
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
*******************
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:
Example 2:
Input: head = []
Output: []
Example 3:
Constraints:
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 };
*******************
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
***********************************
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:
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
Example 1:
Example 2:
Constraints:
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 };
***********************************
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
**************
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:
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];
}
Example 1:
Example 2:
Constraints:
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 };
**************
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
******************
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:
Example 2:
Example 3:
Constraints:
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
************
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validatedaccording to the following rules:
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 '.'.
************
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 };
************
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
*************
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.
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
*************
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and
return its sum.
Example 1:
Example 2:
Example 3:
Constraints:
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.
****************
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 };
****************
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
*******************
Given a string s consists of some words separated by some number of spaces, returnthe length of the last word in the
string.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
*******************
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
********
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:
Example 2:
Example 3:
Constraints:
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 };
********
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
**********
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Example 2:
Constraints:
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 };
**********
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]
***************
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
***************
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 };
***************
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
**********************************
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:
Example 2:
Constraints:
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 };
**********************************
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
******************
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:
Example 2:
Example 3:
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?
******************
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 };
******************
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
*********
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:
Example 2:
Example 3:
Constraints:
The number of nodes in both trees is in the range[0, 100].
-104 <= Node.val <= 10 4
*********
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 };
*********
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
**************
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Example 2:
Constraints:
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
*********************************
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:
Example 2:
Example 3:
Input: root = []
Output: []
Constraints:
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 };
*********************************
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
****************************
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:
Example 2:
Example 3:
Input: root = []
Output: 0
Example 4:
Constraints:
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 };
****************************
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
************************************
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:
Example 2:
Example 3:
Input: root = []
Output: []
Constraints:
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 };
************************************
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
********************
a binary tree in which the left and right subtrees ofevery node differ in height by no more than 1.
Example 1:
Example 2:
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
********************
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
****************************
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Example 1:
Example 2:
Constraints:
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
********
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.
Example 1:
Example 2:
Example 3:
Constraints:
The number of nodes in the tree is in the range[0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
********
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
*****************
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 // 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 };
*****************
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
********************
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:
Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?
********************
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 };
********************
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
*******************************
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:
Example 2:
Constraints:
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 };
*******************************
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
**********************************
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:
Example 2:
Example 3:
Constraints:
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 };
**********************************
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
****************
Given a string s , determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example 1:
Example 2:
Constraints:
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 };
****************
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
*************
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:
Example 2:
Example 3:
Constraints:
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 };
*************
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
*****************
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:
Example 2:
Example 3:
Constraints:
Follow up: Can you solve it using O(1) (i.e. constant) memory?
*****************
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 };
*****************
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
*********
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
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:
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 };
*********
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]
*****************************
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.
Note that read4() has its own file pointer, much likeFILE *fp in C.
Definition of read4:
buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].
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.
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
*****************************
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
********************************
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:
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:
Constraints:
Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?
********************************
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 };
********************************
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
***********************
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 .
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
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.
***********************
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 };
***********************
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
************************
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:
Example 4:
Constraints:
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 };
************************
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
****************
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:
Example 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?
****************
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 };
****************
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]
***********************************
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.
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:
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);
***********************************
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
*************************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
*************************
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
*************************
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
*************************
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:
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 |
+---------------------+
*********************
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
******************************************
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 |
+----------+
******************************************
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
****************
+----+---------+
| 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] |
+---------+
1 # Time: O(n^2)
2 # Space: O(n)
3
4 SELECT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1
5
*************************
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 |
+----+------------+
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
*************************
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
************
Given an array, rotate the array to the right byk steps, where k is non-negative.
Example 1:
Example 2:
Constraints:
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?
************
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 };
************
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
************
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:
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 };
************
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
****************
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:
Follow up: If this function is called many times, how would you optimize it?
****************
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
*******************
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:
987-123-4567
123 456 7890
(123) 456-7890
987-123-4567
(123) 456-7890
*******************
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
**********
Given a text file file.txt, print just the 10th line of the file.
Example:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
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.
**********
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
***********************
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.
***********************
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
******************
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).
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).
******************
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
************
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:
Example 2:
Constraints:
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 };
************
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
************
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.
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
************
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:
Example 2:
Example 3:
Constraints:
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 };
***************************
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
************
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
************
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:
Example 2:
Example 3:
Constraints:
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 };
******************
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
*******************
Given the head of a singly linked list, reverse the list, and returnthe reversed list.
Example 1:
Example 2:
Example 3:
Input: head = []
Output: []
Constraints:
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
*******************
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 };
*******************
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
******************
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:
Example 2:
Example 3:
Constraints:
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 };
******************
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
*********************
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:
Example 2:
Example 3:
Constraints:
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 };
*********************
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
**************
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
**************
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 };
**************
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
****************************
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).
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?
****************************
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
Example 2:
Example 3:
Input: root = []
Output: []
Constraints:
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 };
******************
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
************
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:
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 };
************
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
****************************
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).
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.
****************************
Example 1:
Example 2:
Constraints:
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 };
**********************
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
**********************************************
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:
Example 2:
Example 3:
Constraints:
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 };
**********************************************
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
****************************
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:
Example 2:
Example 4:
Example 5:
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
****************************
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 };
****************************
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
*************
Given two strings s and t, return true if t is an anagram of s , and false otherwise.
Example 1:
Example 2:
Constraints:
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
*************
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 };
*************
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
**********************
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 // 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 };
**********************
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
**********************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
**********************
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
*********************
We can shift a string by shifting each of its letters to its successive letter.
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:
Example 2:
Constraints:
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 };
*********************
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
*************
Given an array of meeting time intervals where intervals[i] = [start i, end i], determine if a person could attend all meetings.
Example 1:
Example 2:
Constraints:
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 };
*************
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
*****************
Given the root of a binary tree, return all root-to-leaf paths in any order.
Example 1:
Example 2:
Constraints:
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 };
*****************
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
**********
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:
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 };
**********
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
***********
An ugly number is a positive integer whose prime factors are limited to2, 3, and 5.
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:
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 // 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 };
**********************
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
********************************
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:
Example 2:
Constraints:
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 };
********************************
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
***********
You are painting a fence of n posts with k different colors. You must paint the posts following these rules:
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 .
***********
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 };
***********
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
*****************
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 // 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 };
*****************
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
***********
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:
Example 2:
Constraints:
Follow up: Could you minimize the total number of operations done?
***********
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 };
***********
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
************************
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.
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:
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
************
You are playing the following Nim Game with your friend:
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
********
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 };
********
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
*********
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:
Example 2:
Constraints:
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
**************
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
***************************
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.
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:
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:
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 };
**************
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
**********************
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.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
**********************
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
*************
Example 1:
Input: n = 16
Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Constraints:
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 };
*************
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
**************
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:
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.
**************
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 };
**************
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
**************************
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 // 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 };
**************************
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
*******************************
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
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 // 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
*******************************
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
**************************
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:
Example 2:
Constraints:
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 };
**************************
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
*****************************
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:
Example 2:
Constraints:
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?
*****************************
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.
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:
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:
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 };
*******************
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).
Example 1:
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
****************************
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 };
****************************
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
***********
Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
***********
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
**********************************
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 // 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 };
**********************************
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
*******************
String t is generated by random shuffling string s and then add one more letter at a random position.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
*******************
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
***************
Assume arrk to be an array obtained by rotatingnums by k positions clock-wise. We define the rotation function F on nums as
follow:
The test cases are generated so that the answer fits in a32-bit integer.
Example 1:
Example 2:
Constraints:
n == nums.length
1 <= n <= 10 5
-100 <= nums[i] <= 100
***************
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 };
***************
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
*********
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
*********
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 };
*********
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
************
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.
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 minute must be consist of two digits and may contain a leading zero.
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
************
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 };
************
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
******************
Given the root of a binary tree, return the sum of all left leaves.
Example 1:
Example 2:
Constraints:
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 };
******************
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
*******************************
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:
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 };
*******************************
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
***********************
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):
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:
Example 2:
Constraints:
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 };
***********************
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
******************
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 // 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 };
******************
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
*********
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
*********
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 };
*********
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
********************
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:
Example 2:
Example 3:
Constraints:
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 };
********************
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
***********
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:
Example 2:
Example 3:
Constraints:
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 };
***********
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
*****************
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:
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:
Constraints:
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 };
*****************
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
******************************
You are given a string s , return the number of segments in the string.
Example 1:
Example 2:
Input: s = "Hello"
Output: 1
Example 3:
Example 4:
Input: s = ""
Output: 0
Constraints:
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 };
******************************
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
************
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:
Example 2:
Constraints:
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 };
************
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
*****************************
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:
Example 2:
Constraints:
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 };
*****************************
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
***************
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
***************
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 };
***************
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
******************
Begin with an empty string s . For each group of consecutive repeating characters in chars:
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
******************
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
********************
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).
Example 1:
Example 2:
Example 3:
Constraints:
n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= x i, y i <= 104
All the points are unique.
********************
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 };
********************
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
****************************************
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:
Example 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.
****************************************
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 };
****************************************
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
*************************************
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
Example 1:
Example 2:
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.
*************************************
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 };
*************************************
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
**************
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:
Example 2:
Constraints:
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 };
**************
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
*********
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.
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:
Example 2:
Example 3:
Constraints:
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 };
*********
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
**************************
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 // 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 };
**************************
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
****************
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
****************
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 };
****************
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:
Example 2:
Example 3:
Constraints:
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
**********************
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.
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 // 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 };
**********************
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))
****************
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.
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
****************
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 };
****************
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
********************
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.
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 |
+-----------+-------------+
********************
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
*********************
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.
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 |
+-----------+-----------+
*********************
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)
**************
We define the usage of capitals in a word to be right when one of the following cases holds:
Example 1:
Example 2:
Constraints:
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 };
**************
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
******************************
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:
Example 2:
Example 3:
Constraints:
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:
Example 2:
Constraints:
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 };
**********************************
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
************************
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:
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
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 };
************************
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
***************************
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.
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.
Example 1:
Example 2:
Example 3:
Example 4:
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 };
***************************
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
*****************
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 // 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 };
*****************
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
***********************
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:
Example 2:
Constraints:
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 };
***********************
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]
***************************
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 // 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 };
***************************
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
*****************************
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:
Example 2:
Constraints:
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 };
*****************************
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
*****************
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:
Example 2:
Constraints:
1 <= n <= 10 4
nums.length == 2 * n
-104 <= nums[i] <= 10 4
*****************
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:
Example 2:
Example 3:
Input: root = [21,7,14,1,1,2,2,3,3]
Output: 9
Constraints:
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 };
****************
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
******************
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:
Example 2:
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
******************
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 };
******************
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
***********************
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:
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
***********************
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:
Example 2:
Example 3:
Constraints:
n == candyType.length
2 <= n <= 10 4
n is even.
-105 <= candyType[i] <= 10 5
******************
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 };
******************
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
*************************************
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.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
*************************************
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
******************************
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:
Example 2:
Example 3:
Constraints:
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 };
******************************
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
*****************
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:
Example 2:
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
*****************
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:
Example 3:
Example 4:
Example 5:
Constraints:
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.
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 // 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 */
*********************************
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
*****************
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:
Example 2:
Constraints:
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
*****************
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
*********************************
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:
Example 2:
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 };
*********************************
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
**********************
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.
Note: The merging process must start from the root nodes of both trees.
Example 1:
Example 2:
Constraints:
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 };
**********************
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
**************************
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| .
Example 1:
Example 2:
Example 3:
Example 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.
**************************
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
**************************
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
********************************
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Example 2:
Example 3:
Constraints:
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
********************************
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
*********************
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
*********************
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:
Example 2:
Constraints:
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
********************************
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
**************************
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:
Example 2:
Constraints:
n == nums.length
1 <= k <= n <= 10 5
-104 <= nums[i] <= 10 4
**************************
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
**************************
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
************
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:
Example 2:
Constraints:
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 };
************
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
***************************
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:
Example 2:
Example 3:
Input: root = [2,1,3], k = 4
Output: true
Example 4:
Example 5:
Constraints:
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
**********************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
**********************
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
**************
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:
Constraints:
m == img.length
n == img[i].length
1 <= m, n <= 200
0 <= img[i][j] <= 255
**************
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 };
**************
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
********************
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:
Example 2:
Constraints:
n == nums.length
1 <= n <= 10 4
-105 <= nums[i] <= 10 5
********************
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 };
********************
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
*************************
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:
Example 2:
Example 3:
Example 4:
Example 5:
Input: root = [1,null,2], low = 2, high = 4
Output: [2]
Constraints:
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 };
*************************
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
************************************
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.
Example 1:
Example 2:
Constraints:
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 };
************************************
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
*****************************************
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:
Example 2:
Constraints:
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 };
*****************************************
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
*******************
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 // 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 };
*******************
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
*************
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:
Example 1:
Example 2:
Example 3:
Constraints:
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 };
*************
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
*********************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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
*********************
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:
Example 2:
Constraints:
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 };
*********************
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
*******************
You have a data structure of employee information, which includes the employee's unique id, their importance value, and
their direct subordinates' id.
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:
Example 2:
Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5
Output: -3
Constraints:
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 };
*******************
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
***********************************
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
***********************************
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 };
***********************************
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
******************
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.
Example 1:
Example 2:
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is either 0 or 1.
******************
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 };
******************
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
***********************
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 // 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 };
***********************
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
******************
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:
Example 2:
Constraints:
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 };
******************
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
*******************************
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.
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.
*******************************
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
*******************************
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
*********
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
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:
Follow up: Could you come up with a solution that supportsO(1) for each top call and O(logn) for each other call?
*********
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
Example 1:
Example 2:
Constraints:
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 };
**************************
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
**************************
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:
Example 2:
Constraints:
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:
Example 2:
Example 3:
Constraints:
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 };
****************
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
******************
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.
Example 1:
Example 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
******************
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 };
******************
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
*******************
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.
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:
Example 2:
Example 3:
Constraints:
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 };
*******************
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
****************************************
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.
For example, if target == 'z' and letters == ['a', 'b'] , the answer is 'a'.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
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 };
****************************************
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
************************
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.
Example 1:
Example 2:
Constraints:
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 };
************************
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
***************************************
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:
Example 2:
Example 3:
Constraints:
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 };
***************************************
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
************************
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:
Example 2:
Example 3:
Example 4:
Example 5:
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.
************************
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 };
************************
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
********************
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:
Example 2:
Constraints:
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:
Example 2:
Constraints:
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 };
*********************
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
*************************************************
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.
Example 1:
Example 2:
Constraints:
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:
Example 2:
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?
***************
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 };
***************
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
*****************
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:
Example 2:
Constraints:
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 };
*****************
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
**********************************
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:
Example 2:
Constraints:
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 };
**********************************
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
***********************
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:
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:
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
**************
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 };
**************
Given two strings s and goal , return true if and only if s can become goal after some number of shifts on s .
Example 1:
Example 2:
Constraints:
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 };
*************
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
*****************
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:
Example 2:
Constraints:
color.length == 7
color[0] == '#'
color[i] is either digit or character in the range['a', 'f'] for i > 0 .
*****************
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 };
*****************
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
***********************
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as
follows:
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.
Example 1:
Example 2:
Constraints:
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 .
Example 1:
Example 2:
Constraints:
widths.length == 26
2 <= widths[i] <= 10
1 <= s.length <= 1000
s contains only lowercase English letters.
*******************************
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 };
*******************************
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
*********************
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:
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 // 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 };
*********************
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
*********************
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:
Example 2:
Constraints:
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 };
*********************
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
****************
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:
Constraints:
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:
Example 2:
Constraints:
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 };
********************************
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
**********
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:
Example 2:
Input: sentence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Constraints:
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].
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 // 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 };
*************************
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
*****************
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.
Example 1:
Example 2:
Constraints:
n == image.length
n == image[i].length
1 <= n <= 20
images[i][j] is either 0 or 1.
*****************
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 };
*****************
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
*****************
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:
Example 2:
Example 3:
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.
*****************
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 };
*****************
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
*********************
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:
In total, there is only one magic square inside the given grid.
Example 2:
Example 3:
Example 4:
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
*********************
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 };
*********************
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
************************
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:
Example 2:
Example 3:
Example 4:
Constraints:
Follow up: Can you solve it in O(n) time and O(1) space?
************************
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 };
************************
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
***********************************
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.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
***********************************
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
******************************
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:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
Follow up: Finding the O(n) is straightforward, could you find an O(log(n)) solution?
******************************
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 };
******************************
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
*************
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].
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
*************
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
***************
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.
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
***************
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
****************
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
****************
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 };
****************
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
**********
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
**********
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:
Example 2:
Example 3:
Input: root1 = [1], root2 = [2]
Output: false
Example 4:
Example 5:
Constraints:
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 };
******************
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
************************
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 :
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:
Example 1:
Example 2:
Constraints:
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 };
************************
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
*************************
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:
Example 2:
Constraints:
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 };
*************************
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
****************************
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.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
****************************
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 };
****************************
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
*********************************
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:
Example 2:
Constraints:
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 };
*********************************
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
***************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
***************
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
*************************
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.
Note: The bottom face of each shape counts toward its surface area.
Example 1:
Example 2:
Example 3:
Example 4:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 32
Example 5:
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
*************************
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 };
*************************
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
************************************
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:
Example 1:
Example 2:
Constraints:
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 };
************************************
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
***************
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:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
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 };
***************
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
****************************
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:
Example 2:
Constraints:
The number of nodes in the given tree will be in the range[1, 100].
0 <= Node.val <= 1000
****************************
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 };
****************************
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
********************
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Example 1:
Example 2:
Constraints:
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 };
********************
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
****************
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:
Example 2:
Example 3:
Constraints:
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 };
****************
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
******************************
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:
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.
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 // 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 };
********************
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
***********************
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.
Example 1:
Example 2:
Constraints:
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 };
***********************
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
*****************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
*****************
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)
**********************
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.
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:
Example 2:
Constraints:
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 };
**********************
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
**********************
You have a RecentCounter class which counts the number of recent requests within a certain time frame.
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 .
**********************
You are given an array of logs. Each log is a space-delimited string of words, where the first word is theidentifier.
Letter-logs: All words (except the identifier) consist of lowercase English letters.
Digit-logs: All words (except the identifier) consist of digits.
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 // 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 };
*****************
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
********************
Given an array of integers arr, return true if and only if it is a valid mountain array.
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:
Example 2:
Example 3:
Constraints:
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 };
********************
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
***************
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:
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 // 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 };
***************
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
*****************************
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:
Example 2:
Example 3:
Example 4:
Constraints:
arr.length == 4
0 <= arr[i] <= 9
*****************************
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 };
*****************************
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
*****************************
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:
Example 2:
Example 3:
Constraints:
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.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
***********************************
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]
*********************
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:
Example 2:
Constraints:
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 };
*********************
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)))
*****************
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:
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:
Example 2:
Constraints:
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
**************************
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
*************************
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:
Example 2:
Constraints:
Follow up: Squaring each element and sorting the new array is very trivial, could you find anO(n) solution using a different
approach?
*************************
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 };
*************************
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
*************************
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:
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 };
*************************
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)
*********************************
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:
Example 2:
Constraints:
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 };
*********************************
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
****************************
The array-form of an integer num is an array representing its digits in left to right order.
Given num, the array-form of an integer, and an integer k , return the array-form of the integer num + k .
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
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:
Example 2:
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Constraints:
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 };
**********************
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
***************
You are given an m x n grid where each cell can have one of three values:
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:
Example 2:
Example 3:
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j] is 0, 1, or 2.
***************
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 };
***************
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
*******************
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.
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:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
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 };
*******************
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
***************************
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.
Example 1:
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:
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'
***************************
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 };
***************************
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
**********************
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:
Example 2:
Constraints:
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 };
**********************
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())
***************************************
Given an integer array nums and an integer k , modify the array in the following way:
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:
Example 2:
Example 3:
Constraints:
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.
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
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 };
*****************************
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
***************************************************
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:
Example 2:
Example 3:
Constraints:
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 };
***************************************************
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
****************************
We define x i as the number whose binary representation is the subarraynums[0..i] (from most-significant-bit to least-
significant-bit).
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
****************************
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]
***********************************************
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:
Example 2:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j] is either 0 or 1.
***********************************************
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 };
***********************************************
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
****************************
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 // 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 };
****************************
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)
**********************************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
**********************************
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)
************
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:
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 // 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 };
************
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, {})
*******************
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:
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Example 2:
Example 3:
Constraints:
2 * n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCost i, bCost i <= 1000
*******************
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:
Example 2:
Example 3:
Constraints:
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 };
******************************
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
*******************************
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).
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 // 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 };
*******************************
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]
***************
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:
Example 2:
Constraints:
points.length == 3
points[i].length == 2
0 <= x i, y i <= 100
***************
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 };
***************
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
********************************
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.
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:
Example 2:
Example 3:
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.
********************************
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 };
********************************
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
*****************
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:
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:
Example 2:
Constraints:
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 };
*****************
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]
****************************************
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.
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 // 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 };
****************************************
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)
********************************************************
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.
********************************************************
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
**************
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).
Example 1:
Example 2:
Example 3:
Constraints:
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 };
**************
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)))
****************
A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.
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.
For example, after rotating 8000, we have 0008 which is considered as just 8.
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
****************
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 };
****************
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
***********
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:
Example 2:
Example 3:
Constraints:
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 };
***********
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
***********************
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:
Example 2:
Constraints:
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.
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.
************************
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
*************************
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.
Product table:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
+------------+--------------+
Result table:
+--------------+----------------+
| product_id | total_quantity |
+--------------+----------------+
| 100 | 22 |
| 200 | 15 |
+--------------+----------------+
*************************
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
**********************************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
**********************************
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 ""
*******************
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.
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
*******************
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
********************
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.
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.
********************
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
************************
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 // 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 };
************************
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
****************
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.
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.
****************
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
*****************
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.
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.
*****************
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");
******************
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.
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.
******************
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');
***********************************
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:
Example 2:
Constraints:
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
*********
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:
Example 2:
Constraints:
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 };
*********
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)]
***************
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:
Example 2:
Constraints:
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 };
***************
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
*******************
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:
Example 2:
Constraints:
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 };
*******************
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
****************************
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:
Example 2:
Constraints:
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 // 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 };
***********************************
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
***********************
Example 1:
Example 2:
Constraints:
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 };
***********************
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)
**************
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.
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.
**************
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
**************
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:
Example 2:
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 };
**************
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
*************************
Given a year year and a month month, return the number of days of that month.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
*************************
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
***************************
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 // 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 };
***************************
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)
***********************
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:
Example 2:
Constraints:
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 };
***********************
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]
*******************
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:
Constraints:
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 };
*******************
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))
*********************************
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:
Constraints:
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 };
*********************************
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())
*********************
Given an integer array nums, return the largest integer that only occurs once. If no integer occurs once, return -1.
Example 1:
Example 2:
Constraints:
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 };
*********************
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)
****************
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
****************
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 };
****************
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
**********************
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 .
**********************
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 };
**********************
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
************************************
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.
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.
************************************
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
*************************************
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.
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.
*************************************
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
***************
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.
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 |
+------+
***************
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
*******************************************************
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:
Example 2:
Constraints:
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 };
*******************************************************
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)
***************
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
Example 2:
Example 3:
Example 4:
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.
***************
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 };
***************
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
*******************************************
A string is good if it can be formed by characters from chars (each character can only be used once).
Example 1:
Example 2:
Constraints:
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:
Example 2:
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.
*******************
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 };
*******************
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
******************************************************
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:
Example 2:
Constraints:
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.
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.
*************************
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;
******************
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:
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.
Example 1:
Example 2:
Example 3:
Constraints:
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 };
*********************
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
*************************
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.
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).
*************************
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;
**********************************************
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 // 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 };
**********************************************
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
**************************
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:
Example 2:
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 // 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 };
**************************
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)
***************
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:
Example 2:
Example 3:
Constraints:
The given dates are valid dates between the years1971 and 2100.
***************
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 };
***************
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]
**************************
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:
Example 2:
Example 3:
Constraints:
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 };
**************************
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:
Example 2:
Constraints:
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 };
*******************************************
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
***************************
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
Example 1:
Example 2:
Example 3:
Constraints:
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 };
***************************
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
****************************
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:
Example 2:
Example 3:
Constraints:
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 };
****************************
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()))
******************************
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.
The average of the ratio between query rating and its position.
Write an SQL query to find each query_name, the quality and poor_query_percentage.
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 |
+------------+---------+-----------------------+
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;
***********************************
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:
Example 2:
Constraints:
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 };
***********************************
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]
**********************************
Balanced strings are those that have an equal quantity of'L' and 'R' characters.
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 // 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 };
**********************************
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
****************************************
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.
Example 1:
Example 2:
Constraints:
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 };
****************************************
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)
******************************
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:
Example 2:
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 };
******************************
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)
***************************************************
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.:
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);
};
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 // 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 };
***************************************************
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
***************************
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.
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.
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.
***************************
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
********************
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:
Example 2:
Constraints:
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 };
********************
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
***********************************
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:
Example 2:
Example 3:
Example 4:
Constraints:
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 };
***********************************
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)
*********************
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.
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
*********************
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;
*********************************
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.
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:
Example 2:
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?
*********************************
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 };
*********************************
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