You are on page 1of 549

Table of Contents

Table of Contents 2
332. Shift 2D Grid 10
332. Shift 2D Grid(C++) 12
332. Shift 2D Grid(Python) 13
333. Minimum Time Visiting All Points 14
333. Minimum Time Visiting All Points(C++) 16
333. Minimum Time Visiting All Points(Python) 17
334. Hexspeak 18
334. Hexspeak(C++) 19
334. Hexspeak(Python) 20
335. Find Winner on a Tic Tac Toe Game 21
335. Find Winner on a Tic Tac Toe Game(C++) 23
335. Find Winner on a Tic Tac Toe Game(Python) 24
336. Traffic Light Controlled Intersection 25
336. Traffic Light Controlled Intersection(C++) 27
336. Traffic Light Controlled Intersection(Python) 28
337. Students and Examinations 29
337. Students and Examinations(Shell) 31
338. Subtract the Product and Sum of Digits of an Integer 32
338. Subtract the Product and Sum of Digits of an Integer(C++) 33
338. Subtract the Product and Sum of Digits of an Integer(Python) 34
339. Element Appearing More Than 25% In Sorted Array 35
339. Element Appearing More Than 25% In Sorted Array(C++) 36
339. Element Appearing More Than 25% In Sorted Array(Python) 37
340. Convert Binary Number in a Linked List to Integer 38
340. Convert Binary Number in a Linked List to Integer(C++) 39
340. Convert Binary Number in a Linked List to Integer(Python) 40
341. Weather Type in Each Country 41
341. Weather Type in Each Country(Shell) 43
342. Find Numbers with Even Number of Digits 44
342. Find Numbers with Even Number of Digits(C++) 45
342. Find Numbers with Even Number of Digits(Python) 47
343. Replace Elements with Greatest Element on Right Side 48
343. Replace Elements with Greatest Element on Right Side(C++) 49
343. Replace Elements with Greatest Element on Right Side(Python) 50
344. Find the Team Size 51
344. Find the Team Size(Shell) 52
345. Find N Unique Integers Sum up to Zero 53
345. Find N Unique Integers Sum up to Zero(C++) 54
345. Find N Unique Integers Sum up to Zero(Python) 55
346. Decrypt String from Alphabet to Integer Mapping 56
346. Decrypt String from Alphabet to Integer Mapping(C++) 57
346. Decrypt String from Alphabet to Integer Mapping(Python) 59
347. Decompress Run-Length Encoded List 61
347. Decompress Run-Length Encoded List(C++) 62
347. Decompress Run-Length Encoded List(Python) 63
348. Convert Integer to the Sum of Two No-Zero Integers 64
348. Convert Integer to the Sum of Two No-Zero Integers(C++) 65
348. Convert Integer to the Sum of Two No-Zero Integers(Python) 66
349. Ads Performance 67
349. Ads Performance(Shell) 69
350. Maximum 69 Number 70
350. Maximum 69 Number(C++) 71
350. Maximum 69 Number(Python) 72
351. List the Products Ordered in a Period 73
351. List the Products Ordered in a Period(Shell) 75
352. Rank Transform of an Array 76
352. Rank Transform of an Array(C++) 77
352. Rank Transform of an Array(Python) 78
353. Remove Palindromic Subsequences 79
353. Remove Palindromic Subsequences(C++) 80
353. Remove Palindromic Subsequences(Python) 81
354. The K Weakest Rows in a Matrix 82
354. The K Weakest Rows in a Matrix(C++) 84
354. The K Weakest Rows in a Matrix(Python) 86
355. Number of Steps to Reduce a Number to Zero 88
355. Number of Steps to Reduce a Number to Zero(C++) 89
355. Number of Steps to Reduce a Number to Zero(Python) 90
356. Check If N and Its Double Exist 91
356. Check If N and Its Double Exist(C++) 92
356. Check If N and Its Double Exist(Python) 93
357. Students With Invalid Departments 94
357. Students With Invalid Departments(Shell) 96
358. Count Negative Numbers in a Sorted Matrix 97
358. Count Negative Numbers in a Sorted Matrix(C++) 98
358. Count Negative Numbers in a Sorted Matrix(Python) 99
359. Sort Integers by The Number of 1 Bits 100
359. Sort Integers by The Number of 1 Bits(C++) 101
359. Sort Integers by The Number of 1 Bits(Python) 102
360. Number of Days Between Two Dates 103
360. Number of Days Between Two Dates(C++) 104
360. Number of Days Between Two Dates(Python) 105
361. How Many Numbers Are Smaller Than the Current Number 106
361. How Many Numbers Are Smaller Than the Current Number(C++) 107
361. How Many Numbers Are Smaller Than the Current Number(Python) 108
362. Increasing Decreasing String 109
362. Increasing Decreasing String(C++) 111
362. Increasing Decreasing String(Python) 113
363. Generate a String With Characters That Have Odd Count 114
363. Generate a String With Characters That Have Odd Count(C++) 115
363. Generate a String With Characters That Have Odd Count(Python) 116
364. Replace Employee ID With The Unique Identifier 117
364. Replace Employee ID With The Unique Identifier(Shell) 119
365. Lucky Numbers in a Matrix 120
365. Lucky Numbers in a Matrix(C++) 121
365. Lucky Numbers in a Matrix(Python) 123
366. Find the Distance Value Between Two Arrays 124
366. Find the Distance Value Between Two Arrays(C++) 125
366. Find the Distance Value Between Two Arrays(Python) 126
367. Create Target Array in the Given Order 127
367. Create Target Array in the Given Order(C++) 128
367. Create Target Array in the Given Order(Python) 129
368. Find Lucky Integer in an Array 130
368. Find Lucky Integer in an Array(C++) 131
368. Find Lucky Integer in an Array(Python) 132
369. Count Largest Group 133
369. Count Largest Group(C++) 134
369. Count Largest Group(Python) 135
370. Minimum Subsequence in Non-Increasing Order 136
370. Minimum Subsequence in Non-Increasing Order(C++) 137
370. Minimum Subsequence in Non-Increasing Order(Python) 138
371. Top Travellers 139
371. Top Travellers(Shell) 141
372. String Matching in an Array 142
372. String Matching in an Array(C++) 143
372. String Matching in an Array(Python) 146
373. Minimum Value to Get Positive Step by Step Sum 149
373. Minimum Value to Get Positive Step by Step Sum(C++) 150
373. Minimum Value to Get Positive Step by Step Sum(Python) 151
374. Reformat The String 152
374. Reformat The String(C++) 153
374. Reformat The String(Python) 154
375. Maximum Score After Splitting a String 155
375. Maximum Score After Splitting a String(C++) 156
375. Maximum Score After Splitting a String(Python) 157
376. Counting Elements 158
376. Counting Elements(C++) 159
376. Counting Elements(Python) 160
377. Perform String Shifts 161
377. Perform String Shifts(C++) 162
377. Perform String Shifts(Python) 163
378. Kids With the Greatest Number of Candies 164
378. Kids With the Greatest Number of Candies(C++) 165
378. Kids With the Greatest Number of Candies(Python) 166
379. Create a Session Bar Chart 167
379. Create a Session Bar Chart(Shell) 168
380. Destination City 169
380. Destination City(C++) 170
380. Destination City(Python) 171
381. Build an Array With Stack Operations 172
381. Build an Array With Stack Operations(C++) 173
381. Build an Array With Stack Operations(Python) 174
382. Consecutive Characters 175
382. Consecutive Characters(C++) 176
382. Consecutive Characters(Python) 177
383. Number of Students Doing Homework at a Given Time 178
383. Number of Students Doing Homework at a Given Time(C++) 179
383. Number of Students Doing Homework at a Given Time(Python) 180
384. Check If a Word Occurs As a Prefix of Any Word in a Sentence 181
384. Check If a Word Occurs As a Prefix of Any Word in a Sentence(C++) 182
384. Check If a Word Occurs As a Prefix of Any Word in a Sentence(Python) 183
385. Make Two Arrays Equal by Reversing Sub-arrays 184
385. Make Two Arrays Equal by Reversing Sub-arrays(C++) 185
385. Make Two Arrays Equal by Reversing Sub-arrays(Python) 186
386. Maximum Product of Two Elements in an Array 187
386. Maximum Product of Two Elements in an Array(C++) 188
386. Maximum Product of Two Elements in an Array(Python) 189
387. Calculate Salaries 190
387. Calculate Salaries(Shell) 192
388. Find All The Lonely Nodes 193
388. Find All The Lonely Nodes(C++) 195
388. Find All The Lonely Nodes(Python) 196
389. Shuffle the Array 197
389. Shuffle the Array(C++) 198
389. Shuffle the Array(Python) 199
390. Delete N Nodes After M Nodes of a Linked List 200
390. Delete N Nodes After M Nodes of a Linked List(C++) 202
390. Delete N Nodes After M Nodes of a Linked List(Python) 203
391. Final Prices With a Special Discount in a Shop 204
391. Final Prices With a Special Discount in a Shop(C++) 205
391. Final Prices With a Special Discount in a Shop(Python) 206
392. Running Sum of 1d Array 207
392. Running Sum of 1d Array(C++) 208
392. Running Sum of 1d Array(Python) 209
393. Group Sold Products By The Date 210
393. Group Sold Products By The Date(Shell) 211
394. XOR Operation in an Array 212
394. XOR Operation in an Array(C++) 213
394. XOR Operation in an Array(Python) 214
395. Average Salary Excluding the Minimum and Maximum Salary 215
395. Average Salary Excluding the Minimum and Maximum Salary(C++) 216
395. Average Salary Excluding the Minimum and Maximum Salary(Python) 217
396. Friendly Movies Streamed Last Month 218
396. Friendly Movies Streamed Last Month(Shell) 220
397. Path Crossing 221
397. Path Crossing(C++) 223
397. Path Crossing(Python) 224
398. Can Make Arithmetic Progression From Sequence 225
398. Can Make Arithmetic Progression From Sequence(C++) 226
398. Can Make Arithmetic Progression From Sequence(Python) 227
399. Reformat Date 228
399. Reformat Date(C++) 229
399. Reformat Date(Python) 230
400. Customer Order Frequency 231
400. Customer Order Frequency(Shell) 233
401. Number of Good Pairs 234
401. Number of Good Pairs(C++) 235
401. Number of Good Pairs(Python) 236
402. Find Users With Valid E-Mails 237
402. Find Users With Valid E-Mails(Shell) 238
403. Water Bottles 239
403. Water Bottles(C++) 241
403. Water Bottles(Python) 242
404. Count Odd Numbers in an Interval Range 243
404. Count Odd Numbers in an Interval Range(C++) 244
404. Count Odd Numbers in an Interval Range(Python) 245
405. Patients With a Condition 246
405. Patients With a Condition(Shell) 247
406. Shuffle String 248
406. Shuffle String(C++) 250
406. Shuffle String(Python) 251
407. Count Good Triplets 252
407. Count Good Triplets(C++) 253
407. Count Good Triplets(Python) 254
408. Kth Missing Positive Number 255
408. Kth Missing Positive Number(C++) 256
408. Kth Missing Positive Number(Python) 257
409. Fix Product Name Format 258
409. Fix Product Name Format(Shell) 259
410. Make The String Great 260
410. Make The String Great(C++) 261
410. Make The String Great(Python) 262
411. Three Consecutive Odds 263
411. Three Consecutive Odds(C++) 264
411. Three Consecutive Odds(Python) 265
412. Thousand Separator 266
412. Thousand Separator(C++) 267
412. Thousand Separator(Python) 268
413. Most Visited Sector in a Circular Track 269
413. Most Visited Sector in a Circular Track(C++) 271
413. Most Visited Sector in a Circular Track(Python) 272
414. Unique Orders and Customers Per Month 273
414. Unique Orders and Customers Per Month(Shell) 274
415. Detect Pattern of Length M Repeated K or More Times 275
415. Detect Pattern of Length M Repeated K or More Times(C++) 277
415. Detect Pattern of Length M Repeated K or More Times(Python) 278
416. Matrix Diagonal Sum 279
416. Matrix Diagonal Sum(C++) 280
416. Matrix Diagonal Sum(Python) 281
417. Replace All ?'s to Avoid Consecutive Repeating Characters 282
417. Replace All ?'s to Avoid Consecutive Repeating Characters(C++) 283
417. Replace All ?'s to Avoid Consecutive Repeating Characters(Python) 284
418. Customer Who Visited but Did Not Make Any Transactions 285
418. Customer Who Visited but Did Not Make Any Transactions(Shell) 287
419. Special Positions in a Binary Matrix 288
419. Special Positions in a Binary Matrix(C++) 289
419. Special Positions in a Binary Matrix(Python) 290
420. Bank Account Summary II 291
420. Bank Account Summary II(Shell) 293
421. Sum of All Odd Length Subarrays 294
421. Sum of All Odd Length Subarrays(C++) 295
421. Sum of All Odd Length Subarrays(Python) 296
422. Rearrange Spaces Between Words 297
422. Rearrange Spaces Between Words(C++) 298
422. Rearrange Spaces Between Words(Python) 299
423. Crawler Log Folder 300
423. Crawler Log Folder(C++) 302
423. Crawler Log Folder(Python) 303
424. Design Parking System 304
424. Design Parking System(C++) 305
424. Design Parking System(Python) 306
425. Special Array With X Elements Greater Than or Equal X 307
425. Special Array With X Elements Greater Than or Equal X(C++) 308
425. Special Array With X Elements Greater Than or Equal X(Python) 311
426. Maximum Nesting Depth of the Parentheses 313
426. Maximum Nesting Depth of the Parentheses(C++) 314
426. Maximum Nesting Depth of the Parentheses(Python) 315
427. Mean of Array After Removing Some Elements 316
427. Mean of Array After Removing Some Elements(C++) 317
427. Mean of Array After Removing Some Elements(Python) 318
428. All Valid Triplets That Can Represent a Country 319
428. All Valid Triplets That Can Represent a Country(Shell) 321
429. Largest Substring Between Two Equal Characters 322
429. Largest Substring Between Two Equal Characters(C++) 323
429. Largest Substring Between Two Equal Characters(Python) 324
430. Slowest Key 325
430. Slowest Key(C++) 326
430. Slowest Key(Python) 327
431. Percentage of Users Attended a Contest 328
431. Percentage of Users Attended a Contest(Shell) 330
432. Sort Array by Increasing Frequency 331
432. Sort Array by Increasing Frequency(C++) 332
432. Sort Array by Increasing Frequency(Python) 333
433. Check Array Formation Through Concatenation 334
433. Check Array Formation Through Concatenation(C++) 335
433. Check Array Formation Through Concatenation(Python) 336
434. Get Maximum in Generated Array 337
434. Get Maximum in Generated Array(C++) 338
434. Get Maximum in Generated Array(Python) 339
435. Defuse the Bomb 340
435. Defuse the Bomb(C++) 341
435. Defuse the Bomb(Python) 342
436. Design an Ordered Stream 343
436. Design an Ordered Stream(C++) 344
436. Design an Ordered Stream(Python) 345
437. Average Time of Process per Machine 346
437. Average Time of Process per Machine(Shell) 348
438. Check If Two String Arrays are Equivalent 349
438. Check If Two String Arrays are Equivalent(C++) 350
438. Check If Two String Arrays are Equivalent(Python) 351
439. Fix Names in a Table 352
439. Fix Names in a Table(Shell) 353
440. Maximum Repeating Substring 354
440. Maximum Repeating Substring(C++) 355
440. Maximum Repeating Substring(Python) 357
441. Richest Customer Wealth 359
441. Richest Customer Wealth(C++) 360
441. Richest Customer Wealth(Python) 361
442. Product's Worth Over Invoices 362
442. Product's Worth Over Invoices(Shell) 364
443. Goal Parser Interpretation 365
443. Goal Parser Interpretation(C++) 366
443. Goal Parser Interpretation(Python) 367
444. Invalid Tweets 368
444. Invalid Tweets(Shell) 369
445. Count the Number of Consistent Strings 370
445. Count the Number of Consistent Strings(C++) 371
445. Count the Number of Consistent Strings(Python) 372
446. Count of Matches in Tournament 373
446. Count of Matches in Tournament(C++) 374
446. Count of Matches in Tournament(Python) 375
447. Daily Leads and Partners 376
447. Daily Leads and Partners(Shell) 377
448. Reformat Phone Number 378
448. Reformat Phone Number(C++) 380
448. Reformat Phone Number(Python) 381
449. Number of Students Unable to Eat Lunch 382
449. Number of Students Unable to Eat Lunch(C++) 383
449. Number of Students Unable to Eat Lunch(Python) 384
450. Determine if String Halves Are Alike 385
450. Determine if String Halves Are Alike(C++) 386
450. Determine if String Halves Are Alike(Python) 387
451. Largest Subarray Length K 388
451. Largest Subarray Length K(C++) 389
451. Largest Subarray Length K(Python) 390
452. Maximum Units on a Truck 391
452. Maximum Units on a Truck(C++) 392
452. Maximum Units on a Truck(Python) 393
453. Calculate Money in Leetcode Bank 394
453. Calculate Money in Leetcode Bank(C++) 395
453. Calculate Money in Leetcode Bank(Python) 396
454. Decode XORed Array 397
454. Decode XORed Array(C++) 398
454. Decode XORed Array(Python) 399
455. Number Of Rectangles That Can Form The Largest Square 400
455. Number Of Rectangles That Can Form The Largest Square(C++) 401
455. Number Of Rectangles That Can Form The Largest Square(Python) 402
456. Find Followers Count 403
456. Find Followers Count(Shell) 404
457. The Number of Employees Which Report to Each Employee 405
457. The Number of Employees Which Report to Each Employee(Shell) 406
458. Latest Time by Replacing Hidden Digits 407
458. Latest Time by Replacing Hidden Digits(C++) 408
458. Latest Time by Replacing Hidden Digits(Python) 409
459. Find Total Time Spent by Each Employee 410
459. Find Total Time Spent by Each Employee(Shell) 411
460. Maximum Number of Balls in a Box 412
460. Maximum Number of Balls in a Box(C++) 413
460. Maximum Number of Balls in a Box(Python) 414
461. Sum of Unique Elements 415
461. Sum of Unique Elements(C++) 416
461. Sum of Unique Elements(Python) 417
462. Check if Array Is Sorted and Rotated 418
462. Check if Array Is Sorted and Rotated(C++) 419
462. Check if Array Is Sorted and Rotated(Python) 420
463. Recyclable and Low Fat Products 421
463. Recyclable and Low Fat Products(Shell) 422
464. Minimum Changes To Make Alternating Binary String 423
464. Minimum Changes To Make Alternating Binary String(C++) 424
464. Minimum Changes To Make Alternating Binary String(Python) 425
465. Longest Nice Substring 426
465. Longest Nice Substring(C++) 427
465. Longest Nice Substring(Python) 428
466. Merge Strings Alternately 429
466. Merge Strings Alternately(C++) 430
466. Merge Strings Alternately(Python) 431
467. Count Items Matching a Rule 432
467. Count Items Matching a Rule(C++) 433
467. Count Items Matching a Rule(Python) 434
468. Product's Price for Each Store 435
468. Product's Price for Each Store(Shell) 436
469. Find Nearest Point That Has the Same X or Y Coordinate 437
469. Find Nearest Point That Has the Same X or Y Coordinate(C++) 438
469. Find Nearest Point That Has the Same X or Y Coordinate(Python) 439
470. Check if Binary String Has at Most One Segment of Ones 440
470. Check if Binary String Has at Most One Segment of Ones(C++) 441
470. Check if Binary String Has at Most One Segment of Ones(Python) 442
471. Primary Department for Each Employee 443
471. Primary Department for Each Employee(Shell) 445
472. Check if One String Swap Can Make Strings Equal 446
472. Check if One String Swap Can Make Strings Equal(C++) 447
472. Check if One String Swap Can Make Strings Equal(Python) 448
473. Rearrange Products Table 449
473. Rearrange Products Table(Shell) 450
474. Second Largest Digit in a String 451
474. Second Largest Digit in a String(C++) 452
474. Second Largest Digit in a String(Python) 453
475. Number of Different Integers in a String 454
475. Number of Different Integers in a String(C++) 455
475. Number of Different Integers in a String(Python) 456
476. Ad-Free Sessions 457
476. Ad-Free Sessions(Shell) 459
477. Determine Color of a Chessboard Square 460
477. Determine Color of a Chessboard Square(C++) 462
477. Determine Color of a Chessboard Square(Python) 463
478. Truncate Sentence 464
478. Truncate Sentence(C++) 465
478. Truncate Sentence(Python) 466
479. Find Customers With Positive Revenue this Year 467
479. Find Customers With Positive Revenue this Year(Shell) 468
480. Sign of the Product of an Array 469
480. Sign of the Product of an Array(C++) 470
480. Sign of the Product of an Array(Python) 471
481. Faulty Sensor 472
481. Faulty Sensor(C++) 473
481. Faulty Sensor(Python) 474
482. Minimum Operations to Make the Array Increasing 475
482. Minimum Operations to Make the Array Increasing(C++) 476
482. Minimum Operations to Make the Array Increasing(Python) 477
483. Check if the Sentence Is Pangram 478
483. Check if the Sentence Is Pangram(C++) 479
483. Check if the Sentence Is Pangram(Python) 480
484. Sum of Digits in Base K 481
484. Sum of Digits in Base K(C++) 482
484. Sum of Digits in Base K(Python) 483
485. Replace All Digits with Characters 484
485. Replace All Digits with Characters(C++) 485
485. Replace All Digits with Characters(Python) 486
486. Minimum Distance to the Target Element 487
486. Minimum Distance to the Target Element(C++) 488
486. Minimum Distance to the Target Element(Python) 489
487. Convert Date Format 490
487. Convert Date Format(Shell) 491
488. Maximum Population Year 492
488. Maximum Population Year(C++) 493
488. Maximum Population Year(Python) 494
489. Sorting the Sentence 495
489. Sorting the Sentence(C++) 496
489. Sorting the Sentence(Python) 497
490. Sum of All Subset XOR Totals 498
490. Sum of All Subset XOR Totals(C++) 499
490. Sum of All Subset XOR Totals(Python) 500
491. Orders With Maximum Quantity Above Average 501
491. Orders With Maximum Quantity Above Average(Shell) 503
492. Longer Contiguous Segments of Ones than Zeros 504
492. Longer Contiguous Segments of Ones than Zeros(C++) 505
492. Longer Contiguous Segments of Ones than Zeros(Python) 506
493. Calculate Special Bonus 507
493. Calculate Special Bonus(Shell) 508
494. Substrings of Size Three with Distinct Characters 509
494. Substrings of Size Three with Distinct Characters(C++) 510
494. Substrings of Size Three with Distinct Characters(Python) 511
495. Get Biggest Three Rhombus Sums in a Grid 512
495. Get Biggest Three Rhombus Sums in a Grid(C++) 514
495. Get Biggest Three Rhombus Sums in a Grid(Python) 515
496. Check if Word Equals Summation of Two Words 516
496. Check if Word Equals Summation of Two Words(C++) 517
496. Check if Word Equals Summation of Two Words(Python) 518
497. Determine Whether Matrix Can Be Obtained By Rotation 519
497. Determine Whether Matrix Can Be Obtained By Rotation(C++) 521
497. Determine Whether Matrix Can Be Obtained By Rotation(Python) 522
498. The Latest Login in 2020 523
498. The Latest Login in 2020(Shell) 524
499. Check if All the Integers in a Range Are Covered 525
499. Check if All the Integers in a Range Are Covered(C++) 526
499. Check if All the Integers in a Range Are Covered(Python) 528
500. Redistribute Characters to Make All Strings Equal 529
500. Redistribute Characters to Make All Strings Equal(C++) 530
500. Redistribute Characters to Make All Strings Equal(Python) 531
501. Largest Odd Number in String 532
501. Largest Odd Number in String(C++) 533
501. Largest Odd Number in String(Python) 534
502. Remove One Element to Make the Array Strictly Increasing 535
503. Build Array from Permutation 536
504. Count Square Sum Triples 537
505. Concatenation of Array 538
506. Check if String Is Decomposable Into Value-Equal Substrings 539
507. Maximum Number of Words You Can Type 540
508. Users That Actively Request Confirmation Messages 541
509. Check if All Characters Have Equal Number of Occurrences 543
510. Sum of Digits of String After Convert 544
511. Three Divisors 545
512. Delete Characters to Make Fancy String 546
513. Check If String Is a Prefix of Array 547
514. Employees With Missing Information 548
*************

332. Shift 2D Grid


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

Given a 2D grid of size m x n and an integer k . You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1] .


Element at grid[i][n - 1] moves to grid[i + 1][0] .
Element at grid[m - 1][n - 1] moves to grid[0][0].

Return the 2D grid after applying shift operation k times.

Example 1:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1


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

Example 2:

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4


Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9


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

Constraints:

m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
*************

332. Shift 2D Grid(C++)


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

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector> shiftGrid(vector>& grid, int k) {
7 rotate(&grid, k);
8 return grid;
9 }
10
11 private:
12 void rotate(vector> *grid, int k) {
13 k %= grid->size() * (*grid)[0].size();
14 reverse(grid, 0, grid->size() * (*grid)[0].size());
15 reverse(grid, 0, k);
16 reverse(grid, k, grid->size() * (*grid)[0].size());
17 }
18
19 void reverse(vector> *grid, int start, int end) {
20 for (; start < end; ++start, --end) {
21 int start_r = start / (*grid)[0].size();
22 int start_c = start % (*grid)[0].size();
23 int end_r = (end - 1) / (*grid)[0].size();
24 int end_c = (end - 1) % (*grid)[0].size();
25 swap((*grid)[start_r][start_c], (*grid)[end_r][end_c]);
26 }
27 }
28 };
*************

332. Shift 2D Grid(Python)


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

1 # Time: O(m * n)
2 # Space: O(1)
3
4 class Solution(object):
5 def shiftGrid(self, grid, k):
6 """
7 :type grid: List[List[int]]
8 :type k: int
9 :rtype: List[List[int]]
10 """
11 def rotate(grids, k):
12 def reverse(grid, start, end):
13 while start < end:
14 start_r, start_c = divmod(start, len(grid[0]))
15 end_r, end_c = divmod(end-1, len(grid[0]))
16 grid[start_r][start_c], grid[end_r][end_c] = grid[end_r][end_c], grid[start_r][start_c]
17 start += 1
18 end -= 1
19
20 k %= len(grid)*len(grid[0])
21 reverse(grid, 0, len(grid)*len(grid[0]))
22 reverse(grid, 0, k)
23 reverse(grid, k, len(grid)*len(grid[0]))
24
25 rotate(grid, k)
26 return grid
********************************

333. Minimum Time Visiting All Points


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

On a 2D plane, there are n points with integer coordinates points[i] = [x i, y i]. Return the minimum time in seconds to visit all the
points in the order given by points.

You can move according to these rules:

In 1 second, you can either:


move vertically by one unit,
move horizontally by one unit, or
move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in1 second).
You have to visit the points in the same order as they appear in the array.
You are allowed to pass through points that appear later in the order, but these do not count as visits.

Example 1:

Input: points = [[1,1],[3,4],[-1,0]]


Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds

Example 2:

Input: points = [[3,2],[-2,2]]


Output: 5

Constraints:

points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000
********************************

333. Minimum Time Visiting All Points(C++)


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

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

333. Minimum Time Visiting All Points(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minTimeToVisitAllPoints(self, points):
6 """
7 :type points: List[List[int]]
8 :rtype: int
9 """
10 return sum(max(abs(points[i+1][0] - points[i][0]),
11 abs(points[i+1][1] - points[i][1]))
12 for i in xrange(len(points)-1))
********

334. Hexspeak
********

A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string,
then replacing all occurrences of the digit 0 with the letter O, and the digit 1 with the letter I. Such a representation is valid if
and only if it consists only of the letters in the set {"A", "B", "C", "D", "E", "F", "I", "O"} .

Given a string num representing a decimal integer N, return the Hexspeak representation of N if it is valid, otherwise return
"ERROR".

Example 1:

Input: num = "257"


Output: "IOI"
Explanation: 257 is 101 in hexadecimal.

Example 2:

Input: num = "3"


Output: "ERROR"

Constraints:

1 <= N <= 10^12


There are no leading zeros in the given string.
All answers must be in uppercase letters.
********

334. Hexspeak(C++)
********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string toHexspeak(string num) {
7 unordered_map lookup = {{0, 'O'}, {1,'I'}};
8 for (int i = 0; i < 6; ++i) {
9 lookup[10 + i] = 'A' + i;
10 }
11 string result;
12 uint64_t n = stoul(num), r = 0;
13 while (n) {
14 r = n % 16;
15 n /= 16;
16 if (!lookup.count(r)) {
17 return "ERROR";
18 }
19 result.push_back(lookup[r]);
20 }
21 reverse(result.begin(), result.end());
22 return result;
23 }
24 };
25
26 // Time: O(n)
27 // Space: O(n)
28 class Solution2 {
29 public:
30 string toHexspeak(string num) {
31 stringstream ss;
32 ss << hex << uppercase << stoul(num);
33 string result(ss.str());
34 for (auto i = 0; i < result.length(); ++i) {
35 if ('2' <= result[i] && result[i] <= '9') {
36 return "ERROR";
37 }
38 if (result[i] == '0') {
39 result[i] = 'O';
40 }
41 if (result[i] == '1') {
42 result[i] = 'I';
43 }
44 }
45 return result;
46 }
47 };
********

334. Hexspeak(Python)
********

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def toHexspeak(self, num):
6 """
7 :type num: str
8 :rtype: str
9 """
10 lookup = {0:'O', 1:'I'}
11 for i in xrange(6):
12 lookup[10+i] = chr(ord('A')+i)
13 result = []
14 n = int(num)
15 while n:
16 n, r = divmod(n, 16)
17 if r not in lookup:
18 return "ERROR"
19 result.append(lookup[r])
20 return "".join(reversed(result))
21
22
23 # Time: O(n)
24 # Space: O(n)
25 class Solution2(object):
26 def toHexspeak(self, num):
27 """
28 :type num: str
29 :rtype: str
30 """
31 result = hex(int(num)).upper()[2:].replace('0', 'O').replace('1', 'I')
32 return result if all(c in "ABCDEFOI" for c in result) else "ERROR"
*********************************

335. Find Winner on a Tic Tac Toe Game


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

Tic-tac-toe is played by two players A and B on a 3 x 3 grid.

Here are the rules of Tic-Tac-Toe:

Players take turns placing characters into empty squares (" ").
The first player A always places "X" characters, while the second player B always places "O" characters.
"X" and "O" characters are always placed into empty squares, never on filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.

Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where
they mark their respective character in the order in which A and B play.

Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still
movements to play return "Pending".

You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.

Example 1:

Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]


Output: "A"
Explanation: "A" wins, he always plays first.
"X " "X " "X " "X " "X "
" " -> " " -> " X " -> " X " -> " X "
" " "O " "O " "OO " "OOX"

Example 2:

Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]


Output: "B"
Explanation: "B" wins.
"X " "X " "XX " "XXO" "XXO" "XXO"
" " -> " O " -> " O " -> " O " -> "XO " -> "XO "
" " " " " " " " " " "O "

Example 3:

Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]


Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"

Example 4:
Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X "
" O "
" "

Constraints:

1 <= moves.length <= 9


moves[i].length == 2
0 <= moves[i][j] <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe.
*********************************

335. Find Winner on a Tic Tac Toe Game(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string tictactoe(vector>& moves) {
7 vector> row(2, vector(3));
8 vector> col(2, vector(3));
9 vector diag(2), anti_diag(2);
10 int p = 0;
11 for (const auto& move : moves) {
12 int r = move[0], c = move[1];
13 ++row[p][r];
14 ++col[p][c];
15 diag[p] += (r == c);
16 anti_diag[p] += (r + c == 2);
17 vector tmp = {row[p][r], col[p][c], diag[p], anti_diag[p]};
18 if (find(tmp.cbegin(), tmp.cend(), 3) != tmp.cend()) {
19 return string(1, "AB"[p]);
20 }
21 p ^= 1;
22 }
23 return moves.size() == 9 ? "Draw" : "Pending";
24 }
25 };
*********************************

335. Find Winner on a Tic Tac Toe Game(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def tictactoe(self, moves):
6 """
7 :type moves: List[List[int]]
8 :rtype: str
9 """
10 row, col = [[0]*3 for _ in xrange(2)], [[0]*3 for _ in xrange(2)]
11 diag, anti_diag = [0]*2, [0]*2
12 p = 0
13 for r, c in moves:
14 row[p][r] += 1
15 col[p][c] += 1
16 diag[p] += r == c
17 anti_diag[p] += r+c == 2
18 if 3 in (row[p][r], col[p][c], diag[p], anti_diag[p]):
19 return "AB"[p]
20 p ^= 1
21 return "Draw" if len(moves) == 9 else "Pending"
*************************************

336. Traffic Light Controlled Intersection


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

There is an intersection of two roads. First road is road A where cars travel from North to South in direction 1 and from South
to North in direction 2. Second road is road B where cars travel from West to East in direction 3 and from East to West in
direction 4.

There is a traffic light located on each road before the intersection. A traffic light can either be green or red.

1. Green means cars can cross the intersection in both directions of the road.
2. Red means cars in both directions cannot cross the intersection and must wait until the light turns green.

The traffic lights cannot be green on both roads at the same time. That means when the light is green on road A, it is red
on road B and when the light is green on road B, it is red on road A.

Initially, the traffic light is green on road A and red on road B. When the light is green on one road, all cars can cross the
intersection in both directions until the light becomes green on the other road. No two cars traveling on different roads
should cross at the same time.

Design a deadlock-free traffic light controlled system at this intersection.

Implement the function void carArrived(carId, roadId, direction, turnGreen, crossCar) where:

carId is the id of the car that arrived.


roadId is the id of the road that the car travels on.
direction is the direction of the car.
turnGreen is a function you can call to turn the traffic light to green on the current road.
crossCar is a function you can call to let the current car cross the intersection.

Your answer is considered correct if it avoids cars deadlock in the intersection. Turning the light green on a road when it was
already green is considered a wrong answer.

Example 1:
Input: cars = [1,3,5,2,4], directions = [2,1,2,4,3], arrivalTimes = [10,20,30,40,50]
Output: [
"Car 1 Has Passed Road A In Direction 2", // Traffic light on road A is green, car 1 can cross the intersection.
"Car 3 Has Passed Road A In Direction 1", // Car 3 crosses the intersection as the light is still green.
"Car 5 Has Passed Road A In Direction 2", // Car 5 crosses the intersection as the light is still green.
"Traffic Light On Road B Is Green", // Car 2 requests green light for road B.
"Car 2 Has Passed Road B In Direction 4", // Car 2 crosses as the light is green on road B now.
"Car 4 Has Passed Road B In Direction 3" // Car 4 crosses the intersection as the light is still green.
]

Example 2:

Input: cars = [1,2,3,4,5], directions = [2,4,3,3,1], arrivalTimes = [10,20,30,40,40]


Output: [
"Car 1 Has Passed Road A In Direction 2", // Traffic light on road A is green, car 1 can cross the intersection.
"Traffic Light On Road B Is Green", // Car 2 requests green light for road B.
"Car 2 Has Passed Road B In Direction 4", // Car 2 crosses as the light is green on road B now.
"Car 3 Has Passed Road B In Direction 3", // Car 3 crosses as the light is green on road B now.
"Traffic Light On Road A Is Green", // Car 5 requests green light for road A.
"Car 5 Has Passed Road A In Direction 1", // Car 5 crosses as the light is green on road A now.
"Traffic Light On Road B Is Green", // Car 4 requests green light for road B. Car 4 blocked until car 5 crosses and then traffic lig
"Car 4 Has Passed Road B In Direction 3" // Car 4 crosses as the light is green on road B now.
]
Explanation: This is a dead-lock free scenario. Note that the scenario when car 4 crosses before turning light into green on road A and allow

Constraints:

1 <= cars.length <= 20


cars.length = directions.length
cars.length = arrivalTimes.length
All values of cars are unique
1 <= directions[i] <= 4
arrivalTimes is non-decreasing
*************************************

336. Traffic Light Controlled Intersection(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class TrafficLight {
5 public:
6 TrafficLight()
7 : light_{1} {
8
9 }
10
11 void carArrived(
12 int carId, // ID of the car
13 int roadId, // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
14 int direction, // Direction of the car
15 function turnGreen, // Use turnGreen() to turn light to green on current road
16 function crossCar // Use crossCar() to make car cross the intersection
17 ) {
18 unique_lock lock{m_};
19 if (light_ != roadId) {
20 light_ = roadId;
21 turnGreen();
22 }
23 crossCar();
24 }
25
26 private:
27 mutex m_;
28 int light_;
29 };
*************************************

336. Traffic Light Controlled Intersection(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 import threading
5
6
7 class TrafficLight(object):
8
9 def __init__(self):
10 self.__l = threading.Lock()
11 self.__light = 1
12
13 def carArrived(self, carId, roadId, direction, turnGreen, crossCar):
14 """
15 :type roadId: int --> // ID of the car
16 :type carId: int --> // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
17 :type direction: int --> // Direction of the car
18 :type turnGreen: method --> // Use turnGreen() to turn light to green on current road
19 :type crossCar: method --> // Use crossCar() to make car cross the intersection
20 :rtype: void
21 """
22 with self.__l:
23 if self.__light != roadId:
24 self.__light = roadId
25 turnGreen()
26 crossCar()
*************************

337. Students and Examinations


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

Table: Students

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| student_id | int |
| student_name | varchar |
+---------------+---------+
student_id is the primary key for this table.
Each row of this table contains the ID and the name of one student in the school.

Table: Subjects

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| subject_name | varchar |
+--------------+---------+
subject_name is the primary key for this table.
Each row of this table contains the name of one subject in the school.

Table: Examinations

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| subject_name | varchar |
+--------------+---------+
There is no primary key for this table. It may contain duplicates.
Each student from the Students table takes every course from Subjects table.
Each row of this table indicates that a student with ID student_id attended the exam of subject_name.

Write an SQL query to find the number of times each student attended each exam.

Order the result table by student_id and subject_name.

The query result format is in the following example:


Students table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1 | Alice |
| 2 | Bob |
| 13 | John |
| 6 | Alex |
+------------+--------------+
Subjects table:
+--------------+
| subject_name |
+--------------+
| Math |
| Physics |
| Programming |
+--------------+
Examinations table:
+------------+--------------+
| student_id | subject_name |
+------------+--------------+
| 1 | Math |
| 1 | Physics |
| 1 | Programming |
| 2 | Programming |
| 1 | Physics |
| 1 | Math |
| 13 | Math |
| 13 | Programming |
| 13 | Physics |
| 2 | Math |
| 1 | Math |
+------------+--------------+
Result table:
+------------+--------------+--------------+----------------+
| student_id | student_name | subject_name | attended_exams |
+------------+--------------+--------------+----------------+
| 1 | Alice | Math | 3 |
| 1 | Alice | Physics | 2 |
| 1 | Alice | Programming | 1 |
| 2 | Bob | Math | 1 |
| 2 | Bob | Physics | 0 |
| 2 | Bob | Programming | 1 |
| 6 | Alex | Math | 0 |
| 6 | Alex | Physics | 0 |
| 6 | Alex | Programming | 0 |
| 13 | John | Math | 1 |
| 13 | John | Physics | 1 |
| 13 | John | Programming | 1 |
+------------+--------------+--------------+----------------+
The result table should contain all students and all subjects.
Alice attended Math exam 3 times, Physics exam 2 times and Programming exam 1 time.
Bob attended Math exam 1 time, Programming exam 1 time and didn't attend the Physics exam.
Alex didn't attend any exam.
John attended Math exam 1 time, Physics exam 1 time and Programming exam 1 time.
*************************

337. Students and Examinations(Shell)


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

1 # Time: O((m * n) * log(m * n))


2 # Space: O(m * n)
3
4 SELECT a.student_id,
5 a.student_name,
6 b.subject_name,
7 Count(c.subject_name) AS attended_exams
8 FROM students AS a
9 CROSS JOIN subjects AS b
10 LEFT JOIN examinations AS c
11 ON a.student_id = c.student_id
12 AND b.subject_name = c.subject_name
13 GROUP BY a.student_id,
14 b.subject_name
15 ORDER BY a.student_id,
16 b.subject_name;
****************************************************

338. Subtract the Product and Sum of Digits of an Integer


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

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example 1:

Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15

Example 2:

Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21

Constraints:

1 <= n <= 10^5


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

338. Subtract the Product and Sum of Digits of an


Integer(C++)
****************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int subtractProductAndSum(int n) {
7 int product = 1, total = 0;
8 for (; n; n /= 10) {
9 product *= n % 10;
10 total += n % 10;
11 }
12 return product - total;
13 }
14 };
****************************************************

338. Subtract the Product and Sum of Digits of an


Integer(Python)
****************************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def subtractProductAndSum(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 product, total = 1, 0
11 while n:
12 n, r = divmod(n, 10)
13 product *= r
14 total += r
15 return product-total
16
17
18 # Time: O(logn)
19 # Space: O(logn)
20 import operator
21
22
23 class Solution2(object):
24 def subtractProductAndSum(self, n):
25 """
26 :type n: int
27 :rtype: int
28 """
29 A = map(int, str(n))
30 return reduce(operator.mul, A) - sum(A)
***********************************************

339. Element Appearing More Than 25% In Sorted Array


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

Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25%
of the time, return that integer.

Example 1:

Input: arr = [1,2,2,6,6,6,6,7,10]


Output: 6

Example 2:

Input: arr = [1,1]


Output: 1

Constraints:

1 <= arr.length <= 10 4


0 <= arr[i] <= 10 5
***********************************************

339. Element Appearing More Than 25% In Sorted


Array(C++)
***********************************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findSpecialInteger(vector& arr) {
7 for (const auto& x : {arr[arr.size() / 4], arr[arr.size() / 2], arr[arr.size() * 3 / 4]}) {
8 if (distance(lower_bound(arr.cbegin(), arr.cend(), x),
9 upper_bound(arr.cbegin(), arr.cend(), x)) * 4 > arr.size()) {
10 return x;
11 }
12 }
13 return -1;
14 }
15 };
***********************************************

339. Element Appearing More Than 25% In Sorted


Array(Python)
***********************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 import bisect
5
6
7 class Solution(object):
8 def findSpecialInteger(self, arr):
9 """
10 :type arr: List[int]
11 :rtype: int
12 """
13 for x in [arr[len(arr)//4], arr[len(arr)//2], arr[len(arr)*3//4]]:
14 if (bisect.bisect_right(arr, x) - bisect.bisect_left(arr, x)) * 4 > len(arr):
15 return x
16 return -1
*************************************************

340. Convert Binary Number in a Linked List to Integer


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

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The
linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list.

Example 1:

Input: head = [1,0,1]


Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]


Output: 0

Example 3:

Input: head = [1]


Output: 1

Example 4:

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


Output: 18880

Example 5:

Input: head = [0,0]


Output: 0

Constraints:

The Linked List is not empty.


Number of nodes will not exceed 30.
Each node's value is either 0 or 1.
*************************************************

340. Convert Binary Number in a Linked List to


Integer(C++)
*************************************************

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

340. Convert Binary Number in a Linked List to


Integer(Python)
*************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 # Definition for singly-linked list.
5 class ListNode(object):
6 def __init__(self, x):
7 self.val = x
8 self.next = None
9
10
11 class Solution(object):
12 def getDecimalValue(self, head):
13 """
14 :type head: ListNode
15 :rtype: int
16 """
17 result = 0
18 while head:
19 result = result*2 + head.val
20 head = head.next
21 return result
****************************

341. Weather Type in Each Country


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

Table: Countries

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| country_id | int |
| country_name | varchar |
+---------------+---------+
country_id is the primary key for this table.
Each row of this table contains the ID and the name of one country.

Table: Weather

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| country_id | int |
| weather_state | varchar |
| day | date |
+---------------+---------+
(country_id, day) is the primary key for this table.
Each row of this table indicates the weather state in a country for one day.

Write an SQL query to find the type of weather in each country for November 2019.

The type of weather is Cold if the average weather_state is less than or equal 15, Hot if the average weather_state is greater
than or equal 25 and Warm otherwise.

Return result table in any order.

The query result format is in the following example:


Countries table:
+------------+--------------+
| country_id | country_name |
+------------+--------------+
| 2 | USA |
| 3 | Australia |
| 7 | Peru |
| 5 | China |
| 8 | Morocco |
| 9 | Spain |
+------------+--------------+
Weather table:
+------------+---------------+------------+
| country_id | weather_state | day |
+------------+---------------+------------+
| 2 | 15 | 2019-11-01 |
| 2 | 12 | 2019-10-28 |
| 2 | 12 | 2019-10-27 |
| 3 | -2 | 2019-11-10 |
| 3 | 0 | 2019-11-11 |
| 3 | 3 | 2019-11-12 |
| 5 | 16 | 2019-11-07 |
| 5 | 18 | 2019-11-09 |
| 5 | 21 | 2019-11-23 |
| 7 | 25 | 2019-11-28 |
| 7 | 22 | 2019-12-01 |
| 7 | 20 | 2019-12-02 |
| 8 | 25 | 2019-11-05 |
| 8 | 27 | 2019-11-15 |
| 8 | 31 | 2019-11-25 |
| 9 | 7 | 2019-10-23 |
| 9 | 3 | 2019-12-23 |
+------------+---------------+------------+
Result table:
+--------------+--------------+
| country_name | weather_type |
+--------------+--------------+
| USA | Cold |
| Austraila | Cold |
| Peru | Hot |
| China | Warm |
| Morocco | Hot |
+--------------+--------------+
Average weather_state in USA in November is (15) / 1 = 15 so weather type is Cold.
Average weather_state in Austraila in November is (-2 + 0 + 3) / 3 = 0.333 so weather type is Cold.
Average weather_state in Peru in November is (25) / 1 = 25 so weather type is Hot.
Average weather_state in China in November is (16 + 18 + 21) / 3 = 18.333 so weather type is Warm.
Average weather_state in Morocco in November is (25 + 27 + 31) / 3 = 27.667 so weather type is Hot.
We know nothing about average weather_state in Spain in November so we don't include it in the result table.
****************************

341. Weather Type in Each Country(Shell)


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

1 # Time: O(m + n)
2 # Space: O(n)
3
4 SELECT c.country_name,
5 CASE
6 WHEN AVG(w.weather_state * 1.0) <= 15.0 THEN 'Cold'
7 WHEN AVG(w.weather_state * 1.0) >= 25.0 THEN 'Hot'
8 ELSE 'Warm'
9 END AS weather_type
10 FROM Countries AS c
11 INNER JOIN Weather AS w ON c.country_id = w.country_id
12 WHERE w.day BETWEEN '2019-11-01' AND '2019-11-30'
13 GROUP BY c.country_id;
***************************************

342. Find Numbers with Even Number of Digits


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

Given an array nums of integers, return how many of them contain aneven number of digits.

Example 1:

Input: nums = [12,345,2,6,7896]


Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.

Example 2:

Input: nums = [555,901,482,1771]


Output: 1
Explanation:
Only 1771 contains an even number of digits.

Constraints:

1 <= nums.length <= 500


1 <= nums[i] <= 10^5
***************************************

342. Find Numbers with Even Number of Digits(C++)


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

1 // Time: O(nlog(logm)), n the length of nums, m is the max value of nums


2 // Space: O(logm)
3
4 class Solution {
5 public:
6 Solution() {
7 static const int M = 1e5;
8 lookup_.emplace_back(0);
9 int i = 10;
10 for (; i < M; i *= 10) {
11 lookup_.emplace_back(i);
12 }
13 lookup_.emplace_back(i);
14 }
15
16 int findNumbers(vector& nums) {
17 return accumulate(nums.cbegin(), nums.cend(), 0,
18 [this](const auto& x, const auto& y) {
19 return x + int(digit_count(y) % 2 == 0);
20 });
21 }
22
23 private:
24 int digit_count(int n) {
25 return distance(lookup_.cbegin(),
26 upper_bound(lookup_.cbegin(), lookup_.cend(), n));
27 }
28
29 vector lookup_;
30 };
31
32 // Time: O(nlogm), n the length of nums, m is the max value of nums
33 // Space: O(logm)
34 class Solution2 {
35 public:
36 int findNumbers(vector& nums) {
37 return accumulate(nums.cbegin(), nums.cend(), 0,
38 [this](const auto& x, const auto& y) {
39 return x + int(digit_count(y) % 2 == 0);
40 });
41 }
42
43 private:
44 int digit_count(int n) {
45 int result = 0;
46 for (; n; n /= 10, ++result);
47 return result;
48 }
49 };
50
51 // Time: O(nlogm), n the length of nums, m is the max value of nums
52 // Space: O(logm)
53 class Solution3 {
54 public:
55 int findNumbers(vector& nums) {
56 return accumulate(nums.cbegin(), nums.cend(), 0,
57 [](const auto& x, const auto& y) {
58 return x + int(to_string(y).length() % 2 == 0);
59 });
60 }
61 };
***************************************

342. Find Numbers with Even Number of Digits(Python)


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

1 # Time: O(nlog(logm)), n the length of nums, m is the max value of nums


2 # Space: O(logm)
3
4 import bisect
5
6
7 class Solution(object):
8 def __init__(self):
9 M = 10**5
10 self.__lookup = [0]
11 i = 10
12 while i < M:
13 self.__lookup.append(i)
14 i *= 10
15 self.__lookup.append(i)
16
17 def findNumbers(self, nums):
18 """
19 :type nums: List[int]
20 :rtype: int
21 """
22 def digit_count(n):
23 return bisect.bisect_right(self.__lookup, n)
24
25 return sum(digit_count(n) % 2 == 0 for n in nums)
26
27
28 # Time: O(nlogm), n the length of nums, m is the max value of nums
29 # Space: O(logm)
30 class Solution2(object):
31 def findNumbers(self, nums):
32 """
33 :type nums: List[int]
34 :rtype: int
35 """
36 def digit_count(n):
37 result = 0
38 while n:
39 n //= 10
40 result += 1
41 return result
42
43 return sum(digit_count(n) % 2 == 0 for n in nums)
44
45
46 # Time: O(nlogm), n the length of nums, m is the max value of nums
47 # Space: O(logm)
48 class Solution3(object):
49 def findNumbers(self, nums):
50 """
51 :type nums: List[int]
52 :rtype: int
53 """
54 return sum(len(str(n)) % 2 == 0 for n in nums)
****************************************************

343. Replace Elements with Greatest Element on Right


Side
****************************************************

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace
the last element with -1.

After doing so, return the array.

Example 1:

Input: arr = [17,18,5,4,6,1]


Output: [18,6,6,6,1,-1]
Explanation:
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.

Example 2:

Input: arr = [400]


Output: [-1]
Explanation: There are no elements to the right of index 0.

Constraints:

1 <= arr.length <= 10 4


1 <= arr[i] <= 10 5
****************************************************

343. Replace Elements with Greatest Element on Right


Side(C++)
****************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector replaceElements(vector& arr) {
7 int curr_max = -1;
8 for (int i = arr.size() - 1; i >= 0; --i) {
9 tie(arr[i], curr_max) = make_pair(curr_max, max(curr_max, arr[i]));
10 }
11 return arr;
12 }
13 };
****************************************************

343. Replace Elements with Greatest Element on Right


Side(Python)
****************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def replaceElements(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: List[int]
9 """
10 curr_max = -1
11 for i in reversed(xrange(len(arr))):
12 arr[i], curr_max = curr_max, max(curr_max, arr[i])
13 return arr
******************

344. Find the Team Size


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

Table: Employee

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| employee_id | int |
| team_id | int |
+---------------+---------+
employee_id is the primary key for this table.
Each row of this table contains the ID of each employee and their respective team.

Write an SQL query to find the team size of each of the employees.

Return result table in any order.

The query result format is in the following example:

Employee Table:
+-------------+------------+
| employee_id | team_id |
+-------------+------------+
| 1 | 8 |
| 2 | 8 |
| 3 | 8 |
| 4 | 7 |
| 5 | 9 |
| 6 | 9 |
+-------------+------------+
Result table:
+-------------+------------+
| employee_id | team_size |
+-------------+------------+
| 1 | 3 |
| 2 | 3 |
| 3 | 3 |
| 4 | 1 |
| 5 | 2 |
| 6 | 2 |
+-------------+------------+
Employees with Id 1,2,3 are part of a team with team_id = 8.
Employees with Id 4 is part of a team with team_id = 7.
Employees with Id 5,6 are part of a team with team_id = 9.
******************

344. Find the Team Size(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT employee_id,
5 team_size
6 FROM employee AS e
7 LEFT JOIN (SELECT team_id,
8 Count(1) AS team_size
9 FROM employee
10 GROUP BY team_id) AS teams
11 ON e.team_id = teams.team_id
*************************************

345. Find N Unique Integers Sum up to Zero


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

Given an integer n, return any array containing n unique integers such that they add up to 0.

Example 1:

Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2:

Input: n = 3
Output: [-1,0,1]

Example 3:

Input: n = 1
Output: [0]

Constraints:

1 <= n <= 1000


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

345. Find N Unique Integers Sum up to Zero(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector sumZero(int n) {
7 vector result;
8 for (int i = -(n / 2); i <= (n / 2); ++i) {
9 if (i == 0 && n % 2 == 0) {
10 continue;
11 }
12 result.emplace_back(i);
13 }
14 return result;
15 }
16 };
*************************************

345. Find N Unique Integers Sum up to Zero(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def sumZero(self, n):
6 """
7 :type n: int
8 :rtype: List[int]
9 """
10 return [i for i in xrange(-(n//2), n//2+1) if not (i == 0 and n%2 == 0)]
***********************************************

346. Decrypt String from Alphabet to Integer Mapping


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

Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:

Characters ('a' to 'i') are represented by ('1' to '9') respectively.


Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.

Return the string formed after mapping.

It's guaranteed that a unique mapping will always exist.

Example 1:

Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".

Example 2:

Input: s = "1326#"
Output: "acz"

Example 3:

Input: s = "25#"
Output: "y"

Example 4:

Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
Output: "abcdefghijklmnopqrstuvwxyz"

Constraints:

1 <= s.length <= 1000


s[i] only contains digits letters ('0'-'9') and '#' letter.
s will be valid string such that mapping is always possible.
***********************************************

346. Decrypt String from Alphabet to Integer


Mapping(C++)
***********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 // forward solution
5 class Solution {
6 public:
7 string freqAlphabets(string s) {
8 string result;
9 int i = 0;
10 while (i < s.length()) {
11 if (i + 2 < s.length() && s[i + 2] == '#') {
12 result.push_back(alpha(s.substr(i, 2)));
13 i += 3;
14 } else {
15 result.push_back(alpha(s.substr(i, 1)));
16 ++i;
17 }
18 }
19 return result;
20 }
21
22 private:
23 char alpha(const string& s) {
24 return 'a' + stoi(s) - 1;
25 }
26 };
27
28 // Time: O(n)
29 // Space: O(1)
30 // backward solution
31 class Solution2 {
32 public:
33 string freqAlphabets(string s) {
34 string result;
35 int i = s.length() - 1;
36 while (i >= 0) {
37 if (s[i] == '#') {
38 result.push_back(alpha(s.substr(i - 2, 2)));
39 i -= 3;
40 } else {
41 result.push_back(alpha(s.substr(i, 1)));
42 --i;
43 }
44 }
45 reverse(result.begin(), result.end());
46 return result;
47 }
48
49 private:
50 char alpha(const string& s) {
51 return 'a' + stoi(s) - 1;
52 }
53 };
54
55 // Time: O(n)
56 // Space: O(1)
57 // regex solution
58 class Solution3 {
59 public:
60 string freqAlphabets(string s) {
60
61 string result;
62 int submatches[] = { 1, 2 };
63 const auto e = regex("(\\d\\d#)|(\\d)");
64 for (regex_token_iterator it(s.cbegin(), s.cend(), e, submatches), end;
65 it != end;) {
66 const auto& a = (it++)->str();
67 const auto& b = (it++)->str();
68 result.push_back(alpha(!a.empty() ? a : b));
69 }
70 return result;
71 }
72
73 private:
74 char alpha(const string& s) {
75 return 'a' + stoi(s) - 1;
76 }
77 };
***********************************************

346. Decrypt String from Alphabet to Integer


Mapping(Python)
***********************************************
1 # Time: O(n)
2 # Space: O(1)
3
4 # forward solution
5 class Solution(object):
6 def freqAlphabets(self, s):
7 """
8 :type s: str
9 :rtype: str
10 """
11 def alpha(num):
12 return chr(ord('a') + int(num)-1)
13
14 i = 0
15 result = []
16 while i < len(s):
17 if i+2 < len(s) and s[i+2] == '#':
18 result.append(alpha(s[i:i+2]))
19 i += 3
20 else:
21 result.append(alpha(s[i]))
22 i += 1
23 return "".join(result)
24
25
26 # Time: O(n)
27 # Space: O(1)
28 # backward solution
29 class Solution2(object):
30 def freqAlphabets(self, s):
31 """
32 :type s: str
33 :rtype: str
34 """
35 def alpha(num):
36 return chr(ord('a') + int(num)-1)
37
38 i = len(s)-1
39 result = []
40 while i >= 0:
41 if s[i] == '#':
42 result.append(alpha(s[i-2:i]))
43 i -= 3
44 else:
45 result.append(alpha(s[i]))
46 i -= 1
47 return "".join(reversed(result))
48
49 # Time: O(n)
50 # Space: O(1)
51 import re
52
53
54 # regex solution
55 class Solution3(object):
56 def freqAlphabets(self, s):
57 """
58 :type s: str
59 :rtype: str
60 """
61 def alpha(num):
62 return chr(ord('a') + int(num)-1)
63
64 return "".join(alpha(i[:2]) for i in re.findall(r"\d\d#|\d", s))
**********************************

347. Decompress Run-Length Encoded List


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

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0 ). For each such pair, there are freq
elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the
decompressed list.

Return the decompressed list.

Example 1:

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


Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].

Example 2:

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


Output: [1,3,3]

Constraints:

2 <= nums.length <= 100


nums.length % 2 == 0
1 <= nums[i] <= 100
**********************************

347. Decompress Run-Length Encoded List(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector decompressRLElist(vector& nums) {
7 vector result;
8 for (int i = 0; i < nums.size(); i += 2) {
9 for (int j = 0; j < nums[i]; ++j) {
10 result.emplace_back(nums[i + 1]);
11 }
12 }
13 return result;
14 }
15 };
**********************************

347. Decompress Run-Length Encoded List(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def decompressRLElist(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: List[int]
9 """
10 return [nums[i+1] for i in xrange(0, len(nums), 2) for _ in xrange(nums[i])]
**************************************************

348. Convert Integer to the Sum of Two No-Zero Integers


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

Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation.

Return a list of two integers [A, B] where:

A and B are No-Zero integers.


A+B=n

It's guarateed that there is at least one valid solution. If there are many valid solutions you can return any of them.

Example 1:

Input: n = 2
Output: [1,1]
Explanation: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.

Example 2:

Input: n = 11
Output: [2,9]

Example 3:

Input: n = 10000
Output: [1,9999]

Example 4:

Input: n = 69
Output: [1,68]

Example 5:

Input: n = 1010
Output: [11,999]

Constraints:

2 <= n <= 10^4


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

348. Convert Integer to the Sum of Two No-Zero


Integers(C++)
**************************************************

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector getNoZeroIntegers(int n) {
7 int a = 0;
8 for (int curr = n, base = 1; curr; base *= 10, curr /= 10) {
9 if (curr % 10 == 0 || (curr % 10 == 1 && curr != 1)) {
10 a += base;
11 curr -= 10; // carry
12 }
13 a += base;
14 }
15 return {a, n - a};
16 }
17 };
18
19 // Time: O(nlogn)
20 // Space: O(logn)
21 class Solution2 {
22 public:
23 vector getNoZeroIntegers(int n) {
24 vector result;
25 for (int a = 1; a < n; ++a) {
26 if (to_string(a).find('0') == string::npos &&
27 to_string(n - a).find('0') == string::npos) {
28 result = {a, n - a};
29 break;
30 }
31 }
32 return result;
33 }
34 };
**************************************************

348. Convert Integer to the Sum of Two No-Zero


Integers(Python)
**************************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def getNoZeroIntegers(self, n):
6 """
7 :type n: int
8 :rtype: List[int]
9 """
10 a, curr, base = 0, n, 1
11 while curr:
12 if curr % 10 == 0 or (curr % 10 == 1 and curr != 1):
13 a += base
14 curr -= 10 # carry
15 a += base
16 base *= 10
17 curr //= 10
18 return [a, n-a]
19
20
21 # Time: O(nlogn)
22 # Space: O(logn)
23 class Solution2(object):
24 def getNoZeroIntegers(self, n):
25 """
26 :type n: int
27 :rtype: List[int]
28 """
29 return next([a, n-a] for a in xrange(1, n) if '0' not in '{}{}'.format(a, n-a))
***************

349. Ads Performance


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

Table: Ads

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| ad_id | int |
| user_id | int |
| action | enum |
+---------------+---------+
(ad_id, user_id) is the primary key for this table.
Each row of this table contains the ID of an Ad, the ID of a user and the action taken by this user regarding this Ad.
The action column is an ENUM type of ('Clicked', 'Viewed', 'Ignored').

A company is running Ads and wants to calculate the performance of each Ad.

Performance of the Ad is measured using Click-Through Rate (CTR) where:

Write an SQL query to find the ctr of each Ad.

Round ctr to 2 decimal points. Order the result table by ctr in descending order and by ad_id in ascending order in case of a
tie.

The query result format is in the following example:


Ads table:
+-------+---------+---------+
| ad_id | user_id | action |
+-------+---------+---------+
| 1 | 1 | Clicked |
| 2 | 2 | Clicked |
| 3 | 3 | Viewed |
| 5 | 5 | Ignored |
| 1 | 7 | Ignored |
| 2 | 7 | Viewed |
| 3 | 5 | Clicked |
| 1 | 4 | Viewed |
| 2 | 11 | Viewed |
| 1 | 2 | Clicked |
+-------+---------+---------+
Result table:
+-------+-------+
| ad_id | ctr |
+-------+-------+
| 1 | 66.67 |
| 3 | 50.00 |
| 2 | 33.33 |
| 5 | 0.00 |
+-------+-------+
for ad_id = 1, ctr = (2/(2+1)) * 100 = 66.67
for ad_id = 2, ctr = (1/(1+2)) * 100 = 33.33
for ad_id = 3, ctr = (1/(1+1)) * 100 = 50.00
for ad_id = 5, ctr = 0.00, Note that ad_id = 5 has no clicks or views.
Note that we don't care about Ignored Ads.
Result table is ordered by the ctr. in case of a tie we order them by ad_id
***************

349. Ads Performance(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT ad_id,
5 CASE
6 WHEN clicks + views = 0 THEN 0
7 ELSE ROUND(100 * clicks / (clicks + views), 2)
8 END ctr
9 FROM
10 (SELECT ad_id,
11 SUM(CASE
12 WHEN action ='Viewed' THEN 1
13 ELSE 0
14 END) views,
15 SUM(CASE
16 WHEN action = 'Clicked' THEN 1
17 ELSE 0
18 END) clicks
19 FROM Ads
20 GROUP BY ad_id) a
21 ORDER BY ctr DESC,
22 ad_id ASC
23
*****************

350. Maximum 69 Number


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

Given a positive integer num consisting only of digits 6 and 9.

Return the maximum number you can get by changingat most one digit (6 becomes 9, and 9 becomes 6).

Example 1:

Input: num = 9669


Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.

Example 2:

Input: num = 9996


Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.

Example 3:

Input: num = 9999


Output: 9999
Explanation: It is better not to apply any change.

Constraints:

1 <= num <= 10^4


num's digits are 6 or 9.
*****************

350. Maximum 69 Number(C++)


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

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maximum69Number (int num) {
7 int change = 0;
8 for (int curr = num, base = 3; curr; base *= 10, curr /= 10) {
9 if (curr % 10 == 6) {
10 change = base;
11 }
12 }
13 return num + change;
14 }
15 };
16
17 // Time: O(logn)
18 // Space: O(logn)
19 class Solution2 {
20 public:
21 int maximum69Number (int num) {
22 auto s = to_string(num);
23 auto i = s.find('6');
24 if (i != string::npos) {
25 s[i] = '9';
26 }
27 return stoi(s);
28 }
29 };
*****************

350. Maximum 69 Number(Python)


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

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def maximum69Number (self, num):
6 """
7 :type num: int
8 :rtype: int
9 """
10 curr, base, change = num, 3, 0
11 while curr:
12 if curr%10 == 6:
13 change = base
14 base *= 10
15 curr //= 10
16 return num+change
17
18
19 # Time: O(logn)
20 # Space: O(logn)
21 class Solution2(object):
22 def maximum69Number (self, num):
23 """
24 :type num: int
25 :rtype: int
26 """
27 return int(str(num).replace('6', '9', 1))
*************************************

351. List the Products Ordered in a Period


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

Table: Products

+------------------+---------+
| Column Name | Type |
+------------------+---------+
| product_id | int |
| product_name | varchar |
| product_category | varchar |
+------------------+---------+
product_id is the primary key for this table.
This table contains data about the company's products.

Table: Orders

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| order_date | date |
| unit | int |
+---------------+---------+
There is no primary key for this table. It may have duplicate rows.
product_id is a foreign key to Products table.
unit is the number of products ordered in order_date.

Write an SQL query to get the names of products with greater than or equal to 100 units ordered in February 2020 and their
amount.

Return result table in any order.

The query result format is in the following example:


Products table:
+-------------+-----------------------+------------------+
| product_id | product_name | product_category |
+-------------+-----------------------+------------------+
| 1 | Leetcode Solutions | Book |
| 2 | Jewels of Stringology | Book |
| 3 | HP | Laptop |
| 4 | Lenovo | Laptop |
| 5 | Leetcode Kit | T-shirt |
+-------------+-----------------------+------------------+

Orders table:
+--------------+--------------+----------+
| product_id | order_date | unit |
+--------------+--------------+----------+
| 1 | 2020-02-05 | 60 |
| 1 | 2020-02-10 | 70 |
| 2 | 2020-01-18 | 30 |
| 2 | 2020-02-11 | 80 |
| 3 | 2020-02-17 | 2 |
| 3 | 2020-02-24 | 3 |
| 4 | 2020-03-01 | 20 |
| 4 | 2020-03-04 | 30 |
| 4 | 2020-03-04 | 60 |
| 5 | 2020-02-25 | 50 |
| 5 | 2020-02-27 | 50 |
| 5 | 2020-03-01 | 50 |
+--------------+--------------+----------+

Result table:
+--------------------+---------+
| product_name | unit |
+--------------------+---------+
| Leetcode Solutions | 130 |
| Leetcode Kit | 100 |
+--------------------+---------+

Products with product_id = 1 is ordered in February a total of (60 + 70) = 130.


Products with product_id = 2 is ordered in February a total of 80.
Products with product_id = 3 is ordered in February a total of (2 + 3) = 5.
Products with product_id = 4 was not ordered in February 2020.
Products with product_id = 5 is ordered in February a total of (50 + 50) = 100.
*************************************

351. List the Products Ordered in a Period(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT p.product_name,
5 o.unit
6 FROM (SELECT product_id,
7 Sum(unit) AS unit
8 FROM orders
9 WHERE order_date BETWEEN '2020-02-01' AND '2020-02-29'
10 GROUP BY product_id
11 HAVING unit >= 100) o
12 INNER JOIN products p
13 ON o.product_id = p.product_id
**************************

352. Rank Transform of an Array


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

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

Rank is an integer starting from 1.


The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.

Example 1:

Input: arr = [40,10,20,30]


Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

Example 2:

Input: arr = [100,100,100]


Output: [1,1,1]
Explanation: Same elements share the same rank.

Example 3:

Input: arr = [37,12,28,9,100,56,80,5,12]


Output: [5,3,4,2,8,6,7,1,3]

Constraints:

0 <= arr.length <= 10 5


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

352. Rank Transform of an Array(C++)


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

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector arrayRankTransform(vector& arr) {
7 set lookup{arr.cbegin(), arr.cend()};
8 unordered_map rank;
9 for (const auto& v : lookup) {
10 rank[v] = rank.size() + 1;
11 }
12 vector result;
13 transform(arr.cbegin(), arr.cend(), back_inserter(result),
14 [&rank](const auto& v) {
15 return rank[v];
16 });
17 return result;
18 }
19 };
**************************

352. Rank Transform of an Array(Python)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 class Solution(object):
5 def arrayRankTransform(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: List[int]
9 """
10 return map({x: i+1 for i, x in enumerate(sorted(set(arr)))}.get, arr)
*******************************

353. Remove Palindromic Subsequences


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

You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove onepalindromic subsequence
from s .

Return the minimum number of steps to make the given string empty.

A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing
its order. Note that a subsequence does not necessarily need to be contiguous.

A string is called palindrome if is one that reads the same backward as well as forward.

Example 1:

Input: s = "ababa"
Output: 1
Explanation: s is already a palindrome, so its entirety can be removed in a single step.

Example 2:

Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".

Example 3:

Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".

Constraints:

1 <= s.length <= 1000


s[i] is either 'a' or 'b'.
*******************************

353. Remove Palindromic Subsequences(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int removePalindromeSub(string s) {
7 return 2 - is_palindrome(s) - s.empty();
8 }
9
10 private:
11 bool is_palindrome(const string& s) {
12 for (int i = 0; i < s.length() / 2; ++i) {
13 if (s[i] != s[s.length() - 1 - i]) {
14 return false;
15 }
16 }
17 return true;
18 }
19 };
*******************************

353. Remove Palindromic Subsequences(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def removePalindromeSub(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 def is_palindrome(s):
11 for i in xrange(len(s)//2):
12 if s[i] != s[-1-i]:
13 return False
14 return True
15
16 return 2 - is_palindrome(s) - (s == "")
******************************

354. The K Weakest Rows in a Matrix


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

You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are
positioned in front of the civilians. That is, all the1's will appear to the left of all the 0's in each row.

A row i is weaker than a row j if one of the following is true:

The number of soldiers in row i is less than the number of soldiers in rowj.
Both rows have the same number of soldiers and i < j .

Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

Example 1:

Input: mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].

Example 2:

Input: mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
The number of soldiers in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
The rows ordered from weakest to strongest are [0,2,3,1].

Constraints:

m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j] is either 0 or 1.
******************************

354. The K Weakest Rows in a Matrix(C++)


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

1 // Time: O(m * n)
2 // Space: O(k)
3
4 class Solution {
5 public:
6 vector kWeakestRows(vector>& mat, int k) {
7 vector result;
8 unordered_set lookup;
9 for (int j = 0; j < mat[0].size(); ++j) {
10 for (int i = 0; i < mat.size(); ++i) {
11 if (mat[i][j] || lookup.count(i)) {
12 continue;
13 }
14 lookup.emplace(i);
15 result.emplace_back(i);
16 if (result.size() == k) {
17 return result;
18 }
19 }
20 }
21 for (int i = 0; i < mat.size(); ++i) {
22 if (lookup.count(i)) {
23 continue;
24 }
25 lookup.emplace(i);
26 result.emplace_back(i);
27 if (result.size() == k) {
28 break;
29 }
30 }
31 return result;
32 }
33 };
34
35 // Time: O(m * n)
36 // Space: O(k)
37 class Solution2 {
38 public:
39 vector kWeakestRows(vector>& mat, int k) {
40 OrderedDict lookup;
41 for (int j = 0; j < mat[0].size(); ++j) {
42 for (int i = 0; i < mat.size(); ++i) {
43 if (mat[i][j] || lookup.count(i)) {
44 continue;
45 }
46 lookup[i] = true;
47 if (lookup.size() == k) {
48 return lookup.keys();
49 }
50 }
51 }
52 for (int i = 0; i < mat.size(); ++i) {
53 if (lookup.count(i)) {
54 continue;
55 }
56 lookup[i] = true;
57 if (lookup.size() == k) {
58 break;
59 }
60 }
61 return lookup.keys();
62 }
63
64 private:
65 template
66 class OrderedDict {
67 public:
68 bool count(const K& key) const {
69 return map_.count(key);
70 }
71
72 V& operator[](const K& key) {
73 if (!map_.count(key)) {
74 list_.emplace_front();
75 list_.begin()->first = key;
76 map_[key] = list_.begin();
77 }
78 return map_[key]->second;
79 }
80
81 void popitem() {
82 auto del = list_.front(); list_.pop_front();
83 map_.erase(del.first);
84 }
85
86 vector keys() const {
87 vector result;
88 transform(list_.crbegin(), list_.crend(), back_inserter(result),
89 [](const auto& x) {
90 return x.first;
91 });
92 return result;
93 }
94
95 int size() const {
96 return list_.size();
97 }
98
99 private:
100 list> list_;
101 unordered_map>::iterator> map_;
102 };
103 };
104
105 // Time: O(m * n + klogk)
106 // Space: O(m)
107 class Solution3 {
108 public:
109 vector kWeakestRows(vector>& mat, int k) {
110 vector> nums;
111 for (int i = 0; i < mat.size(); ++i) {
112 nums.emplace_back(accumulate(mat[i].cbegin(), mat[i].cend(), 0), i);
113 }
114 nth_element(nums.begin(), nums.begin() + k, nums.end());
115 sort(nums.begin(), nums.begin() + k);
116 vector result;
117 transform(nums.cbegin(), nums.cbegin() + k, back_inserter(result),
118 [](const auto& x) {
119 return x.second;
120 });
121 return result;
122 }
123 };
******************************

354. The K Weakest Rows in a Matrix(Python)


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

1 # Time: O(m * n)
2 # Space: O(k)
3
4 class Solution(object):
5 def kWeakestRows(self, mat, k):
6 """
7 :type mat: List[List[int]]
8 :type k: int
9 :rtype: List[int]
10 """
11 result, lookup = [], set()
12 for j in xrange(len(mat[0])):
13 for i in xrange(len(mat)):
14 if mat[i][j] or i in lookup:
15 continue
16 lookup.add(i)
17 result.append(i)
18 if len(result) == k:
19 return result
20 for i in xrange(len(mat)):
21 if i in lookup:
22 continue
23 lookup.add(i)
24 result.append(i)
25 if len(result) == k:
26 break
27 return result
28
29
30 # Time: O(m * n)
31 # Space: O(k)
32 import collections
33
34
35 class Solution2(object):
36 def kWeakestRows(self, mat, k):
37 """
38 :type mat: List[List[int]]
39 :type k: int
40 :rtype: List[int]
41 """
42 lookup = collections.OrderedDict()
43 for j in xrange(len(mat[0])):
44 for i in xrange(len(mat)):
45 if mat[i][j] or i in lookup:
46 continue
47 lookup[i] = True
48 if len(lookup) == k:
49 return lookup.keys()
50 for i in xrange(len(mat)):
51 if i in lookup:
52 continue
53 lookup[i] = True
54 if len(lookup) == k:
55 break
56 return lookup.keys()
57
58
59 # Time: O(m * n + klogk)
60 # Space: O(m)
61 import random
62
63
64 class Solution3(object):
65 def kWeakestRows(self, mat, k):
66 """
67 :type mat: List[List[int]]
68 :type k: int
69 :rtype: List[int]
70 """
71 def nth_element(nums, n, compare=lambda a, b: a < b):
72 def partition_around_pivot(left, right, pivot_idx, nums, compare):
73 new_pivot_idx = left
74 nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
75 for i in xrange(left, right):
76 if compare(nums[i], nums[right]):
77 nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
78 new_pivot_idx += 1
79
80 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
81 return new_pivot_idx
82
83 left, right = 0, len(nums) - 1
84 while left <= right:
85 pivot_idx = random.randint(left, right)
86 new_pivot_idx = partition_around_pivot(left, right, pivot_idx, nums, compare)
87 if new_pivot_idx == n:
88 return
89 elif new_pivot_idx > n:
90 right = new_pivot_idx - 1
91 else: # new_pivot_idx < n
92 left = new_pivot_idx + 1
93
94 nums = [(sum(mat[i]), i) for i in xrange(len(mat))]
95 nth_element(nums, k)
96 return map(lambda x: x[1], sorted(nums[:k]))
******************************************

355. Number of Steps to Reduce a Number to Zero


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

Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by2, otherwise, you have to subtract 1 from it.

Example 1:

Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.

Example 2:

Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.

Example 3:

Input: num = 123


Output: 12

Constraints:

0 <= num <= 106


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

355. Number of Steps to Reduce a Number to Zero(C++)


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

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numberOfSteps (int num) {
7 int result = 0;
8 while (num) {
9 result += (num & 1) ? 2 : 1;
10 num >>= 1;
11 }
12 return max(result - 1, 0);
13 }
14 };
******************************************

355. Number of Steps to Reduce a Number to


Zero(Python)
******************************************

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def numberOfSteps (self, num):
6 """
7 :type num: int
8 :rtype: int
9 """
10 result = 0
11 while num:
12 result += 2 if num%2 else 1
13 num //= 2
14 return max(result-1, 0)
*******************************

356. Check If N and Its Double Exist


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

Given an array arr of integers, check if there exists two integersN and M such that N is the double of M ( i.e. N = 2 * M ).

More formally check if there exists two indices i and j such that :

i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

Example 1:

Input: arr = [10,2,5,3]


Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.

Example 2:

Input: arr = [7,1,14,11]


Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.

Example 3:

Input: arr = [3,1,7,11]


Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.

Constraints:

2 <= arr.length <= 500


-10^3 <= arr[i] <= 10^3
*******************************

356. Check If N and Its Double Exist(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool checkIfExist(vector& arr) {
7 unordered_set lookup;
8 for (const auto& x : arr) {
9 if (lookup.count(2 * x) ||
10 (x % 2 == 0 && lookup.count(x / 2))) {
11 return true;
12 }
13 lookup.emplace(x);
14 }
15 return false;
16 }
17 };
*******************************

356. Check If N and Its Double Exist(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def checkIfExist(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: bool
9 """
10 lookup = set()
11 for x in arr:
12 if 2*x in lookup or \
13 (x%2 == 0 and x//2 in lookup):
14 return True
15 lookup.add(x)
16 return False
*********************************

357. Students With Invalid Departments


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

Table: Departments

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key of this table.
The table has information about the id of each department of a university.

Table: Students

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
| department_id | int |
+---------------+---------+
id is the primary key of this table.
The table has information about the id of each student at a university and the id of the department he/she studies at.

Write an SQL query to find the id and the name of all students who are enrolled in departments that no longer exists.

Return the result table in any order.

The query result format is in the following example:


Departments table:
+------+--------------------------+
| id | name |
+------+--------------------------+
| 1 | Electrical Engineering |
| 7 | Computer Engineering |
| 13 | Bussiness Administration |
+------+--------------------------+

Students table:
+------+----------+---------------+
| id | name | department_id |
+------+----------+---------------+
| 23 | Alice | 1 |
| 1 | Bob | 7 |
| 5 | Jennifer | 13 |
| 2 | John | 14 |
| 4 | Jasmine | 77 |
| 3 | Steve | 74 |
| 6 | Luis | 1 |
| 8 | Jonathan | 7 |
| 7 | Daiana | 33 |
| 11 | Madelynn | 1 |
+------+----------+---------------+

Result table:
+------+----------+
| id | name |
+------+----------+
| 2 | John |
| 7 | Daiana |
| 4 | Jasmine |
| 3 | Steve |
+------+----------+

John, Daiana, Steve and Jasmine are enrolled in departments 14, 33, 74 and 77 respectively. department 14, 33, 74 and 77 doesn't exist in the
*********************************

357. Students With Invalid Departments(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3 SELECT s.id,
4 s.name
5 FROM students s
6 LEFT JOIN departments d
7 ON d.id = s.department_id
8 WHERE d.id IS NULL;
9
10 # Time: O(n)
11 # Space: O(n)
12 SELECT s.id,
13 s.name
14 FROM students s
15 WHERE NOT EXISTS (SELECT id
16 FROM departments d
17 WHERE d.id = s.department_id);
*****************************************

358. Count Negative Numbers in a Sorted Matrix


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

Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, returnthe number of
negative numbers in grid.

Example 1:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]


Output: 8
Explanation: There are 8 negatives number in the matrix.

Example 2:

Input: grid = [[3,2],[1,0]]


Output: 0

Example 3:

Input: grid = [[1,-1],[-1,-1]]


Output: 3

Example 4:

Input: grid = [[-1]]


Output: 1

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100

Follow up: Could you find an O(n + m) solution?


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

358. Count Negative Numbers in a Sorted Matrix(C++)


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

1 // Time: O(m + n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countNegatives(vector>& grid) {
7 int result = 0, c = grid[0].size() - 1;
8 for (const auto& row : grid) {
9 while (c >= 0 && row[c] < 0) {
10 --c;
11 }
12 result += grid[0].size() - 1 - c;
13 }
14 return result;
15 }
16 };
*****************************************

358. Count Negative Numbers in a Sorted Matrix(Python)


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

1 # Time: O(m + n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countNegatives(self, grid):
6 """
7 :type grid: List[List[int]]
8 :rtype: int
9 """
10 result, c = 0, len(grid[0])-1
11 for row in grid:
12 while c >= 0 and row[c] < 0:
13 c -= 1
14 result += len(grid[0])-1-c
15 return result
*************************************

359. Sort Integers by The Number of 1 Bits


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

Given an integer array arr. You have to sort the integers in the array in ascending order by the number of1's in their binary
representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.

Return the sorted array.

Example 1:

Input: arr = [0,1,2,3,4,5,6,7,8]


Output: [0,1,2,4,8,3,5,6,7]
Explantion: [0] is the only integer with 0 bits.
[1,2,4,8] all have 1 bit.
[3,5,6] have 2 bits.
[7] has 3 bits.
The sorted array by bits is [0,1,2,4,8,3,5,6,7]

Example 2:

Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]


Output: [1,2,4,8,16,32,64,128,256,512,1024]
Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.

Example 3:

Input: arr = [10000,10000]


Output: [10000,10000]

Example 4:

Input: arr = [2,3,5,7,11,13,17,19]


Output: [2,3,5,17,7,11,13,19]

Example 5:

Input: arr = [10,100,1000,10000]


Output: [10,100,10000,1000]

Constraints:

1 <= arr.length <= 500


0 <= arr[i] <= 10^4
*************************************

359. Sort Integers by The Number of 1 Bits(C++)


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

1 // Time: O(nlogn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector sortByBits(vector& arr) {
7 sort(begin(arr), end(arr),
8 [](const auto& a, const auto& b) {
9 return make_pair(__builtin_popcount(a), a) <
10 make_pair(__builtin_popcount(b), b);
11 });
12 return arr;
13 }
14 };
*************************************

359. Sort Integers by The Number of 1 Bits(Python)


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

1 # Time: O(nlogn)
2 # Space: O(1)
3
4 class Solution(object):
5 def sortByBits(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: List[int]
9 """
10 def popcount(n): # Time: O(logn) ~= O(1) if n is a 32-bit number
11 result = 0
12 while n:
13 n &= n - 1
14 result += 1
15 return result
16
17 arr.sort(key=lambda x: (popcount(x), x))
18 return arr
********************************

360. Number of Days Between Two Dates


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

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

Example 1:

Input: date1 = "2019-06-29", date2 = "2019-06-30"


Output: 1

Example 2:

Input: date1 = "2020-01-15", date2 = "2019-12-31"


Output: 15

Constraints:

The given dates are valid dates between the years1971 and 2100.
********************************

360. Number of Days Between Two Dates(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 Solution() : lookup_(12) {
7 for (int M = 1; M < lookup_.size(); ++M) {
8 lookup_[M] = lookup_[M - 1] + dayOfMonth(M);
9 }
10 }
11
12 int daysBetweenDates(string date1, string date2) {
13 return abs(dayOfYear(date1) - dayOfYear(date2));
14 }
15
16 private:
17 int dayOfYear(string date) {
18 const auto& result = split(date, '-');
19 const auto& Y = stoi(result[0]), &M = stoi(result[1]), &D = stoi(result[2]);
20 const auto& leap = (M > 2 && (((Y % 4 == 0) && (Y % 100 != 0)) || (Y % 400 == 0))) ? 1 : 0;
21 return (Y - 1) * 365 + ((Y - 1) / 4 - (Y - 1) / 100 + (Y - 1) / 400) + lookup_[M - 1] + D + leap;
22 }
23
24 int dayOfMonth(int M) {
25 return (M == 2) ? 28 : 31 - (M - 1) % 7 % 2;
26 }
27
28 vector split(const string& s, const char delim) {
29 vector result;
30 auto end = string::npos;
31 do {
32 const auto& start = end + 1;
33 end = s.find(delim, start);
34 result.emplace_back(s.substr(start, end - start));
35 } while (end != string::npos);
36 return result;
37 }
38
39 vector lookup_;
40 };
********************************

360. Number of Days Between Two Dates(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def __init__(self):
6 def dayOfMonth(M):
7 return (28 if (M == 2) else 31-(M-1)%7%2)
8
9 self.__lookup = [0]*12
10 for M in xrange(1, len(self.__lookup)):
11 self.__lookup[M] += self.__lookup[M-1]+dayOfMonth(M)
12
13 def daysBetweenDates(self, date1, date2):
14 """
15 :type date1: str
16 :type date2: str
17 :rtype: int
18 """
19 def num_days(date):
20 Y, M, D = map(int, date.split("-"))
21 leap = 1 if M > 2 and (((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0)) else 0
22 return (Y-1)*365 + ((Y-1)//4 - (Y-1)//100 + (Y-1)//400) + self.__lookup[M-1]+D+leap
23
24 return abs(num_days(date1) - num_days(date2))
25
26
27 # Time: O(1)
28 # Space: O(1)
29 import datetime
30
31
32 class Solution2(object):
33 def daysBetweenDates(self, date1, date2):
34 delta = datetime.datetime.strptime(date1, "%Y-%m-%d")
35 delta -= datetime.datetime.strptime(date2, "%Y-%m-%d")
36 return abs(delta.days)
****************************************************

361. How Many Numbers Are Smaller Than the Current


Number
****************************************************

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for eachnums[i] you
have to count the number of valid j's such that j != i and nums[j] < nums[i] .

Return the answer in an array.

Example 1:

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


Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

Example 2:

Input: nums = [6,5,4,8]


Output: [2,1,0,3]

Example 3:

Input: nums = [7,7,7,7]


Output: [0,0,0,0]

Constraints:

2 <= nums.length <= 500


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

361. How Many Numbers Are Smaller Than the Current


Number(C++)
****************************************************

1 // Time: O(n + m), m is the max number of nums


2 // Space: O(m)
3
4 class Solution {
5 public:
6 vector smallerNumbersThanCurrent(vector& nums) {
7 const auto& m = *max_element(cbegin(nums), cend(nums));
8 auto count = counter(nums);
9 for (int i = 0; i <= m; ++i) {
10 count[i] += count[i - 1];
11 }
12 vector result;
13 for (const auto& i : nums) {
14 result.emplace_back(count[i - 1]);
15 }
16 return result;
17 }
18
19 private:
20 unordered_map counter(const vector& nums) const {
21 unordered_map count;
22 for (const auto& num : nums) {
23 ++count[num];
24 }
25 return count;
26 }
27 };
28
29 // Time: O(nlogn)
30 // Space: O(n)
31 class Solution2 {
32 public:
33 vector smallerNumbersThanCurrent(vector& nums) {
34 vector sorted_nums(nums);
35 sort(begin(sorted_nums), end(sorted_nums));
36 vector result;
37 for (const auto& i : nums) {
38 result.emplace_back(distance(cbegin(sorted_nums),
39 lower_bound(cbegin(sorted_nums), cend(sorted_nums), i)));
40 }
41 return result;
42 }
43 };
****************************************************

361. How Many Numbers Are Smaller Than the Current


Number(Python)
****************************************************

1 # Time: O(n + m), m is the max number of nums


2 # Space: O(m)
3
4 import collections
5
6
7 class Solution(object):
8 def smallerNumbersThanCurrent(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: List[int]
12 """
13 count = collections.Counter(nums)
14 for i in xrange(max(nums)+1):
15 count[i] += count[i-1]
16 return [count[i-1] for i in nums]
17
18
19 # Time: O(nlogn)
20 # Space: O(n)
21 import bisect
22
23
24 class Solution2(object):
25 def smallerNumbersThanCurrent(self, nums):
26 """
27 :type nums: List[int]
28 :rtype: List[int]
29 """
30 sorted_nums = sorted(nums)
31 return [bisect.bisect_left(sorted_nums, i) for i in nums]
****************************

362. Increasing Decreasing String


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

Given a string s . You should re-order the string using the following algorithm:

1. Pick the smallest character from s and append it to the result.


2. Pick the smallest character from s which is greater than the last appended character to the result andappend it.
3. Repeat step 2 until you cannot pick more characters.
4. Pick the largest character from s and append it to the result.
5. Pick the largest character from s which is smaller than the last appended character to the result andappend it.
6. Repeat step 5 until you cannot pick more characters.
7. Repeat the steps from 1 to 6 until you pick all characters froms .

In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it
to the result.

Return the result string after sorting s with this algorithm.

Example 1:

Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"

Example 2:

Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.

Example 3:

Input: s = "leetcode"
Output: "cdelotee"

Example 4:

Input: s = "ggggggg"
Output: "ggggggg"

Example 5:

Input: s = "spo"
Output: "ops"

Constraints:
1 <= s.length <= 500
s contains only lower-case English letters.
****************************

362. Increasing Decreasing String(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string sortString(string s) {
7 string result;
8 auto count = counter(s);
9 while(result.length() != s.length()) {
10 for (int c = 0; c < count.size(); ++c) {
11 if (count[c]) {
12 result += ('a' + c);
13 --count[c];
14 }
15 }
16 for (int c = count.size() - 1; c >= 0; --c) {
17 if (count[c]) {
18 result += ('a' + c);
19 --count[c];
20 }
21 }
22 }
23 return result;
24 }
25
26 private:
27 vector counter(const string& word) {
28 vector count(26);
29 for (const auto& c : word) {
30 ++count[c - 'a'];
31 }
32 return count;
33 }
34 };
35
36
37 // Time: O(n)
38 // Space: O(1)
39 class Solution2 {
40 public:
41 string sortString(string s) {
42 string result;
43 for (auto [count, desc] = tuple{counter(s), false}; !count.empty(); desc = !desc) {
44 if (!desc) {
45 for (auto it = begin(count); it != end(count);) {
46 result.push_back(it->first);
47 if (!--it->second) {
48 it = count.erase(it);
49 } else {
50 ++it;
51 }
52 }
53 } else {
54 for (auto rit = rbegin(count); rit != rend(count);) {
55 result.push_back(rit->first);
56 if (!--rit->second) {
57 rit = reverse_iterator(count.erase(next(rit).base()));
58 } else {
59 ++rit;
60 }
61 }
62 }
63 }
64 return result;
65 }
66
67 private:
68 map counter(const string& word) {
69 map count;
70 for (const auto& c : word) {
71 ++count[c];
72 }
73 return count;
74 }
75 };
****************************

362. Increasing Decreasing String(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def sortString(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 result, count = [], [0]*26
11 for c in s:
12 count[ord(c)-ord('a')] += 1
13 while len(result) != len(s):
14 for c in xrange(len(count)):
15 if not count[c]:
16 continue
17 result.append(chr(ord('a')+c))
18 count[c] -= 1
19 for c in reversed(xrange(len(count))):
20 if not count[c]:
21 continue
22 result.append(chr(ord('a')+c))
23 count[c] -= 1
24 return "".join(result)
25
26
27 # Time: O(n)
28 # Space: O(1)
29 import collections
30
31
32 class Solution2(object):
33 def sortString(self, s):
34 """
35 :type s: str
36 :rtype: str
37 """
38 result, count, desc = [], collections.Counter(s), False
39 while count:
40 for c in sorted(count.keys(), reverse=desc):
41 result.append(c)
42 count[c] -= 1
43 if not count[c]:
44 del count[c]
45 desc = not desc
46 return "".join(result)
47
*****************************************************

363. Generate a String With Characters That Have Odd


Count
*****************************************************

Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.

The returned string must contain only lowercase English letters. If there are multiples valid strings, returnany of them.

Example 1:

Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many

Example 2:

Input: n = 2
Output: "xy"
Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" an

Example 3:

Input: n = 7
Output: "holasss"

Constraints:

1 <= n <= 500


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

363. Generate a String With Characters That Have Odd


Count(C++)
*****************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string generateTheString(int n) {
7 auto result = string(n - 1, 'a');
8 result.push_back(n % 2 ? 'a' : 'b');
9 return result;
10 }
11 };
*****************************************************

363. Generate a String With Characters That Have Odd


Count(Python)
*****************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def generateTheString(self, n):
6 """
7 :type n: int
8 :rtype: str
9 """
10 result = ['a']*(n-1)
11 result.append('a' if n%2 else 'b')
12 return "".join(result)
**********************************************

364. Replace Employee ID With The Unique Identifier


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

Table: Employees

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key for this table.
Each row of this table contains the id and the name of an employee in a company.

Table: EmployeeUNI

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| unique_id | int |
+---------------+---------+
(id, unique_id) is the primary key for this table.
Each row of this table contains the id and the corresponding unique id of an employee in the company.

Write an SQL query to show the unique ID of each user, If a user doesn't have a unique ID replace just show null.

Return the result table in any order.

The query result format is in the following example:


Employees table:
+----+----------+
| id | name |
+----+----------+
| 1 | Alice |
| 7 | Bob |
| 11 | Meir |
| 90 | Winston |
| 3 | Jonathan |
+----+----------+

EmployeeUNI table:
+----+-----------+
| id | unique_id |
+----+-----------+
| 3 | 1 |
| 11 | 2 |
| 90 | 3 |
+----+-----------+

Result table:
+-----------+----------+
| unique_id | name |
+-----------+----------+
| null | Alice |
| null | Bob |
| 2 | Meir |
| 3 | Winston |
| 1 | Jonathan |
+-----------+----------+

Alice and Bob don't have a unique ID, We will show null instead.
The unique ID of Meir is 2.
The unique ID of Winston is 3.
The unique ID of Jonathan is 1.
**********************************************

364. Replace Employee ID With The Unique


Identifier(Shell)
**********************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT u.unique_id, e.name
5 FROM employees e
6 LEFT JOIN employeeuni u
7 ON e.id = u.id
*************************

365. Lucky Numbers in a Matrix


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

Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix inany order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

Example 1:

Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]


Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column

Example 2:

Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]


Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.

Example 3:

Input: matrix = [[7,8],[1,2]]


Output: [7]

Constraints:

m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5 .
All elements in the matrix are distinct.
*************************

365. Lucky Numbers in a Matrix(C++)


*************************
1 // Time: O(m * n)
2 // Space: O(m + n)
3
4 class Solution {
5 public:
6 vector luckyNumbers (vector>& matrix) {
7 vector rows;
8 for (const auto& row : matrix) {
9 rows.emplace_back(*min_element(row.cbegin(), row.cend()));
10 }
11 vector cols;
12 for (int c = 0; c < matrix[0].size(); ++c) {
13 int max_cell = 0;
14 for (int r = 0; r < matrix.size(); ++r) {
15 max_cell = max(max_cell, matrix[r][c]);
16 }
17 cols.emplace_back(max_cell);
18 }
19 vector result;
20 for (int r = 0; r < matrix.size(); ++r) {
21 for (int c = 0; c < matrix[0].size(); ++c) {
22 if (rows[r] == cols[c]) {
23 result.emplace_back(matrix[r][c]);
24 }
25 }
26 }
27 return result;
28 }
29 };
30
31 // Time: O(m * n)
32 // Space: O(m + n)
33 class Solution2 {
34 public:
35 vector luckyNumbers (vector>& matrix) {
36 unordered_set rows;
37 for (const auto& row : matrix) {
38 rows.emplace(*min_element(row.cbegin(), row.cend()));
39 }
40 unordered_set cols;
41 for (int c = 0; c < matrix[0].size(); ++c) {
42 int max_cell = 0;
43 for (int r = 0; r < matrix.size(); ++r) {
44 max_cell = max(max_cell, matrix[r][c]);
45 }
46 cols.emplace(max_cell);
47 }
48 unordered_set intersection = set_intersection(rows, cols);
49 return vector(intersection.cbegin(), intersection.cend());
50 }
51
52 private:
53 template
54 unordered_set set_intersection(const unordered_set& a,
55 const unordered_set& b) {
56 if (a.size() > b.size()) {
57 return set_intersection(b, a);
58 }
59 unordered_set result;
60 for (const auto& x : a) {
61 if (b.count(x)) {
62 result.emplace(x);
63 }
64 }
65 return result;
66 }
67 };
*************************

365. Lucky Numbers in a Matrix(Python)


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

1 # Time: O(m * n)
2 # Space: O(m + n)
3
4 import itertools
5
6
7 class Solution(object):
8 def luckyNumbers (self, matrix):
9 """
10 :type matrix: List[List[int]]
11 :rtype: List[int]
12 """
13 rows = map(min, matrix)
14 cols = map(max, itertools.izip(*matrix))
15 return [cell for i, row in enumerate(matrix)
16 for j, cell in enumerate(row) if rows[i] == cols[j]]
17
18
19 # Time: O(m * n)
20 # Space: O(m + n)
21 import itertools
22
23
24 class Solution2(object):
25 def luckyNumbers (self, matrix):
26 """
27 :type matrix: List[List[int]]
28 :rtype: List[int]
29 """
30 return list(set(map(min, matrix)) &
31 set(map(max, itertools.izip(*matrix))))
32
******************************************

366. Find the Distance Value Between Two Arrays


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

Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.

The distance value is defined as the number of elementsarr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <=
d.

Example 1:

Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2


Output: 2
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2

Example 2:

Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3


Output: 2

Example 3:

Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6


Output: 1

Constraints:

1 <= arr1.length, arr2.length <= 500


-10^3 <= arr1[i], arr2[j] <= 10^3
0 <= d <= 100
******************************************

366. Find the Distance Value Between Two Arrays(C++)


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

1 // Time: O((n + m) * logm)


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findTheDistanceValue(vector& arr1, vector& arr2, int d) {
7 sort(begin(arr2), end(arr2));
8 int result = 0;
9 for (const auto& x : arr1) {
10 auto j = distance(cbegin(arr2), lower_bound(cbegin(arr2), cend(arr2), x));
11 const auto& left = (j - 1 >= 0) ? arr2[j - 1] : numeric_limits::min();
12 const auto& right = (j < arr2.size()) ? arr2[j] : numeric_limits::max();
13 result += left + d < x && x < right - d;
14 }
15 return result;
16 }
17 };
18
19 // Time: O(nlogn + mlogm)
20 // Space: O(1)
21 class Solution2 {
22 public:
23 int findTheDistanceValue(vector& arr1, vector& arr2, int d) {
24 sort(begin(arr1), end(arr1)), sort(begin(arr2), end(arr2));
25 int result = 0, i = 0;
26 for (int j = 0; i < arr1.size() && j < arr2.size();) {
27 if (arr1[i] - arr2[j] > d) {
28 ++j;
29 continue;
30 }
31 result += arr2[j] - arr1[i] > d;
32 ++i;
33 }
34 return result + arr1.size() - i;
35 }
36 };
******************************************

366. Find the Distance Value Between Two


Arrays(Python)
******************************************

1 # Time: O((n + m) * logm)


2 # Space: O(1)
3
4 import bisect
5
6
7 class Solution(object):
8 def findTheDistanceValue(self, arr1, arr2, d):
9 """
10 :type arr1: List[int]
11 :type arr2: List[int]
12 :type d: int
13 :rtype: int
14 """
15 arr2.sort()
16 result, i, j = 0, 0, 0
17 for x in arr1:
18 j = bisect.bisect_left(arr2, x)
19 left = arr2[j-1] if j-1 >= 0 else float("-inf")
20 right = arr2[j] if j < len(arr2) else float("inf")
21 result += left+d < x < right-d
22 return result
23
24
25 # Time: O(nlogn + mlogm)
26 # Space: O(1)
27 class Solution2(object):
28 def findTheDistanceValue(self, arr1, arr2, d):
29 """
30 :type arr1: List[int]
31 :type arr2: List[int]
32 :type d: int
33 :rtype: int
34 """
35 arr1.sort(), arr2.sort()
36 result, i, j = 0, 0, 0
37 while i < len(arr1) and j < len(arr2):
38 if arr1[i]-arr2[j] > d:
39 j += 1
40 continue
41 result += arr2[j]-arr1[i] > d
42 i += 1
43 return result+len(arr1)-i
**************************************

367. Create Target Array in the Given Order


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

Given two arrays of integers nums and index. Your task is to create target array under the following rules:

Initially target array is empty.


From left to right read nums[i] and index[i], insert at indexindex[i] the value nums[i] in target array.
Repeat the previous step until there are no elements to read innums and index.

Return the target array.

It is guaranteed that the insertion operations will be valid.

Example 1:

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


Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]

Example 2:

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


Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]

Example 3:

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


Output: [1]

Constraints:

1 <= nums.length, index.length <= 100


nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i
**************************************

367. Create Target Array in the Given Order(C++)


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

1 // Time: O(n^2)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector createTargetArray(vector& nums, vector& index) {
7 for (int i = 0; i < nums.size(); ++i) {
8 for (int j = 0; j < i; ++j) {
9 if (index[j] >= index[i]) {
10 ++index[j];
11 }
12 }
13 }
14 vector result(nums.size(),0);
15 for (int i = 0; i < nums.size(); ++i){
16 result[index[i]] = nums[i];
17 }
18 return result;
19 }
20 };
21
22 // Time: O(n^2)
23 // Space: O(1)
24 class Solution2 {
25 public:
26 vector createTargetArray(vector& nums, vector& index) {
27 vector result;
28 for (int i = 0; i < nums.size(); i++) {
29 result.insert(begin(result) + index[i], nums[i]);
30 }
31 return result;
32 }
33 };
**************************************

367. Create Target Array in the Given Order(Python)


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

1 # Time: O(n^2)
2 # Space: O(1)
3
4 class Solution(object):
5 def createTargetArray(self, nums, index):
6 """
7 :type nums: List[int]
8 :type index: List[int]
9 :rtype: List[int]
10 """
11 for i in xrange(len(nums)):
12 for j in xrange(i):
13 if index[j] >= index[i]:
14 index[j] += 1
15 result = [0]*(len(nums))
16 for i in xrange(len(nums)):
17 result[index[i]] = nums[i]
18 return result
19
20
21 # Time: O(n^2)
22 # Space: O(1)
23 import itertools
24
25
26 class Solution2(object):
27 def createTargetArray(self, nums, index):
28 """
29 :type nums: List[int]
30 :type index: List[int]
31 :rtype: List[int]
32 """
33 result = []
34 for i, x in itertools.izip(index, nums):
35 result.insert(i, x)
36 return result
37
******************************

368. Find Lucky Integer in an Array


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

Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.

Return a lucky integer in the array. If there are multiple lucky integers return thelargest of them. If there is no lucky integer
return -1.

Example 1:

Input: arr = [2,2,3,4]


Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.

Example 2:

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


Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:

Input: arr = [2,2,2,3,3]


Output: -1
Explanation: There are no lucky numbers in the array.

Example 4:

Input: arr = [5]


Output: -1

Example 5:

Input: arr = [7,7,7,7,7,7,7]


Output: 7

Constraints:

1 <= arr.length <= 500


1 <= arr[i] <= 500
******************************

368. Find Lucky Integer in an Array(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int findLucky(vector& arr) {
7 const auto& count = counter(arr);
8 int result = -1;
9 for (const auto& [k, v] : count) {
10 if (k == v) {
11 result = max(result, k);
12 }
13 }
14 return result;
15 }
16
17 private:
18 unordered_map counter(const vector& arr) {
19 unordered_map count;
20 for (const auto& i : arr) {
21 ++count[i];
22 }
23 return count;
24 }
25 };
******************************

368. Find Lucky Integer in an Array(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def findLucky(self, arr):
9 """
10 :type arr: List[int]
11 :rtype: int
12 """
13 count = collections.Counter(arr)
14 result = -1
15 for k, v in count.iteritems():
16 if k == v:
17 result = max(result, k)
18 return result
*******************

369. Count Largest Group


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

Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.

Return how many groups have the largest size.

Example 1:

Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size.

Example 2:

Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.

Example 3:

Input: n = 15
Output: 6

Example 4:

Input: n = 24
Output: 5

Constraints:

1 <= n <= 10^4


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

369. Count Largest Group(C++)


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

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int countLargestGroup(int n) {
7 unordered_map count;
8 for (int i = 1; i <= n; ++i) {
9 int total = 0;
10 for (int j = i; j; j /= 10) {
11 total += j % 10;
12 }
13 ++count[total];
14 }
15 const auto& max_count = max_element(cbegin(count), cend(count),
16 [](const auto& a, const auto& b) {
17 return a.second < b.second;
18 })->second;
19 int result = 0;
20 for (const auto& [_, v]: count) {
21 if (v == max_count) {
22 ++result;
23 }
24 }
25 return result;
26 }
27 };
*******************

369. Count Largest Group(Python)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def countLargestGroup(self, n):
9 """
10 :type n: int
11 :rtype: int
12 """
13 count = collections.Counter()
14 for x in xrange(1, n+1):
15 count[sum(map(int, str(x)))] += 1
16 max_count = max(count.itervalues())
17 return sum(v == max_count for v in count.itervalues())
*******************************************

370. Minimum Subsequence in Non-Increasing Order


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

Given the array nums, obtain a subsequence of the array whose sum of elements isstrictly greater than the sum of the
non included elements in such subsequence.

If there are multiple solutions, return the subsequence withminimum size and if there still exist multiple solutions, return the
subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some
(possibly zero) elements from the array.

Note that the solution with the given constraints is guaranteed to beunique. Also return the answer sorted in non-
increasing order.

Example 1:

Input: nums = [4,3,10,9,8]


Output: [10,9]
Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements

Example 2:

Input: nums = [4,4,7,6,7]


Output: [7,7,6]
Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not include

Example 3:

Input: nums = [6]


Output: [6]

Constraints:

1 <= nums.length <= 500


1 <= nums[i] <= 100
*******************************************

370. Minimum Subsequence in Non-Increasing


Order(C++)
*******************************************

1 // Time: O(nlogn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector minSubsequence(vector& nums) {
7 int total = accumulate(cbegin(nums), cend(nums), 0), curr = 0;
8 sort(begin(nums), end(nums), greater());
9 int result = 0;
10 for (int i = 0; i < nums.size(); ++i) {
11 curr += nums[i];
12 if (curr > total - curr) {
13 result = i + 1;
14 break;
15 }
16 }
17 return vector(cbegin(nums), cbegin(nums) + result);
18 }
19 };
*******************************************

370. Minimum Subsequence in Non-Increasing


Order(Python)
*******************************************

1 # Time: O(nlogn)
2 # Space: O(1)
3
4 class Solution(object):
5 def minSubsequence(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: List[int]
9 """
10 result, total, curr = [], sum(nums), 0
11 nums.sort(reverse=True)
12 for i, x in enumerate(nums):
13 curr += x
14 if curr > total-curr:
15 break
16 return nums[:i+1]
**************

371. Top Travellers


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

Table: Users

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key for this table.
name is the name of the user.

Table: Rides

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| user_id | int |
| distance | int |
+---------------+---------+
id is the primary key for this table.
user_id is the id of the user who travelled the distance "distance".

Write an SQL query to report the distance travelled by each user.

Return the result table ordered by travelled_distance in descending order, if two or more users travelled the same distance,
order them by their name in ascending order.

The query result format is in the following example.


Users table:
+------+-----------+
| id | name |
+------+-----------+
| 1 | Alice |
| 2 | Bob |
| 3 | Alex |
| 4 | Donald |
| 7 | Lee |
| 13 | Jonathan |
| 19 | Elvis |
+------+-----------+

Rides table:
+------+----------+----------+
| id | user_id | distance |
+------+----------+----------+
| 1 | 1 | 120 |
| 2 | 2 | 317 |
| 3 | 3 | 222 |
| 4 | 7 | 100 |
| 5 | 13 | 312 |
| 6 | 19 | 50 |
| 7 | 7 | 120 |
| 8 | 19 | 400 |
| 9 | 7 | 230 |
+------+----------+----------+

Result table:
+----------+--------------------+
| name | travelled_distance |
+----------+--------------------+
| Elvis | 450 |
| Lee | 450 |
| Bob | 317 |
| Jonathan | 312 |
| Alex | 222 |
| Alice | 120 |
| Donald | 0 |
+----------+--------------------+
Elvis and Lee travelled 450 miles, Elvis is the top traveller as his name is alphabetically smaller than Lee.
Bob, Jonathan, Alex and Alice have only one ride and we just order them by the total distances of the ride.
Donald didn't have any rides, the distance travelled by him is 0.
**************

371. Top Travellers(Shell)


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

1 # Time: O(m + nlogn)


2 # Space: O(m + n)
3
4 SELECT name,
5 Ifnull(Sum(distance), 0) AS travelled_distance
6 FROM users
7 LEFT JOIN rides
8 ON users.id = rides.user_id
9 GROUP BY name
10 ORDER BY travelled_distance DESC,
11 name;
12
***************************

372. String Matching in an Array


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

Given an array of string words. Return all strings in words which is substring of another word in any order.

String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side ofwords[j].

Example 1:

Input: words = ["mass","as","hero","superhero"]


Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.

Example 2:

Input: words = ["leetcode","et","code"]


Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".

Example 3:

Input: words = ["blue","green","bu"]


Output: []

Constraints:

1 <= words.length <= 100


1 <= words[i].length <= 30
words[i] contains only lowercase English letters.
It's guaranteed that words[i] will be unique.
***************************

372. String Matching in an Array(C++)


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

1 // Time: O(n + m + z) = O(n), n is the total size of patterns


2 // , m is the total size of query string
3 // , z is the number of all matched strings
4 // , O(n) = O(m) = O(z) in this problem
5 // Space: O(t), t is the total size of ac automata trie
6
7 struct AhoNode {
8 vector children;
9 vector indices;
10 AhoNode *suffix;
11 AhoNode *output;
12 AhoNode() :
13 children(26, nullptr),
14 suffix(nullptr),
15 output(nullptr) {}
16 };
17
18 class AhoTrie {
19 public:
20 AhoTrie(const vector& patterns) : root_(createACTrie(patterns)) {
21 node_ = createACSuffixAndOutputLinks(root_);
22 }
23
24 vector step(char letter) {
25 while (node_ && !node_->children[letter - 'a']) {
26 node_ = node_->suffix;
27 }
28 node_ = node_ ? node_->children[letter - 'a'] : root_;
29 return getACNodeOutputs(node_);
30 }
31
32 void reset() {
33 node_ = root_;
34 }
35
36 private:
37 AhoNode *createACTrie(const vector& patterns) { // Time: O(n), Space: O(t)
38 auto root = new AhoNode();
39 for (int i = 0; i < patterns.size(); ++i) {
40 auto node = root;
41 for (const auto& c : patterns[i]) {
42 if (!node->children[c - 'a']) {
43 node->children[c - 'a'] = new AhoNode();
44 }
45 node = node->children[c - 'a'];
46 }
47 node->indices.emplace_back(i);
48 }
49 return root;
50 }
51
52 AhoNode *createACSuffixAndOutputLinks(AhoNode *root) { // Time: O(n), Space: O(t)
53 queue q;
54 for (auto node : root->children) {
55 if (!node) {
56 continue;
57 }
58 q.emplace(node);
59 node->suffix = root;
60 }
61
62 while (!q.empty()) {
63 auto node = q.front(); q.pop();
64 for (int c = 0; c < node->children.size(); ++c) {
65 if (!node->children[c]) {
66 continue;
67 }
68 auto child = node->children[c];
69 q.emplace(child);
70 auto suffix = node->suffix;
71 while (suffix && !suffix->children[c]) {
72 suffix = suffix->suffix;
73 }
74 child->suffix = suffix ? suffix->children[c] : root;
75 child->output = !child->suffix->indices.empty() ?
76 child->suffix : child->suffix->output;
77 }
78 }
79
80 return root;
81 }
82
83 vector getACNodeOutputs(AhoNode *node) { // Time: O(z)
84 vector result;
85 for (const auto& i : node_->indices) {
86 result.emplace_back(i);
87 // return result;
88 }
89 auto output = node_->output;
90 while (output) {
91 for (const auto& i : output->indices) {
92 result.emplace_back(i);
93 // return result;
94 }
95 output = output->output;
96 }
97 return result;
98 }
99
100 AhoNode * const root_;
101 AhoNode *node_;
102 };
103
104 class Solution {
105 public:
106 vector stringMatching(vector& words) {
107 AhoTrie trie(words);
108 unordered_set lookup;
109 for (int i = 0; i < words.size(); ++i) {
110 trie.reset();
111 for (const auto& c : words[i]) {
112 for (const auto& j : trie.step(c)) {
113 if (j != i) {
114 lookup.emplace(j);
115 }
116 }
117 }
118 }
119 vector result;
120 for (const auto& i : lookup) {
121 result.emplace_back(words[i]);
122 }
123 return result;
124 }
125 };
126
127 // Time: O(n^2 * l), n is the number of strings
128 // Space: O(l) , l is the max length of strings
129 class Solution2 {
130 public:
131 vector stringMatching(vector& words) {
132 vector result;
133 for (int i = 0; i < words.size(); ++i) {
134 const auto& prefix = getPrefix(words[i]);
135 for (int j = 0; j < words.size(); ++j) {
135 for (int j = 0; j < words.size(); ++j) {
136 if (i != j && kmp(words[j], words[i], prefix) != -1) {
137 result.emplace_back(words[i]);
138 break;
139 }
140 }
141
142 }
143 return result;
144 }
145
146 private:
147 int kmp(const string& text, const string& pattern, const vector& prefix) {
148 if (pattern.empty()) {
149 return 0;
150 }
151 if (text.length() < pattern.length()) {
152 return -1;
153 }
154 int j = -1;
155 for (int i = 0; i < text.length(); ++i) {
156 while (j != -1 && pattern[j + 1] != text[i]) {
157 j = prefix[j];
158 }
159 if (pattern[j + 1] == text[i]) {
160 ++j;
161 }
162 if (j + 1 == pattern.length()) {
163 return i - j;
164 }
165 }
166 return -1;
167 }
168
169 vector getPrefix(const string& pattern) {
170 vector prefix(pattern.length(), -1);
171 int j = -1;
172 for (int i = 1; i < pattern.length(); ++i) {
173 while (j != -1 && pattern[j + 1] != pattern[i]) {
174 j = prefix[j];
175 }
176 if (pattern[j + 1] == pattern[i]) {
177 ++j;
178 }
179 prefix[i] = j;
180 }
181 return prefix;
182 }
183 };
184
185 // Time: O(n^2 * l^2), n is the number of strings
186 // Space: O(1) , l is the max length of strings
187 class Solution3 {
188 public:
189 vector stringMatching(vector& words) {
190 vector result;
191 for (int i = 0; i < words.size(); ++i) {
192 for (int j = 0; j < words.size(); ++j) {
193 if (i != j && words[j].find(words[i]) != string::npos) {
194 result.emplace_back(words[i]);
195 break;
196 }
197 }
198 }
199 return result;
200 }
201 };
***************************

372. String Matching in an Array(Python)


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

1 # Time: O(n + m + z) = O(n), n is the total size of patterns


2 # , m is the total size of query string
3 # , z is the number of all matched strings
4 # , O(n) = O(m) = O(z) in this problem
5 # Space: O(t), t is the total size of ac automata trie
6
7 import collections
8
9
10 class AhoNode(object):
11 def __init__(self):
12 self.children = collections.defaultdict(AhoNode)
13 self.indices = []
14 self.suffix = None
15 self.output = None
16
17
18 class AhoTrie(object):
19
20 def step(self, letter):
21 while self.__node and letter not in self.__node.children:
22 self.__node = self.__node.suffix
23 self.__node = self.__node.children[letter] if self.__node else self.__root
24 return self.__get_ac_node_outputs(self.__node)
25
26 def reset(self):
27 self.__node = self.__root
28
29 def __init__(self, patterns):
30 self.__root = self.__create_ac_trie(patterns)
31 self.__node = self.__create_ac_suffix_and_output_links(self.__root)
32
33 def __create_ac_trie(self, patterns): # Time: O(n), Space: O(t)
34 root = AhoNode()
35 for i, pattern in enumerate(patterns):
36 node = root
37 for c in pattern:
38 node = node.children[c]
39 node.indices.append(i)
40 return root
41
42 def __create_ac_suffix_and_output_links(self, root): # Time: O(n), Space: O(t)
43 queue = collections.deque()
44 for node in root.children.itervalues():
45 queue.append(node)
46 node.suffix = root
47
48 while queue:
49 node = queue.popleft()
50 for c, child in node.children.iteritems():
51 queue.append(child)
52 suffix = node.suffix
53 while suffix and c not in suffix.children:
54 suffix = suffix.suffix
55 child.suffix = suffix.children[c] if suffix else root
56 child.output = child.suffix if child.suffix.indices else child.suffix.output
57
58 return root
59
60 def __get_ac_node_outputs(self, node): # Time: O(z)
61 result = []
62 for i in node.indices:
63 result.append(i)
64 output = node.output
65 while output:
66 for i in output.indices:
67 result.append(i)
68 output = output.output
69 return result
70
71
72 class Solution(object):
73 def stringMatching(self, words):
74 """
75 :type words: List[str]
76 :rtype: List[str]
77 """
78 trie = AhoTrie(words)
79 lookup = set()
80 for i in xrange(len(words)):
81 trie.reset()
82 for c in words[i]:
83 for j in trie.step(c):
84 if j != i:
85 lookup.add(j)
86 return [words[i] for i in lookup]
87
88
89 # Time: O(n^2 * l), n is the number of strings
90 # Space: O(l) , l is the max length of strings
91 class Solution2(object):
92 def stringMatching(self, words):
93 """
94 :type words: List[str]
95 :rtype: List[str]
96 """
97 def getPrefix(pattern):
98 prefix = [-1]*len(pattern)
99 j = -1
100 for i in xrange(1, len(pattern)):
101 while j != -1 and pattern[j+1] != pattern[i]:
102 j = prefix[j]
103 if pattern[j+1] == pattern[i]:
104 j += 1
105 prefix[i] = j
106 return prefix
107
108 def kmp(text, pattern, prefix):
109 if not pattern:
110 return 0
111 if len(text) < len(pattern):
112 return -1
113 j = -1
114 for i in xrange(len(text)):
115 while j != -1 and pattern[j+1] != text[i]:
116 j = prefix[j]
117 if pattern[j+1] == text[i]:
118 j += 1
119 if j+1 == len(pattern):
120 return i-j
121 return -1
122
123 result = []
124 for i, pattern in enumerate(words):
125 prefix = getPrefix(pattern)
126 for j, text in enumerate(words):
127 if i != j and kmp(text, pattern, prefix) != -1:
128 result.append(pattern)
129 break
130 return result
131
132
133 # Time: O(n^2 * l^2), n is the number of strings
134 # Space: O(1) , l is the max length of strings
135 class Solution3(object):
135 class Solution3(object):
136 def stringMatching(self, words):
137 """
138 :type words: List[str]
139 :rtype: List[str]
140 """
141 result = []
142 for i, pattern in enumerate(words):
143 for j, text in enumerate(words):
144 if i != j and pattern in text:
145 result.append(pattern)
146 break
147 return result
**********************************************

373. Minimum Value to Get Positive Step by Step Sum


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

Given an array of integers nums, you start with an initial positive value startValue.

In each iteration, you calculate the step by step sum ofstartValue plus elements in nums (from left to right).

Return the minimum positive value of startValue such that the step by step sum is never less than 1.

Example 1:

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


Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
step by step sum
startValue = 4 | startValue = 5 | nums
(4 -3 ) = 1 | (5 -3 ) = 2 | -3
(1 +2 ) = 3 | (2 +2 ) = 4 | 2
(3 -3 ) = 0 | (4 -3 ) = 1 | -3
(0 +4 ) = 4 | (1 +4 ) = 5 | 4
(4 +2 ) = 6 | (5 +2 ) = 7 | 2

Example 2:

Input: nums = [1,2]


Output: 1
Explanation: Minimum start value should be positive.

Example 3:

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


Output: 5

Constraints:

1 <= nums.length <= 100


-100 <= nums[i] <= 100
**********************************************

373. Minimum Value to Get Positive Step by Step


Sum(C++)
**********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minStartValue(vector& nums) {
7 int min_prefix = 0, prefix = 0;
8 for (const auto& num : nums) {
9 prefix += num;
10 min_prefix = min(min_prefix, prefix);
11 }
12 return 1 - min_prefix;
13 }
14 };
**********************************************

373. Minimum Value to Get Positive Step by Step


Sum(Python)
**********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minStartValue(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 min_prefix, prefix = 0, 0
11 for num in nums:
12 prefix += num
13 min_prefix = min(min_prefix, prefix)
14 return 1-min_prefix
*******************

374. Reformat The String


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

Given alphanumeric string s . (Alphanumeric string is a string consisting of lowercase English letters and digits).

You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another
digit. That is, no two adjacent characters have the same type.

Return the reformatted string or return an empty string if it is impossible to reformat the string.

Example 1:

Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.

Example 2:

Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.

Example 3:

Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.

Example 4:

Input: s = "covid2019"
Output: "c2o0v1i9d"

Example 5:

Input: s = "ab123"
Output: "1a2b3"

Constraints:

1 <= s.length <= 500


s consists of only lowercase English letters and/or digits.
*******************

374. Reformat The String(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reformat(string s) {
7 unordered_map count;
8 int alpha_cnt = 0;
9 for (const auto& c : s) {
10 ++count[c];
11 if (isalpha(c)) {
12 ++alpha_cnt;
13 }
14 }
15 if (abs(int(s.length()) - 2 * alpha_cnt) > 1) {
16 return "";
17 }
18
19 char a = 'a', a_end = 'z';
20 char b = '0', b_end = '9';
21 if (alpha_cnt < s.length() - alpha_cnt) {
22 swap(a, b);
23 swap(a_end, b_end);
24 }
25 string result;
26 while (result.length() < s.length()) {
27 result.push_back(a = next_char(a, a_end, &count));
28 result.push_back(b = next_char(b, b_end, &count));
29 }
30 if (result.back() == '\0') {
31 result.pop_back();
32 }
33 return result;
34 }
35
36 private:
37 char next_char(char start, char end, unordered_map *count) {
38 for (char c = start; c <= end; ++c) {
39 if ((*count)[c]) {
40 --(*count)[c];
41 return c;
42 }
43 }
44 return '\0';
45 }
46 };
*******************

374. Reformat The String(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def reformat(self, s):
9 """
10 :type s: str
11 :rtype: str
12 """
13 def char_gen(start, end, count):
14 for c in xrange(ord(start), ord(end)+1):
15 c = chr(c)
16 for i in xrange(count[c]):
17 yield c
18 yield ''
19
20 count = collections.defaultdict(int)
21 alpha_cnt = 0
22 for c in s:
23 count[c] += 1
24 if c.isalpha():
25 alpha_cnt += 1
26 if abs(len(s)-2*alpha_cnt) > 1:
27 return ""
28
29 result = []
30 it1, it2 = char_gen('a', 'z', count), char_gen('0', '9', count)
31 if alpha_cnt < len(s)-alpha_cnt:
32 it1, it2 = it2, it1
33 while len(result) < len(s):
34 result.append(next(it1))
35 result.append(next(it2))
36 return "".join(result)
**************************************

375. Maximum Score After Splitting a String


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

Given a string s of zeros and ones, return the maximum score after splitting the string into twonon-empty substrings (i.e.
left substring and right substring).

The score after splitting a string is the number ofzeros in the left substring plus the number of ones in the right substring.

Example 1:

Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3

Example 2:

Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5

Example 3:

Input: s = "1111"
Output: 3

Constraints:

2 <= s.length <= 500


The string s consists of characters '0' and '1' only.
**************************************

375. Maximum Score After Splitting a String(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxScore(string s) {
7 int result = 0, zeros = 0, ones = 0;
8 for (int i = 1; i + 1 < s.length(); ++i) {
9 (s[i] == '0') ? ++zeros : ++ones;
10 result = max(result, zeros - ones);
11 }
12 return result + ones + (s.front() == '0') + (s.back() == '1');
13 }
14 };
**************************************

375. Maximum Score After Splitting a String(Python)


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

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

376. Counting Elements


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

Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr,
count them separately.

Example 1:

Input: arr = [1,2,3]


Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.

Example 2:

Input: arr = [1,1,3,3,5,5,7,7]


Output: 0
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.

Example 3:

Input: arr = [1,3,2,3,5,0]


Output: 3
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.

Example 4:

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


Output: 2
Explanation: Two 1s are counted cause 2 is in arr.

Example 5:

Input: arr = [1,1,2]


Output: 2
Explanation: Both 1s are counted because 2 is in the array.

Constraints:

1 <= arr.length <= 1000


0 <= arr[i] <= 1000
*****************

376. Counting Elements(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int countElements(vector& arr) {
7 unordered_set lookup(cbegin(arr), cend(arr));
8 return count_if(cbegin(arr), cend(arr),
9 [&lookup](const auto& x) {
10 return lookup.count(x + 1);
11 });
12 }
13 };
14
15 // Time: O(nlogn)
16 // Space: O(1)
17 class Solution2 {
18 public:
19 int countElements(vector& arr) {
20 sort(begin(arr), end(arr));
21 int result = 0, l = 1;
22 for (int i = 0; i + 1 < arr.size(); ++i) {
23 if (arr[i] == arr[i + 1]) {
24 ++l;
25 continue;
26 }
27 if (arr[i] + 1 == arr[i + 1]) {
28 result += l;
29 }
30 l = 1;
31 }
32 return result;
33 }
34 };
*****************

376. Counting Elements(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def countElements(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: int
9 """
10 lookup = set(arr)
11 return sum(1 for x in arr if x+1 in lookup)
12
13
14 # Time: O(nlogn)
15 # Space: O(1)
16 class Solution(object):
17 def countElements(self, arr):
18 """
19 :type arr: List[int]
20 :rtype: int
21 """
22 arr.sort()
23 result, l = 0, 1
24 for i in xrange(len(arr)-1):
25 if arr[i] == arr[i+1]:
26 l += 1
27 continue
28 if arr[i]+1 == arr[i+1]:
29 result += l
30 l = 1
31 return result
*********************

377. Perform String Shifts


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

You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction i, amount i]:

can be 0 (for left shift) or 1 (for right shift).


directioni
amounti is the amount by which string s is to be shifted.
A left shift by 1 means remove the first character ofs and append it to the end.
Similarly, a right shift by 1 means remove the last character ofs and add it to the beginning.

Return the final string after all operations.

Example 1:

Input: s = "abc", shift = [[0,1],[1,2]]


Output: "cab"
Explanation:
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"

Example 2:

Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]


Output: "efgabcd"
Explanation:
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"

Constraints:

1 <= s.length <= 100


s only contains lower case English letters.
1 <= shift.length <= 100
shift[i].length == 2
directioni is either 0 or 1.
0 <= amounti <= 100
*********************

377. Perform String Shifts(C++)


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

1 // Time: O(n + l)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string stringShift(string s, vector>& shift) {
7 int left_shift = 0;
8 for (const auto& x : shift) {
9 if (!x[0]) {
10 left_shift += x[1];
11 } else {
12 left_shift -= x[1];
13 }
14 }
15 left_shift = ((left_shift) % int(s.length()) + int(s.length())) % int(s.length());
16 reverse(begin(s), begin(s) + left_shift);
17 reverse(begin(s) + left_shift, end(s));
18 reverse(begin(s), end(s));
19 return s;
20 }
21 };
*********************

377. Perform String Shifts(Python)


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

1 # Time: O(n + l)
2 # Space: O(l)
3
4 class Solution(object):
5 def stringShift(self, s, shift):
6 """
7 :type s: str
8 :type shift: List[List[int]]
9 :rtype: str
10 """
11 left_shifts = 0
12 for direction, amount in shift:
13 if not direction:
14 left_shifts += amount
15 else:
16 left_shifts -= amount
17 left_shifts %= len(s)
18 return s[left_shifts:] + s[:left_shifts]
****************************************

378. Kids With the Greatest Number of Candies


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

There are n kids with candies. You are given an integer arraycandies, where each candies[i] represents the number of candies
the ith kid has, and an integer extraCandies , denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies , they will have the
greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

Example 1:

Input: candies = [2,3,5,1,3], extraCandies = 3


Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.

Example 2:

Input: candies = [4,2,1,1,2], extraCandies = 1


Output: [true,false,false,false,false]
Explanation: There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.

Example 3:

Input: candies = [12,1,12], extraCandies = 10


Output: [true,false,true]

Constraints:

n == candies.length
2 <= n <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50
****************************************

378. Kids With the Greatest Number of Candies(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector kidsWithCandies(vector& candies, int extraCandies) {
7 const auto& max_num = *max_element(cbegin(candies), cend(candies));
8 vector result;
9 transform(cbegin(candies), cend(candies), back_inserter(result),
10 [&extraCandies, &max_num](const auto& x) {
11 return x + extraCandies >= max_num;
12 });
13 return result;
14 }
15 };
****************************************

378. Kids With the Greatest Number of Candies(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def kidsWithCandies(self, candies, extraCandies):
6 """
7 :type candies: List[int]
8 :type extraCandies: int
9 :rtype: List[bool]
10 """
11 max_num = max(candies)
12 return [x + extraCandies >= max_num for x in candies]
**************************

379. Create a Session Bar Chart


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

Table: Sessions

+---------------------+---------+
| Column Name | Type |
+---------------------+---------+
| session_id | int |
| duration | int |
+---------------------+---------+
session_id is the primary key for this table.
duration is the time in seconds that a user has visited the application.

You want to know how long a user visits your application. You decided to create bins of "[0-5>", "[5-10>", "[10-15>" and "15
minutes or more" and count the number of sessions on it.

Write an SQL query to report the (bin, total) inany order.

The query result format is in the following example.

Sessions table:
+-------------+---------------+
| session_id | duration |
+-------------+---------------+
| 1 | 30 |
| 2 | 199 |
| 3 | 299 |
| 4 | 580 |
| 5 | 1000 |
+-------------+---------------+

Result table:
+--------------+--------------+
| bin | total |
+--------------+--------------+
| [0-5> | 3 |
| [5-10> | 1 |
| [10-15> | 0 |
| 15 or more | 1 |
+--------------+--------------+

For session_id 1, 2 and 3 have a duration greater or equal than 0 minutes and less than 5 minutes.
For session_id 4 has a duration greater or equal than 5 minutes and less than 10 minutes.
There are no session with a duration greater or equial than 10 minutes and less than 15 minutes.
For session_id 5 has a duration greater or equal than 15 minutes.
**************************

379. Create a Session Bar Chart(Shell)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 SELECT '[0-5>' AS bin,
5 Count(1) AS total
6 FROM sessions
7 WHERE duration >= 0
8 AND duration < 300
9 UNION ALL
10 SELECT '[5-10>' AS bin,
11 Count(1) AS total
12 FROM sessions
13 WHERE duration >= 300
14 AND duration < 600
15 UNION ALL
16 SELECT '[10-15>' AS bin,
17 Count(1) AS total
18 FROM sessions
19 WHERE duration >= 600
20 AND duration < 900
21 UNION ALL
22 SELECT '15 or more' AS bin,
23 Count(1) AS total
24 FROM sessions
25 WHERE duration >= 900;
26
27 # Time: O(n)
28 # Space: O(n)
29 SELECT
30 t2.BIN,
31 COUNT(t1.BIN) AS TOTAL
32 FROM (
33 SELECT
34 CASE
35 WHEN duration/60 BETWEEN 0 AND 5 THEN "[0-5>"
36 WHEN duration/60 BETWEEN 5 AND 10 THEN "[5-10>"
37 WHEN duration/60 BETWEEN 10 AND 15 THEN "[10-15>"
38 WHEN duration/60 >= 15 THEN "15 or more"
39 ELSE NULL END AS BIN
40 FROM Sessions
41 ) t1
42 RIGHT JOIN(
43 SELECT "[0-5>" AS BIN
44 UNION ALL
45 SELECT "[5-10>" AS BIN
46 UNION ALL
47 SELECT "[10-15>" AS BIN
48 UNION ALL
49 SELECT "15 or more" AS BIN
50 ) t2
51 ON t1.bin = t2.bin
52 GROUP BY t2.bin
53 ORDER BY NULL;
****************

380. Destination City


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

You are given the array paths, where paths[i] = [cityA i, cityB i] means there exists a direct path going fromcityAi to cityBi. Return the
destination city, that is, the city without any path outgoing to another city.

It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

Example 1:

Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]


Output: "Sao Paulo"
Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New

Example 2:

Input: paths = [["B","C"],["D","B"],["C","A"]]


Output: "A"
Explanation: All possible trips are:
"D" -> "B" -> "C" -> "A".
"B" -> "C" -> "A".
"C" -> "A".
"A".
Clearly the destination city is "A".

Example 3:

Input: paths = [["A","Z"]]


Output: "Z"

Constraints:

1 <= paths.length <= 100


paths[i].length == 2
1 <= cityAi.length, cityB i.length <= 10
cityAi != cityB i
All strings consist of lowercase and uppercase English letters and the space character.
****************

380. Destination City(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 string destCity(vector>& paths) {
7 unordered_set A, B;
8 for (const auto& path : paths) {
9 A.emplace(path[0]);
10 B.emplace(path[1]);
11 }
12 for (const auto& dst : B) {
13 if (!A.count(dst)) {
14 return dst;
15 }
16 }
17 return "";
18 }
19 };
****************

380. Destination City(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 import itertools
5
6
7 class Solution(object):
8 def destCity(self, paths):
9 """
10 :type paths: List[List[str]]
11 :rtype: str
12 """
13 A, B = map(set, itertools.izip(*paths))
14 return (B-A).pop()
************************************

381. Build an Array With Stack Operations


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

Given an array target and an integer n. In each iteration, you will read a number from list = {1,2,3..., n} .

Build the target array using the following operations:

Push: Read a new element from the beginning list, and push it in the array.
Pop: delete the last element of the array.
If the target array is already built, stop reading more elements.

Return the operations to build the target array. You are guaranteed that the answer is unique.

Example 1:

Input: target = [1,3], n = 3


Output: ["Push","Push","Pop","Push"]
Explanation:
Read number 1 and automatically push in the array -> [1]
Read number 2 and automatically push in the array then Pop it -> [1]
Read number 3 and automatically push in the array -> [1,3]

Example 2:

Input: target = [1,2,3], n = 3


Output: ["Push","Push","Push"]

Example 3:

Input: target = [1,2], n = 4


Output: ["Push","Push"]
Explanation: You only need to read the first 2 numbers and stop.

Example 4:

Input: target = [2,3,4], n = 4


Output: ["Push","Pop","Push","Push","Push"]

Constraints:

1 <= target.length <= 100


1 <= target[i] <= n
1 <= n <= 100
target is strictly increasing.
************************************

381. Build an Array With Stack Operations(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector buildArray(vector& target, int n) {
7 vector result;
8 int curr = 1;
9 for (const auto& t : target) {
10 for (int i = curr; i < t; ++i) {
11 result.emplace_back("Push");
12 result.emplace_back("Pop");
13 }
14 result.emplace_back("Push");
15 curr = t + 1;
16 }
17 return result;
18 }
19 };
************************************

381. Build an Array With Stack Operations(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def buildArray(self, target, n):
6 """
7 :type target: List[int]
8 :type n: int
9 :rtype: List[str]
10 """
11 result, curr = [], 1
12 for t in target:
13 result.extend(["Push", "Pop"]*(t-curr))
14 result.append("Push")
15 curr = t+1
16 return result
**********************

382. Consecutive Characters


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

The power of the string is the maximum length of a non-empty substring that contains only one unique character.

Given a string s , return the power of s .

Example 1:

Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Example 3:

Input: s = "triplepillooooow"
Output: 5

Example 4:

Input: s = "hooraaaaaaaaaaay"
Output: 11

Example 5:

Input: s = "tourist"
Output: 1

Constraints:

1 <= s.length <= 500


s consists of only lowercase English letters.
**********************

382. Consecutive Characters(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxPower(string s) {
7 int result = 1, count = 1;
8 for (int i = 1; i < s.length(); ++i) {
9 if (s[i] == s[i - 1]) {
10 ++count;
11 } else {
12 count = 1;
13 }
14 result = max(result, count);
15 }
16 return result;
17 }
18 };
**********************

382. Consecutive Characters(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxPower(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result, count = 1, 1
11 for i in xrange(1, len(s)):
12 if s[i] == s[i-1]:
13 count += 1
14 else:
15 count = 1
16 result = max(result, count)
17 return result
18
19
20 # Time: O(n)
21 # Space: O(n)
22 import itertools
23
24
25 class Solution2(object):
26 def maxPower(self, s):
27 return max(len(list(v)) for _, v in itertools.groupby(s))
*************************************************

383. Number of Students Doing Homework at a Given


Time
*************************************************

Given two integer arrays startTime and endTime and given an integer queryTime.

The ith student started doing their homework at the timestartTime[i] and finished it at time endTime[i].

Return the number of students doing their homework at time queryTime. More formally, return the number of students where
queryTime lays in the interval [startTime[i], endTime[i]] inclusive.

Example 1:

Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4


Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.

Example 2:

Input: startTime = [4], endTime = [4], queryTime = 4


Output: 1
Explanation: The only student was doing their homework at the queryTime.

Example 3:

Input: startTime = [4], endTime = [4], queryTime = 5


Output: 0

Example 4:

Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7


Output: 0

Example 5:

Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5


Output: 5

Constraints:

startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
*************************************************

383. Number of Students Doing Homework at a Given


Time(C++)
*************************************************

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

383. Number of Students Doing Homework at a Given


Time(Python)
*************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def busyStudent(self, startTime, endTime, queryTime):
9 """
10 :type startTime: List[int]
11 :type endTime: List[int]
12 :type queryTime: int
13 :rtype: int
14 """
15 return sum(s <= queryTime <= e for s, e in itertools.izip(startTime, endTime))
************************************************************

384. Check If a Word Occurs As a Prefix of Any Word in a


Sentence
************************************************************

Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of
any word in sentence.

Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more
than one word, return the index of the first word (minimum index). If there is no such word return -1.

A prefix of a string s is any leading contiguous substring of s .

Example 1:

Input: sentence = "i love eating burger", searchWord = "burg"


Output: 4
Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.

Example 2:

Input: sentence = "this problem is an easy problem", searchWord = "pro"


Output: 2
Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.

Example 3:

Input: sentence = "i am tired", searchWord = "you"


Output: -1
Explanation: "you" is not a prefix of any word in the sentence.

Example 4:

Input: sentence = "i use triple pillow", searchWord = "pill"


Output: 4

Example 5:

Input: sentence = "hello from the other side", searchWord = "they"


Output: -1

Constraints:

1 <= sentence.length <= 100


1 <= searchWord.length <= 10
sentence consists of lowercase English letters and spaces.
searchWord consists of lowercase English letters.
************************************************************

384. Check If a Word Occurs As a Prefix of Any Word in a


Sentence(C++)
************************************************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int isPrefixOfWord(string sentence, string searchWord) {
7 if (sentence.compare(0, searchWord.size(), searchWord) == 0) {
8 return 1;
9 }
10 searchWord = " " + searchWord;
11 auto p = KMP(sentence, searchWord);
12 if (p == -1) {
13 return -1;
14 }
15 return 1 + accumulate(cbegin(sentence), cbegin(sentence) + p + 1, 0,
16 [](const auto& a, const auto& b) {
17 return a + (b == ' ');
18 });
19 }
20
21 private:
22 int KMP(const string& text, const string& pattern) {
23 const vector prefix = getPrefix(pattern);
24 int j = -1;
25 for (int i = 0; i < text.length(); ++i) {
26 while (j > -1 && pattern[j + 1] != text[i]) {
27 j = prefix[j];
28 }
29 if (pattern[j + 1] == text[i]) {
30 ++j;
31 }
32 if (j == pattern.length() - 1) {
33 return i - j;
34 }
35 }
36 return -1;
37 }
38
39 vector getPrefix(const string& pattern) {
40 vector prefix(pattern.length(), -1);
41 int j = -1;
42 for (int i = 1; i < pattern.length(); ++i) {
43 while (j > -1 && pattern[j + 1] != pattern[i]) {
44 j = prefix[j];
45 }
46 if (pattern[j + 1] == pattern[i]) {
47 ++j;
48 }
49 prefix[i] = j;
50 }
51 return prefix;
52 }
53 };
************************************************************

384. Check If a Word Occurs As a Prefix of Any Word in a


Sentence(Python)
************************************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def isPrefixOfWord(self, sentence, searchWord):
6 """
7 :type sentence: str
8 :type searchWord: str
9 :rtype: int
10 """
11 def KMP(text, pattern):
12 def getPrefix(pattern):
13 prefix = [-1] * len(pattern)
14 j = -1
15 for i in xrange(1, len(pattern)):
16 while j > -1 and pattern[j + 1] != pattern[i]:
17 j = prefix[j]
18 if pattern[j + 1] == pattern[i]:
19 j += 1
20 prefix[i] = j
21 return prefix
22
23 prefix = getPrefix(pattern)
24 j = -1
25 for i in xrange(len(text)):
26 while j != -1 and pattern[j+1] != text[i]:
27 j = prefix[j]
28 if pattern[j+1] == text[i]:
29 j += 1
30 if j+1 == len(pattern):
31 return i-j
32 return -1
33
34 if sentence.startswith(searchWord):
35 return 1
36 p = KMP(sentence, ' ' + searchWord)
37 if p == -1:
38 return -1
39 return 1+sum(sentence[i] == ' ' for i in xrange(p+1))
*********************************************

385. Make Two Arrays Equal by Reversing Sub-arrays


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

Given two integer arrays of equal length target and arr.

In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.

Return True if you can make arr equal to target, or False otherwise.

Example 1:

Input: target = [1,2,3,4], arr = [2,4,1,3]


Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.

Example 2:

Input: target = [7], arr = [7]


Output: true
Explanation: arr is equal to target without any reverses.

Example 3:

Input: target = [1,12], arr = [12,1]


Output: true

Example 4:

Input: target = [3,7,9], arr = [3,7,11]


Output: false
Explanation: arr doesn't have value 9 and it can never be converted to target.

Example 5:

Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]


Output: true

Constraints:

target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
*********************************************

385. Make Two Arrays Equal by Reversing Sub-


arrays(C++)
*********************************************

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool canBeEqual(vector& target, vector& arr) {
7 return counter(target) == counter(arr);
8 }
9
10 private:
11 unordered_map counter(const vector& arr) {
12 unordered_map count;
13 for (const auto& x : arr) {
14 ++count[x];
15 }
16 return count;
17 }
18 };
19
20 // Time: O(nlogn)
21 // Space: O(1)
22 class Solution2 {
23 public:
24 bool canBeEqual(vector& target, vector& arr) {
25 sort(begin(target), end(target));
26 sort(begin(arr), end(arr));
27 return target == arr;
28 }
29 };
*********************************************

385. Make Two Arrays Equal by Reversing Sub-


arrays(Python)
*********************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def canBeEqual(self, target, arr):
9 """
10 :type target: List[int]
11 :type arr: List[int]
12 :rtype: bool
13 """
14 return collections.Counter(target) == collections.Counter(arr)
15
16
17 # Time: O(nlogn)
18 # Space: O(1)
19 class Solution2(object):
20 def canBeEqual(self, target, arr):
21 """
22 :type target: List[int]
23 :type arr: List[int]
24 :rtype: bool
25 """
26 target.sort(), arr.sort()
27 return target == arr
*******************************************

386. Maximum Product of Two Elements in an Array


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

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of
(nums[i]-1)*(nums[j]-1) .

Example 1:

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


Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)

Example 2:

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


Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

Input: nums = [3,7]


Output: 12

Constraints:

2 <= nums.length <= 500


1 <= nums[i] <= 10^3
*******************************************

386. Maximum Product of Two Elements in an Array(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxProduct(vector& nums) {
7 int m1 = 0, m2 = 0;
8 for (const auto& num : nums) {
9 if (num > m1) {
10 m2 = m1;
11 m1 = num;
12 } else if (num > m2) {
13 m2 = num;
14 }
15 }
16 return (m1 - 1) * (m2 - 1);
17 }
18 };
*******************************************

386. Maximum Product of Two Elements in an


Array(Python)
*******************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxProduct(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 m1 = m2 = 0
11 for num in nums:
12 if num > m1:
13 m1, m2 = num, m1
14 elif num > m2:
15 m2 = num
16 return (m1-1)*(m2-1)
******************

387. Calculate Salaries


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

Table Salaries:

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| company_id | int |
| employee_id | int |
| employee_name | varchar |
| salary | int |
+---------------+---------+
(company_id, employee_id) is the primary key for this table.
This table contains the company id, the id, the name and the salary for an employee.

Write an SQL query to find the salaries of the employees after applying taxes.

The tax rate is calculated for each company based on the following criteria:

0% If the max salary of any employee in the company is less than 1000$.
24% If the max salary of any employee in the company is in the range [1000, 10000] inclusive.
49% If the max salary of any employee in the company is greater than 10000$.

Return the result table in any order. Round the salary to the nearest integer.

The query result format is in the following example:


Salaries table:
+------------+-------------+---------------+--------+
| company_id | employee_id | employee_name | salary |
+------------+-------------+---------------+--------+
| 1 | 1 | Tony | 2000 |
| 1 | 2 | Pronub | 21300 |
| 1 | 3 | Tyrrox | 10800 |
| 2 | 1 | Pam | 300 |
| 2 | 7 | Bassem | 450 |
| 2 | 9 | Hermione | 700 |
| 3 | 7 | Bocaben | 100 |
| 3 | 2 | Ognjen | 2200 |
| 3 | 13 | Nyancat | 3300 |
| 3 | 15 | Morninngcat | 7777 |
+------------+-------------+---------------+--------+

Result table:
+------------+-------------+---------------+--------+
| company_id | employee_id | employee_name | salary |
+------------+-------------+---------------+--------+
| 1 | 1 | Tony | 1020 |
| 1 | 2 | Pronub | 10863 |
| 1 | 3 | Tyrrox | 5508 |
| 2 | 1 | Pam | 300 |
| 2 | 7 | Bassem | 450 |
| 2 | 9 | Hermione | 700 |
| 3 | 7 | Bocaben | 76 |
| 3 | 2 | Ognjen | 1672 |
| 3 | 13 | Nyancat | 2508 |
| 3 | 15 | Morninngcat | 5911 |
+------------+-------------+---------------+--------+
For company 1, Max salary is 21300. Employees in company 1 have taxes = 49%
For company 2, Max salary is 700. Employees in company 2 have taxes = 0%
For company 3, Max salary is 7777. Employees in company 3 have taxes = 24%
The salary after taxes = salary - (taxes percentage / 100) * salary
For example, Salary for Morninngcat (3, 15) after taxes = 7777 - 7777 * (24 / 100) = 7777 - 1866.48 = 5910.52, which is rounded to 5911.
******************

387. Calculate Salaries(Shell)


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

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 SELECT s.company_id,
5 s.employee_id,
6 s.employee_name,
7 ROUND(s.salary * t.rate) salary
8 FROM Salaries s
9 INNER JOIN
10 (SELECT company_id,
11 CASE
12 WHEN MAX(salary) < 1000 THEN 1.0
13 WHEN MAX(salary) <= 10000 THEN 0.76
14 ELSE 0.51
15 END AS rate
16 FROM Salaries
17 GROUP BY company_id
18 ORDER BY NULL) t ON s.company_id = t.company_id;
19
*************************

388. Find All The Lonely Nodes


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

In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely because it
does not have a parent node.

Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any
order.

Example 1:

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


Output: [4]
Explanation: Light blue node is the only lonely node.
Node 1 is the root and is not lonely.
Nodes 2 and 3 have the same parent and are not lonely.

Example 2:

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


Output: [6,2]
Explanation: Light blue nodes are lonely nodes.
Please remember that order doesn't matter, [2,6] is also an acceptable answer.

Example 3:
Input: root = [11,99,88,77,null,null,66,55,null,null,44,33,null,null,22]
Output: [77,55,33,66,44,22]
Explanation: Nodes 99 and 88 share the same parent. Node 11 is the root.
All other nodes are lonely.

Example 4:

Input: root = [197]


Output: []

Example 5:

Input: root = [31,null,78,null,28]


Output: [78,28]

Constraints:

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


Each node's value is between [1, 10^6].
*************************

388. Find All The Lonely Nodes(C++)


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

1 // Time: O(n)
2 // Space: O(h)
3
4 /**
5 * Definition for a binary tree node.
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode() : 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 vector getLonelyNodes(TreeNode* root) {
18 vector result;
19 vector stk = {root};
20 while (!stk.empty()) {
21 auto node = stk.back(); stk.pop_back();
22 if (!node) {
23 continue;
24 }
25 if (node->left && !node->right) {
26 result.emplace_back(node->left->val);
27 } else if (node->right && !node->left) {
28 result.emplace_back(node->right->val);
29 }
30 stk.emplace_back(node->right);
31 stk.emplace_back(node->left);
32 }
33 return result;
34 }
35 };
36
37 // Time: O(n)
38 // Space: O(h)
39 class Solution2 {
40 public:
41 vector getLonelyNodes(TreeNode* root) {
42 vector result;
43 dfs(root, &result);
44 return result;
45 }
46
47 private:
48 void dfs(TreeNode *node, vector *result) {
49 if (!node) {
50 return;
51 }
52 if (node->left && !node->right) {
53 result->emplace_back(node->left->val);
54 } else if (node->right && !node->left) {
55 result->emplace_back(node->right->val);
56 }
57 dfs(node->left, result);
58 dfs(node->right, result);
59 }
60 };
*************************

388. Find All The Lonely Nodes(Python)


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

1 # Time: O(n)
2 # Space: O(h)
3
4 # Definition for a binary tree node.
5 class TreeNode(object):
6 def __init__(self, val=0, left=None, right=None):
7 self.val = val
8 self.left = left
9 self.right = right
10
11
12 class Solution(object):
13 def getLonelyNodes(self, root):
14 """
15 :type root: TreeNode
16 :rtype: List[int]
17 """
18 result = []
19 stk = [root]
20 while stk:
21 node = stk.pop()
22 if not node:
23 continue
24 if node.left and not node.right:
25 result.append(node.left.val)
26 elif node.right and not node.left:
27 result.append(node.right.val)
28 stk.append(node.right)
29 stk.append(node.left)
30 return result
31
32
33 # Time: O(n)
34 # Space: O(h)
35 class Solution2(object):
36 def getLonelyNodes(self, root):
37 """
38 :type root: TreeNode
39 :rtype: List[int]
40 """
41 def dfs(node, result):
42 if not node:
43 return
44 if node.left and not node.right:
45 result.append(node.left.val)
46 elif node.right and not node.left:
47 result.append(node.right.val)
48 dfs(node.left, result)
49 dfs(node.right, result)
50
51 result = []
52 dfs(root, result)
53 return result
*****************

389. Shuffle the Array


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

Given the array nums consisting of 2n elements in the form [x1,x2,...,x n,y1,y2,...,y n].

Return the array in the form [x1,y1,x2,y2,...,x n,yn].

Example 1:

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


Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

Example 2:

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


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

Example 3:

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


Output: [1,2,1,2]

Constraints:

1 <= n <= 500


nums.length == 2n
1 <= nums[i] <= 10^3
*****************

389. Shuffle the Array(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector shuffle(vector& nums, int n) {
7 static const auto& dest = [](int i, int n) {
8 return (i < n) ? 2 * i : 2 * (i - n) + 1;
9 };
10 for (int i = 0; i < nums.size(); ++i) {
11 if (nums[i] < 0) {
12 continue;
13 }
14 int j = i;
15 do {
16 j = dest(j, n);
17 swap(nums[i], nums[j]);
18 nums[j] = -nums[j];
19 } while (j != i);
20 }
21 for (auto& num : nums) {
22 num = -num;
23 }
24 return nums;
25 }
26 };
*****************

389. Shuffle the Array(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def shuffle(self, nums, n):
6 """
7 :type nums: List[int]
8 :type n: int
9 :rtype: List[int]
10 """
11 def dest(i, n):
12 return 2*i if i < n else 2*(i-n)+1
13
14 for i in xrange(len(nums)):
15 if nums[i] < 0:
16 continue
17 j = i
18 while True:
19 j = dest(j, n)
20 nums[i], nums[j] = nums[j], nums[i]
21 nums[j] = -nums[j]
22 if i == j:
23 break
24 for i in xrange(len(nums)):
25 nums[i] = -nums[i]
26 return nums
*********************************************

390. Delete N Nodes After M Nodes of a Linked List


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

Given the head of a linked list and two integers m and n. Traverse the linked list and remove some nodes in the following way:

Start with the head as the current node.


Keep the first m nodes starting with the current node.
Remove the next n nodes
Keep repeating steps 2 and 3 until you reach the end of the list.

Return the head of the modified list after removing the mentioned nodes.

Follow up question: How can you solve this problem by modifying the list in-place?

Example 1:

Input: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3


Output: [1,2,6,7,11,12]
Explanation: Keep the first (m = 2) nodes starting from the head of the linked List (1 ->2) show in black nodes.
Delete the next (n = 3) nodes (3 -> 4 -> 5) show in read nodes.
Continue with the same procedure until reaching the tail of the Linked List.
Head of linked list after removing nodes is returned.

Example 2:

Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 1, n = 3


Output: [1,5,9]
Explanation: Head of linked list after removing nodes is returned.

Example 3:

Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 3, n = 1


Output: [1,2,3,5,6,7,9,10,11]

Example 4:

Input: head = [9,3,7,7,9,10,8,2], m = 1, n = 2


Output: [9,7,8]
Constraints:

The given linked list will contain between 1 and 10^4 nodes.
The value of each node in the linked list will be in the range[1, 10^6].
1 <= m,n <= 1000
*********************************************

390. Delete N Nodes After M Nodes of a Linked List(C++)


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

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

390. Delete N Nodes After M Nodes of a Linked


List(Python)
*********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 # Definition for singly-linked list.
5 class ListNode(object):
6 def __init__(self, val=0, next=None):
7 self.val = val
8 self.next = next
9
10
11 class Solution(object):
12 def deleteNodes(self, head, m, n):
13 """
14 :type head: ListNode
15 :type m: int
16 :type n: int
17 :rtype: ListNode
18 """
19 head = dummy = ListNode(next=head)
20 while head:
21 for _ in xrange(m):
22 if not head.next:
23 return dummy.next
24 head = head.next
25 prev = head
26 for _ in xrange(n):
27 if not head.next:
28 prev.next = None
29 return dummy.next
30 head = head.next
31 prev.next = head.next
32 return dummy.next
**********************************************

391. Final Prices With a Special Discount in a Shop


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

Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if
you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and
prices[j] <= prices[i] , otherwise, you will not receive any discount at all.

Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special
discount.

Example 1:

Input: prices = [8,4,6,2,3]


Output: [4,2,4,2,3]
Explanation:
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.
For items 3 and 4 you will not receive any discount at all.

Example 2:

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


Output: [1,2,3,4,5]
Explanation: In this case, for all items, you will not receive any discount at all.

Example 3:

Input: prices = [10,1,1,6]


Output: [9,0,1,6]

Constraints:

1 <= prices.length <= 500


1 <= prices[i] <= 10^3
**********************************************

391. Final Prices With a Special Discount in a Shop(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector finalPrices(vector& prices) {
7 vector stk;
8 for (int i = 0; i < prices.size(); ++i) {
9 while (!stk.empty() && prices[stk.back()] >= prices[i]) {
10 prices[stk.back()] -= prices[i];
11 stk.pop_back();
12 }
13 stk.emplace_back(i);
14 }
15 return prices;
16 }
17 };
**********************************************

391. Final Prices With a Special Discount in a


Shop(Python)
**********************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def finalPrices(self, prices):
6 """
7 :type prices: List[int]
8 :rtype: List[int]
9 """
10 stk = []
11 for i, p in enumerate(prices):
12 while stk and prices[stk[-1]] >= p:
13 prices[stk.pop()] -= p
14 stk.append(i)
15 return prices
***********************

392. Running Sum of 1d Array


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

Given an array nums. We define a running sum of an array asrunningSum[i] = sum(nums[0]…nums[i]) .

Return the running sum of nums.

Example 1:

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


Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:

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


Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:

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


Output: [3,4,6,16,17]

Constraints:

1 <= nums.length <= 1000


-10^6 <= nums[i] <= 10^6
***********************

392. Running Sum of 1d Array(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector runningSum(vector& nums) {
7 partial_sum(begin(nums), end(nums), begin(nums));
8 return nums;
9 }
10 };
***********************

392. Running Sum of 1d Array(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def runningSum(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: List[int]
9 """
10 for i in xrange(len(nums)-1):
11 nums[i+1] += nums[i]
12 return nums
*******************************

393. Group Sold Products By The Date


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

Table Activities:

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| sell_date | date |
| product | varchar |
+-------------+---------+
There is no primary key for this table, it may contains duplicates.
Each row of this table contains the product name and the date it was sold in a market.

Write an SQL query to find for each date, the number of distinct products sold and their names.

The sold-products names for each date should be sorted lexicographically.

Return the result table ordered by sell_date.

The query result format is in the following example.

Activities table:
+------------+-------------+
| sell_date | product |
+------------+-------------+
| 2020-05-30 | Headphone |
| 2020-06-01 | Pencil |
| 2020-06-02 | Mask |
| 2020-05-30 | Basketball |
| 2020-06-01 | Bible |
| 2020-06-02 | Mask |
| 2020-05-30 | T-Shirt |
+------------+-------------+

Result table:
+------------+----------+------------------------------+
| sell_date | num_sold | products |
+------------+----------+------------------------------+
| 2020-05-30 | 3 | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2 | Bible,Pencil |
| 2020-06-02 | 1 | Mask |
+------------+----------+------------------------------+
For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by comma.
For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by comma.
For 2020-06-02, Sold item is (Mask), we just return it.
*******************************

393. Group Sold Products By The Date(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT sell_date,
5 COUNT(DISTINCT(product)) AS num_sold,
6 GROUP_CONCAT(DISTINCT product ORDER BY product ASC SEPARATOR ',') AS products
7 FROM Activities
8 GROUP BY sell_date
9 ORDER BY sell_date ASC;
*************************

394. XOR Operation in an Array


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

Given an integer n and an integer start.

Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length .

Return the bitwise XOR of all elements of nums.

Example 1:

Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.

Example 2:

Input: n = 4, start = 3
Output: 8
Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.

Example 3:

Input: n = 1, start = 7
Output: 7

Example 4:

Input: n = 10, start = 5


Output: 2

Constraints:

1 <= n <= 1000


0 <= start <= 1000
n == nums.length
*************************

394. XOR Operation in an Array(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int xorOperation(int n, int start) {
7 return int(n % 2 && start % 2) + 2 * xorNums(n, start / 2);
8 }
9
10 private:
11 int xorNums(int n, int start) {
12 return (start % 2)
13 ? start ^ xorNumsBeginEven(n - 1, start + 1)
14 : xorNumsBeginEven(n, start);
15 }
16
17 int xorNumsBeginEven(int n, int start) {
18 assert(start % 2 == 0);
19 // 2*i ^ (2*i+1) = 1
20 return ((n / 2) % 2) ^ ((n % 2) ? (start + n - 1) : 0);
21 }
22 };
23
24 // Time: O(n)
25 // Space: O(1)
26 class Solution2 {
27 public:
28 int xorOperation(int n, int start) {
29 int result = 0;
30 for (int i = start + 2 * n - 2; i >= start; i -= 2) {
31 result ^= i;
32 }
33 return result;
34 }
35 };
*************************

394. XOR Operation in an Array(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def xorOperation(self, n, start):
6 """
7 :type n: int
8 :type start: int
9 :rtype: int
10 """
11 def xorNums(n, start):
12 def xorNumsBeginEven(n, start):
13 assert(start%2 == 0)
14 # 2*i ^ (2*i+1) = 1
15 return ((n//2)%2)^((start+n-1) if n%2 else 0)
16
17 return start^xorNumsBeginEven(n-1, start+1) if start%2 else xorNumsBeginEven(n, start)
18
19 return int(n%2 and start%2) + 2*xorNums(n, start//2)
20
21
22 # Time: O(n)
23 # Space: O(1)
24 import operator
25
26
27 class Solution2(object):
28 def xorOperation(self, n, start):
29 """
30 :type n: int
31 :type start: int
32 :rtype: int
33 """
34 return reduce(operator.xor, (i for i in xrange(start, start+2*n, 2)))
*******************************************************

395. Average Salary Excluding the Minimum and


Maximum Salary
*******************************************************

Given an array of unique integers salary where salary[i] is the salary of the employee i.

Return the average salary of employees excluding the minimum and maximum salary.

Example 1:

Input: salary = [4000,3000,1000,2000]


Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500

Example 2:

Input: salary = [1000,2000,3000]


Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000)/1= 2000

Example 3:

Input: salary = [6000,5000,4000,3000,2000,1000]


Output: 3500.00000

Example 4:

Input: salary = [8000,9000,2000,3000,6000,1000]


Output: 4750.00000

Constraints:

3 <= salary.length <= 100


10^3 <= salary[i] <= 10^6
salary[i] is unique.
Answers within 10^-5 of the actual value will be accepted as correct.
*******************************************************

395. Average Salary Excluding the Minimum and


Maximum Salary(C++)
*******************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 // one-pass solution
5 class Solution {
6 public:
7 double average(vector& salary) {
8 int total = 0;
9 int mi = numeric_limits::max(), ma = numeric_limits::min();
10 for (const auto& s : salary) {
11 total += s;
12 mi = min(mi, s), ma = max(ma, s);
13 }
14 return double(total - mi - ma) / (salary.size() - 2);
15 }
16 };
17
18 // Time: O(n)
19 // Space: O(1)
20 // one-liner solution
21 class Solution2 {
22 public:
23 double average(vector& salary) {
24 return (accumulate(cbegin(salary), cend(salary), 0.0) -
25 *min_element(cbegin(salary), cend(salary)) -
26 *max_element(cbegin(salary), cend(salary)))
27 / (salary.size() - 2);
28 }
29 };
*******************************************************

395. Average Salary Excluding the Minimum and


Maximum Salary(Python)
*******************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 # one pass solution
5 class Solution(object):
6 def average(self, salary):
7 """
8 :type salary: List[int]
9 :rtype: float
10 """
11 total, mi, ma = 0, float("inf"), float("-inf")
12 for s in salary:
13 total += s
14 mi, ma = min(mi, s), max(ma, s)
15 return 1.0*(total-mi-ma)/(len(salary)-2)
16
17
18 # Time: O(n)
19 # Space: O(1)
20 # one-liner solution
21 class Solution2(object):
22 def average(self, salary):
23 """
24 :type salary: List[int]
25 :rtype: float
26 """
27 return 1.0*(sum(salary)-min(salary)-max(salary))/(len(salary)-2)
***********************************

396. Friendly Movies Streamed Last Month


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

Table: TVProgram

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| program_date | date |
| content_id | int |
| channel | varchar |
+---------------+---------+
(program_date, content_id) is the primary key for this table.
This table contains information of the programs on the TV.
content_id is the id of the program in some channel on the TV.

Table: Content

+------------------+---------+
| Column Name | Type |
+------------------+---------+
| content_id | varchar |
| title | varchar |
| Kids_content | enum |
| content_type | varchar |
+------------------+---------+
content_id is the primary key for this table.
Kids_content is an enum that takes one of the values ('Y', 'N') where:
'Y' means is content for kids otherwise 'N' is not content for kids.
content_type is the category of the content as movies, series, etc.

Write an SQL query to report the distinct titles of the kid-friendly movies streamed in June 2020.

Return the result table in any order.

The query result format is in the following example.


TVProgram table:
+--------------------+--------------+-------------+
| program_date | content_id | channel |
+--------------------+--------------+-------------+
| 2020-06-10 08:00 | 1 | LC-Channel |
| 2020-05-11 12:00 | 2 | LC-Channel |
| 2020-05-12 12:00 | 3 | LC-Channel |
| 2020-05-13 14:00 | 4 | Disney Ch |
| 2020-06-18 14:00 | 4 | Disney Ch |
| 2020-07-15 16:00 | 5 | Disney Ch |
+--------------------+--------------+-------------+

Content table:
+------------+----------------+---------------+---------------+
| content_id | title | Kids_content | content_type |
+------------+----------------+---------------+---------------+
| 1 | Leetcode Movie | N | Movies |
| 2 | Alg. for Kids | Y | Series |
| 3 | Database Sols | N | Series |
| 4 | Aladdin | Y | Movies |
| 5 | Cinderella | Y | Movies |
+------------+----------------+---------------+---------------+

Result table:
+--------------+
| title |
+--------------+
| Aladdin |
+--------------+
"Leetcode Movie" is not a content for kids.
"Alg. for Kids" is not a movie.
"Database Sols" is not a movie
"Alladin" is a movie, content for kids and was streamed in June 2020.
"Cinderella" was not streamed in June 2020.
***********************************

396. Friendly Movies Streamed Last Month(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT DISTINCT title
5 FROM content ctt
6 INNER JOIN TVProgram tv
7 ON ctt.content_id = tv.content_id
8 WHERE content_type = 'Movies'
9 AND Kids_content = 'Y'
10 AND program_date BETWEEN '2020-06-01' AND '2020-06-30';
*************

397. Path Crossing


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

Given a string path, where path[i] = 'N' , 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively.
You start at the origin (0, 0) on a 2D plane and walk on the path specified bypath.

Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited
.
Return false otherwise.

Example 1:

Input: path = "NES"


Output: false
Explanation: Notice that the path doesn't cross any point more than once.

Example 2:
Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.

Constraints:

1 <= path.length <= 10 4


path[i] is either 'N', 'S' , 'E' , or 'W'.
*************

397. Path Crossing(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool isPathCrossing(string path) {
7 unordered_set, PairHash> lookup = {{0, 0}};
8 int x = 0, y = 0;
9 for (const auto& c : path) {
10 switch(c) {
11 case 'E':
12 ++x;
13 break;
14 case 'W':
15 --x;
16 break;
17 case 'N':
18 ++y;
19 break;
20 case 'S':
21 --y;
22 break;
23 }
24 if (!lookup.emplace(x, y).second) {
25 return true;
26 }
27 }
28 return false;
29 }
30
31 private:
32 template
33 struct PairHash {
34 size_t operator()(const pair& p) const {
35 size_t seed = 0;
36 seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
37 seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
38 return seed;
39 }
40 };
41 };
*************

397. Path Crossing(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def isPathCrossing(self, path):
6 """
7 :type path: str
8 :rtype: bool
9 """
10 x = y = 0
11 lookup = {(0, 0)}
12 for c in path:
13 if c == 'E':
14 x += 1
15 elif c == 'W':
16 x -= 1
17 elif c == 'N':
18 y += 1
19 elif c == 'S':
20 y -= 1
21 if (x, y) in lookup:
22 return True
23 lookup.add((x, y))
24 return False
*********************************************

398. Can Make Arithmetic Progression From Sequence


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

A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the
same.

Given an array of numbers arr, return true if the array can be rearranged to form anarithmetic progression. Otherwise,
return false.

Example 1:

Input: arr = [3,5,1]


Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.

Example 2:

Input: arr = [1,2,4]


Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.

Constraints:

2 <= arr.length <= 1000


-106 <= arr[i] <= 10 6
*********************************************

398. Can Make Arithmetic Progression From


Sequence(C++)
*********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool canMakeArithmeticProgression(vector& arr) {
7 const auto m = *min_element(cbegin(arr), cend(arr));
8 const auto& d = (*max_element(cbegin(arr), cend(arr)) - m) / (arr.size() - 1);
9 if (!d) {
10 return true;
11 }
12 for (int i = 0; i < arr.size();) {
13 if (arr[i] == m + i * d) {
14 ++i;
15 } else {
16 const auto& diff = arr[i] - m;
17 if (diff % d || diff / d >= arr.size() || arr[i] == arr[diff / d]) {
18 return false;
19 }
20 swap(arr[i], arr[diff / d]);
21 }
22 }
23 return true;
24 }
25 };
*********************************************

398. Can Make Arithmetic Progression From


Sequence(Python)
*********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def canMakeArithmeticProgression(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: bool
9 """
10 m = min(arr)
11 d = (max(arr)-m)//(len(arr)-1)
12 if not d:
13 return True
14 i = 0
15 while i < len(arr):
16 if arr[i] == m+i*d:
17 i += 1
18 else:
19 j, r = divmod(arr[i]-m, d)
20 if r or j >= len(arr) or arr[i] == arr[j]:
21 return False
22 arr[i], arr[j] = arr[j], arr[i]
23 return True
*************

399. Reformat Date


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

Given a date string in the form Day Month Year, where:

Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"} .
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} .
Year is in the range [1900, 2100].

Convert the date string to the formatYYYY-MM-DD, where:

YYYY denotes the 4 digit year.


MM denotes the 2 digit month.
DD denotes the 2 digit day.

Example 1:

Input: date = "20th Oct 2052"


Output: "2052-10-20"

Example 2:

Input: date = "6th Jun 1933"


Output: "1933-06-06"

Example 3:

Input: date = "26th May 1960"


Output: "1960-05-26"

Constraints:

The given dates are guaranteed to be valid, so no error handling is necessary.


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

399. Reformat Date(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string reformatDate(string date) {
7 static const unordered_map lookup = {
8 {"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Apr", 4},
9 {"May", 5}, {"Jun", 6}, {"Jul", 7}, {"Aug", 8},
10 {"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12}
11 };
12 stringstream ss;
13 int y = stoi(date.substr(date.length() - 4));
14 ss << setfill('0') << setw(4) << y;
15 int m = lookup.at(date.substr(date.length() - 4 - 4, 3));
16 ss << "-" << setfill('0') << setw(2) << m;
17 int d = stoi(date.substr(0, date.find(' ', 0) - 2));
18 ss << "-" << setfill('0') << setw(2) << d;
19 return ss.str();
20 }
21 };
22
*************

399. Reformat Date(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def reformatDate(self, date):
6 """
7 :type date: str
8 :rtype: str
9 """
10 lookup = {"Jan":1, "Feb":2, "Mar":3, "Apr":4,
11 "May":5, "Jun":6, "Jul":7, "Aug":8,
12 "Sep":9, "Oct":10, "Nov":11, "Dec":12}
13 return "{:04d}-{:02d}-{:02d}".format(int(date[-4:]), lookup[date[-8:-5]], int(date[:date.index(' ')-2]))
************************

400. Customer Order Frequency


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

Table: Customers

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| customer_id | int |
| name | varchar |
| country | varchar |
+---------------+---------+
customer_id is the primary key for this table.
This table contains information of the customers in the company.

Table: Product

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| description | varchar |
| price | int |
+---------------+---------+
product_id is the primary key for this table.
This table contains information of the products in the company.
price is the product cost.

Table: Orders

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| order_id | int |
| customer_id | int |
| product_id | int |
| order_date | date |
| quantity | int |
+---------------+---------+
order_id is the primary key for this table.
This table contains information on customer orders.
customer_id is the id of the customer who bought "quantity" products with id "product_id".
Order_date is the date in format ('YYYY-MM-DD') when the order was shipped.

Write an SQL query to report the customer_id and customer_name of customers who have spent at least $100 in each
month of June and July 2020.

Return the result table in any order.

The query result format is in the following example.


Customers
+--------------+-----------+-------------+
| customer_id | name | country |
+--------------+-----------+-------------+
| 1 | Winston | USA |
| 2 | Jonathan | Peru |
| 3 | Moustafa | Egypt |
+--------------+-----------+-------------+

Product
+--------------+-------------+-------------+
| product_id | description | price |
+--------------+-------------+-------------+
| 10 | LC Phone | 300 |
| 20 | LC T-Shirt | 10 |
| 30 | LC Book | 45 |
| 40 | LC Keychain | 2 |
+--------------+-------------+-------------+

Orders
+--------------+-------------+-------------+-------------+-----------+
| order_id | customer_id | product_id | order_date | quantity |
+--------------+-------------+-------------+-------------+-----------+
| 1 | 1 | 10 | 2020-06-10 | 1 |
| 2 | 1 | 20 | 2020-07-01 | 1 |
| 3 | 1 | 30 | 2020-07-08 | 2 |
| 4 | 2 | 10 | 2020-06-15 | 2 |
| 5 | 2 | 40 | 2020-07-01 | 10 |
| 6 | 3 | 20 | 2020-06-24 | 2 |
| 7 | 3 | 30 | 2020-06-25 | 2 |
| 9 | 3 | 30 | 2020-05-08 | 3 |
+--------------+-------------+-------------+-------------+-----------+

Result table:
+--------------+------------+
| customer_id | name |
+--------------+------------+
| 1 | Winston |
+--------------+------------+
Winston spent $300 (300 * 1) in June and $100 ( 10 * 1 + 45 * 2) in July 2020.
Jonathan spent $600 (300 * 2) in June and $20 ( 2 * 10) in July 2020.
Moustafa spent $110 (10 * 2 + 45 * 2) in June and $0 in July 2020.
************************

400. Customer Order Frequency(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT a.customer_id,
5 a.name
6 FROM Customers AS a
7 INNER JOIN
8 (SELECT *
9 FROM Orders
10 WHERE order_date BETWEEN "2020-06-01" AND "2020-07-31" ) AS b
11 ON a.customer_id = b.customer_id
12 INNER JOIN Product AS c
13 ON b.product_id = c.product_id
14 GROUP BY a.customer_id
15 HAVING SUM(CASE
16 WHEN LEFT(b.order_date, 7) = "2020-06" THEN c.price * b.quantity
17 ELSE 0
18 END) >= 100
19 AND SUM(CASE
20 WHEN LEFT(b.order_date, 7) = "2020-07" THEN c.price * b.quantity
21 ELSE 0
22 END) >= 100
23 ORDER BY NULL;
********************

401. Number of Good Pairs


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

Given an array of integers nums.

A pair (i,j) is called good if nums[i] == nums[j] and i < j.

Return the number of good pairs.

Example 1:

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


Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Example 2:

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


Output: 6
Explanation: Each pair in the array are good.

Example 3:

Input: nums = [1,2,3]


Output: 0

Constraints:

1 <= nums.length <= 100


1 <= nums[i] <= 100
********************

401. Number of Good Pairs(C++)


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

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

401. Number of Good Pairs(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def numIdenticalPairs(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: int
12 """
13 return sum(c*(c-1)//2 for c in collections.Counter(nums).itervalues())
*****************************

402. Find Users With Valid E-Mails


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

Table: Users

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| name | varchar |
| mail | varchar |
+---------------+---------+
user_id is the primary key for this table.
This table contains information of the users signed up in a website. Some e-mails are invalid.

Write an SQL query to find the users who have valid emails.

A valid e-mail has a prefix name and a domain where:

The prefix name is a string that may contain letters (upper or lower case), digits, underscore'_', period '.' and/or dash '-
'. The prefix name must start with a letter.
The domain is '@leetcode.com'.

Return the result table in any order.

The query result format is in the following example.

Users
+---------+-----------+-------------------------+
| user_id | name | mail |
+---------+-----------+-------------------------+
| 1 | Winston | winston@leetcode.com |
| 2 | Jonathan | jonathanisgreat |
| 3 | Annabelle | bella-@leetcode.com |
| 4 | Sally | sally.come@leetcode.com |
| 5 | Marwan | quarz#2020@leetcode.com |
| 6 | David | david69@gmail.com |
| 7 | Shapiro | .shapo@leetcode.com |
+---------+-----------+-------------------------+

Result table:
+---------+-----------+-------------------------+
| user_id | name | mail |
+---------+-----------+-------------------------+
| 1 | Winston | winston@leetcode.com |
| 3 | Annabelle | bella-@leetcode.com |
| 4 | Sally | sally.come@leetcode.com |
+---------+-----------+-------------------------+
The mail of user 2 doesn't have a domain.
The mail of user 5 has # sign which is not allowed.
The mail of user 6 doesn't have leetcode domain.
The mail of user 7 starts with a period.
*****************************

402. Find Users With Valid E-Mails(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT *
5 FROM users AS u
6 WHERE u.mail REGEXP '^[a-zA-Z][a-zA-Z0-9._-]*@leetcode.com$';
*************

403. Water Bottles


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

Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.

The operation of drinking a full water bottle turns it into an empty bottle.

Return the maximum number of water bottles you can drink.

Example 1:

Input: numBottles = 9, numExchange = 3


Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.

Example 2:

Input: numBottles = 15, numExchange = 4


Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.

Example 3:
Input: numBottles = 5, numExchange = 5
Output: 6

Example 4:

Input: numBottles = 2, numExchange = 3


Output: 2

Constraints:

1 <= numBottles <= 100


2 <= numExchange <= 100
*************

403. Water Bottles(C++)


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

1 // Time: O(logn/logm), n is numBottles, m is numExchange


2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numWaterBottles(int numBottles, int numExchange) {
7 int result = numBottles;
8 while (numBottles >= numExchange) {
9 result += numBottles / numExchange;
10 numBottles = numBottles / numExchange + numBottles % numExchange;
11 }
12 return result;
13 }
14 };
*************

403. Water Bottles(Python)


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

1 # Time: O(logn/logm), n is numBottles, m is numExchange


2 # Space: O(1)
3
4 class Solution(object):
5 def numWaterBottles(self, numBottles, numExchange):
6 """
7 :type numBottles: int
8 :type numExchange: int
9 :rtype: int
10 """
11 result = numBottles
12 while numBottles >= numExchange:
13 numBottles, remainder = divmod(numBottles, numExchange)
14 result += numBottles
15 numBottles += remainder
16 return result
**************************************

404. Count Odd Numbers in an Interval Range


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

Given two non-negative integers low and high . Return the count of odd numbers between low and high (inclusive).

Example 1:

Input: low = 3, high = 7


Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

Input: low = 8, high = 10


Output: 1
Explanation: The odd numbers between 8 and 10 are [9].

Constraints:

0 <= low <= high <= 10^9


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

404. Count Odd Numbers in an Interval Range(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countOdds(int low, int high) {
7 return (high + 1) / 2 - ((low - 1) + 1) / 2;
8 }
9 };
**************************************

404. Count Odd Numbers in an Interval Range(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countOdds(self, low, high):
6 """
7 :type low: int
8 :type high: int
9 :rtype: int
10 """
11 return (high+1)//2 - ((low-1)+1)//2
*************************

405. Patients With a Condition


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

Table: Patients

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| patient_id | int |
| patient_name | varchar |
| conditions | varchar |
+--------------+---------+
patient_id is the primary key for this table.
'conditions' contains 0 or more code separated by spaces.
This table contains information of the patients in the hospital.

Write an SQL query to report the patient_id, patient_name all conditions of patients who have Type I Diabetes. Type I
Diabetes always starts with DIAB1 prefix

Return the result table in any order.

The query result format is in the following example.

Patients
+------------+--------------+--------------+
| patient_id | patient_name | conditions |
+------------+--------------+--------------+
| 1 | Daniel | YFEV COUGH |
| 2 | Alice | |
| 3 | Bob | DIAB100 MYOP |
| 4 | George | ACNE DIAB100 |
| 5 | Alain | DIAB201 |
+------------+--------------+--------------+

Result table:
+------------+--------------+--------------+
| patient_id | patient_name | conditions |
+------------+--------------+--------------+
| 3 | Bob | DIAB100 MYOP |
| 4 | George | ACNE DIAB100 |
+------------+--------------+--------------+
Bob and George both have a condition that starts with DIAB1.
*************************

405. Patients With a Condition(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT *
5 FROM Patients AS p
6 WHERE p.conditions REGEXP '^DIAB1| DIAB1';
**************

406. Shuffle String


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

Given a string s and an integer array indices of the same length.

The string s will be shuffled such that the character at theith position moves to indices[i] in the shuffled string.

Return the shuffled string.

Example 1:

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]


Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.

Example 2:

Input: s = "abc", indices = [0,1,2]


Output: "abc"
Explanation: After shuffling, each character remains in its position.

Example 3:

Input: s = "aiohn", indices = [3,1,4,2,0]


Output: "nihao"

Example 4:

Input: s = "aaiougrt", indices = [4,0,2,6,7,3,1,5]


Output: "arigatou"

Example 5:

Input: s = "art", indices = [1,0,2]


Output: "rat"
Constraints:

s.length == indices.length == n
1 <= n <= 100
s contains only lower-case English letters.
0 <= indices[i] < n
All values of indices are unique (i.e. indices is a permutation of the integers from 0 to n - 1).
**************

406. Shuffle String(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 // in-place solution
5 class Solution {
6 public:
7 string restoreString(string s, vector& indices) {
8 for (int i = 0; i < s.length(); ++i) {
9 if (indices[i] == i) {
10 continue;
11 }
12 auto move = s[i];
13 for (int j = indices[i]; j != i; swap(indices[j], j)) {
14 swap(s[j], move);
15 }
16 s[i] = move;
17 }
18 return s;
19 }
20 };
21
22 // Time: O(n)
23 // Space: O(1)
24 class Solution2 {
25 public:
26 string restoreString(string s, vector& indices) {
27 string result(s.length(), 0);
28 for (int i = 0; i < s.length(); ++i) {
29 result[indices[i]] = s[i];
30 }
31 return result;
32 }
33 };
**************

406. Shuffle String(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 # in-place solution
5 class Solution(object):
6 def restoreString(self, s, indices):
7 """
8 :type s: str
9 :type indices: List[int]
10 :rtype: str
11 """
12 result = list(s)
13 for i, c in enumerate(result):
14 if indices[i] == i:
15 continue
16 move, j = c, indices[i]
17 while j != i:
18 result[j], move = move, result[j]
19 indices[j], j = j, indices[j]
20 result[i] = move
21 return "".join(result)
22
23
24 # Time: O(n)
25 # Space: O(1)
26 import itertools
27
28
29 class Solution2(object):
30 def restoreString(self, s, indices):
31 """
32 :type s: str
33 :type indices: List[int]
34 :rtype: str
35 """
36 result = ['']*len(s)
37 for i, c in itertools.izip(indices, s):
38 result[i] = c
39 return "".join(result)
*******************

407. Count Good Triplets


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

Given an array of integers arr, and three integers a, b and c . You need to find the number of good triplets.

A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

0 <= i < j < k < arr.length


|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c

Where |x| denotes the absolute value of x .

Return the number of good triplets.

Example 1:

Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3


Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].

Example 2:

Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1


Output: 0
Explanation: No triplet satisfies all conditions.

Constraints:

3 <= arr.length <= 100


0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
*******************

407. Count Good Triplets(C++)


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

1 // Time: O(n^3)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countGoodTriplets(vector& arr, int a, int b, int c) {
7 int result = 0;
8 for (int i = 0; i + 2 < arr.size(); ++i) {
9 for (int j = i + 1; j + 1 < arr.size(); ++j) {
10 for (int k = j + 1; k < arr.size(); ++k) {
11 if (abs(arr[i] - arr[j]) <= a &&
12 abs(arr[j] - arr[k]) <= b &&
13 abs(arr[k] - arr[i]) <= c) {
14 ++result;
15 }
16 }
17 }
18 }
19 return result;
20 }
21 };
*******************

407. Count Good Triplets(Python)


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

1 # Time: O(n^3)
2 # Space: O(1)
3
4 class Solution(object):
5 def countGoodTriplets(self, arr, a, b, c):
6 """
7 :type arr: List[int]
8 :type a: int
9 :type b: int
10 :type c: int
11 :rtype: int
12 """
13 return sum(abs(arr[i]-arr[j]) <= a and
14 abs(arr[j]-arr[k]) <= b and
15 abs(arr[k]-arr[i]) <= c
16 for i in xrange(len(arr)-2)
17 for j in xrange(i+1, len(arr)-1)
18 for k in xrange(j+1, len(arr)))
19
***************************

408. Kth Missing Positive Number


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

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k .

Find the k th positive integer that is missing from this array.

Example 1:

Input: arr = [2,3,4,7,11], k = 5


Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.

Example 2:

Input: arr = [1,2,3,4], k = 2


Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.

Constraints:

1 <= arr.length <= 1000


1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
***************************

408. Kth Missing Positive Number(C++)


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

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int findKthPositive(vector& arr, int k) {
7 int left = 0, right = arr.size() - 1;
8 while (left <= right) {
9 const auto& mid = left + (right - left) / 2;
10 if (!check(arr, k, mid)) {
11 right = mid - 1;
12 } else {
13 left = mid + 1;
14 }
15 }
16 return right + 1 + k; // right >= 0 ? arr[right] + (k - (arr[right] - (right + 1))) : k;
17 }
18
19 private:
20 bool check(const vector& arr, int k, int x) {
21 return arr[x] - (x + 1) < k;
22 }
23 };
***************************

408. Kth Missing Positive Number(Python)


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

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def findKthPositive(self, arr, k):
6 """
7 :type arr: List[int]
8 :type k: int
9 :rtype: int
10 """
11 def check(arr, k, x):
12 return arr[x]-(x+1) < k
13
14 left, right = 0, len(arr)-1
15 while left <= right:
16 mid = left + (right-left)//2
17 if not check(arr, k, mid):
18 right = mid-1
19 else:
20 left = mid+1
21 return right+1+k # arr[right] + (k-(arr[right]-(right+1))) if right >= 0 else k
***********************

409. Fix Product Name Format


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

Table: Sales

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| sale_id | int |
| product_name | varchar |
| sale_date | date |
+--------------+---------+
sale_id is the primary key for this table.
Each row of this table contains the product name and the date it was sold.

Since table Sales was filled manually in the year2000, product_name may contain leading and/or trailing white spaces, also
they are case-insensitive.

Write an SQL query to report

product_name in lowercase without leading or trailing white spaces.


sale_date in the format ('YYYY-MM').
total the number of times the product was sold in this month.

Return the result table ordered by product_name in ascending order. In case of a tie, order it bysale_date in ascending order.

The query result format is in the following example.

Sales
+---------+--------------+------------+
| sale_id | product_name | sale_date |
+---------+--------------+------------+
| 1 | LCPHONE | 2000-01-16 |
| 2 | LCPhone | 2000-01-17 |
| 3 | LcPhOnE | 2000-02-18 |
| 4 | LCKeyCHAiN | 2000-02-19 |
| 5 | LCKeyChain | 2000-02-28 |
| 6 | Matryoshka | 2000-03-31 |
+---------+--------------+------------+

Result table:
+--------------+-----------+-------+
| product_name | sale_date | total |
+--------------+-----------+-------+
| lckeychain | 2000-02 | 2 |
| lcphone | 2000-01 | 2 |
| lcphone | 2000-02 | 1 |
| matryoshka | 2000-03 | 1 |
+--------------+-----------+-------+
In January, 2 LcPhones were sold, please note that the product names are not case sensitive and may contain spaces.
In Februery, 2 LCKeychains and 1 LCPhone were sold.
In March, 1 matryoshka was sold.
***********************

409. Fix Product Name Format(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT LOWER(TRIM(product_name)) product_name,
5 substring(sale_date, 1, 7) sale_date,
6 count(sale_id) total
7 FROM sales
8 GROUP BY 1, 2
9 ORDER BY 1, 2;
*********************

410. Make The String Great


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

Given a string s of lower and upper case English letters.

A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

0 <= i <= s.length - 2


s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case orvice-versa.

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can
keep doing this until the string becomes good.

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

Notice that an empty string is also good.

Example 1:

Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

Example 2:

Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""

Example 3:

Input: s = "s"
Output: "s"

Constraints:

1 <= s.length <= 100


s contains only lower and upper case English letters.
*********************

410. Make The String Great(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string makeGood(string s) {
7 string result;
8 for (const auto& ch : s) {
9 char counter_ch = islower(ch) ? toupper(ch) : tolower(ch);
10 if (!result.empty() && result.back() == counter_ch) {
11 result.pop_back();
12 } else {
13 result.push_back(ch);
14 }
15 }
16 return result;
17 }
18 };
*********************

410. Make The String Great(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def makeGood(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 stk = []
11 for ch in s:
12 counter_ch = ch.upper() if ch.islower() else ch.lower()
13 if stk and stk[-1] == counter_ch:
14 stk.pop()
15 else:
16 stk.append(ch)
17 return "".join(stk)
**********************

411. Three Consecutive Odds


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

Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, returnfalse.

Example 1:

Input: arr = [2,6,4,1]


Output: false
Explanation: There are no three consecutive odds.

Example 2:

Input: arr = [1,2,34,3,4,5,7,23,12]


Output: true
Explanation: [5,7,23] are three consecutive odds.

Constraints:

1 <= arr.length <= 1000


1 <= arr[i] <= 1000
**********************

411. Three Consecutive Odds(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool threeConsecutiveOdds(vector& arr) {
7 int count = 0;
8 for (const auto& x : arr) {
9 count = x % 2 ? count + 1 : 0;
10 if (count == 3) {
11 return true;
12 }
13 }
14 return false;
15 }
16 };
**********************

411. Three Consecutive Odds(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def threeConsecutiveOdds(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: bool
9 """
10 count = 0
11 for x in arr:
12 count = count+1 if x%2 else 0
13 if count == 3:
14 return True
15 return False
******************

412. Thousand Separator


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

Given an integer n, add a dot (".") as the thousands separator and return it in string format.

Example 1:

Input: n = 987
Output: "987"

Example 2:

Input: n = 1234
Output: "1.234"

Example 3:

Input: n = 123456789
Output: "123.456.789"

Example 4:

Input: n = 0
Output: "0"

Constraints:

0 <= n < 2^31


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

412. Thousand Separator(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string thousandSeparator(int n) {
7 string result;
8 const auto& s = to_string(n);
9 for (int i = 0; i < s.length(); ++i) {
10 if (i > 0 && (s.length() - i) % 3 == 0) {
11 result += ".";
12 }
13 result += s[i];
14 }
15 return result;
16 }
17 };
******************

412. Thousand Separator(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def thousandSeparator(self, n):
6 """
7 :type n: int
8 :rtype: str
9 """
10 result = []
11 s = str(n)
12 for i, c in enumerate(str(n)):
13 if i and (len(s)-i)%3 == 0:
14 result.append(".")
15 result.append(c)
16 return "".join(result)
***************************************

413. Most Visited Sector in a Circular Track


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

Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A
marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at
sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]

Return an array of the most visited sectors sorted in ascending order.

Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first
example).

Example 1:

Input: n = 4, rounds = [1,3,1,2]


Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.

Example 2:

Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]


Output: [2]

Example 3:

Input: n = 7, rounds = [1,3,5,7]


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

Constraints:

2 <= n <= 100


1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1] for 0 <= i < m
***************************************

413. Most Visited Sector in a Circular Track(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector mostVisited(int n, vector& rounds) {
7 vector result;
8 if (rounds.front() <= rounds.back()) {
9 for (int i = rounds.front(); i <= rounds.back(); ++i) {
10 result.emplace_back(i);
11 }
12 } else {
13 for (int i = 1; i <= rounds.back(); ++i) {
14 result.emplace_back(i);
15 }
16 for (int i = rounds.front(); i <= n; ++i) {
17 result.emplace_back(i);
18 }
19 }
20 return result;
21 }
22 };
***************************************

413. Most Visited Sector in a Circular Track(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def mostVisited(self, n, rounds):
6 """
7 :type n: int
8 :type rounds: List[int]
9 :rtype: List[int]
10 """
11 return range(rounds[0], rounds[-1]+1) or \
12 range(1, rounds[-1]+1) + range(rounds[0], n+1)
*************************************

414. Unique Orders and Customers Per Month


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

Table: Orders

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| order_id | int |
| order_date | date |
| customer_id | int |
| invoice | int |
+---------------+---------+
order_id is the primary key for this table.
This table contains information about the orders made by customer_id.

Write an SQL query to find the number ofunique orders and the number of unique customers with invoices > $20 for each
different month.

Return the result table sorted in any order.

The query result format is in the following example:

Orders
+----------+------------+-------------+------------+
| order_id | order_date | customer_id | invoice |
+----------+------------+-------------+------------+
| 1 | 2020-09-15 | 1 | 30 |
| 2 | 2020-09-17 | 2 | 90 |
| 3 | 2020-10-06 | 3 | 20 |
| 4 | 2020-10-20 | 3 | 21 |
| 5 | 2020-11-10 | 1 | 10 |
| 6 | 2020-11-21 | 2 | 15 |
| 7 | 2020-12-01 | 4 | 55 |
| 8 | 2020-12-03 | 4 | 77 |
| 9 | 2021-01-07 | 3 | 31 |
| 10 | 2021-01-15 | 2 | 20 |
+----------+------------+-------------+------------+

Result table:
+---------+-------------+----------------+
| month | order_count | customer_count |
+---------+-------------+----------------+
| 2020-09 | 2 | 2 |
| 2020-10 | 1 | 1 |
| 2020-12 | 2 | 1 |
| 2021-01 | 1 | 1 |
+---------+-------------+----------------+
In September 2020 we have two orders from 2 different customers with invoices > $20.
In October 2020 we have two orders from 1 customer, and only one of the two orders has invoice > $20.
In November 2020 we have two orders from 2 different customers but invoices < $20, so we don't include that month.
In December 2020 we have two orders from 1 customer both with invoices > $20.
In January 2021 we have two orders from 2 different customers, but only one of them with invoice > $20.
*************************************

414. Unique Orders and Customers Per Month(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT LEFT(order_date, 7) month,
5 COUNT(DISTINCT order_id) order_count,
6 COUNT(DISTINCT customer_id) customer_count
7 FROM orders
8 WHERE invoice > 20
9 GROUP BY 1
10 ORDER BY NULL;
***************************************************

415. Detect Pattern of Length M Repeated K or More


Times
***************************************************

Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.

A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times
consecutively without overlapping. A pattern is defined by its length and the number of repetitions.

Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.

Example 1:

Input: arr = [1,2,4,4,4,4], m = 1, k = 3


Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.

Example 2:

Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2


Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.

Example 3:

Input: arr = [1,2,1,2,1,3], m = 2, k = 3


Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.

Example 4:

Input: arr = [1,2,3,1,2], m = 2, k = 2


Output: false
Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.

Example 5:

Input: arr = [2,2,2,2], m = 2, k = 3


Output: false
Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.

Constraints:

2 <= arr.length <= 100


1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100
***************************************************

415. Detect Pattern of Length M Repeated K or More


Times(C++)
***************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool containsPattern(vector& arr, int m, int k) {
7 int cnt = 0;
8 for (int i = 0; i + m < arr.size(); ++i) {
9 if (arr[i] != arr[i + m]) {
10 cnt = 0;
11 continue;
12 }
13 if (++cnt == (k - 1) * m) {
14 return true;
15 }
16 }
17 return false;
18 }
19 };
***************************************************

415. Detect Pattern of Length M Repeated K or More


Times(Python)
***************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def containsPattern(self, arr, m, k):
6 """
7 :type arr: List[int]
8 :type m: int
9 :type k: int
10 :rtype: bool
11 """
12 cnt = 0
13 for i in xrange(len(arr)-m):
14 if arr[i] != arr[i+m]:
15 cnt = 0
16 continue
17 cnt += 1
18 if cnt == (k-1)*m:
19 return True
20 return False
*******************

416. Matrix Diagonal Sum


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

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are
not part of the primary diagonal.

Example 1:

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


[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.

Example 2:

Input: mat = [[1,1,1,1],


[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8

Example 3:

Input: mat = [[5]]


Output: 5

Constraints:

n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
*******************

416. Matrix Diagonal Sum(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int diagonalSum(vector>& mat) {
7 const int n = mat.size();
8 int result = 0;
9 for (int i = 0; i < n; ++i) {
10 result += mat[i][i] + mat[n - 1 - i][i];
11 }
12 if (n % 2) {
13 result -= mat[n / 2][n / 2];
14 }
15 return result;
16 }
17 };
*******************

416. Matrix Diagonal Sum(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def diagonalSum(self, mat):
6 """
7 :type mat: List[List[int]]
8 :rtype: int
9 """
10 return sum(mat[i][i]+mat[~i][i] for i in xrange(len(mat))) - (mat[len(mat)//2][len(mat)//2] if len(mat)%2 == 1 else
*********************************************************

417. Replace All ?'s to Avoid Consecutive Repeating


Characters
*********************************************************

Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase
letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?'
characters.

It is guaranteed that there are no consecutive repeating characters in the given stringexcept for '?'.

Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return
any of them. It can be shown that an answer is always possible with the given constraints.

Example 1:

Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string w

Example 2:

Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive r

Example 3:

Input: s = "j?qg??b"
Output: "jaqgacb"

Example 4:

Input: s = "??yw?ipkj?"
Output: "acywaipkja"

Constraints:

1 <= s.length <= 100


s consist of lowercase English letters and '?'.
*********************************************************

417. Replace All ?'s to Avoid Consecutive Repeating


Characters(C++)
*********************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string modifyString(string s) {
7 for (int i = 0; i < s.length(); ++i) {
8 if (s[i] != '?') {
9 continue;
10 }
11 for (s[i] = 'a'; s[i] <= 'c'; ++s[i]) {
12 if ((i == 0 || s[i - 1] != s[i]) && (i == s.size() - 1 || s[i + 1] != s[i])) {
13 break;
14 }
15 }
16 }
17 return s;
18 }
19 };
*********************************************************

417. Replace All ?'s to Avoid Consecutive Repeating


Characters(Python)
*********************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def modifyString(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 s = list(s)
11 for i in xrange(len(s)):
12 if s[i] != '?':
13 continue
14 for c in ('a', 'b', 'c'):
15 if (i == 0 or s[i-1] != c) and (i == len(s)-1 or c != s[i+1]):
16 break
17 s[i] = c
18 return "".join(s)
******************************************************

418. Customer Who Visited but Did Not Make Any


Transactions
******************************************************

Table: Visits

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| visit_id | int |
| customer_id | int |
+-------------+---------+
visit_id is the primary key for this table.
This table contains information about the customers who visited the mall.

Table: Transactions

+----------------+---------+
| Column Name | Type |
+----------------+---------+
| transaction_id | int |
| visit_id | int |
| amount | int |
+----------------+---------+
transaction_id is the primary key for this table.
This table contains information about the transactions made during the visit_id.

Write an SQL query to find the IDs of the users who visited without making any transactions and the number of times they
made these types of visits.

Return the result table sorted in any order.

The query result format is in the following example:


Visits
+----------+-------------+
| visit_id | customer_id |
+----------+-------------+
| 1 | 23 |
| 2 | 9 |
| 4 | 30 |
| 5 | 54 |
| 6 | 96 |
| 7 | 54 |
| 8 | 54 |
+----------+-------------+

Transactions
+----------------+----------+--------+
| transaction_id | visit_id | amount |
+----------------+----------+--------+
| 2 | 5 | 310 |
| 3 | 5 | 300 |
| 9 | 5 | 200 |
| 12 | 1 | 910 |
| 13 | 2 | 970 |
+----------------+----------+--------+

Result table:
+-------------+----------------+
| customer_id | count_no_trans |
+-------------+----------------+
| 54 | 2 |
| 30 | 1 |
| 96 | 1 |
+-------------+----------------+
Customer with id = 23 visited the mall once and made one transaction during the visit with id = 12.
Customer with id = 9 visited the mall once and made one transaction during the visit with id = 13.
Customer with id = 30 visited the mall once and did not make any transactions.
Customer with id = 54 visited the mall three times. During 2 visits they did not make any transactions, and during one visit they made 3 tran
Customer with id = 96 visited the mall once and did not make any transactions.
As we can see, users with IDs 30 and 96 visited the mall one time without making any transactions. Also user 54 visited the mall twice and di
******************************************************

418. Customer Who Visited but Did Not Make Any


Transactions(Shell)
******************************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT DISTINCT customer_id,
5 count(customer_id) AS count_no_trans
6 FROM visits v
7 LEFT JOIN transactions t ON v.visit_id = t.visit_id
8 WHERE transaction_id IS NULL
9 GROUP BY customer_id
10 ORDER BY NULL;
************************************

419. Special Positions in a Binary Matrix


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

Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat.

A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-
indexed).

Example 1:

Input: mat = [[1,0,0],


[0,0,1],
[1,0,0]]
Output: 1
Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.

Example 2:

Input: mat = [[1,0,0],


[0,1,0],
[0,0,1]]
Output: 3
Explanation: (0,0), (1,1) and (2,2) are special positions.

Example 3:

Input: mat = [[0,0,0,1],


[1,0,0,0],
[0,1,1,0],
[0,0,0,0]]
Output: 2

Example 4:

Input: mat = [[0,0,0,0,0],


[1,0,0,0,0],
[0,1,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1]]
Output: 3

Constraints:

rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j] is 0 or 1.
************************************

419. Special Positions in a Binary Matrix(C++)


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

1 // Time: O(n^2)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int numSpecial(vector>& mat) {
7 vector rows(size(mat)), cols(size(mat[0]));
8 for (int i = 0; i < size(rows); ++i) {
9 for (int j = 0; j < size(cols); ++j) {
10 if (mat[i][j]) {
11 ++rows[i], ++cols[j];
12 }
13 }
14 }
15 int result = 0;
16 for (int i = 0; i < size(rows); ++i) {
17 for (int j = 0; j < size(cols); ++j) {
18 if (mat[i][j] && rows[i] == 1 && cols[j] == 1) {
19 ++result;
20 }
21 }
22 }
23 return result;
24 }
25 };
************************************

419. Special Positions in a Binary Matrix(Python)


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

1 # Time: O(n^2)
2 # Space: O(n)
3
4 class Solution(object):
5 def numSpecial(self, mat):
6 """
7 :type mat: List[List[int]]
8 :rtype: int
9 """
10 rows, cols = [0]*len(mat), [0]*len(mat[0])
11 for i in xrange(len(rows)):
12 for j in xrange(len(cols)):
13 if mat[i][j]:
14 rows[i] += 1
15 cols[j] += 1
16 result = 0
17 for i in xrange(len(rows)):
18 for j in xrange(len(cols)):
19 if mat[i][j] == rows[i] == cols[j] == 1:
20 result += 1
21 return result
***********************

420. Bank Account Summary II


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

Table: Users

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| account | int |
| name | varchar |
+--------------+---------+
account is the primary key for this table.
Each row of this table contains the account number of each user in the bank.

Table: Transactions

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| trans_id | int |
| account | int |
| amount | int |
| transacted_on | date |
+---------------+---------+
trans_id is the primary key for this table.
Each row of this table contains all changes made to all accounts.
amount is positive if the user received money and negative if they transferred money.
All accounts start with a balance 0.

Write an SQL query to report the name and balance of users with a balance higher than 10000. The balance of an account is
equal to the sum of the amounts of all transactions involving that account.

Return the result table in any order.

The query result format is in the following example.


Users table:
+------------+--------------+
| account | name |
+------------+--------------+
| 900001 | Alice |
| 900002 | Bob |
| 900003 | Charlie |
+------------+--------------+

Transactions table:
+------------+------------+------------+---------------+
| trans_id | account | amount | transacted_on |
+------------+------------+------------+---------------+
| 1 | 900001 | 7000 | 2020-08-01 |
| 2 | 900001 | 7000 | 2020-09-01 |
| 3 | 900001 | -3000 | 2020-09-02 |
| 4 | 900002 | 1000 | 2020-09-12 |
| 5 | 900003 | 6000 | 2020-08-07 |
| 6 | 900003 | 6000 | 2020-09-07 |
| 7 | 900003 | -4000 | 2020-09-11 |
+------------+------------+------------+---------------+

Result table:
+------------+------------+
| name | balance |
+------------+------------+
| Alice | 11000 |
+------------+------------+
Alice's balance is (7000 + 7000 - 3000) = 11000.
Bob's balance is 1000.
Charlie's balance is (6000 + 6000 - 4000) = 8000.
***********************

420. Bank Account Summary II(Shell)


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

1 # Time: O(m + n)
2 # Space: O(m + n)
3
4 SELECT u.name,
5 SUM(amount) balance
6 FROM users u
7 INNER JOIN transactions t ON u.account = t.account
8 GROUP BY u.name
9 HAVING balance > 10000
10 ORDER BY NULL;
*******************************

421. Sum of All Odd Length Subarrays


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

Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.

A subarray is a contiguous subsequence of the array.

Return the sum of all odd-length subarrays of arr.

Example 1:

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


Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

Example 2:

Input: arr = [1,2]


Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.

Example 3:

Input: arr = [10,11,12]


Output: 66

Constraints:

1 <= arr.length <= 100


1 <= arr[i] <= 1000
*******************************

421. Sum of All Odd Length Subarrays(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int sumOddLengthSubarrays(vector& arr) {
7 // begin\pos |0 i (n-1)
8 // ----------------------------
9 // 0 --101.... ↑
10 // 1 -010.... i-0+1
11 // i 101.... ↓
12 // â†​ (n-1-i+1) →
13 //
14 // for each number x with its position i, as the graph depicted above,
15 // (begin, pos) pair represents a subarray arr[begin:pos+1] containing x, marked 1 if odd length else 0,
16 // so the total number of 0 and 1 are exactly the total number of subarrays with x, which is (i-0+1)*((len(arr)-1)-i+1),
17 // because the number of 1 is always equal to or one more than the number of 0, (always begins with 1010... and alternatively fl
18 // so there are ceil(count/2) odd length subarrays with x
19 int result = 0;
20 for (int i = 0; i < size(arr); ++i) {
21 result += arr[i] * ceil_divide((i - 0 + 1) * ((size(arr) - 1) - i + 1), 2);
22 }
23 return result;
24 }
25
26 private:
27 int ceil_divide(int a, int b) {
28 return (a + (b - 1)) / b;
29 }
30 };
*******************************

421. Sum of All Odd Length Subarrays(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def sumOddLengthSubarrays(self, arr):
6 """
7 :type arr: List[int]
8 :rtype: int
9 """
10 def ceil_divide(a, b):
11 return (a+(b-1))//b
12
13 # begin\pos |0 i (n-1)
14 # ----------------------------
15 # 0 --101.... ↑
16 # 1 -010.... i-0+1
17 # i 101.... ↓
18 # â†​ (n-1-i+1) →
19 #
20 # for each number x with its position i, we want to know how many odd length subarrays is with x,
21 # as the graph depicted above,
22 # (begin, pos) pair represents a subarray arr[begin:pos+1] containing x, marked 1 if odd length else 0,
23 # so the total number of 0 and 1 are exactly the total number of subarrays with x, which is (i-0+1)*((len(arr)-1)-i+1),
24 # because the number of 1 is always equal to or one more than the number of 0, (always begins with 1010... and alternatively fli
25 # so there are ceil((i-0+1)*((len(arr)-1)-i+1)/2) odd length subarrays with x
26 #
27 return sum(x * ceil_divide((i-0+1)*((len(arr)-1)-i+1), 2) for i, x in enumerate(arr))
******************************

422. Rearrange Spaces Between Words


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

You are given a string text of words that are placed among some number of spaces. Each word consists of one or more
lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.

Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is
maximized. If you cannot redistribute all the spaces equally, place theextra spaces at the end, meaning the returned
string should be the same length as text.

Return the string after rearranging the spaces.

Example 1:

Input: text = " this is a sentence "


Output: "this is a sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.

Example 2:

Input: text = " practice makes perfect"


Output: "practice makes perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the

Example 3:

Input: text = "hello world"


Output: "hello world"

Example 4:

Input: text = " walks udp package into bar a"


Output: "walks udp package into bar a "

Example 5:

Input: text = "a"


Output: "a"

Constraints:

1 <= text.length <= 100


text consists of lowercase English letters and ' '.
text contains at least one word.
******************************

422. Rearrange Spaces Between Words(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 // inplace solution
5 class Solution {
6 public:
7 string reorderSpaces(string text) {
8 // count spaces and words
9 int space_count = 0, word_count = 0;
10 for (int i = 0; i < size(text); ++i) {
11 if (text[i] == ' ') {
12 ++space_count;
13 } else if (i == 0 || text[i - 1] == ' ') {
14 ++word_count;
15 }
16 }
17 // rearrange the spaces to the right
18 int left = 0, curr = 0;
19 for (int i = 0; i < size(text); ++i) {
20 bool has_word = false;
21 while (i < size(text) && text[i] != ' ') {
22 swap(text[left++], text[i++]);
23 has_word = true;
24 }
25 if (has_word) {
26 ++left; // keep one space
27 }
28 }
29 // rearrange the spaces to the left
30 int equal_count = word_count - 1 > 0 ? space_count / (word_count - 1) : 0;
31 int extra_count = word_count - 1 > 0 ? space_count % (word_count - 1) : space_count;
32 int right = size(text) - 1 - extra_count;
33 for (int i = size(text) - 1; i >= 0; --i) {
34 bool has_word = false;
35 while (i >= 0 && text[i] != ' ') {
36 swap(text[right--], text[i--]);
37 has_word = true;
38 }
39 if (has_word) {
40 right -= equal_count; // keep equal_count spaces
41 }
42 }
43 return text;
44 }
45 };
******************************

422. Rearrange Spaces Between Words(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 # inplace solution
5 class Solution(object):
6 def reorderSpaces(self, text):
7 """
8 :type text: str
9 :rtype: str
10 """
11 text = list(text)
12 # count the spaces and words
13 space_count, word_count = 0, 0
14 for i, c in enumerate(text):
15 if c == ' ':
16 space_count += 1
17 elif i == 0 or text[i-1] == ' ':
18 word_count += 1
19
20 # rearrange all the spaces to the right
21 left, i = 0, 0
22 while i < len(text):
23 has_word = False
24 while i < len(text) and text[i] != ' ':
25 text[left], text[i] = text[i], text[left]
26 left += 1
27 i += 1
28 has_word = True
29 if has_word:
30 left += 1 # keep one space
31 i += 1
32
33 # rearrange all the spaces to the left
34 equal_count = space_count//(word_count-1) if word_count-1 > 0 else 0
35 extra_count = space_count%(word_count-1) if word_count-1 > 0 else space_count
36 right, i = len(text)-1-extra_count, len(text)-1
37 while i >= 0:
38 has_word = False
39 while i >= 0 and text[i] != ' ':
40 text[right], text[i] = text[i], text[right]
41 right -= 1
42 i -= 1
43 has_word = True
44 if has_word:
45 right -= equal_count # keep equal_count spaces
46 i -= 1
47 return "".join(text)
******************

423. Crawler Log Folder


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

The Leetcode file system keeps a log each time some user performs achange folder operation.

The operations are described below:

"../" : Move to the parent folder of the current folder. (If you are already in the main folder,remain in the same folder).
"./" : Remain in the same folder.
"x/" : Move to the child folder namedx (This folder is guaranteed to always exist).

You are given a list of strings logs where logs[i] is the operation performed by the user at theith step.

The file system starts in the main folder, then the operations inlogs are performed.

Return the minimum number of operations needed to go back to the main folder after the change folder operations.

Example 1:

Input: logs = ["d1/","d2/","../","d21/","./"]


Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.

Example 2:

Input: logs = ["d1/","d2/","./","d3/","../","d31/"]


Output: 3

Example 3:
Input: logs = ["d1/","../","../","../"]
Output: 0

Constraints:

1 <= logs.length <= 10 3


2 <= logs[i].length <= 10
logs[i] contains lowercase English letters, digits, '.' , and '/' .
logs[i] follows the format described in the statement.
Folder names consist of lowercase English letters and digits.
******************

423. Crawler Log Folder(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minOperations(vector& logs) {
7 int result = 0;
8 for (const auto& log: logs) {
9 if (log == "../") {
10 if (result > 0) {
11 --result;
12 }
13 } else if (log != "./") {
14 ++result;
15 }
16 }
17 return result;
18 }
19 };
******************

423. Crawler Log Folder(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minOperations(self, logs):
6 """
7 :type logs: List[str]
8 :rtype: int
9 """
10 result = 0
11 for log in logs:
12 if log == "../":
13 if result > 0:
14 result -= 1
15 elif log != "./":
16 result += 1
17 return result
*********************

424. Design Parking System


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

Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a
fixed number of slots for each size.

Implement the ParkingSystem class:

Initializes object of the ParkingSystem class. The number of slots for each parking
ParkingSystem(int big, int medium, int small)
space are given as part of the constructor.
bool addCar(int carType) Checks whether there is a parking space ofcarType for the car that wants to get into the parking
lot. carType can be of three kinds: big, medium, or small, which are represented by1, 2, and 3 respectively. A car can
only park in a parking space of its carType. If there is no space available, return false, else park the car in that size
space and return true.

Example 1:

Input
["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
[[1, 1, 0], [1], [2], [3], [1]]
Output
[null, true, true, false, false]

Explanation
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.

Constraints:

0 <= big, medium, small <= 1000


carType is 1, 2, or 3
At most 1000 calls will be made to addCar
*********************

424. Design Parking System(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class ParkingSystem {
5 public:
6 ParkingSystem(int big, int medium, int small)
7 : space_{0, big, medium, small} {
8 }
9
10 bool addCar(int carType) {
11 if (space_[carType] > 0) {
12 --space_[carType];
13 return true;
14 }
15 return false;
16 }
17
18 private:
19 vector space_;
20 };
*********************

424. Design Parking System(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class ParkingSystem(object):
5
6 def __init__(self, big, medium, small):
7 """
8 :type big: int
9 :type medium: int
10 :type small: int
11 """
12 self.__space = [0, big, medium, small]
13
14 def addCar(self, carType):
15 """
16 :type carType: int
17 :rtype: bool
18 """
19 if self.__space[carType] > 0:
20 self.__space[carType] -= 1
21 return True
22 return False
*****************************************************

425. Special Array With X Elements Greater Than or Equal


X
*****************************************************

You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there
are exactly x numbers in nums that are greater than or equal to x .

Notice that x does not have to be an element in nums.

Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

Example 1:

Input: nums = [3,5]


Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.

Example 2:

Input: nums = [0,0]


Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.

Example 3:

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


Output: 3
Explanation: There are 3 values that are greater than or equal to 3.

Example 4:

Input: nums = [3,6,7,7,0]


Output: -1

Constraints:

1 <= nums.length <= 100


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

425. Special Array With X Elements Greater Than or Equal


X(C++)
*****************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 // counting sort solution
5 class Solution {
6 public:
7 int specialArray(vector& nums) {
8 static const int MAX_NUM = 1000;
9 vector count(MAX_NUM + 1);
10 for (const auto& num : nums) {
11 ++count[num];
12 }
13 for (int n = size(nums), i = 0; i < size(count); n -= count[i++]) {
14 if (i == n) {
15 return i;
16 }
17 }
18 return -1;
19 }
20 };
21
22
23 // Time: O(n)
24 // Space: O(1)
25 // binary search + counting sort solution
26 class Solution2 {
27 public:
28 int specialArray(vector& nums) {
29 inplace_counting_sort(&nums, true);
30 int left = 0, right = size(nums) - 1;
31 while (left <= right) {
32 const auto& mid = left + (right - left) / 2;
33 if (nums[mid] <= mid) {
34 right = mid - 1;
35 } else {
36 left = mid + 1;
37 }
38 }
39 return left < size(nums) && nums[left] == left ? -1 : left;
40 }
41
42 private:
43 void inplace_counting_sort(vector *nums, bool is_reverse) {
44 static const int MAX_NUM = 1000;
45 vector count(MAX_NUM + 1);
46 for (const auto& num : *nums) {
47 ++count[num];
48 }
49 for (int i = 1; i < size(count); ++i) {
50 count[i] += count[i - 1];
51 }
52 vector result(size(*nums));
53 for (int i = size(*nums) - 1; i >= 0; --i) { // inplace but unstable sort
54 if ((*nums)[i] < 0) { // processed
55 continue;
56 }
57 while (i != count[(*nums)[i]] - 1) {
58 --count[(*nums)[i]];
59 tie((*nums)[count[(*nums)[i]]], (*nums)[i]) = pair(~(*nums)[i], (*nums)[count[(*nums)[i]]]);
60 }
60
61 --count[(*nums)[i]];
62 (*nums)[i] = ~(*nums)[i];
63 }
64 for (auto& num : *nums) {
65 num = ~num; // restore values
66 }
67 if (is_reverse) { // unstable sort
68 reverse(begin(*nums), end(*nums));
69 }
70 }
71 };
72
73 // Time: O(n)
74 // Space: O(n)
75 // binary search + counting sort solution
76 class Solution3 {
77 public:
78 int specialArray(vector& nums) {
79 nums = counting_sort(nums, true); // extra O(n) space for stable sort
80 int left = 0, right = size(nums) - 1;
81 while (left <= right) {
82 const auto& mid = left + (right - left) / 2;
83 if (nums[mid] <= mid) {
84 right = mid - 1;
85 } else {
86 left = mid + 1;
87 }
88 }
89 return left < size(nums) && nums[left] == left ? -1 : left;
90 }
91
92 private:
93 vector counting_sort(const vector& nums, bool is_reverse) {
94 static const int MAX_NUM = 1000;
95 vector count(MAX_NUM + 1);
96 for (const auto& num : nums) {
97 ++count[num];
98 }
99 for (int i = 1; i < size(count); ++i) {
100 count[i] += count[i - 1];
101 }
102 vector result(size(nums));
103 if (!is_reverse) {
104 for (int i = size(nums) - 1; i >= 0; --i) { // stable sort
105 result[--count[nums[i]]] = nums[i];
106 }
107 } else {
108 for (const auto& num : nums) { // stable sort
109 result[--count[num]] = num;
110 }
111 reverse(begin(result), end(result));
112 }
113 return result;
114 }
115 };
116
117 // Time: O(nlogn)
118 // Space: O(1)
119 // sort solution
120 class Solution4 {
121 public:
122 int specialArray(vector& nums) {
123 sort(rbegin(nums), rend(nums));
124 int i = 0;
125 while (i < size(nums)) {
126 if (nums[i] <= i) {
127 break;
128 }
129 ++i;
130 }
131 return i < size(nums) && nums[i] == i ? -1 : i;
132 }
133 };
133 };
*****************************************************

425. Special Array With X Elements Greater Than or Equal


X(Python)
*****************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 # counting sort solution
5 class Solution(object):
6 def specialArray(self, nums):
7 """
8 :type nums: List[int]
9 :rtype: int
10 """
11 MAX_NUM = 1000
12 count = [0]*(MAX_NUM+1)
13 for num in nums:
14 count[num] += 1
15 n = len(nums)
16 for i in xrange(len(count)):
17 if i == n:
18 return i
19 n -= count[i]
20 return -1
21
22
23 # Time: O(n)
24 # Space: O(1)
25 # counting sort + binary search solution
26 class Solution2(object):
27 def specialArray(self, nums):
28 """
29 :type nums: List[int]
30 :rtype: int
31 """
32 MAX_NUM = 1000
33 def inplace_counting_sort(nums, reverse=False): # Time: O(n)
34 count = [0]*(MAX_NUM+1)
35 for num in nums:
36 count[num] += 1
37 for i in xrange(1, len(count)):
38 count[i] += count[i-1]
39 for i in reversed(xrange(len(nums))): # inplace but unstable sort
40 if nums[i] < 0: # processed
41 continue
42 while i != count[nums[i]]-1:
43 count[nums[i]] -= 1
44 nums[count[nums[i]]], nums[i] = ~nums[i], nums[count[nums[i]]]
45 count[nums[i]] -= 1
46 nums[i] = ~nums[i]
47 for i in xrange(len(nums)):
48 nums[i] = ~nums[i] # restore values
49 if reverse: # unstable sort
50 nums.reverse()
51
52 inplace_counting_sort(nums, reverse=True)
53 left, right = 0, len(nums)-1
54 while left <= right: # Time: O(logn)
55 mid = left + (right-left)//2
56 if nums[mid] <= mid:
57 right = mid-1
58 else:
59 left = mid+1
60 return -1 if left < len(nums) and nums[left] == left else left
60
61
62
63 # Time: O(n)
64 # Space: O(n)
65 # counting sort + binary search solution
66 class Solution3(object):
67 def specialArray(self, nums):
68 """
69 :type nums: List[int]
70 :rtype: int
71 """
72 MAX_NUM = 1000
73 def counting_sort(nums, reverse=False): # Time: O(n), Space: O(n)
74 count = [0]*(MAX_NUM+1)
75 for num in nums:
76 count[num] += 1
77 for i in xrange(1, len(count)):
78 count[i] += count[i-1]
79 result = [0]*len(nums)
80 if not reverse:
81 for num in reversed(nums): # stable sort
82 count[num] -= 1
83 result[count[num]] = num
84 else:
85 for num in nums: # stable sort
86 count[num] -= 1
87 result[count[num]] = num
88 result.reverse()
89 return result
90
91 nums = counting_sort(nums, reverse=True) # extra O(n) space for stable sort
92 left, right = 0, len(nums)-1
93 while left <= right: # Time: O(logn)
94 mid = left + (right-left)//2
95 if nums[mid] <= mid:
96 right = mid-1
97 else:
98 left = mid+1
99 return -1 if left < len(nums) and nums[left] == left else left
100
101
102 # Time: O(nlogn)
103 # Space: O(1)
104 # sort solution
105 class Solution4(object):
106 def specialArray(self, nums):
107 """
108 :type nums: List[int]
109 :rtype: int
110 """
111 nums.sort(reverse=True) # Time: O(nlogn)
112 for i in xrange(len(nums)): # Time: O(n)
113 if nums[i] <= i:
114 break
115 else:
116 i += 1
117 return -1 if i < len(nums) and nums[i] == i else i
****************************************

426. Maximum Nesting Depth of the Parentheses


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

A string is a valid parentheses string (denoted VPS) if it meets one of the following:

It is an empty string "", or a single character not equal to"(" or ")" ,


It can be written as AB (A concatenated with B), where A and B are VPS's, or
It can be written as (A), where A is a VPS.

We can similarly define the nesting depth depth(S) of any VPS S as follows:

depth("") = 0
depth(C) = 0 , where C is a string with a single character not equal to"(" or ")" .
depth(A + B) = max(depth(A), depth(B)) , where A and B are VPS's.
depth("(" + A + ")") = 1 + depth(A) , where A is a VPS.

For example, "", "()()" , and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

Given a VPS represented as string s , return the nesting depth of s .

Example 1:

Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.

Example 2:

Input: s = "(1)+((2))+(((3)))"
Output: 3

Example 3:

Input: s = "1+(2*3)/(2-1)"
Output: 1

Example 4:

Input: s = "1"
Output: 0

Constraints:

1 <= s.length <= 100


s consists of digits 0-9
and characters '+' , '-', '*', '/', '(', and ')'.
It is guaranteed that parentheses expression s is a VPS.
****************************************

426. Maximum Nesting Depth of the Parentheses(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxDepth(string s) {
7 int result = 0, curr = 0;
8 for (const auto& c : s) {
9 if (c == '(') {
10 result = max(result, ++curr);
11 } else if (c == ')') {
12 --curr;
13 }
14 }
15 return result;
16 }
17 };
****************************************

426. Maximum Nesting Depth of the Parentheses(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxDepth(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result = curr = 0
11 for c in s:
12 if c == '(':
13 curr += 1
14 result = max(result, curr)
15 elif c == ')':
16 curr -= 1
17 return result
******************************************

427. Mean of Array After Removing Some Elements


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

Given an integer array arr, return the mean of the remaining integers after removing the smallest5% and the largest 5% of the
elements.

Answers within 10-5 of the actual answer will be considered accepted.

Example 1:

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


Output: 2.00000
Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.

Example 2:

Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]


Output: 4.00000

Example 3:

Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]


Output: 4.77778

Example 4:

Input: arr = [9,7,8,7,7,8,4,4,6,8,8,7,6,8,8,9,2,6,0,0,1,10,8,6,3,3,5,1,10,9,0,7,10,0,10,4,1,10,6,9,3,6,0,0,2,7,0,6,7,2,9,7,7,3,0,1,6,1,10,3]


Output: 5.27778

Example 5:

Input: arr = [4,8,4,10,0,7,1,3,7,8,8,3,4,1,6,2,1,1,8,0,9,8,0,3,9,10,3,10,1,10,7,3,2,1,4,9,10,7,6,4,0,8,5,1,2,1,6,2,5,0,7,10,9,10,3,7,10,5,8,5


Output: 5.29167

Constraints:

20 <= arr.length <= 1000


arr.length is a multiple of 20.
0 <= arr[i] <= 10 5
******************************************

427. Mean of Array After Removing Some Elements(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 double trimMean(vector& arr) {
7 static const int P = 20;
8 const int k = size(arr) / P;
9 nth_element(begin(arr), begin(arr) + k - 1, end(arr));
10 nth_element(begin(arr) + k, end(arr) - k, end(arr));
11 return accumulate(begin(arr) + k, end(arr) - k, 0.0) / (size(arr) - 2 * k);
12 }
13 };
******************************************

427. Mean of Array After Removing Some


Elements(Python)
******************************************

1 # Time: O(n) on average, using Median of Medians could achieve O(n) (Intro Select)
2 # Space: O(1)
3
4 import random
5
6
7 class Solution(object):
8 def trimMean(self, arr):
9 """
10 :type arr: List[int]
11 :rtype: float
12 """
13 P = 20
14 def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
15 def tri_partition(nums, left, right, target, compare):
16 mid = left
17 while mid <= right:
18 if nums[mid] == target:
19 mid += 1
20 elif compare(nums[mid], target):
21 nums[left], nums[mid] = nums[mid], nums[left]
22 left += 1
23 mid += 1
24 else:
25 nums[mid], nums[right] = nums[right], nums[mid]
26 right -= 1
27 return left, right
28
29 right = len(nums)-1
30 while left <= right:
31 pivot_idx = random.randint(left, right)
32 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
33 if pivot_left <= n <= pivot_right:
34 return
35 elif pivot_left > n:
36 right = pivot_left-1
37 else: # pivot_right < n.
38 left = pivot_right+1
39
40 k = len(arr)//P
41 nth_element(arr, k-1)
42 nth_element(arr, len(arr)-k, left=k)
43 return float(sum(arr[i] for i in xrange(k, len(arr)-k)))/(len(arr)-2*k)
***********************************************

428. All Valid Triplets That Can Represent a Country


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

Table: SchoolA

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| student_id | int |
| student_name | varchar |
+---------------+---------+
student_id is the primary key for this table.
Each row of this table contains the name and the id of a student in school A.
All student_name are distinct.

Table: SchoolB

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| student_id | int |
| student_name | varchar |
+---------------+---------+
student_id is the primary key for this table.
Each row of this table contains the name and the id of a student in school B.
All student_name are distinct.

Table: SchoolC

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| student_id | int |
| student_name | varchar |
+---------------+---------+
student_id is the primary key for this table.
Each row of this table contains the name and the id of a student in school C.
All student_name are distinct.

There is a country with three schools, where each student is enrolled inexactly one school. The country is joining a
competition and wants to select one student from each school to represent the country such that:

member_A is selected from SchoolA,


member_B is selected from SchoolB,
member_C is selected from SchoolC, and
The selected students' names and IDs are pairwise distinct (i.e. no two students share the same name, and no two
students share the same ID).

Write an SQL query to find all the possible triplets representing the country under the given constraints.

Return the result table in any order.


The query result format is in the following example.

SchoolA table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1 | Alice |
| 2 | Bob |
+------------+--------------+

SchoolB table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 3 | Tom |
+------------+--------------+

SchoolC table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 3 | Tom |
| 2 | Jerry |
| 10 | Alice |
+------------+--------------+

Result table:
+----------+----------+----------+
| member_A | member_B | member_C |
+----------+----------+----------+
| Alice | Tom | Jerry |
| Bob | Tom | Alice |
+----------+----------+----------+
Let us see all the possible triplets.
- (Alice, Tom, Tom) --> Rejected because member_B and member_C have the same name and the same ID.
- (Alice, Tom, Jerry) --> Valid triplet.
- (Alice, Tom, Alice) --> Rejected because member_A and member_C have the same name.
- (Bob, Tom, Tom) --> Rejected because member_B and member_C have the same name and the same ID.
- (Bob, Tom, Jerry) --> Rejected because member_A and member_C have the same ID.
- (Bob, Tom, Alice) --> Valid triplet.
***********************************************

428. All Valid Triplets That Can Represent a


Country(Shell)
***********************************************

1 # Time: O(n^3)
2 # Space: O(n^3)
3
4 SELECT a.student_name AS member_A,
5 b.student_name AS member_B,
6 c.student_name AS member_c
7 FROM schoola a
8 INNER JOIN schoolb b ON (a.student_id != b.student_id
9 AND a.student_name != b.student_name)
10 INNER JOIN schoolc c ON (a.student_id != c.student_id
11 AND a.student_name != c.student_name)
12 AND (b.student_id != c.student_id
13 AND b.student_name != c.student_name);
**********************************************

429. Largest Substring Between Two Equal Characters


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

Given a string s , return the length of the longest substring between two equal characters, excluding the two characters.If
there is no such substring return -1.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty substring between the two 'a's.

Example 2:

Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".

Example 3:

Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.

Example 4:

Input: s = "cabbac"
Output: 4
Explanation: The optimal substring here is "abba". Other non-optimal substrings include "bb" and "".

Constraints:

1 <= s.length <= 300


s contains only lowercase English letters.
**********************************************

429. Largest Substring Between Two Equal


Characters(C++)
**********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maxLengthBetweenEqualCharacters(string s) {
7 int result = -1;
8 vector lookup(26, -1);
9 for (int i = 0; i < size(s); ++i) {
10 if (lookup[s[i] - 'a'] >= 0) {
11 result = max(result, i - lookup[s[i] - 'a'] - 1);
12 } else {
13 lookup[s[i] - 'a'] = i;
14 }
15 }
16 return result;
17 }
18 };
**********************************************

429. Largest Substring Between Two Equal


Characters(Python)
**********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maxLengthBetweenEqualCharacters(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 result, lookup = -1, {}
11 for i, c in enumerate(s):
12 result = max(result, i-lookup.setdefault(c, i)-1)
13 return result
***********

430. Slowest Key


***********

A newly designed keypad was tested, where a tester pressed a sequence ofn keys, one at a time.

You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a
sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was
pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.

The tester wants to know the key of the keypress that had thelongest duration. The ith keypress had a duration of
releaseTimes[i] - releaseTimes[i - 1] , and the 0th keypress had a duration of releaseTimes[0].

Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key
may not have had the same duration.

Return the key of the keypress that had thelongest duration. If there are multiple such keypresses, return the
lexicographically largest key of the keypresses.

Example 1:

Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"


Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50)
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.

Example 2:

Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"


Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.

Constraints:

releaseTimes.length == n
keysPressed.length == n
2 <= n <= 1000
1 <= releaseTimes[i] <= 10 9
releaseTimes[i] < releaseTimes[i+1]
keysPressed contains only lowercase English letters.
***********

430. Slowest Key(C++)


***********

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 char slowestKey(vector& releaseTimes, string keysPressed) {
7 char result = 'a';
8 vector lookup(26);
9 for (int i = 0; i < size(keysPressed); ++i) {
10 auto c = keysPressed[i];
11 lookup[c - 'a'] = max(lookup[keysPressed[i] - 'a'],
12 releaseTimes[i] - (i > 0 ? releaseTimes[i - 1] : 0));
13 if (lookup[c - 'a'] > lookup[result - 'a'] ||
14 (lookup[c - 'a'] == lookup[result - 'a'] && c > result)) {
15 result = c;
16 }
17 }
18 return result;
19 }
20 };
***********

430. Slowest Key(Python)


***********

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def slowestKey(self, releaseTimes, keysPressed):
9 """
10 :type releaseTimes: List[int]
11 :type keysPressed: str
12 :rtype: str
13 """
14 result, lookup = 'a', collections.Counter()
15 for i, c in enumerate(keysPressed):
16 lookup[c] = max(lookup[c], releaseTimes[i]-(releaseTimes[i-1] if i > 0 else 0))
17 if lookup[c] > lookup[result] or lookup[c] == lookup[result] and c > result:
18 result = c
19 return result
**************************************

431. Percentage of Users Attended a Contest


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

Table: Users

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| user_name | varchar |
+-------------+---------+
user_id is the primary key for this table.
Each row of this table contains the name and the id of a user.

Table: Register

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| contest_id | int |
| user_id | int |
+-------------+---------+
(contest_id, user_id) is the primary key for this table.
Each row of this table contains the id of a user and the contest they registered into.

Write an SQL query to find the percentage of the users registered in each contest rounded to two decimals.

Return the result table ordered by percentage in descending order. In case of a tie, order it bycontest_id in ascending order.

The query result format is in the following example.


Users table:
+---------+-----------+
| user_id | user_name |
+---------+-----------+
| 6 | Alice |
| 2 | Bob |
| 7 | Alex |
+---------+-----------+

Register table:
+------------+---------+
| contest_id | user_id |
+------------+---------+
| 215 | 6 |
| 209 | 2 |
| 208 | 2 |
| 210 | 6 |
| 208 | 6 |
| 209 | 7 |
| 209 | 6 |
| 215 | 7 |
| 208 | 7 |
| 210 | 2 |
| 207 | 2 |
| 210 | 7 |
+------------+---------+

Result table:
+------------+------------+
| contest_id | percentage |
+------------+------------+
| 208 | 100.0 |
| 209 | 100.0 |
| 210 | 100.0 |
| 215 | 66.67 |
| 207 | 33.33 |
+------------+------------+
All the users registered in contests 208, 209, and 210. The percentage is 100% and we sort them in the answer table by contest_id in ascendin
Alice and Alex registered in contest 215 and the percentage is ((2/3) * 100) = 66.67%
Bob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33%
**************************************

431. Percentage of Users Attended a Contest(Shell)


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

1 # Time: O(m + nlogn)


2 # Space: O(n)
3
4 SELECT contest_id,
5 ROUND(COUNT(user_id) * 100 / (SELECT COUNT(*) FROM Users), 2) AS percentage
6 FROM Register
7 GROUP BY contest_id
8 ORDER BY 2 DESC, 1;
**********************************

432. Sort Array by Increasing Frequency


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

Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values
have the same frequency, sort them in decreasing order.

Return the sorted array.

Example 1:

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


Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.

Example 2:

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


Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.

Example 3:

Input: nums = [-1,1,-6,4,5,-6,1,4,1]


Output: [5,-1,4,4,-6,-6,1,1,1]

Constraints:

1 <= nums.length <= 100


-100 <= nums[i] <= 100
**********************************

432. Sort Array by Increasing Frequency(C++)


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

1 // Time: O(nlogn)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 vector frequencySort(vector& nums) {
7 unordered_map count;
8 for (const auto& x : nums) {
9 ++count[x];
10 }
11 sort(begin(nums), end(nums),
12 [&count](const auto& a, const auto& b) {
13 return count[a] == count[b] ? a > b : count[a] < count[b];
14 });
15 return nums;
16 }
17 };
**********************************

432. Sort Array by Increasing Frequency(Python)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def frequencySort(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: List[int]
12 """
13 count = collections.Counter(nums)
14 return sorted(nums, key=lambda x: (count[x], -x))
*******************************************

433. Check Array Formation Through Concatenation


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

You are given an array of distinct integers arr and an array of integer arrays pieces , where the integers in pieces are distinct.
Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the
integers in each array pieces[i].

Return true if it is possible to form the array arr from pieces . Otherwise, return false.

Example 1:

Input: arr = [85], pieces = [[85]]


Output: true

Example 2:

Input: arr = [15,88], pieces = [[88],[15]]


Output: true
Explanation: Concatenate [15] then [88]

Example 3:

Input: arr = [49,18,16], pieces = [[16,18,49]]


Output: false
Explanation: Even though the numbers match, we cannot reorder pieces[0].

Example 4:

Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]


Output: true
Explanation: Concatenate [91] then [4,64] then [78]

Example 5:

Input: arr = [1,3,5,7], pieces = [[2,4,6,8]]


Output: false

Constraints:

1 <= pieces.length <= arr.length <= 100


sum(pieces[i].length) == arr.length
1 <= pieces[i].length <= arr.length
1 <= arr[i], pieces[i][j] <= 100
The integers in arr are distinct.
The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
*******************************************

433. Check Array Formation Through Concatenation(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 bool canFormArray(vector& arr, vector>& pieces) {
7 unordered_map lookup;
8 for (int i = 0; i < size(pieces); ++i) {
9 lookup[pieces[i][0]] = i;
10 }
11 for (int i = 0; i < size(arr);) {
12 if (!lookup.count(arr[i])) {
13 return false;
14 }
15 for (const auto& c : pieces[lookup[arr[i]]]) {
16 if (i == size(arr) || arr[i] != c) {
17 return false;
18 }
19 ++i;
20 }
21 }
22 return true;
23 }
24 };
*******************************************

433. Check Array Formation Through


Concatenation(Python)
*******************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def canFormArray(self, arr, pieces):
6 """
7 :type arr: List[int]
8 :type pieces: List[List[int]]
9 :rtype: bool
10 """
11 lookup = {x[0]: i for i, x in enumerate(pieces)}
12 i = 0
13 while i < len(arr):
14 if arr[i] not in lookup:
15 return False
16 for c in pieces[lookup[arr[i]]]:
17 if i == len(arr) or arr[i] != c:
18 return False
19 i += 1
20 return True
******************************

434. Get Maximum in Generated Array


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

You are given an integer n. An array nums of length n + 1 is generated in the following way:

nums[0] = 0
nums[1] = 1
nums[2 * i] = nums[i] when 2 <= 2 * i <= n
nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n

Return the maximum integer in the array nums​​​.

Example 1:

Input: n = 7
Output: 3
Explanation: According to the given rules:
nums[0] = 0
nums[1] = 1
nums[(1 * 2) = 2] = nums[1] = 1
nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
nums[(2 * 2) = 4] = nums[2] = 1
nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
nums[(3 * 2) = 6] = nums[3] = 2
nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is 3.

Example 2:

Input: n = 2
Output: 1
Explanation: According to the given rules, the maximum between nums[0], nums[1], and nums[2] is 1.

Example 3:

Input: n = 3
Output: 2
Explanation: According to the given rules, the maximum between nums[0], nums[1], nums[2], and nums[3] is 2.

Constraints:

0 <= n <= 100


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

434. Get Maximum in Generated Array(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 vector nums = {0, 1};
5 vector dp = {0, 1};
6 class Solution {
7 public:
8 int getMaximumGenerated(int n) {
9 if (n + 1 > size(dp)) {
10 for (int i = size(nums); i <= n; ++i) {
11 if (i % 2 == 0) {
12 nums.emplace_back(nums[i / 2]);
13 } else {
14 nums.emplace_back(nums[i / 2] + nums[i / 2 + 1]);
15 }
16 dp.emplace_back(max(dp.back(), nums.back()));
17 }
18 }
19 return dp[n];
20 }
21 };
22
23
24 // Time: O(n)
25 // Space: O(n)
26 class Solution2 {
27 public:
28 int getMaximumGenerated(int n) {
29 if (n == 0) {
30 return 0;
31 }
32 vector nums(n + 1);
33 nums[1] = 1;
34 int result = 1;
35 for (int i = 2; i <= n; ++i) {
36 if (i % 2 == 0) {
37 nums[i] = nums[i / 2];
38 } else {
39 nums[i] = nums[i / 2] + nums[i / 2 + 1];
40 }
41 result = max(result, nums[i]);
42 }
43 return result;
44 }
45 };
******************************

434. Get Maximum in Generated Array(Python)


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

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

435. Defuse the Bomb


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

You have a bomb to defuse, and your time is running out! Your informer will provide you with acircular array code of length
of n and a key k .

To decrypt the code, you must replace every number. All the numbers are replacedsimultaneously.

If k > 0 , replace the ith number with the sum of thenext k numbers.
If k < 0 , replace the ith number with the sum of theprevious k numbers.
If k == 0 , replace the ith number with 0.

As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].

Given the circular array code and an integer key k , return the decrypted code to defuse the bomb!

Example 1:

Input: code = [5,7,1,4], k = 3


Output: [12,10,16,13]
Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the nu

Example 2:

Input: code = [1,2,3,4], k = 0


Output: [0,0,0,0]
Explanation: When k is zero, the numbers are replaced by 0.

Example 3:

Input: code = [2,4,9,3], k = -2


Output: [12,5,6,13]
Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previ

Constraints:

n == code.length
1 <= n <= 100
1 <= code[i] <= 100
-(n - 1) <= k <= n - 1
***************

435. Defuse the Bomb(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector decrypt(vector& code, int k) {
7 vector result(size(code));
8 if (k == 0) {
9 return result;
10 }
11 int left = 1, right = k;
12 if (k < 0) {
13 k = -k;
14 left = size(code) - k, right = size(code) - 1;
15 }
16 int total = accumulate(begin(code) + left, begin(code) + right + 1, 0);
17 for (int i = 0; i < size(code); ++i) {
18 result[i] = total;
19 total -= code[left++ % size(code)];
20 total += code[++right % size(code)];
21 }
22 return result;
23 }
24 };
***************

435. Defuse the Bomb(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def decrypt(self, code, k):
6 """
7 :type code: List[int]
8 :type k: int
9 :rtype: List[int]
10 """
11 result = [0]*len(code)
12 if k == 0:
13 return result
14 left, right = 1, k
15 if k < 0:
16 k = -k
17 left, right = len(code)-k, len(code)-1
18 total = sum(code[i] for i in xrange(left, right+1))
19 for i in xrange(len(code)):
20 result[i] = total
21 total -= code[left%len(code)]
22 total += code[(right+1)%len(code)]
23 left += 1
24 right += 1
25 return result
************************

436. Design an Ordered Stream


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

There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a
string. No two pairs have the same id.

Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each
insertion. The concatenation of all the chunks should result in a list of the sorted values.

Implement the OrderedStream class:

OrderedStream(int n) Constructs the stream to take n values.


String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of
currently inserted values that appear next in the order.

Example:

Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
Output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]

Explanation
// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].
os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].
os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].
os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].
// Concatentating all the chunks returned:
// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]
// The resulting order is the same as the order above.

Constraints:

1 <= n <= 1000


1 <= id <= n
value.length == 5
value consists only of lowercase letters.
Each call to insert will have a unique id.
Exactly n calls will be made to insert.
************************

436. Design an Ordered Stream(C++)


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

1 // Time: O(1), amortized


2 // Space: O(n)
3
4 class OrderedStream {
5 public:
6 OrderedStream(int n)
7 : i_(0)
8 , values_(n) {
9
10 }
11
12 vector insert(int id, string value) {
13 --id;
14 values_[id] = value;
15 vector result;
16 if (id != i_) {
17 return result;
18 }
19 while (i_ < size(values_) && !empty(values_[i_])) {
20 result.emplace_back(values_[i_++]);
21 }
22 return result;
23 }
24
25 private:
26 int i_;
27 vector values_;
28 };
************************

436. Design an Ordered Stream(Python)


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

1 # Time: O(1), amortized


2 # Space: O(n)
3
4 class OrderedStream(object):
5
6 def __init__(self, n):
7 """
8 :type n: int
9 """
10 self.__i = 0
11 self.__values = [None]*n
12
13 def insert(self, id, value):
14 """
15 :type id: int
16 :type value: str
17 :rtype: List[str]
18 """
19 id -= 1
20 self.__values[id] = value
21 result = []
22 if self.__i != id:
23 return result
24 while self.__i < len(self.__values) and self.__values[self.__i]:
25 result.append(self.__values[self.__i])
26 self.__i += 1
27 return result
***********************************

437. Average Time of Process per Machine


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

Table: Activity

+----------------+---------+
| Column Name | Type |
+----------------+---------+
| machine_id | int |
| process_id | int |
| activity_type | enum |
| timestamp | float |
+----------------+---------+
The table shows the user activities for a factory website.
(machine_id, process_id, activity_type) is the primary key of this table.
machine_id is the ID of a machine.
process_id is the ID of a process running on the machine with ID machine_id.
activity_type is an ENUM of type ('start', 'end').
timestamp is a float representing the current time in seconds.
'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp.
The 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair.

There is a factory website that has several machines each running thesame number of processes. Write an SQL query to
find the average time each machine takes to complete a process.

The time to complete a process is the 'end' timestamp minus the 'start' timestamp. The average time is calculated by the total time
to complete every process on the machine divided by the number of processes that were run.

The resulting table should have the machine_id along with the average time as processing_time , which should be rounded to 3
decimal places.

The query result format is in the following example:


Activity table:
+------------+------------+---------------+-----------+
| machine_id | process_id | activity_type | timestamp |
+------------+------------+---------------+-----------+
| 0 | 0 | start | 0.712 |
| 0 | 0 | end | 1.520 |
| 0 | 1 | start | 3.140 |
| 0 | 1 | end | 4.120 |
| 1 | 0 | start | 0.550 |
| 1 | 0 | end | 1.550 |
| 1 | 1 | start | 0.430 |
| 1 | 1 | end | 1.420 |
| 2 | 0 | start | 4.100 |
| 2 | 0 | end | 4.512 |
| 2 | 1 | start | 2.500 |
| 2 | 1 | end | 5.000 |
+------------+------------+---------------+-----------+

Result table:
+------------+-----------------+
| machine_id | processing_time |
+------------+-----------------+
| 0 | 0.894 |
| 1 | 0.995 |
| 2 | 1.456 |
+------------+-----------------+

There are 3 machines running 2 processes each.


Machine 0's average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894
Machine 1's average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995
Machine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456
***********************************

437. Average Time of Process per Machine(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT s.machine_id, ROUND(AVG(e.timestamp-s.timestamp), 3) AS processing_time
5 FROM Activity s INNER JOIN Activity e
6 ON s.machine_id = e.machine_id
7 AND s.process_id = e.process_id
8 AND s.activity_type = 'start'
9 AND e.activity_type = 'end'
10 GROUP BY s.machine_id
11 ORDER BY NULL;
*****************************************

438. Check If Two String Arrays are Equivalent


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

Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

A string is represented by an array if the array elements concatenatedin order forms the string.

Example 1:

Input: word1 = ["ab", "c"], word2 = ["a", "bc"]


Output: true
Explanation:
word1 represents string "ab" + "c" -> "abc"
word2 represents string "a" + "bc" -> "abc"
The strings are the same, so return true.

Example 2:

Input: word1 = ["a", "cb"], word2 = ["ab", "c"]


Output: false

Example 3:

Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]


Output: true

Constraints:

1 <= word1.length, word2.length <= 10 3


1 <= word1[i].length, word2[i].length <= 10 3
1 <= sum(word1[i].length), sum(word2[i].length) <= 10 3
word1[i] and word2[i] consist of lowercase letters.
*****************************************

438. Check If Two String Arrays are Equivalent(C++)


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

1 // Time: O(n), n is the total length of word1 and word2


2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool arrayStringsAreEqual(vector& word1, vector& word2) {
7 int idx1 = 0, idx2 = 0, arrIdx1 = 0, arrIdx2 = 0;
8 while (arrIdx1 < size(word1) && arrIdx2 < size(word2)) {
9 if (word1[arrIdx1][idx1] != word2[arrIdx2][idx2]) {
10 break;
11 }
12 ++idx1;
13 if (idx1 == size(word1[arrIdx1])) {
14 idx1 = 0;
15 ++arrIdx1;
16 }
17 ++idx2;
18 if (idx2 == size(word2[arrIdx2])) {
19 idx2 = 0;
20 ++arrIdx2;
21 }
22 }
23 return arrIdx1 == size(word1) && arrIdx2 == size(word2);
24 }
25 };
*****************************************

438. Check If Two String Arrays are Equivalent(Python)


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

1 # Time: O(n), n is the total length of word1 and word2


2 # Space: O(1)
3
4 class Solution(object):
5 def arrayStringsAreEqual(self, word1, word2):
6 """
7 :type word1: List[str]
8 :type word2: List[str]
9 :rtype: bool
10 """
11 idx1 = idx2 = arr_idx1 = arr_idx2 = 0
12 while arr_idx1 < len(word1) and arr_idx2 < len(word2):
13 if word1[arr_idx1][idx1] != word2[arr_idx2][idx2]:
14 break
15 idx1 += 1
16 if idx1 == len(word1[arr_idx1]):
17 idx1 = 0
18 arr_idx1 += 1
19 idx2 += 1
20 if idx2 == len(word2[arr_idx2]):
21 idx2 = 0
22 arr_idx2 += 1
23 return arr_idx1 == len(word1) and arr_idx2 == len(word2)
********************

439. Fix Names in a Table


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

Table: Users

+----------------+---------+
| Column Name | Type |
+----------------+---------+
| user_id | int |
| name | varchar |
+----------------+---------+
user_id is the primary key for this table.
This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters.

Write an SQL query to fix the names so that only the first character is uppercase and the rest are lowercase.

Return the result table ordered by user_id.

The query result format is in the following example:

Users table:
+---------+-------+
| user_id | name |
+---------+-------+
| 1 | aLice |
| 2 | bOB |
+---------+-------+

Result table:
+---------+-------+
| user_id | name |
+---------+-------+
| 1 | Alice |
| 2 | Bob |
+---------+-------+
********************

439. Fix Names in a Table(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT user_id, CONCAT(UPPER(SUBSTRING(name, 1, 1)), LOWER(SUBSTRING(name, 2))) AS name
5 FROM Activity
6 ORDER BY user_id;
***************************

440. Maximum Repeating Substring


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

For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum
k-repeating value is the highest value k where word is k -repeating in sequence. If word is not a substring of sequence, word's
maximum k -repeating value is 0.

Given strings sequence and word, return the maximum k-repeating value of word in sequence.

Example 1:

Input: sequence = "ababc", word = "ab"


Output: 2
Explanation: "abab" is a substring in "ababc".

Example 2:

Input: sequence = "ababc", word = "ba"


Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".

Example 3:

Input: sequence = "ababc", word = "ac"


Output: 0
Explanation: "ac" is not a substring in "ababc".

Constraints:

1 <= sequence.length <= 100


1 <= word.length <= 100
sequence and word contains only lowercase English letters.
***************************

440. Maximum Repeating Substring(C++)


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

1 // Time: O(n), n is the length of sequence


2 // Space: O(m), m is the length of word
3
4 // optimized kmp solution
5 class Solution {
6 public:
7 int maxRepeating(string sequence, string word) {
8 if (size(sequence) < size(word)) {
9 return 0;
10 }
11 const vector prefix = getPrefix(word);
12 int result = 0, count = 0, j = -1, prev = -1;
13 for (int i = 0; i < size(sequence); ++i) {
14 while (j > -1 && word[j + 1] != sequence[i]) {
15 j = prefix[j];
16 }
17 if (word[j + 1] == sequence[i]) {
18 ++j;
19 }
20 if (j + 1 == size(word)) {
21 count = (i - prev == size(word)) ? count + 1 : 1;
22 result = max(result, count);
23 j = -1, prev = i;
24 }
25 }
26 return result;
27 }
28
29 private:
30 vector getPrefix(const string& pattern) {
31 vector prefix(size(pattern), -1);
32 int j = -1;
33 for (int i = 1; i < size(pattern); ++i) {
34 while (j > -1 && pattern[j + 1] != pattern[i]) {
35 j = prefix[j];
36 }
37 if (pattern[j + 1] == pattern[i]) {
38 ++j;
39 }
40 prefix[i] = j;
41 }
42 return prefix;
43 }
44 };
45
46 // Time: O(n), n is the length of sequence
47 // Space: O(n)
48 // kmp solution
49 class Solution2 {
50 public:
51 int maxRepeating(string sequence, string word) {
52 if (size(sequence) < size(word)) {
53 return 0;
54 }
55 string new_word;
56 for (int i = 0; i < size(sequence) / size(word); ++i) {
57 new_word += word;
58 }
59 const vector prefix = getPrefix(new_word);
60 int result = 0, j = -1;
61 for (int i = 0; i < size(sequence); ++i) {
62 while (j > -1 && new_word[j + 1] != sequence[i]) {
63 j = prefix[j];
64 }
65 if (new_word[j + 1] == sequence[i]) {
66 ++j;
67 }
68 result = max(result, j + 1);
69 if (j + 1 == size(new_word)) {
70 break;
71 }
72 }
73 return result / size(word);
74 }
75
76 private:
77 vector getPrefix(const string& pattern) {
78 vector prefix(size(pattern), -1);
79 int j = -1;
80 for (int i = 1; i < size(pattern); ++i) {
81 while (j > -1 && pattern[j + 1] != pattern[i]) {
82 j = prefix[j];
83 }
84 if (pattern[j + 1] == pattern[i]) {
85 ++j;
86 }
87 prefix[i] = j;
88 }
89 return prefix;
90 }
91 };
***************************

440. Maximum Repeating Substring(Python)


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

1 # Time: O(n), n is the length of sequence


2 # Space: O(m), m is the length of word
3
4 # optimized kmp solution
5 class Solution(object):
6 def maxRepeating(self, sequence, word):
7 """
8 :type sequence: str
9 :type word: str
10 :rtype: int
11 """
12 def getPrefix(pattern):
13 prefix = [-1] * len(pattern)
14 j = -1
15 for i in xrange(1, len(pattern)):
16 while j > -1 and pattern[j + 1] != pattern[i]:
17 j = prefix[j]
18 if pattern[j+1] == pattern[i]:
19 j += 1
20 prefix[i] = j
21 return prefix
22
23 if len(sequence) < len(word):
24 return 0
25
26 prefix = getPrefix(word)
27 result, count, j, prev = 0, 0, -1, -1
28 for i in xrange(len(sequence)):
29 while j > -1 and word[j+1] != sequence[i]:
30 j = prefix[j]
31 if word[j+1] == sequence[i]:
32 j += 1
33 if j+1 == len(word):
34 count = count+1 if i-prev == len(word) else 1
35 result = max(result, count)
36 j, prev = -1, i
37 return result
38
39
40 # Time: O(n), n is the length of sequence
41 # Space: O(n)
42 # kmp solution
43 class Solution2(object):
44 def maxRepeating(self, sequence, word):
45 """
46 :type sequence: str
47 :type word: str
48 :rtype: int
49 """
50 def getPrefix(pattern):
51 prefix = [-1] * len(pattern)
52 j = -1
53 for i in xrange(1, len(pattern)):
54 while j > -1 and pattern[j + 1] != pattern[i]:
55 j = prefix[j]
56 if pattern[j+1] == pattern[i]:
57 j += 1
58 prefix[i] = j
59 return prefix
60
61 if len(sequence) < len(word):
62 return 0
63
64 new_word = word*(len(sequence)//len(word))
65 prefix = getPrefix(new_word)
66 result, j = 0, -1
67 for i in xrange(len(sequence)):
68 while j > -1 and new_word[j+1] != sequence[i]:
69 j = prefix[j]
70 if new_word[j+1] == sequence[i]:
71 j += 1
72 result = max(result, j+1)
73 if j+1 == len(new_word):
74 break
75 return result//len(word)
***********************

441. Richest Customer Wealth


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

You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the
i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the
wealth that the richest customer has.

A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that
has the maximum wealth.

Example 1:

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


Output: 6
Explanation:
1st customer has wealth = 1 + 2 + 3 = 6
2nd customer has wealth = 3 + 2 + 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6.

Example 2:

Input: accounts = [[1,5],[7,3],[3,5]]


Output: 10
Explanation:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.

Example 3:

Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]


Output: 17

Constraints:

m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
***********************

441. Richest Customer Wealth(C++)


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

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maximumWealth(vector>& accounts) {
7 int result = 0;
8 for (const auto& account : accounts) {
9 int total = accumulate(cbegin(account), cend(account), 0);
10 result = max(result, total);
11 }
12 return result;
13 }
14 };
***********************

441. Richest Customer Wealth(Python)


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

1 # Time: O(m * n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def maximumWealth(self, accounts):
9 """
10 :type accounts: List[List[int]]
11 :rtype: int
12 """
13 return max(itertools.imap(sum, accounts))
*****************************

442. Product's Worth Over Invoices


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

Table: Product

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| name | varchar |
+-------------+---------+
product_id is the primary key for this table.
This table contains the ID and the name of the product. The name consists of only lowercase English letters. No two products have the same na

Table: Invoice

+-------------+------+
| Column Name | Type |
+-------------+------+
| invoice_id | int |
| product_id | int |
| rest | int |
| paid | int |
| canceled | int |
| refunded | int |
+-------------+------+
invoice_id is the primary key for this table and the id of this invoice.
product_id is the id of the product for this invoice.
rest is the amount left to pay for this invoice.
paid is the amount paid for this invoice.
canceled is the amount canceled for this invoice.
refunded is the amount refunded for this invoice.

Write an SQL query that will, for all products, return each product name with total amount due, paid, canceled, and refunded
across all invoices.

Return the result table ordered by product_name.

The query result format is in the following example:


Product table:
+------------+-------+
| product_id | name |
+------------+-------+
| 0 | ham |
| 1 | bacon |
+------------+-------+
Invoice table:
+------------+------------+------+------+----------+----------+
| invoice_id | product_id | rest | paid | canceled | refunded |
+------------+------------+------+------+----------+----------+
| 23 | 0 | 2 | 0 | 5 | 0 |
| 12 | 0 | 0 | 4 | 0 | 3 |
| 1 | 1 | 1 | 1 | 0 | 1 |
| 2 | 1 | 1 | 0 | 1 | 1 |
| 3 | 1 | 0 | 1 | 1 | 1 |
| 4 | 1 | 1 | 1 | 1 | 0 |
+------------+------------+------+------+----------+----------+
Result table:
+-------+------+------+----------+----------+
| name | rest | paid | canceled | refunded |
+-------+------+------+----------+----------+
| bacon | 3 | 3 | 3 | 3 |
| ham | 2 | 4 | 5 | 3 |
+-------+------+------+----------+----------+
- The amount of money left to pay for bacon is 1 + 1 + 0 + 1 = 3
- The amount of money paid for bacon is 1 + 0 + 1 + 1 = 3
- The amount of money canceled for bacon is 0 + 1 + 1 + 1 = 3
- The amount of money refunded for bacon is 1 + 1 + 1 + 0 = 3
- The amount of money left to pay for ham is 2 + 0 = 2
- The amount of money paid for ham is 0 + 4 = 4
- The amount of money canceled for ham is 5 + 0 = 5
- The amount of money refunded for ham is 0 + 3 = 3
*****************************

442. Product's Worth Over Invoices(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT name,
5 Sum(rest) rest,
6 Sum(paid) paid,
7 Sum(canceled) canceled,
8 Sum(refunded) refunded
9 FROM product p
10 INNER JOIN invoice i
11 ON p.product_id = i.product_id
12 GROUP BY name
13 ORDER BY name;
**************************

443. Goal Parser Interpretation


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

You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in
some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted
strings are then concatenated in the original order.

Given the string command, return the Goal Parser's interpretation of command.

Example 1:

Input: command = "G()(al)"


Output: "Goal"
Explanation: The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal".

Example 2:

Input: command = "G()()()()(al)"


Output: "Gooooal"

Example 3:

Input: command = "(al)G(al)()()G"


Output: "alGalooG"

Constraints:

1 <= command.length <= 100


command consists of "G", "()", and/or "(al)" in some order.
**************************

443. Goal Parser Interpretation(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string interpret(string command) {
7 string result;
8 for (int i = 0; i < size(command);) {
9 if (command[i] == 'G') {
10 result += 'G', ++i;
11 } else if (command[i + 1] == ')') {
12 result += 'o', i += 2;
13 } else {
14 result += "al", i += 4;
15 }
16 }
17 return result;
18 }
19 };
**************************

443. Goal Parser Interpretation(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def interpret(self, command):
6 """
7 :type command: str
8 :rtype: str
9 """
10 result, i = [], 0
11 while i < len(command):
12 if command[i] == 'G':
13 result += ["G"]
14 i += 1
15 elif command[i] == '(' and command[i+1] == ')':
16 result += ["o"]
17 i += 2
18 else:
19 result += ["al"]
20 i += 4
21 return "".join(result)
**************

444. Invalid Tweets


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

Table: Tweets

+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
tweet_id is the primary key for this table.
This table contains all the tweets in a social media app.

Write an SQL query to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content
of the tweet is strictly greater than 15.

Return the result table in any order.

The query result format is in the following example:

Tweets table:
+----------+----------------------------------+
| tweet_id | content |
+----------+----------------------------------+
| 1 | Vote for Biden |
| 2 | Let us make America great again! |
+----------+----------------------------------+

Result table:
+----------+
| tweet_id |
+----------+
| 2 |
+----------+
Tweet 1 has length = 14. It is a valid tweet.
Tweet 2 has length = 32. It is an invalid tweet.
**************

444. Invalid Tweets(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT tweet_id
5 FROM Tweets
6 WHERE CHAR_LENGTH(content) > 15;
**************************************

445. Count the Number of Consistent Strings


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

You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all
characters in the string appear in the string allowed.

Return the number of consistent strings in the array words.

Example 1:

Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]


Output: 2
Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.

Example 2:

Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]


Output: 7
Explanation: All strings are consistent.

Example 3:

Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]


Output: 4
Explanation: Strings "cc", "acd", "ac", and "d" are consistent.

Constraints:

1 <= words.length <= 10 4


1 <= allowed.length <= 26
1 <= words[i].length <= 10
The characters in allowed are distinct.
words[i] and allowed contain only lowercase English letters.
**************************************

445. Count the Number of Consistent Strings(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countConsistentStrings(string allowed, vector& words) {
7 int result = size(words);
8 vector lookup(26);
9 for (const auto& c: allowed) {
10 lookup[c - 'a'] = true;
11 }
12 for (const auto& word: words) {
13 for (const auto& c: word) {
14 if (!lookup[c - 'a']) {
15 --result;
16 break;
17 }
18 }
19 }
20 return result;
21 }
22 };
**************************************

445. Count the Number of Consistent Strings(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countConsistentStrings(self, allowed, words):
6 """
7 :type allowed: str
8 :type words: List[str]
9 :rtype: int
10 """
11 lookup = [False]*26
12 for c in allowed:
13 lookup[ord(c)-ord('a')] = True
14 result = len(words)
15 for word in words:
16 for c in word:
17 if not lookup[ord(c)-ord('a')]:
18 result -= 1
19 break
20 return result
******************************

446. Count of Matches in Tournament


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

You are given an integer n, the number of teams in a tournament that has strange rules:

If the current number of teams is even, each team gets paired with another team. A total ofn / 2 matches are played,
and n / 2 teams advance to the next round.
If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A
total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.

Return the number of matches played in the tournament until a winner is decided.

Example 1:

Input: n = 7
Output: 6
Explanation: Details of the tournament:
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.

Example 2:

Input: n = 14
Output: 13
Explanation: Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.

Constraints:

1 <= n <= 200


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

446. Count of Matches in Tournament(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int numberOfMatches(int n) {
7 return n - 1;
8 }
9 };
******************************

446. Count of Matches in Tournament(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def numberOfMatches(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 return n-1
************************

447. Daily Leads and Partners


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

Table: DailySales

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| date_id | date |
| make_name | varchar |
| lead_id | int |
| partner_id | int |
+-------------+---------+
This table does not have a primary key.
This table contains the date and the name of the product sold and the IDs of the lead and partner it was sold to.
The name consists of only lowercase English letters.

Write an SQL query that will, for each date_id and make_name, return the number of distinct lead_id's and distinct partner_id's.

Return the result table in any order.

The query result format is in the following example:

DailySales table:
+-----------+-----------+---------+------------+
| date_id | make_name | lead_id | partner_id |
+-----------+-----------+---------+------------+
| 2020-12-8 | toyota | 0 | 1 |
| 2020-12-8 | toyota | 1 | 0 |
| 2020-12-8 | toyota | 1 | 2 |
| 2020-12-7 | toyota | 0 | 2 |
| 2020-12-7 | toyota | 0 | 1 |
| 2020-12-8 | honda | 1 | 2 |
| 2020-12-8 | honda | 2 | 1 |
| 2020-12-7 | honda | 0 | 1 |
| 2020-12-7 | honda | 1 | 2 |
| 2020-12-7 | honda | 2 | 1 |
+-----------+-----------+---------+------------+
Result table:
+-----------+-----------+--------------+-----------------+
| date_id | make_name | unique_leads | unique_partners |
+-----------+-----------+--------------+-----------------+
| 2020-12-8 | toyota | 2 | 3 |
| 2020-12-7 | toyota | 1 | 2 |
| 2020-12-8 | honda | 2 | 2 |
| 2020-12-7 | honda | 3 | 2 |
+-----------+-----------+--------------+-----------------+
For 2020-12-8, toyota gets leads = [0, 1] and partners = [0, 1, 2] while honda gets leads = [1, 2] and partners = [1, 2].
For 2020-12-7, toyota gets leads = [0] and partners = [1, 2] while honda gets leads = [0, 1, 2] and partners = [1, 2].
************************

447. Daily Leads and Partners(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT date_id,
5 make_name,
6 COUNT(DISTINCT lead_id) AS unique_leads,
7 COUNT(DISTINCT partner_id) AS unique_partners
8 FROM DailySales
9 GROUP BY 1, 2
10 ORDER BY NULL;
*********************

448. Reformat Phone Number


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

You are given a phone number as a stringnumber. number consists of digits, spaces ' ', and/or dashes '-'.

You would like to reformat the phone number in a certain manner. Firstly,remove all spaces and dashes. Then, group the
digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:

2 digits: A single block of length 2.


3 digits: A single block of length 3.
4 digits: Two blocks of length 2 each.

The blocks are then joined by dashes. Notice that the reformatting process shouldnever produce any blocks of length 1 and
produce at most two blocks of length 2.

Return the phone number after formatting.

Example 1:

Input: number = "1-23-45 6"


Output: "123-456"
Explanation: The digits are "123456".
Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456".
Joining the blocks gives "123-456".

Example 2:

Input: number = "123 4-567"


Output: "123-45-67"
Explanation: The digits are "1234567".
Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67".
Joining the blocks gives "123-45-67".

Example 3:

Input: number = "123 4-5678"


Output: "123-456-78"
Explanation: The digits are "12345678".
Step 1: The 1st block is "123".
Step 2: The 2nd block is "456".
Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78".
Joining the blocks gives "123-456-78".

Example 4:

Input: number = "12"


Output: "12"

Example 5:
Input: number = "--17-5 229 35-39475 "
Output: "175-229-353-94-75"

Constraints:

2 <= number.length <= 100


number consists of digits
and the characters '-' and ' '.
There are at least two digits in number.
*********************

448. Reformat Phone Number(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 // inplace solution
5 class Solution {
6 public:
7 string reformatNumber(string number) {
8 int src_len = 0;
9 for (const auto& c : number) { // remove non-digit characters
10 if (isdigit(c)) {
11 number[src_len++] = c;
12 }
13 }
14 int dst_len = src_len + (src_len - 1) / 3;
15 number.resize(dst_len); // resize the buffer to expected final size
16 for (int i = src_len - 1, curr = dst_len - 1, l = (3 - src_len % 3) % 3; i >= 0; --i, ++l) {
17 if (l && l % 3 == 0) { // group by 3 digits
18 number[curr--] = '-';
19 }
20 number[curr--] = number[i];
21 }
22 if (dst_len >= 3 && number[dst_len - 2] == '-') { // adjust for the 4 digits case
23 swap(number[dst_len - 3], number[dst_len - 2]);
24 }
25 return number;
26 }
27 };
*********************

448. Reformat Phone Number(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 # inplace solution
5 class Solution(object):
6 def reformatNumber(self, number):
7 """
8 :type number: str
9 :rtype: str
10 """
11 number = list(number)
12 src_len = 0
13 for c in number: # remove non-digit characters
14 if c.isdigit():
15 number[src_len] = c
16 src_len += 1
17 dst_len = src_len + (src_len-1)//3
18 if dst_len > len(number): # resize the buffer to expected final size
19 number.extend([0]*(dst_len-len(number)))
20 while dst_len < len(number):
21 number.pop()
22 curr = dst_len-1
23 for l, i in enumerate(reversed(xrange(src_len)), (3-src_len%3)%3):
24 if l and l%3 == 0: # group by 3 digits
25 number[curr] = '-'
26 curr -= 1
27 number[curr] = number[i]
28 curr -= 1
29 if dst_len >= 3 and number[dst_len-2] == '-': # adjust for the 4 digits case
30 number[dst_len-3], number[dst_len-2] = number[dst_len-2], number[dst_len-3]
31 return "".join(number)
**************************************

449. Number of Students Unable to Eat Lunch


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

The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers0 and 1 respectively. All
students stand in a queue. Each student either prefers square or circular sandwiches.

The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in astack. At
each step:

If the student at the front of the queueprefers the sandwich on the top of the stack, they willtake it and leave the
queue.
Otherwise, they will leave it and go to the queue's end.

This continues until none of the queue students want to take the top sandwich and are thus unable to eat.

You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the
stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the
front of the queue). Return the number of students that are unable to eat.

Example 1:

Input: students = [1,1,0,0], sandwiches = [0,1,0,1]


Output: 0
Explanation:
- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
Hence all students are able to eat.

Example 2:

Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]


Output: 3

Constraints:

1 <= students.length, sandwiches.length <= 100


students.length == sandwiches.length
sandwiches[i] is 0 or 1.
students[i] is 0 or 1.
**************************************

449. Number of Students Unable to Eat Lunch(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countStudents(vector& students, vector& sandwiches) {
7 vector count(2);
8 for (const auto& s : students) {
9 ++count[s];
10 }
11 int i = 0;
12 for (; i < size(sandwiches); ++i) {
13 if (!count[sandwiches[i]]) {
14 break;
15 }
16 --count[sandwiches[i]];
17 }
18 return size(sandwiches) - i;
19 }
20 };
**************************************

449. Number of Students Unable to Eat Lunch(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def countStudents(self, students, sandwiches):
9 """
10 :type students: List[int]
11 :type sandwiches: List[int]
12 :rtype: int
13 """
14 count = collections.Counter(students)
15 for i, s in enumerate(sandwiches):
16 if not count[s]:
17 break
18 count[s] -= 1
19 else:
20 i = len(sandwiches)
21 return len(sandwiches)-i
************************************

450. Determine if String Halves Are Alike


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

You are given a string s of even length. Split this string into two halves of equal lengths, and leta be the first half and b be the
second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains
uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

Example 1:

Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Example 2:

Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

Example 3:

Input: s = "MerryChristmas"
Output: false

Example 4:

Input: s = "AbCdEfGh"
Output: true

Constraints:

2 <= s.length <= 1000


s.length is even.
s consists of uppercase and lowercase letters.
************************************

450. Determine if String Halves Are Alike(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool halvesAreAlike(string s) {
7 static const unordered_set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
8 int cnt1 = 0, cnt2 = 0;
9 int left = 0, right = size(s) - 1;
10 while (left < right) {
11 cnt1 += vowels.count(s[left]);
12 cnt2 += vowels.count(s[right]);
13 ++left;
14 --right;
15 }
16 return cnt1 == cnt2;
17 }
18 };
************************************

450. Determine if String Halves Are Alike(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def halvesAreAlike(self, s):
6 """
7 :type s: str
8 :rtype: bool
9 """
10 vowels = set("aeiouAEIOU")
11 cnt1 = cnt2 = 0
12 left, right = 0, len(s)-1
13 while left < right:
14 cnt1 += s[left] in vowels
15 cnt2 += s[right] in vowels
16 left += 1
17 right -= 1
18 return cnt1 == cnt2
*************************

451. Largest Subarray Length K


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

An array A is larger than some array B if for the first index i where A[i] != B[i] , A[i] > B[i] .

For example, consider 0-indexing:

[1,3,2,4] > [1,2,2,4] , since at index 1, 3 > 2 .


[1,4,4,4] < [2,1,1,1] , since at index 0, 1 < 2 .

A subarray is a contiguous subsequence of the array.

Given an integer array nums of distinct integers, return the largest subarray of nums of length k .

Example 1:

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


Output: [5,2,3]
Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3].
Of these, [5,2,3] is the largest.

Example 2:

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


Output: [4,5,2,3]
Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3].
Of these, [4,5,2,3] is the largest.

Example 3:

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


Output: [5]

Constraints:

1 <= k <= nums.length <= 10 5


1 <= nums[i] <= 10 9
All the integers of nums are unique.

Follow up: What if the integers in nums are not distinct?


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

451. Largest Subarray Length K(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector largestSubarray(vector& nums, int k) {
7 int left = 0, right = 1, l = 0;
8 while (right + k - 1 < size(nums) && right + l < size(nums)) {
9 if (nums[left + l] == nums[right + l]) {
10 ++l;
11 continue;
12 }
13 if (nums[left + l] > nums[right + l]) {
14 right += l + 1;
15 } else {
16 left = max(right, min(left + l + 1, int(size(nums)) - k));
17 right = left + 1;
18 }
19 l = 0;
20 }
21 return {cbegin(nums) + left, cbegin(nums) + left + k};
22 }
23 };
*************************

451. Largest Subarray Length K(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def largestSubarray(self, nums, k):
6 """
7 :type nums: List[int]
8 :type k: int
9 :rtype: List[int]
10 """
11 left, right, l = 0, 1, 0
12 while right+k-1 < len(nums) and right+l < len(nums):
13 if nums[left+l] == nums[right+l]:
14 l += 1
15 continue
16 if nums[left+l] > nums[right+l]:
17 right += l+1
18 else:
19 left = max(right, min(left+l+1, len(nums)-k))
20 right = left+1
21 l = 0
22 return nums[left:left+k]
************************

452. Maximum Units on a Truck


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

You are assigned to put some amount of boxes ontoone truck. You are given a 2D arrayboxTypes, where boxTypes[i] =
[numberOfBoxesi, numberOfUnitsPerBox i] :

numberOfBoxesi is the number of boxes of type i.


numberOfUnitsPerBoxi is the number of units in each box of the typei.

You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can
choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Return the maximum total number of units that can be put on the truck.

Example 1:

Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4


Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.

Example 2:

Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10


Output: 91

Constraints:

1 <= boxTypes.length <= 1000


1 <= numberOfBoxes i, numberOfUnitsPerBox i <= 1000
1 <= truckSize <= 106
************************

452. Maximum Units on a Truck(C++)


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

1 // Time: O(nlogn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maximumUnits(vector>& boxTypes, int truckSize) {
7 sort(begin(boxTypes), end(boxTypes),
8 [](const auto& a, const auto& b) {
9 return a[1] > b[1];
10 });
11 int result = 0;
12 for (const auto& boxType : boxTypes) {
13 if (truckSize > boxType[0]) {
14 truckSize -= boxType[0];
15 result += boxType[0] * boxType[1];
16 } else {
17 result += truckSize * boxType[1];
18 break;
19 }
20 }
21 return result;
22 }
23 };
************************

452. Maximum Units on a Truck(Python)


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

1 # Time: O(nlogn)
2 # Space: O(1)
3
4 class Solution(object):
5 def maximumUnits(self, boxTypes, truckSize):
6 """
7 :type boxTypes: List[List[int]]
8 :type truckSize: int
9 :rtype: int
10 """
11 boxTypes.sort(key=lambda x: x[1], reverse=True)
12 result = 0
13 for box, units in boxTypes:
14 if truckSize > box:
15 truckSize -= box
16 result += box*units
17 else:
18 result += truckSize*units
19 break
20 return result
********************************

453. Calculate Money in Leetcode Bank


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

Hercy wants to save money for his first car. He puts money in the Leetcode bankevery day.

He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in$1 more than the day
before. On every subsequent Monday, he will put in $1 more than the previous Monday.

Given n, return the total amount of money he will have in the Leetcode bank at the end of thenth day.

Example 1:

Input: n = 4
Output: 10
Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.

Example 2:

Input: n = 10
Output: 37
Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts

Example 3:

Input: n = 20
Output: 96
Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.

Constraints:

1 <= n <= 1000


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

453. Calculate Money in Leetcode Bank(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int totalMoney(int n) {
7 static const int cost = 1, day = 7;
8 static const auto arithmetic_sequence_sum =
9 [](int a, int d, int n) {
10 return (2 * a + (n - 1) * d) * n / 2;
11 };
12
13 int first_week_cost = arithmetic_sequence_sum(cost, cost, day);
14 int week = n / day, remain_day = n % day;
15 return arithmetic_sequence_sum(first_week_cost, cost * day, week) +
16 arithmetic_sequence_sum(cost * (week + 1), cost, remain_day);
17 }
18 };
********************************

453. Calculate Money in Leetcode Bank(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def totalMoney(self, n):
6 """
7 :type n: int
8 :rtype: int
9 """
10 def arithmetic_sequence_sum(a, d, n):
11 return (2*a + (n-1)*d) * n //2
12
13 cost, day = 1, 7
14 first_week_cost = arithmetic_sequence_sum(cost, cost, day)
15 week, remain_day = divmod(n, day)
16 return arithmetic_sequence_sum(first_week_cost, cost*day, week) + \
17 arithmetic_sequence_sum(cost*(week+1), cost, remain_day)
******************

454. Decode XORed Array


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

There is a hidden integer array arr that consists of n non-negative integers.

It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1] . For example, if arr =
[1,0,2,1], then encoded = [1,2,3] .

You are given the encoded array. You are also given an integerfirst, that is the first element of arr, i.e. arr[0].

Return the original array arr. It can be proved that the answer exists and is unique.

Example 1:

Input: encoded = [1,2,3], first = 1


Output: [1,0,2,1]
Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]

Example 2:

Input: encoded = [6,2,7,3], first = 4


Output: [4,2,0,7,4]

Constraints:

2 <= n <= 10 4
encoded.length == n - 1
0 <= encoded[i] <= 10 5
0 <= first <= 10 5
******************

454. Decode XORed Array(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 vector decode(vector& encoded, int first) {
7 vector result = {first};
8 for (const auto& x: encoded) {
9 result.emplace_back(result.back() ^ x);
10 }
11 return result;
12 }
13 };
******************

454. Decode XORed Array(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def decode(self, encoded, first):
6 """
7 :type encoded: List[int]
8 :type first: int
9 :rtype: List[int]
10 """
11 result = [first]
12 for x in encoded:
13 result.append(result[-1]^x)
14 return result
*****************************************************

455. Number Of Rectangles That Can Form The Largest


Square
*****************************************************

You are given an array rectangles where rectangles[i] = [l i, wi] represents the ith rectangle of length li and width wi.

You can cut the ith rectangle to form a square with a side length ofk if both k <= l i and k <= w i. For example, if you have a
rectangle [4,6], you can cut it to get a square with a side length of at most4.

Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.

Return the number of rectangles that can make a square with a side length ofmaxLen.

Example 1:

Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]


Output: 3
Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].
The largest possible square is of length 5, and you can get it out of 3 rectangles.

Example 2:

Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]


Output: 3

Constraints:

1 <= rectangles.length <= 1000


rectangles[i].length == 2
1 <= l i, w i <= 109
li != wi
*****************************************************

455. Number Of Rectangles That Can Form The Largest


Square(C++)
*****************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countGoodRectangles(vector>& rectangles) {
7 int result = 0, mx = 0;
8 for (const auto& rec : rectangles) {
9 int side = min(rec[0], rec[1]);
10 if (side > mx) {
11 mx = side;
12 result = 1;
13 } else if (side == mx) {
14 ++result;
15 }
16 }
17 return result;
18 }
19 };
*****************************************************

455. Number Of Rectangles That Can Form The Largest


Square(Python)
*****************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countGoodRectangles(self, rectangles):
6 """
7 :type rectangles: List[List[int]]
8 :rtype: int
9 """
10 result = mx = 0
11 for l, w in rectangles:
12 side = min(l, w)
13 if side > mx:
14 result, mx = 1, side
15 elif side == mx:
16 result += 1
17 return result
********************

456. Find Followers Count


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

Table: Followers

+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| follower_id | int |
+-------------+------+
(user_id, follower_id) is the primary key for this table.
This table contains the IDs of a user and a follower in a social media app where the follower follows the user.

Write an SQL query that will, for each user, return the number of followers.

Return the result table ordered by user_id.

The query result format is in the following example:

Followers table:
+---------+-------------+
| user_id | follower_id |
+---------+-------------+
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 2 | 1 |
+---------+-------------+
Result table:
+---------+----------------+
| user_id | followers_count|
+---------+----------------+
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
+---------+----------------+
The followers of 0 are {1}
The followers of 1 are {0}
The followers of 2 are {0,1}
********************

456. Find Followers Count(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT user_id,
5 Count(follower_id) AS followers_count
6 FROM followers
7 GROUP BY user_id
8 ORDER BY user_id;
*****************************************************

457. The Number of Employees Which Report to Each


Employee
*****************************************************

Table: Employees

+-------------+----------+
| Column Name | Type |
+-------------+----------+
| employee_id | int |
| name | varchar |
| reports_to | int |
| age | int |
+-------------+----------+
employee_id is the primary key for this table.
This table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports

For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.

Write an SQL query to report the ids and the names of allmanagers, the number of employees who reportdirectly to them,
and the average age of the reports rounded to the nearest integer.

Return the result table ordered by employee_id.

The query result format is in the following example:

Employees table:
+-------------+---------+------------+-----+
| employee_id | name | reports_to | age |
+-------------+---------+------------+-----+
| 9 | Hercy | null | 43 |
| 6 | Alice | 9 | 41 |
| 4 | Bob | 9 | 36 |
| 2 | Winston | null | 37 |
+-------------+---------+------------+-----+

Result table:
+-------------+-------+---------------+-------------+
| employee_id | name | reports_count | average_age |
+-------------+-------+---------------+-------------+
| 9 | Hercy | 2 | 39 |
+-------------+-------+---------------+-------------+
Hercy has 2 people report directly to him, Alice and Bob. Their average age is (41+36)/2 = 38.5, which is 39 after rounding it to the nearest
*****************************************************

457. The Number of Employees Which Report to Each


Employee(Shell)
*****************************************************

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT e1.employee_id,
5 e1.NAME,
6 Count(e2.reports_to) AS reports_count,
7 Round(Avg(e2.age), 0) AS average_age
8 FROM employees e1
9 INNER JOIN employees e2
10 ON e1.employee_id = e2.reports_to
11 GROUP BY e1.employee_id,
12 e1.NAME
13 ORDER BY 1 ASC;
**************************************

458. Latest Time by Replacing Hidden Digits


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

You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by?).

The valid times are those inclusively between 00:00 and 23:59.

Return the latest valid time you can get from time by replacing the hidden digits.

Example 1:

Input: time = "2?:?0"


Output: "23:50"
Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.

Example 2:

Input: time = "0?:3?"


Output: "09:39"

Example 3:

Input: time = "1?:22"


Output: "19:22"

Constraints:

time is in the format hh:mm.


It is guaranteed that you can produce a valid time from the given string.
**************************************

458. Latest Time by Replacing Hidden Digits(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string maximumTime(string time) {
7 for (int i = 0; i < size(time); ++i) {
8 if (time[i] != '?') {
9 continue;
10 }
11 if (i == 0) {
12 time[i] = (time[1] <= '3' || time[1] == '?') ? '2' : '1';
13 } else if (i == 1) {
14 time[i] = (time[0] == '2') ? '3' : '9';
15 } else if (i == 3) {
16 time[i] = '5';
17 } else if (i == 4) {
18 time[i] = '9';
19 }
20 }
21 return time;
22 }
23 };
**************************************

458. Latest Time by Replacing Hidden Digits(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def maximumTime(self, time):
6 """
7 :type time: str
8 :rtype: str
9 """
10 result = list(time)
11 for i, c in enumerate(time):
12 if c != "?":
13 continue
14 if i == 0:
15 result[i] = '2' if result[i+1] in "?0123" else '1'
16 elif i == 1:
17 result[i] = '3' if result[0] == '2' else '9'
18 elif i == 3:
19 result[i] = '5'
20 elif i == 4:
21 result[i] = '9'
22 return "".join(result)
**************************************

459. Find Total Time Spent by Each Employee


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

Table: Employees

+-------------+------+
| Column Name | Type |
+-------------+------+
| emp_id | int |
| event_day | date |
| in_time | int |
| out_time | int |
+-------------+------+
(emp_id, event_day, in_time) is the primary key of this table.
The table shows the employees' entries and exits in an office.
event_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute
in_time and out_time are between 1 and 1440.
It is guaranteed that no two events on the same day intersect in time, and in_time < out_time.

Write an SQL query to calculate the total timein minutes spent by each employee on each day at the office. Note that
within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is out_time -
in_time.

Return the result table in any order.

The query result format is in the following example:

Employees table:
+--------+------------+---------+----------+
| emp_id | event_day | in_time | out_time |
+--------+------------+---------+----------+
| 1 | 2020-11-28 | 4 | 32 |
| 1 | 2020-11-28 | 55 | 200 |
| 1 | 2020-12-03 | 1 | 42 |
| 2 | 2020-11-28 | 3 | 33 |
| 2 | 2020-12-09 | 47 | 74 |
+--------+------------+---------+----------+
Result table:
+------------+--------+------------+
| day | emp_id | total_time |
+------------+--------+------------+
| 2020-11-28 | 1 | 173 |
| 2020-11-28 | 2 | 30 |
| 2020-12-03 | 1 | 41 |
| 2020-12-09 | 2 | 27 |
+------------+--------+------------+
Employee 1 has three events: two on day 2020-11-28 with a total of (32 - 4) + (200 - 55) = 173, and one on day 2020-12-03 with a total of (42
Employee 2 has two events: one on day 2020-11-28 with a total of (33 - 3) = 30, and one on day 2020-12-09 with a total of (74 - 47) = 27.
**************************************

459. Find Total Time Spent by Each Employee(Shell)


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

1 # Time: O(nlogn)
2 # Space: O(n)
3
4 SELECT event_day AS day,
5 emp_id,
6 Sum(out_time - in_time) AS total_time
7 FROM employees
8 GROUP BY 1, 2
9 ORDER BY 1, 2;
********************************

460. Maximum Number of Balls in a Box


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

You are working in a ball factory where you haven balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit -
lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.

Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For
example, the ball number 321 will be put in the box number3 + 2 + 1 = 6 and the ball number 10 will be put in the box number1
+ 0 = 1.

Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.

Example 1:

Input: lowLimit = 1, highLimit = 10


Output: 2
Explanation:
Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...
Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ...
Box 1 has the most number of balls with 2 balls.

Example 2:

Input: lowLimit = 5, highLimit = 15


Output: 2
Explanation:
Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...
Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ...
Boxes 5 and 6 have the most number of balls with 2 balls in each.

Example 3:

Input: lowLimit = 19, highLimit = 28


Output: 2
Explanation:
Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...
Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...
Box 10 has the most number of balls with 2 balls.

Constraints:

1 <= lowLimit <= highLimit <= 10 5


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

460. Maximum Number of Balls in a Box(C++)


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

1 // Time: O(nlogm)
2 // Space: O(logm)
3
4 class Solution {
5 public:
6 int countBalls(int lowLimit, int highLimit) {
7 unordered_map count;
8 for (int i = lowLimit; i <= highLimit; ++i) {
9 int total = 0;
10 for (int d = i; d; d /= 10) {
11 total += d % 10;
12 }
13 ++count[total];
14 }
15 return max_element(cbegin(count), cend(count),
16 [](const auto& a, const auto& b) {
17 return a.second < b.second;
18 })->second;
19 }
20 };
********************************

460. Maximum Number of Balls in a Box(Python)


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

1 # Time: O(nlogm)
2 # Space: O(logm)
3
4 import collections
5 import itertools
6
7
8 class Solution(object):
9 def countBalls(self, lowLimit, highLimit):
10 """
11 :type lowLimit: int
12 :type highLimit: int
13 :rtype: int
14 """
15 count = collections.Counter()
16 for i in xrange(lowLimit, highLimit+1):
17 count[sum(itertools.imap(int, str(i)))] += 1
18 return max(count.itervalues())
**********************

461. Sum of Unique Elements


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

You are given an integer array nums. The unique elements of an array are the elements that appearexactly once in the
array.

Return the sum of all the unique elements of nums.

Example 1:

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


Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.

Example 2:

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


Output: 0
Explanation: There are no unique elements, and the sum is 0.

Example 3:

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


Output: 15
Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.

Constraints:

1 <= nums.length <= 100


1 <= nums[i] <= 100
**********************

461. Sum of Unique Elements(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int sumOfUnique(vector& nums) {
7 unordered_map count;
8 for (const auto& num : nums) {
9 ++count[num];
10 }
11 return accumulate(cbegin(count), cend(count), 0,
12 [](const auto& total, const auto& p) {
13 return total + (p.second == 1 ? p.first : 0);
14 });
15 }
16 };
**********************

461. Sum of Unique Elements(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 import collections
5
6
7 class Solution(object):
8 def sumOfUnique(self, nums):
9 """
10 :type nums: List[int]
11 :rtype: int
12 """
13 return sum(x for x, c in collections.Counter(nums).iteritems() if c == 1)
************************************

462. Check if Array Is Sorted and Rotated


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

Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotatedsome number of
positions (including zero). Otherwise, return false.

There may be duplicates in the original array.

Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is
the modulo operation.

Example 1:

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


Output: true
Explanation: [1,2,3,4,5] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].

Example 2:

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


Output: false
Explanation: There is no sorted array once rotated that can make nums.

Example 3:

Input: nums = [1,2,3]


Output: true
Explanation: [1,2,3] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.

Example 4:

Input: nums = [1,1,1]


Output: true
Explanation: [1,1,1] is the original sorted array.
You can rotate any number of positions to make nums.

Example 5:

Input: nums = [2,1]


Output: true
Explanation: [1,2] is the original sorted array.
You can rotate the array by x = 5 positions to begin on the element of value 2: [2,1].

Constraints:

1 <= nums.length <= 100


1 <= nums[i] <= 100
************************************

462. Check if Array Is Sorted and Rotated(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool check(vector& nums) {
7 for (int i = 0, count = 0; i < size(nums); ++i) {
8 if (nums[i] > nums[(i + 1) % size(nums)] && ++count > 1) {
9 return false;
10 }
11 }
12 return true;
13 }
14 };
************************************

462. Check if Array Is Sorted and Rotated(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def check(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: bool
9 """
10 count = 0
11 for i in xrange(len(nums)):
12 if nums[i] > nums[(i+1)%len(nums)]:
13 count += 1
14 if count > 1:
15 return False
16 return True
*******************************

463. Recyclable and Low Fat Products


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

Table: Products

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| low_fats | enum |
| recyclable | enum |
+-------------+---------+
product_id is the primary key for this table.
low_fats is an ENUM of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
recyclable is an ENUM of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.

Write an SQL query to find the ids of products that are both low fat and recyclable.

Return the result table in any order.

The query result format is in the following example:

Products table:
+-------------+----------+------------+
| product_id | low_fats | recyclable |
+-------------+----------+------------+
| 0 | Y | N |
| 1 | Y | Y |
| 2 | N | Y |
| 3 | Y | Y |
| 4 | N | N |
+-------------+----------+------------+
Result table:
+-------------+
| product_id |
+-------------+
| 1 |
| 3 |
+-------------+
Only products 1 and 3 are both low fat and recyclable.
*******************************

463. Recyclable and Low Fat Products(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT product_id
5 FROM Products
6 WHERE low_fats = 'Y'
7 AND recyclable = 'Y'
8 ORDER BY NULL;
*************************************************

464. Minimum Changes To Make Alternating Binary String


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

You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice
versa.

The string is called alternating if no two adjacent characters are equal. For example, the string"010" is alternating, while the
string "0100" is not.

Return the minimum number of operations needed to make s alternating.

Example 1:

Input: s = "0100"
Output: 1
Explanation: If you change the last character to '1', s will be "0101", which is alternating.

Example 2:

Input: s = "10"
Output: 0
Explanation: s is already alternating.

Example 3:

Input: s = "1111"
Output: 2
Explanation: You need two operations to reach "0101" or "1010".

Constraints:

1 <= s.length <= 104


s[i] is either '0' or '1'.
*************************************************

464. Minimum Changes To Make Alternating Binary


String(C++)
*************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minOperations(string s) {
7 int cnt = 0;
8 for (int i = 0; i < size(s); ++i) {
9 if (s[i] - '0' == i % 2) {
10 ++cnt;
11 }
12 }
13 return min(cnt, int(size(s)) - cnt);
14 }
15 };
*************************************************

464. Minimum Changes To Make Alternating Binary


String(Python)
*************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minOperations(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 cnt = sum(int(c) == i%2 for i, c in enumerate(s))
11 return min(cnt, len(s)-cnt)
**********************

465. Longest Nice Substring


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

A string s is nice if, for every letter of the alphabet thats contains, it appears both in uppercase and lowercase. For
example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B'
does not.

Given a string s , return the longest substring of s that is nice. If there are multiple, return the substring of theearliest
occurrence. If there are none, return an empty string.

Example 1:

Input: s = "YazaAay"
Output: "aAa"
Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.
"aAa" is the longest nice substring.

Example 2:

Input: s = "Bb"
Output: "Bb"
Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.

Example 3:

Input: s = "c"
Output: ""
Explanation: There are no nice substrings.

Example 4:

Input: s = "dDzeE"
Output: "dD"
Explanation: Both "dD" and "eE" are the longest nice substrings.
As there are multiple longest nice substrings, return "dD" since it occurs earlier.

Constraints:

1 <= s.length <= 100


s consists of uppercase and lowercase English letters.
**********************

465. Longest Nice Substring(C++)


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

1 // Time: O(26 * n) = O(n)


2 // Space: O(26 * n) = O(n)
3
4 class Solution {
5 public:
6 string longestNiceSubstring(string s) {
7 array, 26> lookup = {0};
8 for (const auto& c : s) {
9 lookup[tolower(c) - 'a'][isupper(c) != 0] = 1;
10 }
11 string result;
12 for (int i = 0, prev = -1; i <= size(s); ++i) {
13 if (!(i == size(s) || !lookup[tolower(s[i]) - 'a'][0] || !lookup[tolower(s[i]) - 'a'][1])) {
14 continue;
15 }
16 if (prev == -1 && i == size(s)) {
17 return s;
18 }
19 auto tmp = longestNiceSubstring(s.substr(prev + 1, i - prev - 1));
20 if (size(tmp) > size(result)) {
21 result = move(tmp);
22 }
23 prev = i;
24 }
25 return result;
26 }
27 };
**********************

465. Longest Nice Substring(Python)


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

1 # Time: O(26 * n) = O(n)


2 # Space: O(26 * n) = O(n)
3
4 class Solution(object):
5 def longestNiceSubstring(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 lookup = set(list(s))
11 prev = -1
12 result = ""
13 for i in xrange(len(s)+1):
14 if not (i == len(s) or s[i] not in lookup or s[i].swapcase() not in lookup):
15 continue
16 if prev == -1 and i == len(s):
17 return s
18 tmp = self.longestNiceSubstring(s[prev+1:i])
19 if len(tmp) > len(result):
20 result = tmp
21 prev = i
22 return result
*************************

466. Merge Strings Alternately


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

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting withword1. If a
string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Example 1:

Input: word1 = "abc", word2 = "pqr"


Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r

Example 2:

Input: word1 = "ab", word2 = "pqrs"


Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s

Example 3:

Input: word1 = "abcd", word2 = "pq"


Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d

Constraints:

1 <= word1.length, word2.length <= 100


word1 and word2 consist of lowercase English letters.
*************************

466. Merge Strings Alternately(C++)


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

1 // Time: O(m + n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string mergeAlternately(string word1, string word2) {
7 string result;
8 for (int i = 0; i < size(word1) || i < size(word2); ++i) {
9 if (i < size(word1)) {
10 result.push_back(word1[i]);
11 }
12 if (i < size(word2)) {
13 result.push_back(word2[i]);
14 }
15 }
16 return result;
17 }
18 };
*************************

466. Merge Strings Alternately(Python)


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

1 # Time: O(m + n)
2 # Space: O(1)
3
4 class Solution(object):
5 def mergeAlternately(self, word1, word2):
6 """
7 :type word1: str
8 :type word2: str
9 :rtype: str
10 """
11 result = []
12 i = 0
13 while i < len(word1) or i < len(word2):
14 if i < len(word1):
15 result.append(word1[i])
16 if i < len(word2):
17 result.append(word2[i])
18 i += 1
19 return "".join(result)
***************************

467. Count Items Matching a Rule


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

You are given an array items, where each items[i] = [type i, color i, namei] describes the type, color, and name of theith item. You
are also given a rule represented by two strings, ruleKey and ruleValue.

The ith item is said to match the rule if one of the following is true:

and ruleValue == type i.


ruleKey == "type"
and ruleValue == color i.
ruleKey == "color"
ruleKey == "name" and ruleValue == namei.

Return the number of items that match the given rule.

Example 1:

Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"


Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].

Example 2:

Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"


Output: 2
Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that th

Constraints:

1 <= items.length <= 10 4


1 <= type i.length, color i.length, namei.length, ruleValue.length <= 10
ruleKey is equal to either "type", "color", or "name".
All strings consist only of lowercase letters.
***************************

467. Count Items Matching a Rule(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countMatches(vector>& items, string ruleKey, string ruleValue) {
7 static const unordered_map rule = {{"type", 0}, {"color", 1}, {"name", 2}};
8 int result = 0;
9 for (const auto& item : items) {
10 if (item[rule.at(ruleKey)] == ruleValue) {
11 ++result;
12 }
13 }
14 return result;
15 }
16 };
***************************

467. Count Items Matching a Rule(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def countMatches(self, items, ruleKey, ruleValue):
6 """
7 :type items: List[List[str]]
8 :type ruleKey: str
9 :type ruleValue: str
10 :rtype: int
11 """
12 rule = {"type":0, "color":1, "name":2}
13 return sum(item[rule[ruleKey]] == ruleValue for item in items)
******************************

468. Product's Price for Each Store


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

Table: Products

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| store | enum |
| price | int |
+-------------+---------+
(product_id,store) is the primary key for this table.
store is an ENUM of type ('store1', 'store2', 'store3') where each represents the store this product is available at.
price is the price of the product at this store.

Write an SQL query to find the price of each product in each store.

Return the result table in any order.

The query result format is in the following example:

Products table:
+-------------+--------+-------+
| product_id | store | price |
+-------------+--------+-------+
| 0 | store1 | 95 |
| 0 | store3 | 105 |
| 0 | store2 | 100 |
| 1 | store1 | 70 |
| 1 | store3 | 80 |
+-------------+--------+-------+
Result table:
+-------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+-------------+--------+--------+--------+
| 0 | 95 | 100 | 105 |
| 1 | 70 | null | 80 |
+-------------+--------+--------+--------+
Product 0 price's are 95 for store1, 100 for store2 and, 105 for store3.
Product 1 price's are 70 for store1, 80 for store3 and, it's not sold in store2.
******************************

468. Product's Price for Each Store(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT
5 product_id,
6 MAX(CASE WHEN store = 'store1' THEN price END) AS store1,
7 MAX(CASE WHEN store = 'store2' THEN price END) AS store2,
8 MAX(CASE WHEN store = 'store3' THEN price END) AS store3
9 FROM Products
10 GROUP BY 1
11 ORDER BY NULL;
******************************************************

469. Find Nearest Point That Has the Same X or Y


Coordinate
******************************************************

You are given two integers, x and y , which represent your current location on a Cartesian grid:(x, y). You are also given an
array points where each points[i] = [a i, b i] represents that a point exists at (a i, b i). A point is valid if it shares the same x-coordinate
or the same y-coordinate as your location.

Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are
multiple, return the valid point with the smallest index. If there are no valid points, return -1.

The Manhattan distance between two points (x1, y 1) and (x2, y 2) is abs(x1 - x 2) + abs(y 1 - y 2).

Example 1:

Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]


Output: 2
Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan dista

Example 2:

Input: x = 3, y = 4, points = [[3,4]]


Output: 0
Explanation: The answer is allowed to be on the same location as your current location.

Example 3:

Input: x = 3, y = 4, points = [[2,3]]


Output: -1
Explanation: There are no valid points.

Constraints:

1 <= points.length <= 10 4


points[i].length == 2
1 <= x, y, a i, b i <= 104
******************************************************

469. Find Nearest Point That Has the Same X or Y


Coordinate(C++)
******************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int nearestValidPoint(int x, int y, vector>& points) {
7 int smallest = numeric_limits::max();
8 int idx = -1;
9 for (int i = 0; i < size(points); ++i) {
10 int dx = x - points[i][0], dy = y - points[i][1];
11 if (dx * dy == 0 && abs(dx) + abs(dy) < smallest) {
12 smallest = abs(dx) + abs(dy);
13 idx = i;
14 }
15 }
16 return idx;
17 }
18 };
******************************************************

469. Find Nearest Point That Has the Same X or Y


Coordinate(Python)
******************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def nearestValidPoint(self, x, y, points):
6 """
7 :type x: int
8 :type y: int
9 :type points: List[List[int]]
10 :rtype: int
11 """
12 smallest, idx = float("inf"), -1
13 for i, (r, c) in enumerate(points):
14 dx, dy = x-r, y-c
15 if dx*dy == 0 and abs(dx)+abs(dy) < smallest:
16 smallest = abs(dx)+abs(dy)
17 idx = i
18 return idx
******************************************************

470. Check if Binary String Has at Most One Segment of


Ones
******************************************************

Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous
segment of ones. Otherwise, return false.

Example 1:

Input: s = "1001"
Output: false
Explanation: The ones do not form a contiguous segment.

Example 2:

Input: s = "110"
Output: true

Constraints:

1 <= s.length <= 100


s[i] ​​​​ is either '0' or '1'.
s[0] is '1'.
******************************************************

470. Check if Binary String Has at Most One Segment of


Ones(C++)
******************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool checkOnesSegment(string s) {
7 return s.find("01") == string::npos;
8 }
9 };
******************************************************

470. Check if Binary String Has at Most One Segment of


Ones(Python)
******************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def checkOnesSegment(self, s):
6 """
7 :type s: str
8 :rtype: bool
9 """
10 return "01" not in s
************************************

471. Primary Department for Each Employee


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

Table: Employee

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| employee_id | int |
| department_id | int |
| primary_flag | varchar |
+---------------+---------+
(employee_id, department_id) is the primary key for this table.
employee_id is the id of the employee.
department_id is the id of the department to which the employee belongs.
primary_flag is an ENUM of type ('Y', 'N'). If the flag is 'Y', the department is the primary department for the employee. If the flag is 'N'

Employees can belong to multiple departments. When the employee joins other departments, they need to decide which
department is their primary department. Note that when an employee belongs to only one department, their primary column
is 'N'.

Write an SQL query to report all the employees with their primary department. For employees who belong to one
department, report their only department.

Return the result table in any order.

The query result format is in the following example.

Employee table:
+-------------+---------------+--------------+
| employee_id | department_id | primary_flag |
+-------------+---------------+--------------+
| 1 | 1 | N |
| 2 | 1 | Y |
| 2 | 2 | N |
| 3 | 3 | N |
| 4 | 2 | N |
| 4 | 3 | Y |
| 4 | 4 | N |
+-------------+---------------+--------------+

Result table:
+-------------+---------------+
| employee_id | department_id |
+-------------+---------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 3 |
| 4 | 3 |
+-------------+---------------+
- The Primary department for employee 1 is 1.
- The Primary department for employee 2 is 1.
- The Primary department for employee 3 is 3.
- The Primary department for employee 4 is 3.
************************************

471. Primary Department for Each Employee(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 (SELECT employee_id,
5 department_id
6 FROM Employee
7 WHERE primary_flag = 'Y')
8 UNION
9 (SELECT employee_id,
10 department_id
11 FROM Employee
12 GROUP BY employee_id
13 HAVING COUNT(employee_id) = 1
14 ORDER BY NULL);
***********************************************

472. Check if One String Swap Can Make Strings Equal


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

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string
(not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performingat most one string swap on exactly one of the strings.
Otherwise, return false.

Example 1:

Input: s1 = "bank", s2 = "kanb"


Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".

Example 2:

Input: s1 = "attack", s2 = "defend"


Output: false
Explanation: It is impossible to make them equal with one string swap.

Example 3:

Input: s1 = "kelb", s2 = "kelb"


Output: true
Explanation: The two strings are already equal, so no string swap operation is required.

Example 4:

Input: s1 = "abcd", s2 = "dcba"


Output: false

Constraints:

1 <= s1.length, s2.length <= 100


s1.length == s2.length
s1 and s2 consist of only lowercase English letters.
***********************************************

472. Check if One String Swap Can Make Strings


Equal(C++)
***********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool areAlmostEqual(string s1, string s2) {
7 vector> diff;
8 for (int i = 0; i < size(s1); ++i) {
9 if (s1[i] == s2[i]) {
10 continue;
11 }
12 if (size(diff) == 2) {
13 return false;
14 }
15 diff.emplace_back(empty(diff) ? pair(s1[i], s2[i]) : pair(s2[i], s1[i]));
16 }
17 return empty(diff) || (size(diff) == 2 && diff[0] == diff[1]);
18 }
19 };
***********************************************

472. Check if One String Swap Can Make Strings


Equal(Python)
***********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import itertools
5
6
7 class Solution(object):
8 def areAlmostEqual(self, s1, s2):
9 """
10 :type s1: str
11 :type s2: str
12 :rtype: bool
13 """
14 diff = []
15 for a, b in itertools.izip(s1, s2):
16 if a == b:
17 continue
18 if len(diff) == 2:
19 return False
20 diff.append([a, b] if not diff else [b, a])
21 return not diff or (len(diff) == 2 and diff[0] == diff[1])
************************

473. Rearrange Products Table


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

Table: Products

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| store1 | int |
| store2 | int |
| store3 | int |
+-------------+---------+
product_id is the primary key for this table.
Each row in this table indicates the product's price in 3 different stores: store1, store2, and store3.
If the product is not available in a store, the price will be null in that store's column.

Write an SQL query to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a
store, do not include a row with that product_id and store combination in the result table.

Return the result table in any order.

The query result format is in the following example:

Products table:
+------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+------------+--------+--------+--------+
| 0 | 95 | 100 | 105 |
| 1 | 70 | null | 80 |
+------------+--------+--------+--------+

Result table:
+------------+--------+-------+
| product_id | store | price |
+------------+--------+-------+
| 0 | store1 | 95 |
| 0 | store2 | 100 |
| 0 | store3 | 105 |
| 1 | store1 | 70 |
| 1 | store3 | 80 |
+------------+--------+-------+

Product 0 is available in all three stores with prices 95, 100, and 105 respectively.
Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.
************************

473. Rearrange Products Table(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT product_id,
5 'store1' AS store,
6 store1 AS price
7 FROM products
8 WHERE store1 IS NOT NULL
9 UNION ALL
10 SELECT product_id,
11 'store2' AS store,
12 store2 AS price
13 FROM products
14 WHERE store2 IS NOT NULL
15 UNION ALL
16 SELECT product_id,
17 'store3' AS store,
18 store3 AS price
19 FROM products
20 WHERE store3 IS NOT NULL;
********************************

474. Second Largest Digit in a String


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

Given an alphanumeric string s , return the second largest numerical digit that appears in s , or -1 if it does not exist.

An alphanumeric string is a string consisting of lowercase English letters and digits.

Example 1:

Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.

Example 2:

Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.

Constraints:

1 <= s.length <= 500


s consists of only lowercase English letters and/or digits.
********************************

474. Second Largest Digit in a String(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int secondHighest(string s) {
7 int first = -1, second = -1;
8 for (const auto& c : s) {
9 if (!isdigit(c)) {
10 continue;
11 }
12 int d = c - '0';
13 if (d > first) {
14 second = first;
15 first = d;
16 } else if (first > d && d > second) {
17 second = d;
18 }
19 }
20 return second;
21 }
22 };
********************************

474. Second Largest Digit in a String(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def secondHighest(self, s):
6 """
7 :type s: str
8 :rtype: int
9 """
10 first = second = -1
11 for c in s:
12 if not c.isdigit():
13 continue
14 d = int(c)
15 if d > first:
16 first, second = d, first
17 elif first > d > second:
18 second = d
19 return second
****************************************

475. Number of Different Integers in a String


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

You are given a string word that consists of digits and lowercase English letters.

You will replace every non-digit character with a space. For example,"a123bc34d8ef34" will become " 123 34 8 34" . Notice that
you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".

Return the number of different integers after performing the replacement operations on word.

Two integers are considered different if their decimal representationswithout any leading zeros are different.

Example 1:

Input: word = "a123bc34d8ef34"


Output: 3
Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.

Example 2:

Input: word = "leet1234code234"


Output: 2

Example 3:

Input: word = "a1b01c001"


Output: 1
Explanation: The three integers "1", "01", and "001" all represent the same integer because
the leading zeros are ignored when comparing their decimal values.

Constraints:

1 <= word.length <= 1000


word consists of digits and lowercase English letters.
****************************************

475. Number of Different Integers in a String(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 int numDifferentIntegers(string word) {
7 word.push_back(' ');
8 unordered_set result;
9 string num;
10 for (const auto& c : word) {
11 if (isdigit(c)) {
12 if (!empty(num) && num[0] == '0') {
13 num[0] = c;
14 } else {
15 num.push_back(c);
16 }
17 } else if (!empty(num)) {
18 result.emplace(move(num));
19 }
20 }
21 return size(result);
22 }
23 };
****************************************

475. Number of Different Integers in a String(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 class Solution(object):
5 def numDifferentIntegers(self, word):
6 """
7 :type word: str
8 :rtype: int
9 """
10 result, num = set(), None
11 for i in xrange(len(word)+1):
12 c = word[i] if i < len(word) else ' '
13 if c.isdigit():
14 num = 10*num+int(c) if num is not None else int(c)
15 elif num is not None:
16 result.add(num)
17 num = None
18 return len(result)
****************

476. Ad-Free Sessions


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

Table: Playback

+-------------+------+
| Column Name | Type |
+-------------+------+
| session_id | int |
| customer_id | int |
| start_time | int |
| end_time | int |
+-------------+------+
session_id is the primary key for this table.
customer_id is the ID of the customer watching this session.
The session runs during the inclusive interval between start_time and end_time.
It is guaranteed that start_time <= end_time and that two sessions for the same customer do not intersect.

Table: Ads

+-------------+------+
| Column Name | Type |
+-------------+------+
| ad_id | int |
| customer_id | int |
| timestamp | int |
+-------------+------+
ad_id is the primary key for this table.
customer_id is the ID of the customer viewing this ad.
timestamp is the moment of time at which the ad was shown.

Write an SQL query to report all the sessions that did not get shown any ads.

Return the result table in any order.

The query result format is in the following example:


Playback table:
+------------+-------------+------------+----------+
| session_id | customer_id | start_time | end_time |
+------------+-------------+------------+----------+
| 1 | 1 | 1 | 5 |
| 2 | 1 | 15 | 23 |
| 3 | 2 | 10 | 12 |
| 4 | 2 | 17 | 28 |
| 5 | 2 | 2 | 8 |
+------------+-------------+------------+----------+

Ads table:
+-------+-------------+-----------+
| ad_id | customer_id | timestamp |
+-------+-------------+-----------+
| 1 | 1 | 5 |
| 2 | 2 | 17 |
| 3 | 2 | 20 |
+-------+-------------+-----------+

Result table:
+------------+
| session_id |
+------------+
| 2 |
| 3 |
| 5 |
+------------+
The ad with ID 1 was shown to user 1 at time 5 while they were in session 1.
The ad with ID 2 was shown to user 2 at time 17 while they were in session 4.
The ad with ID 3 was shown to user 2 at time 20 while they were in session 4.
We can see that sessions 1 and 4 had at least one ad. Sessions 2, 3, and 5 did not have any ads, so we return them.
****************

476. Ad-Free Sessions(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT p.session_id
5 FROM playback p
6 LEFT JOIN ads a
7 ON p.customer_id = a.customer_id
8 AND a.timestamp BETWEEN p.start_time AND p.end_time
9 WHERE a.customer_id IS NULL;
**************************************

477. Determine Color of a Chessboard Square


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

You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for
your reference.

Return true if the square is white, and false if the square is black.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the
number second.

Example 1:

Input: coordinates = "a1"


Output: false
Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false.

Example 2:

Input: coordinates = "h3"


Output: true
Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true.

Example 3:

Input: coordinates = "c7"


Output: false

Constraints:

coordinates.length == 2
'a' <= coordinates[0] <= 'h'
'1' <= coordinates[1] <= '8'
**************************************

477. Determine Color of a Chessboard Square(C++)


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

1 // Time: O(1)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool squareIsWhite(string coordinates) {
7 return (coordinates[0] - 'a') % 2 != (coordinates[1] - '1') % 2;
8 }
9 };
**************************************

477. Determine Color of a Chessboard Square(Python)


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

1 # Time: O(1)
2 # Space: O(1)
3
4 class Solution(object):
5 def squareIsWhite(self, coordinates):
6 """
7 :type coordinates: str
8 :rtype: bool
9 """
10 return (ord(coordinates[0])-ord('a'))%2 != (ord(coordinates[1])-ord('1'))%2
*****************

478. Truncate Sentence


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

A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words
consists of only uppercase and lowercase English letters (no punctuation).

For example, "Hello World" , "HELLO", and "hello world hello world" are all sentences.

You are given a sentence s ​​​​​​ and an integer k ​​​​​​. You want to truncate
s ​​​​​​ such that it contains only the first k ​​​​​​ words. Return s ​​​​​​ after
truncating it.

Example 1:

Input: s = "Hello how are you Contestant", k = 4


Output: "Hello how are you"
Explanation:
The words in s are ["Hello", "how" "are", "you", "Contestant"].
The first 4 words are ["Hello", "how", "are", "you"].
Hence, you should return "Hello how are you".

Example 2:

Input: s = "What is the solution to this problem", k = 4


Output: "What is the solution"
Explanation:
The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].
The first 4 words are ["What", "is", "the", "solution"].
Hence, you should return "What is the solution".

Example 3:

Input: s = "chopper is not a tanuki", k = 5


Output: "chopper is not a tanuki"

Constraints:

1 <= s.length <= 500


k is in the range [1, the number of words in s] .
s consist of only lowercase and uppercase English letters and spaces.
The words in s are separated by a single space.
There are no leading or trailing spaces.
*****************

478. Truncate Sentence(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string truncateSentence(string s, int k) {
7 for (int i = 0; i < size(s); ++i) {
8 if (s[i] == ' ' && --k == 0) {
9 return s.substr(0, i);
10 }
11 }
12 return s;
13 }
14 };
*****************

478. Truncate Sentence(Python)


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

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

479. Find Customers With Positive Revenue this Year


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

Table: Customers

+--------------+------+
| Column Name | Type |
+--------------+------+
| customer_id | int |
| year | int |
| revenue | int |
+--------------+------+
(customer_id, year) is the primary key for this table.
This table contains the customer ID and the revenue of customers in different years.
Note that this revenue can be negative.

Write an SQL query to report the customers withpostive revenue in the year 2021.

Return the result table in any order.

The query result format is in the following example:

Customers
+-------------+------+---------+
| customer_id | year | revenue |
+-------------+------+---------+
| 1 | 2018 | 50 |
| 1 | 2021 | 30 |
| 1 | 2020 | 70 |
| 2 | 2021 | -50 |
| 3 | 2018 | 10 |
| 3 | 2016 | 50 |
| 4 | 2021 | 20 |
+-------------+------+---------+

Result table:
+-------------+
| customer_id |
+-------------+
| 1 |
| 4 |
+-------------+

Customer 1 has revenue equal to 30 in year 2021.


Customer 2 has revenue equal to -50 in year 2021.
Customer 3 has no revenue in year 2021.
Customer 4 has revenue equal to 20 in year 2021.
Thus only customers 1 and 4 have postive revenue in year 2021.
**********************************************

479. Find Customers With Positive Revenue this


Year(Shell)
**********************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT customer_id
5 FROM customers
6 WHERE YEAR = 2021 AND revenue > 0;
*******************************

480. Sign of the Product of an Array


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

There is a function signFunc(x) that returns:

1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the arraynums.

Return signFunc(product).

Example 1:

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


Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1

Example 2:

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


Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0

Example 3:

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


Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1

Constraints:

1 <= nums.length <= 1000


-100 <= nums[i] <= 100
*******************************

480. Sign of the Product of an Array(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int arraySign(vector& nums) {
7 uint8_t flag = 0;
8 for (const auto& x : nums) {
9 if (x == 0) {
10 return 0;
11 }
12 if (x < 0) {
13 flag ^= 1;
14 }
15 }
16 return flag % 2 ? -1 : 1;
17 }
18 };
*******************************

480. Sign of the Product of an Array(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def arraySign(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 flag = 0
11 for x in nums:
12 if not x:
13 return 0
14 if x < 0:
15 flag ^= 1
16 return -1 if flag else 1
*************

481. Faulty Sensor


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

An experiment is being conducted in a lab. To ensure accuracy, there aretwo sensors collecting data simultaneously. You
are given two arrays sensor1 and sensor2, where sensor1[i] and sensor2[i] are the ith data points collected by the two sensors.

However, this type of sensor has a chance of being defective, which causesexactly one data point to be dropped. After the
data is dropped, all the data points to the right of the dropped data are shifted one place to the left, and the last data point
is replaced with some random value. It is guaranteed that this random value will not be equal to the dropped value.

For example, if the correct data is [1,2,3,4,5] and 3 is dropped, the sensor could return [1,2,4,5,7] (the last position can be
any value, not just 7).

We know that there is a defect in at most one of the sensors. Return the sensor number (1 or 2) with the defect. If there is
no defect in either sensor or if it is impossible to determine the defective sensor, return -1.

Example 1:

Input: sensor1 = [2,3,4,5], sensor2 = [2,1,3,4]


Output: 1
Explanation: Sensor 2 has the correct values.
The second data point from sensor 2 is dropped, and the last value of sensor 1 is replaced by a 5.

Example 2:

Input: sensor1 = [2,2,2,2,2], sensor2 = [2,2,2,2,5]


Output: -1
Explanation: It is impossible to determine which sensor has a defect.
Dropping the last value for either sensor could produce the output for the other sensor.

Example 3:

Input: sensor1 = [2,3,2,2,3,2], sensor2 = [2,3,2,3,2,7]


Output: 2
Explanation: Sensor 1 has the correct values.
The fourth data point from sensor 1 is dropped, and the last value of sensor 1 is replaced by a 7.

Constraints:

sensor1.length == sensor2.length
1 <= sensor1.length <= 100
1 <= sensor1[i], sensor2[i] <= 100
*************

481. Faulty Sensor(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int badSensor(vector& sensor1, vector& sensor2) {
7 for (int i = 0; i + 1 < size(sensor1); ++i) {
8 if (sensor1[i] == sensor2[i]) {
9 continue;
10 }
11 while (i + 1 < size(sensor2) && sensor2[i + 1] == sensor1[i]) {
12 ++i;
13 }
14 return i + 1 == size(sensor2) ? 1 : 2;
15 }
16 return -1;
17 }
18 };
*************

481. Faulty Sensor(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def badSensor(self, sensor1, sensor2):
6 """
7 :type sensor1: List[int]
8 :type sensor2: List[int]
9 :rtype: int
10 """
11 for i in xrange(len(sensor1)-1):
12 if sensor1[i] == sensor2[i]:
13 continue
14 while i+1 < len(sensor2) and sensor2[i+1] == sensor1[i]:
15 i += 1
16 return 1 if i+1 == len(sensor2) else 2
17 return -1
***********************************************

482. Minimum Operations to Make the Array Increasing


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

You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it
by 1.

For example, if nums = [1,2,3] , you can choose to increment nums[1] to make nums = [1,3,3].

Return the minimum number of operations needed to make nums strictly increasing.

An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1 . An array of length 1 is trivially strictly
increasing.

Example 1:

Input: nums = [1,1,1]


Output: 3
Explanation: You can do the following operations:
1) Increment nums[2], so nums becomes [1,1,2].
2) Increment nums[1], so nums becomes [1,2,2].
3) Increment nums[2], so nums becomes [1,2,3].

Example 2:

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


Output: 14

Example 3:

Input: nums = [8]


Output: 0

Constraints:

1 <= nums.length <= 5000


1 <= nums[i] <= 10 4
***********************************************

482. Minimum Operations to Make the Array


Increasing(C++)
***********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int minOperations(vector& nums) {
7 int result = 0, prev = 0;
8 for (const auto& curr : nums) {
9 if (prev < curr) {
10 prev = curr;
11 continue;
12 }
13 result += (++prev) - curr;
14 }
15 return result;
16 }
17 };
***********************************************

482. Minimum Operations to Make the Array


Increasing(Python)
***********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def minOperations(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 result = prev = 0
11 for curr in nums:
12 if prev < curr:
13 prev = curr
14 continue
15 prev += 1
16 result += prev-curr
17 return result
********************************

483. Check if the Sentence Is Pangram


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

A pangram is a sentence where every letter of the English alphabet appears at least once.

Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

Example 1:

Input: sentence = "thequickbrownfoxjumpsoverthelazydog"


Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.

Example 2:

Input: sentence = "leetcode"


Output: false

Constraints:

1 <= sentence.length <= 1000


sentence consists of lowercase English letters.
********************************

483. Check if the Sentence Is Pangram(C++)


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

1 // Time: O(n)
2 // Space: O(26) = O(1)
3
4 class Solution {
5 public:
6 bool checkIfPangram(string sentence) {
7 return size(unordered_set(cbegin(sentence), cend(sentence))) == 26;
8 }
9 };
********************************

483. Check if the Sentence Is Pangram(Python)


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

1 # Time: O(n)
2 # Space: O(26) = O(1)
3
4 class Solution(object):
5 def checkIfPangram(self, sentence):
6 """
7 :type sentence: str
8 :rtype: bool
9 """
10 return len(set(sentence)) == 26
***********************

484. Sum of Digits in Base K


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

Given an integer n (in base 10) and a base k , return the sum of the digits of n after converting n from base 10 to base k .

After converting, each digit should be interpreted as a base10 number, and the sum should be returned in base 10.

Example 1:

Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.

Example 2:

Input: n = 10, k = 10
Output: 1
Explanation: n is already in base 10. 1 + 0 = 1.

Constraints:

1 <= n <= 100


2 <= k <= 10
***********************

484. Sum of Digits in Base K(C++)


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

1 // Time: O(logn)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int sumBase(int n, int k) {
7 int result = 0;
8 for (; n; n /= k) {
9 result += n % k;
10 }
11 return result;
12 }
13 };
***********************

484. Sum of Digits in Base K(Python)


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

1 # Time: O(logn)
2 # Space: O(1)
3
4 class Solution(object):
5 def sumBase(self, n, k):
6 """
7 :type n: int
8 :type k: int
9 :rtype: int
10 """
11 result = 0
12 while n:
13 n, r = divmod(n, k)
14 result += r
15 return result
**********************************

485. Replace All Digits with Characters


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

You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.

There is a function shift(c, x), where c is a character and x is a digit, that returns the x th character after c .

For example, shift('a', 5) = 'f' and shift('x', 0) = 'x' .

For every odd index i, you want to replace the digits[i] with shift(s[i-1], s[i]).

Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.

Example 1:

Input: s = "a1c1e1"
Output: "abcdef"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('c',1) = 'd'
- s[5] -> shift('e',1) = 'f'

Example 2:

Input: s = "a1b2c3d4e"
Output: "abbdcfdhe"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('b',2) = 'd'
- s[5] -> shift('c',3) = 'f'
- s[7] -> shift('d',4) = 'h'

Constraints:

1 <= s.length <= 100


s consists only of lowercase English letters and digits.
shift(s[i-1], s[i]) <= 'z' for all odd indices i.
**********************************

485. Replace All Digits with Characters(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string replaceDigits(string s) {
7 for (int i = 1; i < size(s); i += 2) {
8 s[i] += s[i - 1] - '0';
9 }
10 return s;
11 }
12 };
**********************************

485. Replace All Digits with Characters(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def replaceDigits(self, s):
6 """
7 :type s: str
8 :rtype: str
9 """
10 return "".join(chr(ord(s[i-1])+int(s[i])) if i%2 else s[i] for i in xrange(len(s)))
**************************************

486. Minimum Distance to the Target Element


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

Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i -
start) is minimized. Note that abs(x) is the absolute value of x .

Return abs(i - start) .

It is guaranteed that target exists in nums.

Example 1:

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


Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.

Example 2:

Input: nums = [1], target = 1, start = 0


Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.

Example 3:

Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0


Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.

Constraints:

1 <= nums.length <= 1000


1 <= nums[i] <= 10 4
0 <= start < nums.length
target is in nums.
**************************************

486. Minimum Distance to the Target Element(C++)


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

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

486. Minimum Distance to the Target Element(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def getMinDistance(self, nums, target, start):
6 """
7 :type nums: List[int]
8 :type target: int
9 :type start: int
10 :rtype: int
11 """
12 for i in xrange(len(nums)):
13 if (start-i >= 0 and nums[start-i] == target) or \
14 (start+i < len(nums) and nums[start+i] == target):
15 break
16 return i
*******************

487. Convert Date Format


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

Table: Days

+-------------+------+
| Column Name | Type |
+-------------+------+
| day | date |
+-------------+------+
day is the primary key for this table.

Write an SQL query to convert each date inDays into a string formatted as "day_name, month_name day, year" .

Return the result table in any order.

The query result format is in the following example:

Days table:
+------------+
| day |
+------------+
| 2022-04-12 |
| 2021-08-09 |
| 2020-06-26 |
+------------+

Result table:
+-------------------------+
| day |
+-------------------------+
| Tuesday, April 12, 2022 |
| Monday, August 9, 2021 |
| Friday, June 26, 2020 |
+-------------------------+
Please note that the output is case-sensitive.
*******************

487. Convert Date Format(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT DATE_FORMAT(day, "%W, %M %e, %Y") AS day
5 FROM Days;
***********************

488. Maximum Population Year


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

You are given a 2D integer arraylogs where each logs[i] = [birth i, deathi] indicates the birth and death years of theith person.

The population of some year x is the number of people alive during that year. Theith person is counted in year x 's
population if x is in the inclusive range [birthi, deathi - 1] . Note that the person is not counted in the year that they die.

Return the earliest year with the maximum population.

Example 1:

Input: logs = [[1993,1999],[2000,2010]]


Output: 1993
Explanation: The maximum population is 1, and 1993 is the earliest year with this population.

Example 2:

Input: logs = [[1950,1961],[1960,1971],[1970,1981]]


Output: 1960
Explanation:
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.

Constraints:

1 <= logs.length <= 100


1950 <= birth i < death i <= 2050
***********************

488. Maximum Population Year(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int maximumPopulation(vector>& logs) {
7 static const int MIN_YEAR = 1950;
8 static const int MAX_YEAR = 2050;
9 vector years(MAX_YEAR - MIN_YEAR + 1);
10 for (int i = 0; i < size(logs); ++i) {
11 ++years[logs[i][0] - MIN_YEAR];
12 --years[logs[i][1] - MIN_YEAR];
13 }
14 int result = 0;
15 for (int i = 0; i < size(years); ++i) {
16 if (i) {
17 years[i] += years[i - 1];
18 }
19 if (years[i] > years[result]) {
20 result = i;
21 }
22 }
23 return result + MIN_YEAR;
24 }
25 };
***********************

488. Maximum Population Year(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def maximumPopulation(self, logs):
6 """
7 :type logs: List[List[int]]
8 :rtype: int
9 """
10 MIN_YEAR, MAX_YEAR = 1950, 2050
11 years = [0]*(MAX_YEAR-MIN_YEAR+1)
12 for s, e in logs:
13 years[s-MIN_YEAR] += 1
14 years[e-MIN_YEAR] -= 1
15 result = 0
16 for i in xrange(len(years)):
17 if i:
18 years[i] += years[i-1]
19 if years[i] > years[result]:
20 result = i
21 return result+MIN_YEAR
********************

489. Sorting the Sentence


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

A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of
lowercase and uppercase English letters.

A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the
sentence.

For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3" .

Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.

Example 1:

Input: s = "is2 sentence4 This1 a3"


Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.

Example 2:

Input: s = "Myself2 Me1 I4 and3"


Output: "Me Myself and I"
Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.

Constraints:

2 <= s.length <= 200


s consists of lowercase and uppercase English letters, spaces, and digits from1 to 9.
The number of words in s is between 1 and 9.
The words in s are separated by a single space.
s contains no leading or trailing spaces.
********************

489. Sorting the Sentence(C++)


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

1 // Time: O(n)
2 // Space: O(n)
3
4 class Solution {
5 public:
6 string sortSentence(string s) {
7 vector words = split(s, ' ');
8 for (int i = 0; i < size(words); ++i) {
9 while (words[i].back() - '1' != i) {
10 swap(words[i], words[words[i].back() - '1']);
11 }
12 }
13 string result;
14 for (const auto& word : words) {
15 result += word;
16 result.back() = ' ';
17 }
18 result.pop_back();
19 return result;
20 }
21
22 private:
23 vector split(const string& s, const char delim) {
24 vector result;
25 auto end = string::npos;
26 do {
27 const auto& start = end + 1;
28 end = s.find(delim, start);
29 result.emplace_back(s.substr(start, end - start));
30 } while (end != string::npos);
31 return result;
32 }
33 };
********************

489. Sorting the Sentence(Python)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 import itertools
5
6
7 class Solution(object):
8 def sortSentence(self, s):
9 """
10 :type s: str
11 :rtype: str
12 """
13 words = s.split()
14 for i in xrange(len(words)):
15 while int(words[i][-1])-1 != i:
16 words[int(words[i][-1])-1], words[i] = words[i], words[int(words[i][-1])-1]
17 return " ".join(itertools.imap(lambda x: x[:-1], words))
****************************

490. Sum of All Subset XOR Totals


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

The XOR total of an array is defined as the bitwiseXOR of all its elements, or 0 if the array is empty.

For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1 .

Given an array nums, return the sum of all XOR totals for every subset of nums.

Note: Subsets with the same elements should be counted multiple times.

An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements ofb.

Example 1:

Input: nums = [1,3]


Output: 6
Explanation: The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6

Example 2:

Input: nums = [5,1,6]


Output: 28
Explanation: The 8 subsets of [5,1,6] are:
- The empty subset has an XOR total of 0.
- [5] has an XOR total of 5.
- [1] has an XOR total of 1.
- [6] has an XOR total of 6.
- [5,1] has an XOR total of 5 XOR 1 = 4.
- [5,6] has an XOR total of 5 XOR 6 = 3.
- [1,6] has an XOR total of 1 XOR 6 = 7.
- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28

Example 3:

Input: nums = [3,4,5,6,7,8]


Output: 480
Explanation: The sum of all XOR totals for every subset is 480.

Constraints:

1 <= nums.length <= 12


1 <= nums[i] <= 20
****************************

490. Sum of All Subset XOR Totals(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int subsetXORSum(vector& nums) {
7 // given there are k (k >= 1) nums of which ith bit is 1,
8 // the bit contributes to sum is:
9 // (nCr(k, 1) + nCr(k, 3) + ...) * (nCr(n - k, 0) + nCr(n - k, 1) + ...) * 2^i
10 // = 2^(k-1) * 2^(n-k) = 2^(n-1) * 2^i
11 int result = 0;
12 for (const auto& x : nums) {
13 result |= x;
14 }
15 return result * pow(2, size(nums) - 1);
16 }
17 };
****************************

490. Sum of All Subset XOR Totals(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def subsetXORSum(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 # given there are k (k >= 1) nums of which ith bit is 1,
11 # the bit contributes to sum is:
12 # (nCr(k, 1) + nCr(k, 3) + ...) * (nCr(n - k, 0) + nCr(n - k, 1) + ...) * 2^i
13 # = 2^(k-1) * 2^(n-k) = 2^(n-1) * 2^i
14 result = 0
15 for x in nums:
16 result |= x
17 return result * 2**(len(nums)-1)
******************************************

491. Orders With Maximum Quantity Above Average


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

Table: OrdersDetails

+-------------+------+
| Column Name | Type |
+-------------+------+
| order_id | int |
| product_id | int |
| quantity | int |
+-------------+------+
(order_id, product_id) is the primary key for this table.
A single order is represented as multiple rows, one row for each product in the order.
Each row of this table contains the quantity ordered of the product product_id in the order order_id.

You are running an ecommerce site that is looking for imbalanced orders. An imbalanced order is one whose maximum
quantity is strictly greater than the average quantity of every order (including itself).

The average quantity of an order is calculated as (total quantity of all products in the order) / (number of different products in the order) . The
maximum quantity of an order is the highest quantity of any single product in the order.

Write an SQL query to find the order_id of all imbalanced orders.

Return the result table in any order.

The query result format is in the following example:


OrdersDetails table:
+----------+------------+----------+
| order_id | product_id | quantity |
+----------+------------+----------+
| 1 | 1 | 12 |
| 1 | 2 | 10 |
| 1 | 3 | 15 |
| 2 | 1 | 8 |
| 2 | 4 | 4 |
| 2 | 5 | 6 |
| 3 | 3 | 5 |
| 3 | 4 | 18 |
| 4 | 5 | 2 |
| 4 | 6 | 8 |
| 5 | 7 | 9 |
| 5 | 8 | 9 |
| 3 | 9 | 20 |
| 2 | 9 | 4 |
+----------+------------+----------+

Result table:
+----------+
| order_id |
+----------+
| 1 |
| 3 |
+----------+

The average quantity of each order is:


- order_id=1: (12+10+15)/3 = 12.3333333
- order_id=2: (8+4+6+4)/4 = 5.5
- order_id=3: (5+18+20)/3 = 14.333333
- order_id=4: (2+8)/2 = 5
- order_id=5: (9+9)/2 = 9

The maximum quantity of each order is:


- order_id=1: max(12, 10, 15) = 15
- order_id=2: max(8, 4, 6, 4) = 8
- order_id=3: max(5, 18, 20) = 20
- order_id=4: max(2, 8) = 8
- order_id=5: max(9, 9) = 9

Orders 1 and 3 are imbalanced because they have a maximum quantity that exceeds the average quantity of every order.
******************************************

491. Orders With Maximum Quantity Above


Average(Shell)
******************************************

1 # Time: O(n)
2 # Space: O(n)
3
4 WITH cte AS
5 (SELECT order_id,
6 AVG(quantity) AS avg_quantity,
7 MAX(quantity) AS max_quantity
8 FROM OrdersDetails
9 GROUP BY order_id
10 ORDER BY NULL)
11
12 SELECT order_id
13 FROM cte
14 WHERE max_quantity >
15 (SELECT MAX(avg_quantity) AS max_avg_quantity
16 FROM cte);
*********************************************

492. Longer Contiguous Segments of Ones than Zeros


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

Given a binary string s , return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous
segment of 0s in s . Return false otherwise.

For example, in s = " 110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment
of 0s has length 3.

Note that if there are no 0s, then the longest contiguous segment of0s is considered to have length 0. The same applies if
there are no 1s.

Example 1:

Input: s = "1101"
Output: true
Explanation:
The longest contiguous segment of 1s has length 2: "1101"
The longest contiguous segment of 0s has length 1: "1101"
The segment of 1s is longer, so return true.

Example 2:

Input: s = "111000"
Output: false
Explanation:
The longest contiguous segment of 1s has length 3: "111000"
The longest contiguous segment of 0s has length 3: "111000"
The segment of 1s is not longer, so return false.

Example 3:

Input: s = "110100010"
Output: false
Explanation:
The longest contiguous segment of 1s has length 2: "110100010"
The longest contiguous segment of 0s has length 3: "110100010"
The segment of 1s is not longer, so return false.

Constraints:

1 <= s.length <= 100


s[i] is either '0' or '1'.
*********************************************

492. Longer Contiguous Segments of Ones than


Zeros(C++)
*********************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool checkZeroOnes(string s) {
7 vector max_cnt(2);
8 for (int i = 0, cnt = 0; i <= size(s); ++i, ++cnt) {
9 if (i == size(s) || (i >= 1 && s[i] != s[i - 1])) {
10 max_cnt[s[i - 1] - '0'] = max(max_cnt[s[i - 1] - '0'], cnt);
11 cnt = 0;
12 }
13 }
14 return max_cnt[0] < max_cnt[1];
15 }
16 };
*********************************************

492. Longer Contiguous Segments of Ones than


Zeros(Python)
*********************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def checkZeroOnes(self, s):
6 """
7 :type s: str
8 :rtype: bool
9 """
10 max_cnt = [0]*2
11 cnt = 0
12 for i in xrange(len(s)+1):
13 if i == len(s) or (i >= 1 and s[i] != s[i-1]):
14 max_cnt[int(s[i-1])] = max(max_cnt[int(s[i-1])], cnt)
15 cnt = 0
16 cnt += 1
17 return max_cnt[0] < max_cnt[1]
***********************

493. Calculate Special Bonus


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

Table: Employees

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| name | varchar |
| salary | int |
+-------------+---------+
employee_id is the primary key for this table.
Each row of this table indicates the employee ID, employee name, and salary.

Write an SQL query to calculate the bonus of each employee. The bonus of an employee is100% of their salary if the ID of
the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an
employee is 0 otherwise.

Return the result table ordered by employee_id.

The query result format is in the following example:

Employees table:
+-------------+---------+--------+
| employee_id | name | salary |
+-------------+---------+--------+
| 2 | Meir | 3000 |
| 3 | Michael | 3800 |
| 7 | Addilyn | 7400 |
| 8 | Juan | 6100 |
| 9 | Kannon | 7700 |
+-------------+---------+--------+

Result table:
+-------------+-------+
| employee_id | bonus |
+-------------+-------+
| 2 | 0 |
| 3 | 0 |
| 7 | 7400 |
| 8 | 0 |
| 9 | 7700 |
+-------------+-------+

The employees with IDs 2 and 8 get 0 bonus because they have an even employee_id.
The employee with ID 3 gets 0 bonus because their name starts with 'M'.
The rest of the employees get a 100% bonus.
***********************

493. Calculate Special Bonus(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT employee_id,
5 IF(employee_id%2 = 1
6 AND name NOT LIKE('M%'), salary, 0) AS bonus
7 FROM Employees;
*************************************************

494. Substrings of Size Three with Distinct Characters


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

A string is good if there are no repeated characters.

Given a string s ​​​​​, return the number of good substrings of length three in s ​​​​​​.

Note that if there are multiple occurrences of the same substring, every occurrence should be counted.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = "xyzzaz"
Output: 1
Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz".
The only good substring of length 3 is "xyz".

Example 2:

Input: s = "aababcabc"
Output: 4
Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".
The good substrings are "abc", "bca", "cab", and "abc".

Constraints:

1 <= s.length <= 100


s ​​​​​​ consists of lowercase English letters.
*************************************************

494. Substrings of Size Three with Distinct


Characters(C++)
*************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 int countGoodSubstrings(string s) {
7 static const int K = 3;
8
9 int result = 0;
10 unordered_map count;
11 for (int i = 0; i < size(s); ++i) {
12 if (i >= K) {
13 if (--count[s[i - K]] == 0) {
14 count.erase(s[i - K]);
15 }
16 }
17 ++count[s[i]];
18 if (size(count) == K) {
19 ++result;
20 }
21 }
22 return result;
23 }
24 };
*************************************************

494. Substrings of Size Three with Distinct


Characters(Python)
*************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def countGoodSubstrings(self, s):
9 """
10 :type s: str
11 :rtype: int
12 """
13 K = 3
14
15 result = 0
16 count = collections.Counter()
17 for i in xrange(len(s)):
18 if i >= K:
19 count[s[i-K]] -= 1
20 if not count[s[i-K]]:
21 del count[s[i-K]]
22 count[s[i]] += 1
23 if len(count) == K:
24 result += 1
25 return result
****************************************

495. Get Biggest Three Rhombus Sums in a Grid


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

You are given an m x n integer matrix grid​​​.

A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus
must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of
four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:

Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.

Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct
values, return all of them.

Example 1:
Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211

Example 2:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]]


Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)

Example 3:

Input: grid = [[7,7,7]]


Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 10 5
****************************************

495. Get Biggest Three Rhombus Sums in a Grid(C++)


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

1 // Time: O(m * n * min(m, n))


2 // Space: O(m * n)
3
4 class Solution {
5 public:
6 vector getBiggestThree(vector>& grid) {
7 static const int K = 3;
8
9 vector> left{grid}, right{grid};
10 for (int i = 1; i < size(grid); ++i) {
11 for (int j = 0; j < size(grid[0]) - 1; ++j) {
12 left[i][j] += left[i - 1][j + 1];
13 }
14 }
15 for (int i = 1; i < size(grid); ++i) {
16 for (int j = 1; j < size(grid[0]); ++j) {
17 right[i][j] += right[i - 1][j - 1];
18 }
19 }
20 priority_queue, greater> min_heap;
21 unordered_set lookup;
22 for (int k = 0; k <= (min(size(grid), size(grid[0])) + 1) / 2; ++k) {
23 for (int i = k; i < size(grid) - k; ++i) {
24 for (int j = k; j < size(grid[0]) - k; ++j) {
25 int total = k ? ((left[i][j - k] - left[i - k][j]) + (right[i][j + k] - right[i - k][j]) + grid[i - k][j
26 ((left[i + k][j] - left[i][j + k]) + (right[i + k][j] - right[i][j - k]) - grid[i + k][j]
27 : grid[i][j];
28 if (lookup.count(total)) {
29 continue;
30 }
31 lookup.emplace(total);
32 min_heap.emplace(total);
33 if (size(min_heap) == K + 1) {
34 lookup.erase(min_heap.top()); min_heap.pop();
35 }
36 }
37 }
38 }
39 vector result;
40 while (!empty(min_heap)) {
41 result.emplace_back(min_heap.top()); min_heap.pop();
42 }
43 reverse(begin(result), end(result));
44 return result;
45 }
46 };
****************************************

495. Get Biggest Three Rhombus Sums in a Grid(Python)


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

1 # Time: O(m * n * min(m, n))


2 # Space: O(m * n)
3
4 import heapq
5
6
7 class Solution(object):
8 def getBiggestThree(self, grid):
9 """
10 :type grid: List[List[int]]
11 :rtype: List[int]
12 """
13 K = 3
14 left = [[grid[i][j] for j in xrange(len(grid[i]))] for i in xrange(len(grid))]
15 right = [[grid[i][j] for j in xrange(len(grid[i]))] for i in xrange(len(grid))]
16 for i in xrange(1, len(grid)):
17 for j in xrange(len(grid[0])-1):
18 left[i][j] += left[i-1][j+1]
19 for i in xrange(1, len(grid)):
20 for j in xrange(1, len(grid[0])):
21 right[i][j] += right[i-1][j-1]
22 min_heap = []
23 lookup = set()
24 for k in xrange((min(len(grid), len(grid[0]))+1)//2):
25 for i in xrange(k, len(grid)-k):
26 for j in xrange(k, len(grid[0])-k):
27 total = (((left[i][j-k]-left[i-k][j])+(right[i][j+k]-right[i-k][j])+grid[i-k][j]) +
28 ((left[i+k][j]-left[i][j+k])+(right[i+k][j]-right[i][j-k])-grid[i+k][j])) if k else grid[i][j]
29 if total in lookup:
30 continue
31 lookup.add(total)
32 heapq.heappush(min_heap, total)
33 if len(min_heap) == K+1:
34 lookup.remove(heapq.heappop(min_heap))
35 min_heap.sort(reverse=True)
36 return min_heap
*******************************************

496. Check if Word Equals Summation of Two Words


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

The letter value of a letter is its position in the alphabetstarting from 0 (i.e. 'a' -> 0 , 'b' -> 1 , 'c' -> 2, etc.).

The numerical value of some string of lowercase English letterss is the concatenation of the letter values of each letter in
s , which is then converted into an integer.

For example, if s = "acb" , we concatenate each letter's letter value, resulting in"021". After converting it, we get 21.

You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j'
inclusive.

Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or
false otherwise.

Example 1:

Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"


Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.

Example 2:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"


Output: false
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.

Example 3:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"


Output: true
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aaaa" -> "0000" -> 0.
We return true because 0 + 0 == 0.

Constraints:

1 <= firstWord.length, secondWord.length, targetWord.length <= 8


firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.
*******************************************

496. Check if Word Equals Summation of Two


Words(C++)
*******************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool isSumEqual(string firstWord, string secondWord, string targetWord) {
7 return stoi(firstWord) + stoi(secondWord) == stoi(targetWord);
8 }
9
10 private:
11 int stoi(const string& s) {
12 int result = 0;
13 for (const auto& c : s) {
14 result = result * 10 + c - 'a';
15 }
16 return result;
17 }
18 };
*******************************************

496. Check if Word Equals Summation of Two


Words(Python)
*******************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def isSumEqual(self, firstWord, secondWord, targetWord):
6 """
7 :type firstWord: str
8 :type secondWord: str
9 :type targetWord: str
10 :rtype: bool
11 """
12 def stoi(s):
13 result = 0
14 for c in s:
15 result = result*10 + ord(c)-ord('a')
16 return result
17
18 return stoi(firstWord) + stoi(secondWord) == stoi(targetWord)
****************************************************

497. Determine Whether Matrix Can Be Obtained By


Rotation
****************************************************

Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-
degree increments, or false otherwise.

Example 1:

Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]


Output: true
Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.

Example 2:

Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]


Output: false
Explanation: It is impossible to make mat equal to target by rotating mat.

Example 3:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]


Output: true
Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.

Constraints:

n == mat.length == target.length
n == mat[i].length == target[i].length
1 <= n <= 10
mat[i][j] and target[i][j] are either 0 or 1.
****************************************************

497. Determine Whether Matrix Can Be Obtained By


Rotation(C++)
****************************************************

1 // Time: O(m * n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool findRotation(vector>& mat, vector>& target) {
7 vector> checks = {
8 [&mat, &target](int i, int j) { return mat[i][j] == target[i][j]; },
9 [&mat, &target](int i, int j) { return mat[i][j] == target[j][size(mat) - 1 - i]; },
10 [&mat, &target](int i, int j) { return mat[i][j] == target[size(mat) - 1 - i][size(mat[0]) - 1 - j]; },
11 [&mat, &target](int i, int j) { return mat[i][j] == target[size(mat[0]) - 1 - j][i]; },
12 };
13 const auto& traverse = [&mat, &target](const auto& check) {
14 for (int i = 0; i < size(mat); ++i) {
15 for (int j = 0; j < size(mat[0]); ++j) {
16 if (!check(i, j)) {
17 return false;
18 }
19 }
20 }
21 return true;
22 };
23 for (const auto& check : checks) {
24 if (traverse(check)) {
25 return true;
26 }
27 }
28 return false;
29 }
30 };
****************************************************

497. Determine Whether Matrix Can Be Obtained By


Rotation(Python)
****************************************************

1 # Time: O(m * n)
2 # Space: O(1)
3
4 class Solution(object):
5 def findRotation(self, mat, target):
6 """
7 :type mat: List[List[int]]
8 :type target: List[List[int]]
9 :rtype: bool
10 """
11 checks = [lambda i, j: mat[i][j] == target[i][j],
12 lambda i, j: mat[i][j] == target[j][-1-i],
13 lambda i, j: mat[i][j] == target[-1-i][-1-j],
14 lambda i, j: mat[i][j] == target[-1-j][i]]
15 traverse = lambda check: all(check(i, j) for i in xrange(len(mat)) for j in xrange(len(mat[0])))
16 return any(traverse(check) for check in checks)
************************

498. The Latest Login in 2020


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

Table: Logins

+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
+----------------+----------+
(user_id, time_stamp) is the primary key for this table.
Each row contains information about the login time for the user with ID user_id.

Write an SQL query to report the latest login for all users in the year 2020. Do not include the users who did not login in2020.

Return the result table in any order.

The query result format is in the following example:

Logins table:
+---------+---------------------+
| user_id | time_stamp |
+---------+---------------------+
| 6 | 2020-06-30 15:06:07 |
| 6 | 2021-04-21 14:06:06 |
| 6 | 2019-03-07 00:18:15 |
| 8 | 2020-02-01 05:10:53 |
| 8 | 2020-12-30 00:46:50 |
| 2 | 2020-01-16 02:49:50 |
| 2 | 2019-08-25 07:59:08 |
| 14 | 2019-07-14 09:00:00 |
| 14 | 2021-01-06 11:59:59 |
+---------+---------------------+

Result table:
+---------+---------------------+
| user_id | last_stamp |
+---------+---------------------+
| 6 | 2020-06-30 15:06:07 |
| 8 | 2020-12-30 00:46:50 |
| 2 | 2020-01-16 02:49:50 |
+---------+---------------------+

User 6 logged into their account 3 times but only once in 2020, so we include this login in the result table.
User 8 logged into their account 2 times in 2020, once in February and once in December. We include only the latest one (December) in the res
User 2 logged into their account 2 times but only once in 2020, so we include this login in the result table.
User 14 did not login in 2020, so we do not include them in the result table.
************************

498. The Latest Login in 2020(Shell)


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

1 # Time: O(n)
2 # Space: O(n)
3
4 SELECT user_id,
5 MAX(time_stamp) AS last_stamp
6 FROM Logins
7 WHERE YEAR(time_stamp) = 2020
8 GROUP BY user_id
9 ORDER BY NULL;
************************************************

499. Check if All the Integers in a Range Are Covered


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

You are given a 2D integer arrayranges and two integers left and right. Each ranges[i] = [start i, end i] represents an inclusive
interval between starti and endi.

Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.

An integer x is covered by an interval ranges[i] = [start i, end i] if starti <= x <= end i.

Example 1:

Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5


Output: true
Explanation: Every integer between 2 and 5 is covered:
- 2 is covered by the first range.
- 3 and 4 are covered by the second range.
- 5 is covered by the third range.

Example 2:

Input: ranges = [[1,10],[10,20]], left = 21, right = 21


Output: false
Explanation: 21 is not covered by any range.

Constraints:

1 <= ranges.length <= 50


1 <= starti <= end i <= 50
1 <= left <= right <= 50
************************************************

499. Check if All the Integers in a Range Are


Covered(C++)
************************************************
1 // Time: O(n + r)
2 // Space: O(r)
3
4 // if r is small, this is better
5 class Solution {
6 public:
7 bool isCovered(vector>& ranges, int left, int right) {
8 static const int RANGE_SIZE = 50;
9
10 vector interval(RANGE_SIZE + 1);
11 for (const auto& r : ranges) {
12 ++interval[r[0] - 1];
13 --interval[(r[1] - 1) + 1];
14 }
15 for (int i = 0, cnt = 0; i <= right - 1; ++i) {
16 cnt += interval[i];
17 if (i >= left - 1 && !cnt) {
18 return false;
19 }
20 }
21 return true;
22 }
23 };
24
25 // Time: O(nlogn)
26 // Space: O(1)
27 // if r is big, this is better
28 class Solution2 {
29 public:
30 bool isCovered(vector>& ranges, int left, int right) {
31 sort(begin(ranges), end(ranges));
32 for (const auto& r : ranges) {
33 if (r[0] <= left && left <= r[1]) {
34 left = r[1] + 1;
35 }
36 }
37 return left > right;
38 }
39 };
40
41 // Time: O(n * r)
42 // Space: O(1)
43 class Solution3 {
44 public:
45 bool isCovered(vector>& ranges, int left, int right) {
46 for (int i = left; i <= right; ++i) {
47 bool found = false;
48 for (const auto& r : ranges) {
49 if (r[0] <= i && i <= r[1]) {
50 found = true;
51 break;
52 }
53 }
54 if (!found) {
55 return false;
56 }
57 }
58 return true;
59 }
60 };
************************************************

499. Check if All the Integers in a Range Are


Covered(Python)
************************************************

1 # Time: O(n + r)
2 # Space: O(r)
3
4 # if r is small, this is better
5 class Solution(object):
6 def isCovered(self, ranges, left, right):
7 """
8 :type ranges: List[List[int]]
9 :type left: int
10 :type right: int
11 :rtype: bool
12 """
13 RANGE_SIZE = 50
14
15 interval = [0]*(RANGE_SIZE+1)
16 for l, r in ranges:
17 interval[l-1] += 1
18 interval[(r-1)+1] -= 1
19 cnt = 0
20 for i in xrange((right-1)+1):
21 cnt += interval[i]
22 if i >= left-1 and not cnt:
23 return False
24 return True
25
26
27 # Time: O(nlogn)
28 # Space: O(1)
29 # if r is big, this is better
30 class Solution2(object):
31 def isCovered(self, ranges, left, right):
32 """
33 :type ranges: List[List[int]]
34 :type left: int
35 :type right: int
36 :rtype: bool
37 """
38 ranges.sort()
39 for l, r in ranges:
40 if l <= left <= r:
41 left = r+1
42 return left > right
43
44
45 # Time: O(n * r)
46 # Space: O(1)
47 class Solution3(object):
48 def isCovered(self, ranges, left, right):
49 """
50 :type ranges: List[List[int]]
51 :type left: int
52 :type right: int
53 :rtype: bool
54 """
55 return all(any(l <= i <= r for l, r in ranges) for i in xrange(left, right+1))
*************************************************

500. Redistribute Characters to Make All Strings Equal


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

You are given an array of stringswords (0-indexed).

In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i]
to any position in words[j].

Return true if you can make every string in words equal using any number of operations, and false otherwise.

Example 1:

Input: words = ["abc","aabc","bc"]


Output: true
Explanation: Move the first 'a' in words[1] to the front of words[2],
to make words[1] = "abc" and words[2] = "abc".
All the strings are now equal to "abc", so return true.

Example 2:

Input: words = ["ab","a"]


Output: false
Explanation: It is impossible to make all the strings equal using the operation.

Constraints:

1 <= words.length <= 100


1 <= words[i].length <= 100
words[i] consists of lowercase English letters.
*************************************************

500. Redistribute Characters to Make All Strings


Equal(C++)
*************************************************

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 bool makeEqual(vector& words) {
7 vector cnt(26);
8 for (const auto& w : words) {
9 for (const auto& c : w) {
10 ++cnt[c - 'a'];
11 }
12 }
13 return all_of(cbegin(cnt), cend(cnt),
14 [&words](int c) {
15 return c % size(words) == 0;
16 });
17 }
18 };
*************************************************

500. Redistribute Characters to Make All Strings


Equal(Python)
*************************************************

1 # Time: O(n)
2 # Space: O(1)
3
4 import collections
5
6
7 class Solution(object):
8 def makeEqual(self, words):
9 """
10 :type words: List[str]
11 :rtype: bool
12 """
13 cnt = collections.defaultdict(int)
14 for w in words:
15 for c in w:
16 cnt[c] += 1
17 return all(v%len(words) == 0 for v in cnt.itervalues())
****************************

501. Largest Odd Number in String


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

You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-
empty substring of num, or an empty string "" if no odd integer exists.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: num = "52"


Output: "5"
Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.

Example 2:

Input: num = "4206"


Output: ""
Explanation: There are no odd numbers in "4206".

Example 3:

Input: num = "35427"


Output: "35427"
Explanation: "35427" is already an odd number.

Constraints:

1 <= num.length <= 10 5


num only consists of digits and does not contain any leading zeros.
****************************

501. Largest Odd Number in String(C++)


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

1 // Time: O(n)
2 // Space: O(1)
3
4 class Solution {
5 public:
6 string largestOddNumber(string num) {
7 for (int i = size(num) - 1; i >= 0; --i) {
8 if ((num[i] - '0') % 2) {
9 return num.substr(0, i + 1);
10 }
11 }
12 return "";
13 }
14 };
****************************

501. Largest Odd Number in String(Python)


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

1 # Time: O(n)
2 # Space: O(1)
3
4 class Solution(object):
5 def largestOddNumber(self, num):
6 """
7 :type num: str
8 :rtype: str
9 """
10 for i in reversed(xrange(len(num))):
11 if int(num[i])%2:
12 return num[:i+1]
13 return ""
********************************************************

502. Remove One Element to Make the Array Strictly


Increasing
********************************************************

Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element,
or false otherwise. If the array is already strictly increasing, returntrue.

The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).

Example 1:

Input: nums = [1,2,10,5,7]


Output: true
Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].
[1,2,5,7] is strictly increasing, so return true.

Example 2:

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


Output: false
Explanation:
[3,1,2] is the result of removing the element at index 0.
[2,1,2] is the result of removing the element at index 1.
[2,3,2] is the result of removing the element at index 2.
[2,3,1] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.

Example 3:

Input: nums = [1,1,1]


Output: false
Explanation: The result of removing any element is [1,1].
[1,1] is not strictly increasing, so return false.

Example 4:

Input: nums = [1,2,3]


Output: true
Explanation: [1,2,3] is already strictly increasing, so return true.

Constraints:

2 <= nums.length <= 1000


1 <= nums[i] <= 1000
****************************

503. Build Array from Permutation


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

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each
0 <= i < nums.length and return it.

A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).

Example 1:

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


Output: [0,1,2,4,5,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
= [0,1,2,4,5,3]

Example 2:

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


Output: [4,5,0,1,2,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
= [4,5,0,1,2,3]

Constraints:

1 <= nums.length <= 1000


0 <= nums[i] < nums.length
The elements in nums are distinct.

Follow-up: Can you solve it without using an extra space (i.e.,O(1) memory)?
************************

504. Count Square Sum Triples


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

A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b 2 = c 2.

Given an integer n, return the number of square triples such that 1 <= a, b, c <= n .

Example 1:

Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).

Example 2:

Input: n = 10
Output: 4
Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).

Constraints:

1 <= n <= 250


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

505. Concatenation of Array


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

Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i]
for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans.

Example 1:

Input: nums = [1,2,1]


Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]

Example 2:

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


Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]

Constraints:

n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
***********************************************************

506. Check if String Is Decomposable Into Value-Equal


Substrings
***********************************************************

A value-equal string is a string where all characters are the same.

For example, "1111" and "33" are value-equal strings.


In contrast, "123" is not a value-equal string.

Given a digit string s , decompose the string into some number ofconsecutive value-equal substrings where exactly one
substring has a length of 2 and the remaining substrings have a length of 3.

Return true if you can decompose s according to the above rules. Otherwise, returnfalse.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = "000111000"
Output: false
Explanation: s cannot be decomposed according to the rules because ["000", "111", "000"] does not have a substring of length 2.

Example 2:

Input: s = "00011111222"
Output: true
Explanation: s can be decomposed into ["000", "111", "11", "222"].

Example 3:

Input: s = "011100022233"
Output: false
Explanation: s cannot be decomposed according to the rules because of the first '0'.

Constraints:

1 <= s.length <= 1000


s consists of only digits '0' through '9'.
************************************

507. Maximum Number of Words You Can Type


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

There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.

Given a string text of words separated by a single space (no leading or trailing spaces) and a stringbrokenLetters of all distinct
letter keys that are broken, return the number of words in text you can fully type using this keyboard.

Example 1:

Input: text = "hello world", brokenLetters = "ad"


Output: 1
Explanation: We cannot type "world" because the 'd' key is broken.

Example 2:

Input: text = "leet code", brokenLetters = "lt"


Output: 1
Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.

Example 3:

Input: text = "leet code", brokenLetters = "e"


Output: 0
Explanation: We cannot type either word because the 'e' key is broken.

Constraints:

1 <= text.length <= 10 4


0 <= brokenLetters.length <= 26
text consists of words separated by a single space without any leading or trailing spaces.
Each word only consists of lowercase English letters.
brokenLetters consists of distinct lowercase English letters.
*************************************************

508. Users That Actively Request Confirmation Messages


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

Table: Signups

+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
+----------------+----------+
user_id is the primary key for this table.
Each row contains information about the signup time for the user with ID user_id.

Table: Confirmations

+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
| action | ENUM |
+----------------+----------+
(user_id, time_stamp) is the primary key for this table.
user_id is a foreign key with a reference to the Signups table.
action is an ENUM of the type ('confirmed', 'timeout')
Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message w

Write an SQL query to find the IDs of the users that requested a confirmation messagetwice within a 24-hour window. Two
messages exactly 24 hours apart are considered to be within the window. The action does not affect the answer, only the
request time.

Return the result table in any order.

The query result format is in the following example:


Signups table:
+---------+---------------------+
| user_id | time_stamp |
+---------+---------------------+
| 3 | 2020-03-21 10:16:13 |
| 7 | 2020-01-04 13:57:59 |
| 2 | 2020-07-29 23:09:44 |
| 6 | 2020-12-09 10:39:37 |
+---------+---------------------+

Confirmations table:
+---------+---------------------+-----------+
| user_id | time_stamp | action |
+---------+---------------------+-----------+
| 3 | 2021-01-06 03:30:46 | timeout |
| 3 | 2021-01-06 03:37:45 | timeout |
| 7 | 2021-06-12 11:57:29 | confirmed |
| 7 | 2021-06-13 11:57:30 | confirmed |
| 2 | 2021-01-22 00:00:00 | confirmed |
| 2 | 2021-01-23 00:00:00 | timeout |
| 6 | 2021-10-23 14:14:14 | confirmed |
| 6 | 2021-10-24 14:14:13 | timeout |
+---------+---------------------+-----------+

Result table
+---------+
| user_id |
+---------+
| 2 |
| 3 |
| 6 |
+---------+

User 2 requested two messages within exactly 24 hours of each other, so we include them.
User 3 requested two messages within 6 minutes and 59 seconds of each other, so we include them.
User 6 requested two messages within 23 hours, 59 minutes, and 59 seconds of each other, so we include them.
User 7 requested two messages within 24 hours and 1 second of each other, so we exclude them from the answer.
********************************************************

509. Check if All Characters Have Equal Number of


Occurrences
********************************************************

Given a string s , return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Example 1:

Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.

Example 2:

Input: s = "aaabb"
Output: false
Explanation: The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.

Constraints:

1 <= s.length <= 1000


s consists of lowercase English letters.
*************************************

510. Sum of Digits of String After Convert


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

You are given a string s consisting of lowercase English letters, and an integerk .

First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace'a' with 1, 'b' with 2, ..., 'z'
with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in
total.

For example, if s = "zbax" and k = 2 , then the resulting integer would be 8 by the following operations:

Convert: "zbax" âž​ "(26)(2)(1)(24)" âž​ "262124" âž​ 262124


Transform #1: 262124 âž​ 2 + 6 + 2 + 1 + 2 + 4 âž​ 17
Transform #2: 17 âž​ 1 + 7 âž​ 8

Return the resulting integer after performing the operations described above.

Example 1:

Input: s = "iiii", k = 1
Output: 36
Explanation: The operations are as follows:
- Convert: "iiii" âž​ "(9)(9)(9)(9)" âž​ "9999" âž​ 9999
- Transform #1: 9999 âž​ 9 + 9 + 9 + 9 âž​ 36
Thus the resulting integer is 36.

Example 2:

Input: s = "leetcode", k = 2
Output: 6
Explanation: The operations are as follows:
- Convert: "leetcode" âž​ "(12)(5)(5)(20)(3)(15)(4)(5)" âž​ "12552031545" âž​ 12552031545
- Transform #1: 12552031545 âž​ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 âž​ 33
- Transform #2: 33 âž​ 3 + 3 âž​ 6
Thus the resulting integer is 6.

Example 3:

Input: s = "zbax", k = 2
Output: 8

Constraints:

1 <= s.length <= 100


1 <= k <= 10
s consists of lowercase English letters.
**************

511. Three Divisors


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

Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.

An integer m is a divisor of n if there exists an integer k such that n = k * m .

Example 1:

Input: n = 2
Output: false
Explantion: 2 has only two divisors: 1 and 2.

Example 2:

Input: n = 4
Output: true
Explantion: 4 has three divisors: 1, 2, and 4.

Constraints:

1 <= n <= 10 4
**************************************

512. Delete Characters to Make Fancy String


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

A fancy string is a string where no three consecutive characters are equal.

Given a string s , delete the minimum possible number of characters from s to make it fancy.

Return the final string after the deletion. It can be shown that the answer will always beunique.

Example 1:

Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".

Example 2:

Input: s = "aaabaaaa"
Output: "aabaa"
Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".

Example 3:

Input: s = "aab"
Output: "aab"
Explanation: No three consecutive characters are equal, so return "aab".

Constraints:

1 <= s.length <= 105


s consists only of lowercase English letters.
************************************

513. Check If String Is a Prefix of Array


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

Given a string s and an array of strings words, determine whether s is a prefix string of words.

A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger
than words.length.

Return true if s is a prefix string of words, or false otherwise.

Example 1:

Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]


Output: true
Explanation:
s can be made by concatenating "i", "love", and "leetcode" together.

Example 2:

Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]


Output: false
Explanation:
It is impossible to make s using a prefix of arr.

Constraints:

1 <= words.length <= 100


1 <= words[i].length <= 20
1 <= s.length <= 1000
words[i] and s consist of only lowercase English letters.
**********************************

514. Employees With Missing Information


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

Table: Employees

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| name | varchar |
+-------------+---------+
employee_id is the primary key for this table.
Each row of this table indicates the name of the employee whose ID is employee_id.

Table: Salaries

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| salary | int |
+-------------+---------+
employee_id is the primary key for this table.
Each row of this table indicates the salary of the employee whose ID is employee_id.

Write an SQL query to report the IDs of all the employees withmissing information. The information of an employee is
missing if:

The employee's name is missing, or


The employee's salary is missing.

Return the result table ordered by employee_id in ascending order.

The query result format is in the following example:


Employees table:
+-------------+----------+
| employee_id | name |
+-------------+----------+
| 2 | Crew |
| 4 | Haven |
| 5 | Kristian |
+-------------+----------+
Salaries table:
+-------------+--------+
| employee_id | salary |
+-------------+--------+
| 5 | 76071 |
| 1 | 22517 |
| 4 | 63539 |
+-------------+--------+

Result table:
+-------------+
| employee_id |
+-------------+
| 1 |
| 2 |
+-------------+

Employees 1, 2, 4, and 5 are working at this company.


The name of employee 1 is missing.
The salary of employee 2 is missing.

You might also like