-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblind75_questions.json
More file actions
1127 lines (1127 loc) · 79.8 KB
/
blind75_questions.json
File metadata and controls
1127 lines (1127 loc) · 79.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[
{
"id": 1,
"title": "Two Sum",
"slug": "two-sum",
"difficulty": "Easy",
"category": "Array",
"tags": ["Array", "Hash Table"],
"problem": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.",
"solution": "Use a hash map to store complements. For each number, check if its complement exists in the hash map.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def two_sum(nums, target):\n hash_map = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hash_map:\n return [hash_map[complement], i]\n hash_map[num] = i\n return []",
"explanation": "We iterate through the array once, storing each number's index in a hash map. For each number, we calculate its complement (target - current number) and check if that complement exists in our hash map. If it does, we've found our pair.",
"relatedQuestions": [15, 18, 167]
},
{
"id": 2,
"title": "Best Time to Buy and Sell Stock",
"slug": "best-time-to-buy-and-sell-stock",
"difficulty": "Easy",
"category": "Array",
"tags": ["Array", "Dynamic Programming"],
"problem": "You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve.",
"solution": "Keep track of minimum price seen so far and maximum profit achievable.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def max_profit(prices):\n if not prices:\n return 0\n min_price = prices[0]\n max_profit = 0\n for price in prices[1:]:\n max_profit = max(max_profit, price - min_price)\n min_price = min(min_price, price)\n return max_profit",
"explanation": "As we iterate through the prices, we update the minimum price encountered so far. For each price, we calculate the potential profit (current price - minimum price) and update the maximum profit if this potential profit is higher.",
"relatedQuestions": [121, 122, 188]
},
{
"id": 3,
"title": "Contains Duplicate",
"slug": "contains-duplicate",
"difficulty": "Easy",
"category": "Array",
"tags": ["Array", "Hash Table"],
"problem": "Given an integer array nums, return true if any value appears at least twice in the array.",
"solution": "Use a set to track seen elements. If element already exists in set, return true.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def contains_duplicate(nums):\n seen = set()\n for num in nums:\n if num in seen:\n return True\n seen.add(num)\n return False",
"explanation": "We maintain a set of seen numbers. As we iterate through the array, we check if the current number is in the set. If it is, we have found a duplicate. If not, we add the number to the set.",
"relatedQuestions": [217, 219, 220]
},
{
"id": 4,
"title": "Product of Array Except Self",
"slug": "product-of-array-except-self",
"difficulty": "Medium",
"category": "Array",
"tags": ["Array"],
"problem": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].",
"solution": "Use two passes: left products and right products, then multiply them together.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def product_except_self(nums):\n n = len(nums)\n result = [1] * n\n \n # Left pass\n for i in range(1, n):\n result[i] = result[i-1] * nums[i-1]\n \n # Right pass\n right = 1\n for i in range(n-1, -1, -1):\n result[i] *= right\n right *= nums[i]\n \n return result",
"explanation": "We first calculate the products of all elements to the left of each index. Then, we calculate the products of all elements to the right of each index. The result for each index is the product of the two.",
"relatedQuestions": [238, 239, 240]
},
{
"id": 5,
"title": "Maximum Subarray",
"slug": "maximum-subarray",
"difficulty": "Medium",
"category": "Array",
"tags": ["Array", "Dynamic Programming"],
"problem": "Given an integer array nums, find the contiguous subarray which has the largest sum and return its sum.",
"solution": "Use Kadane's algorithm. Keep track of maximum sum ending at current position and global maximum.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def max_subarray(nums):\n max_current = max_global = nums[0]\n for i in range(1, len(nums)):\n max_current = max(nums[i], max_current + nums[i])\n max_global = max(max_global, max_current)\n return max_global",
"explanation": "We iterate through the array, at each position calculating the maximum subarray sum that ends at that position. We update the global maximum subarray sum whenever we find a new maximum at a position.",
"relatedQuestions": [53, 54, 55]
},
{
"id": 6,
"title": "Longest Substring Without Repeating Characters",
"slug": "longest-substring-without-repeating-characters",
"difficulty": "Medium",
"category": "String",
"tags": ["String", "Sliding Window", "Hash Table"],
"problem": "Given a string s, find the length of the longest substring without repeating characters.",
"solution": "Use sliding window technique with a hash set to track characters in current window.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(min(m,n)) where m is size of charset",
"code": "def length_of_longest_substring(s):\n char_set = set()\n left = max_len = 0\n \n for right in range(len(s)):\n while s[right] in char_set:\n char_set.remove(s[left])\n left += 1\n char_set.add(s[right])\n max_len = max(max_len, right - left + 1)\n \n return max_len",
"explanation": "Use two pointers (left and right) to maintain a window of non-repeating characters. When we encounter a duplicate, we remove characters from the left until we no longer have that duplicate. Keep track of maximum window length seen.",
"relatedQuestions": [3, 159, 340]
},
{
"id": 7,
"title": "Search in Rotated Sorted Array",
"slug": "search-in-rotated-sorted-array",
"difficulty": "Medium",
"category": "Binary Search",
"tags": ["Array", "Binary Search"],
"problem": "Given a sorted array nums that was rotated at an unknown pivot index, and a target value, return the index of target if it exists in nums, or -1 if it does not exist.",
"solution": "Use modified binary search that handles rotation.",
"timeComplexity": "O(log n)",
"spaceComplexity": "O(1)",
"code": "def search(nums, target):\n if not nums:\n return -1\n \n left, right = 0, len(nums) - 1\n \n while left <= right:\n mid = (left + right) // 2\n \n if nums[mid] == target:\n return mid\n \n # Left half is sorted\n if nums[left] <= nums[mid]:\n if nums[left] <= target < nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n # Right half is sorted\n else:\n if nums[mid] < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n \n return -1",
"explanation": "Modified binary search that first identifies which half is sorted, then checks if target lies in sorted portion. If yes, search there; if no, search other half.",
"relatedQuestions": [33, 81, 153]
},
{
"id": 8,
"title": "3Sum",
"slug": "3sum",
"difficulty": "Medium",
"category": "Array",
"tags": ["Array", "Two Pointers"],
"problem": "Given an array nums of n integers, find all unique triplets in the array which gives the sum of zero.",
"solution": "Sort array and use two pointers technique for each fixed element.",
"timeComplexity": "O(n²)",
"spaceComplexity": "O(1)",
"code": "def threeSum(nums):\n nums.sort()\n result = []\n \n for i in range(len(nums)-2):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n \n left, right = i+1, len(nums)-1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n \n if total < 0:\n left += 1\n elif total > 0:\n right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]:\n left += 1\n while left < right and nums[right] == nums[right-1]:\n right -= 1\n left += 1\n right -= 1\n \n return result",
"explanation": "Sort array first. For each element, use two pointers to find pairs that sum to its negative. Skip duplicates to avoid duplicate triplets.",
"relatedQuestions": [15, 16, 18]
},
{
"id": 9,
"title": "Container With Most Water",
"slug": "container-with-most-water",
"difficulty": "Medium",
"category": "Array",
"tags": ["Array", "Two Pointers"],
"problem": "Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn at points. Find two lines, which, with the x-axis forms a container, such that the container contains the most water.",
"solution": "Use two pointers moving inward, always moving the shorter line.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def maxArea(height):\n max_area = 0\n left, right = 0, len(height) - 1\n \n while left < right:\n width = right - left\n area = width * min(height[left], height[right])\n max_area = max(max_area, area)\n \n if height[left] < height[right]:\n left += 1\n else:\n right -= 1\n \n return max_area",
"explanation": "Area is limited by shorter line. Moving the pointer of shorter line might increase area. Moving pointer of taller line will definitely decrease area.",
"relatedQuestions": [11, 42, 84]
},
{
"id": 10,
"title": "Sum of Two Integers",
"slug": "sum-of-two-integers",
"difficulty": "Medium",
"category": "Bit Manipulation",
"tags": ["Bit Manipulation"],
"problem": "Given two integers a and b, return the sum of the two integers without using the operators + and -.",
"solution": "Use bitwise XOR for addition without carry and AND with shift for carry.",
"timeComplexity": "O(1)",
"spaceComplexity": "O(1)",
"code": "def getSum(a, b):\n mask = 0xffffffff\n while b != 0:\n carry = (a & b) << 1\n a = (a ^ b) & mask\n b = carry & mask\n return a if a <= 0x7fffffff else ~(a ^ mask)",
"explanation": "XOR gives sum without carry, AND with shift gives carry. Repeat until no carry left.",
"relatedQuestions": [371, 67, 415]
},
{
"id": 11,
"title": "Number of 1 Bits",
"slug": "number-of-1-bits",
"difficulty": "Easy",
"category": "Bit Manipulation",
"tags": ["Bit Manipulation"],
"problem": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).",
"solution": "Use bit manipulation to count set bits.",
"timeComplexity": "O(1)",
"spaceComplexity": "O(1)",
"code": "def hammingWeight(n):\n count = 0\n while n:\n n &= (n - 1) # Clear least significant set bit\n count += 1\n return count",
"explanation": "n & (n-1) clears least significant set bit. Count how many times we can do this.",
"relatedQuestions": [191, 338, 461]
},
{
"id": 12,
"title": "Counting Bits",
"slug": "counting-bits",
"difficulty": "Easy",
"category": "Bit Manipulation",
"tags": ["Dynamic Programming", "Bit Manipulation"],
"problem": "Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.",
"solution": "Use dynamic programming with bit manipulation.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def countBits(n):\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n dp[i] = dp[i >> 1] + (i & 1)\n return dp",
"explanation": "Number of 1's in i equals number of 1's in i/2 plus 1 if i is odd.",
"relatedQuestions": [338, 191, 401]
},
{
"id": 13,
"title": "Missing Number",
"slug": "missing-number",
"difficulty": "Easy",
"category": "Bit Manipulation",
"tags": ["Bit Manipulation", "Array", "Math"],
"problem": "Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.",
"solution": "Use XOR to find missing number.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def missingNumber(nums):\n result = len(nums)\n for i in range(len(nums)):\n result ^= i ^ nums[i]\n return result",
"explanation": "XOR all numbers from 0 to n with array elements. Same numbers cancel out, leaving missing number.",
"relatedQuestions": [268, 287, 41]
},
{
"id": 14,
"title": "Reverse Bits",
"slug": "reverse-bits",
"difficulty": "Easy",
"category": "Bit Manipulation",
"tags": ["Bit Manipulation"],
"problem": "Reverse bits of a given 32 bits unsigned integer.",
"solution": "Use bit manipulation to swap bits from ends to middle.",
"timeComplexity": "O(1)",
"spaceComplexity": "O(1)",
"code": "def reverseBits(n):\n result = 0\n for i in range(32):\n result = (result << 1) | (n & 1)\n n >>= 1\n return result",
"explanation": "Process each bit from right to left, building reversed number from left to right.",
"relatedQuestions": [190, 7, 1009]
},
{
"id": 15,
"title": "Climbing Stairs",
"slug": "climbing-stairs",
"difficulty": "Easy",
"category": "Dynamic Programming",
"tags": ["Dynamic Programming"],
"problem": "You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. How many distinct ways can you climb to the top?",
"solution": "Use dynamic programming to build solution from smaller subproblems.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def climbStairs(n):\n if n <= 2: return n\n prev1, prev2 = 2, 1\n \n for i in range(3, n + 1):\n curr = prev1 + prev2\n prev2 = prev1\n prev1 = curr\n \n return prev1",
"explanation": "At each step i, ways[i] = ways[i-1] + ways[i-2]. We only need to store previous two numbers.",
"relatedQuestions": [70, 746, 1137]
},
{
"id": 16,
"title": "Reverse Linked List",
"slug": "reverse-linked-list",
"difficulty": "Easy",
"category": "Linked List",
"tags": ["Linked List"],
"problem": "Given the head of a singly linked list, reverse the list, and return the reversed list.",
"solution": "Use three pointers to reverse links one at a time.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def reverseList(head):\n prev = None\n curr = head\n \n while curr:\n next_temp = curr.next\n curr.next = prev\n prev = curr\n curr = next_temp\n \n return prev",
"explanation": "Keep track of previous, current, and next nodes. For each node, save its next pointer, point it to previous node, then advance all pointers.",
"relatedQuestions": [206, 92, 25]
},
{
"id": 17,
"title": "Linked List Cycle",
"slug": "linked-list-cycle",
"difficulty": "Easy",
"category": "Linked List",
"tags": ["Linked List", "Two Pointers"],
"problem": "Given head of a linked list, determine if the linked list has a cycle in it.",
"solution": "Use Floyd's cycle-finding algorithm (tortoise and hare).",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def hasCycle(head):\n if not head or not head.next:\n return False\n \n slow = head\n fast = head.next\n \n while slow != fast:\n if not fast or not fast.next:\n return False\n slow = slow.next\n fast = fast.next.next\n \n return True",
"explanation": "Use two pointers moving at different speeds. If they meet, there's a cycle. If fast pointer reaches end, no cycle.",
"relatedQuestions": [141, 142, 287]
},
{
"id": 18,
"title": "Merge Two Sorted Lists",
"slug": "merge-two-sorted-lists",
"difficulty": "Easy",
"category": "Linked List",
"tags": ["Linked List", "Two Pointers"],
"problem": "Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.",
"solution": "Compare current nodes of both lists and build result by linking smaller nodes first.",
"timeComplexity": "O(n + m)",
"spaceComplexity": "O(1)",
"code": "def mergeTwoLists(l1, l2):\n dummy = ListNode(0)\n current = dummy\n \n while l1 and l2:\n if l1.val <= l2.val:\n current.next = l1\n l1 = l1.next\n else:\n current.next = l2\n l2 = l2.next\n current = current.next\n \n current.next = l1 or l2\n return dummy.next",
"explanation": "Use a dummy head to simplify edge cases. Compare nodes from both lists and link the smaller one. After one list is exhausted, link the remaining nodes.",
"relatedQuestions": [21, 23, 148]
},
{
"id": 19,
"title": "Merge K Sorted Lists",
"slug": "merge-k-sorted-lists",
"difficulty": "Hard",
"category": "Linked List",
"tags": ["Linked List", "Divide and Conquer", "Heap"],
"problem": "Given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.",
"solution": "Use min heap to track smallest nodes from each list.",
"timeComplexity": "O(N log k) where N is total nodes and k is number of lists",
"spaceComplexity": "O(k)",
"code": "def mergeKLists(lists):\n # Custom comparison for ListNode\n ListNode.__lt__ = lambda self, other: self.val < other.val\n \n heap = []\n dummy = ListNode(0)\n curr = dummy\n \n # Add first node from each list to heap\n for head in lists:\n if head:\n heapq.heappush(heap, head)\n \n while heap:\n node = heapq.heappop(heap)\n curr.next = node\n curr = curr.next\n \n if node.next:\n heapq.heappush(heap, node.next)\n \n return dummy.next",
"explanation": "Maintain min heap with one node from each list. Always take smallest node and add next node from its list to heap.",
"relatedQuestions": [23, 21, 264]
},
{
"id": 20,
"title": "Remove Nth Node From End of List",
"slug": "remove-nth-node-from-end-of-list",
"difficulty": "Medium",
"category": "Linked List",
"tags": ["Linked List", "Two Pointers"],
"problem": "Given the head of a linked list, remove the nth node from the end of the list and return its head.",
"solution": "Use two pointers with n nodes gap between them.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def removeNthFromEnd(head, n):\n dummy = ListNode(0)\n dummy.next = head\n first = dummy\n second = dummy\n \n # Advance first pointer by n+1 steps\n for i in range(n + 1):\n first = first.next\n \n # Move both pointers until first reaches end\n while first:\n first = first.next\n second = second.next\n \n # Remove nth node from end\n second.next = second.next.next\n return dummy.next",
"explanation": "Use two pointers n+1 nodes apart. When first reaches end, second is at node before the one to remove.",
"relatedQuestions": [19, 61, 143]
},
{
"id": 21,
"title": "Reorder List",
"slug": "reorder-list",
"difficulty": "Medium",
"category": "Linked List",
"tags": ["Linked List", "Two Pointers"],
"problem": "Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…",
"solution": "Find middle, reverse second half, merge two halves.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def reorderList(head):\n if not head or not head.next:\n return\n \n # Find middle\n slow = fast = head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n \n # Reverse second half\n prev = None\n curr = slow.next\n slow.next = None\n while curr:\n next_temp = curr.next\n curr.next = prev\n prev = curr\n curr = next_temp\n \n # Merge two halves\n first = head\n second = prev\n while second:\n next_first = first.next\n next_second = second.next\n first.next = second\n second.next = next_first\n first = next_first\n second = next_second",
"explanation": "Split list in middle, reverse second half, then merge by alternating nodes from both halves.",
"relatedQuestions": [143, 234, 61]
},
{
"id": 22,
"title": "Binary Tree Level Order Traversal",
"slug": "binary-tree-level-order-traversal",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Tree", "BFS"],
"problem": "Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).",
"solution": "Use queue for BFS traversal, tracking levels.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def levelOrder(root):\n if not root:\n return []\n \n result = []\n queue = deque([root])\n \n while queue:\n level = []\n level_size = len(queue)\n \n for _ in range(level_size):\n node = queue.popleft()\n level.append(node.val)\n \n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n \n result.append(level)\n \n return result",
"explanation": "Use BFS with queue, processing nodes level by level. Keep track of level size to separate levels.",
"relatedQuestions": [102, 107, 103]
},
{
"id": 23,
"title": "Maximum Depth of Binary Tree",
"slug": "maximum-depth-of-binary-tree",
"difficulty": "Easy",
"category": "Tree",
"tags": ["Tree", "DFS"],
"problem": "Given the root of a binary tree, return its maximum depth (the number of nodes along the longest path from root to leaf).",
"solution": "Use recursive DFS to find maximum depth.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(h) where h is height",
"code": "def maxDepth(root):\n if not root:\n return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1",
"explanation": "Recursively find max depth of left and right subtrees, add 1 for current node.",
"relatedQuestions": [104, 111, 543]
},
{
"id": 24,
"title": "Same Tree",
"slug": "same-tree",
"difficulty": "Easy",
"category": "Tree",
"tags": ["Tree", "DFS"],
"problem": "Given the roots of two binary trees p and q, check if they are the same tree (structurally identical and nodes have same values).",
"solution": "Use recursive DFS to compare nodes.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(h) where h is height",
"code": "def isSameTree(p, q):\n if not p and not q:\n return True\n if not p or not q:\n return False\n return (p.val == q.val and\n isSameTree(p.left, q.left) and\n isSameTree(p.right, q.right))",
"explanation": "Recursively compare node values and structure. Trees are same if values match and subtrees are same.",
"relatedQuestions": [100, 101, 104]
},
{
"id": 25,
"title": "Invert Binary Tree",
"slug": "invert-binary-tree",
"difficulty": "Easy",
"category": "Tree",
"tags": ["Tree", "DFS"],
"problem": "Given the root of a binary tree, invert the tree, and return its root.",
"solution": "Recursively swap left and right children.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(h) where h is height",
"code": "def invertTree(root):\n if not root:\n return None\n \n # Swap children\n root.left, root.right = root.right, root.left\n \n # Recursively invert subtrees\n invertTree(root.left)\n invertTree(root.right)\n \n return root",
"explanation": "For each node, swap its left and right children, then recursively invert both subtrees.",
"relatedQuestions": [226, 101, 951]
},
{
"id": 26,
"title": "Subtree of Another Tree",
"slug": "subtree-of-another-tree",
"difficulty": "Easy",
"category": "Tree",
"tags": ["Tree", "DFS"],
"problem": "Given two binary trees root and subRoot, return true if there is a subtree of root with same structure and node values as subRoot.",
"solution": "For each node in main tree, check if it forms same tree as subRoot.",
"timeComplexity": "O(m*n)",
"spaceComplexity": "O(h)",
"code": "def isSubtree(root, subRoot):\n if not root:\n return False\n \n def isSameTree(p, q):\n if not p and not q:\n return True\n if not p or not q:\n return False\n return (p.val == q.val and\n isSameTree(p.left, q.left) and\n isSameTree(p.right, q.right))\n \n return (isSameTree(root, subRoot) or\n isSubtree(root.left, subRoot) or\n isSubtree(root.right, subRoot))",
"explanation": "For each node in main tree, check if subtree rooted at that node is identical to subRoot.",
"relatedQuestions": [572, 100, 101]
},
{
"id": 27,
"title": "Lowest Common Ancestor of BST",
"slug": "lowest-common-ancestor-of-a-binary-search-tree",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Tree", "BST"],
"problem": "Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.",
"solution": "Use BST property to navigate to LCA.",
"timeComplexity": "O(h)",
"spaceComplexity": "O(1)",
"code": "def lowestCommonAncestor(root, p, q):\n while root:\n if p.val < root.val and q.val < root.val:\n root = root.left\n elif p.val > root.val and q.val > root.val:\n root = root.right\n else:\n return root",
"explanation": "If both nodes are less than current, go left. If both greater, go right. Otherwise, current is LCA.",
"relatedQuestions": [235, 236, 1650]
},
{
"id": 28,
"title": "Validate Binary Search Tree",
"slug": "validate-binary-search-tree",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Tree", "BST", "DFS"],
"problem": "Given the root of a binary tree, determine if it is a valid binary search tree (BST).",
"solution": "Use DFS with range validation.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(h)",
"code": "def isValidBST(root):\n def validate(node, min_val, max_val):\n if not node:\n return True\n \n if node.val <= min_val or node.val >= max_val:\n return False\n \n return (validate(node.left, min_val, node.val) and\n validate(node.right, node.val, max_val))\n \n return validate(root, float('-inf'), float('inf'))",
"explanation": "Use range validation. Left subtree values must be less than node, right subtree greater.",
"relatedQuestions": [98, 99, 255]
},
{
"id": 29,
"title": "Kth Smallest Element in a BST",
"slug": "kth-smallest-element-in-a-bst",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Tree", "BST", "DFS"],
"problem": "Given the root of a binary search tree, and an integer k, return the kth smallest value in the BST.",
"solution": "Use inorder traversal to find kth element.",
"timeComplexity": "O(H + k)",
"spaceComplexity": "O(H)",
"code": "def kthSmallest(root, k):\n stack = []\n curr = root\n \n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n \n curr = stack.pop()\n k -= 1\n if k == 0:\n return curr.val\n \n curr = curr.right",
"explanation": "Use iterative inorder traversal, decrement k each time we process a node. When k=0, we've found kth element.",
"relatedQuestions": [230, 285, 783]
},
{
"id": 30,
"title": "Construct Binary Tree from Preorder and Inorder Traversal",
"slug": "construct-binary-tree-from-preorder-and-inorder-traversal",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Tree", "Array", "DFS"],
"problem": "Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.",
"solution": "Use preorder to get root, inorder to determine subtrees.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def buildTree(preorder, inorder):\n if not preorder or not inorder:\n return None\n \n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n \n root.left = buildTree(preorder[1:mid+1], inorder[:mid])\n root.right = buildTree(preorder[mid+1:], inorder[mid+1:])\n \n return root",
"explanation": "First element in preorder is root. Find it in inorder to determine left and right subtrees. Recursively build subtrees.",
"relatedQuestions": [105, 106, 889]
},
{
"id": 31,
"title": "Binary Tree Maximum Path Sum",
"slug": "binary-tree-maximum-path-sum",
"difficulty": "Hard",
"category": "Tree",
"tags": ["Tree", "DFS"],
"problem": "A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. Find the path with the maximum sum and return its sum.",
"solution": "Use DFS to compute max path sum through each node.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(h)",
"code": "def maxPathSum(root):\n def max_gain(node):\n nonlocal max_sum\n if not node:\n return 0\n\n left_gain = max(max_gain(node.left), 0)\n right_gain = max(max_gain(node.right), 0)\n \n current_path_sum = node.val + left_gain + right_gain\n max_sum = max(max_sum, current_path_sum)\n \n return node.val + max(left_gain, right_gain)\n \n max_sum = float('-inf')\n max_gain(root)\n return max_sum",
"explanation": "For each node, compute max path sum including it. Update global max sum if current path is larger.",
"relatedQuestions": [124, 543, 687]
},
{
"id": 32,
"title": "Serialize and Deserialize Binary Tree",
"slug": "serialize-and-deserialize-binary-tree",
"difficulty": "Hard",
"category": "Tree",
"tags": ["Tree", "Design"],
"problem": "Design an algorithm to serialize and deserialize a binary tree.",
"solution": "Use preorder traversal with null markers.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "class Codec:\n def serialize(self, root):\n if not root:\n return 'null'\n return f'{root.val},{self.serialize(root.left)},{self.serialize(root.right)}'\n \n def deserialize(self, data):\n def dfs():\n val = next(values)\n if val == 'null':\n return None\n node = TreeNode(int(val))\n node.left = dfs()\n node.right = dfs()\n return node\n \n values = iter(data.split(','))\n return dfs()",
"explanation": "Serialize using preorder traversal, marking null nodes. Deserialize by reconstructing tree from preorder sequence.",
"relatedQuestions": [297, 449, 428]
},
{
"id": 33,
"title": "Implement Trie (Prefix Tree)",
"slug": "implement-trie-prefix-tree",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Trie", "Design"],
"problem": "Implement a trie with insert, search, and startsWith methods.",
"solution": "Use TrieNode class with children dictionary and isEnd flag.",
"timeComplexity": "O(m) for all operations where m is word length",
"spaceComplexity": "O(ALPHABET_SIZE * m * n) for n words",
"code": "class Trie:\n def __init__(self):\n self.root = {}\n self.end = '#'\n \n def insert(self, word):\n node = self.root\n for char in word:\n node = node.setdefault(char, {})\n node[self.end] = self.end\n \n def search(self, word):\n node = self.root\n for char in word:\n if char not in node:\n return False\n node = node[char]\n return self.end in node\n \n def startsWith(self, prefix):\n node = self.root\n for char in prefix:\n if char not in node:\n return False\n node = node[char]\n return True",
"explanation": "Use nested dictionaries for trie structure. Mark end of words with special character.",
"relatedQuestions": [208, 211, 212]
},
{
"id": 34,
"title": "Design Add and Search Words Data Structure",
"slug": "design-add-and-search-words-data-structure",
"difficulty": "Medium",
"category": "Tree",
"tags": ["Trie", "Design", "DFS"],
"problem": "Design a data structure that supports adding new words and finding if a string matches any previously added string (. matches any letter).",
"solution": "Use Trie with DFS for wildcard search.",
"timeComplexity": "O(n) for add, O(26^m) for search with wildcards",
"spaceComplexity": "O(ALPHABET_SIZE * sum(word_lengths))",
"code": "class WordDictionary:\n def __init__(self):\n self.root = {}\n self.end = '#'\n \n def addWord(self, word):\n node = self.root\n for char in word:\n node = node.setdefault(char, {})\n node[self.end] = self.end\n \n def search(self, word):\n def dfs(node, i):\n if i == len(word):\n return self.end in node\n \n if word[i] == '.':\n return any(dfs(node[c], i+1) for c in node if c != self.end)\n \n if word[i] not in node:\n return False\n \n return dfs(node[word[i]], i+1)\n \n return dfs(self.root, 0)",
"explanation": "Similar to basic trie but with recursive DFS for wildcard matches.",
"relatedQuestions": [211, 208, 212]
},
{
"id": 35,
"title": "Word Search II",
"slug": "word-search-ii",
"difficulty": "Hard",
"category": "Tree",
"tags": ["Trie", "Backtracking", "DFS"],
"problem": "Given an m x n board of characters and a list of strings words, return all words on the board.",
"solution": "Build trie from words, use DFS with backtracking on board.",
"timeComplexity": "O(M * N * 4^L) where L is max word length",
"spaceComplexity": "O(sum(word_lengths))",
"code": "class Solution:\n def findWords(self, board, words):\n WORD_KEY = '$'\n trie = {}\n \n for word in words:\n node = trie\n for char in word:\n node = node.setdefault(char, {})\n node[WORD_KEY] = word\n \n rowNum = len(board)\n colNum = len(board[0])\n matchedWords = []\n \n def backtracking(row, col, parent):\n letter = board[row][col]\n currNode = parent[letter]\n \n word_match = currNode.pop(WORD_KEY, False)\n if word_match:\n matchedWords.append(word_match)\n \n board[row][col] = '#'\n \n for (rowOffset, colOffset) in [(-1, 0), (0, 1), (1, 0), (0, -1)]:\n newRow, newCol = row + rowOffset, col + colOffset\n if newRow < 0 or newRow >= rowNum or newCol < 0 or newCol >= colNum:\n continue\n if board[newRow][newCol] not in currNode:\n continue\n backtracking(newRow, newCol, currNode)\n \n board[row][col] = letter\n \n if not currNode:\n parent.pop(letter)\n \n for row in range(rowNum):\n for col in range(colNum):\n if board[row][col] in trie:\n backtracking(row, col, trie)\n \n return matchedWords",
"explanation": "Build trie from words, then use DFS with backtracking to find all words on board.",
"relatedQuestions": [212, 79, 425]
},
{
"id": 36,
"title": "Top K Frequent Elements",
"slug": "top-k-frequent-elements",
"difficulty": "Medium",
"category": "Heap",
"tags": ["Hash Table", "Heap"],
"problem": "Given an integer array nums and an integer k, return the k most frequent elements.",
"solution": "Use hash map for frequency count and heap for top k.",
"timeComplexity": "O(n log k)",
"spaceComplexity": "O(n)",
"code": "def topKFrequent(nums, k):\n count = Counter(nums)\n return heapq.nlargest(k, count.keys(), key=count.get)",
"explanation": "Count frequency of each number, then use heap to find k numbers with highest frequency.",
"relatedQuestions": [347, 692, 451]
},
{
"id": 37,
"title": "Find Median from Data Stream",
"slug": "find-median-from-data-stream",
"difficulty": "Hard",
"category": "Heap",
"tags": ["Heap", "Design"],
"problem": "Design a data structure that supports adding integers and finding the median.",
"solution": "Use two heaps: max heap for lower half, min heap for upper half.",
"timeComplexity": "O(log n) add, O(1) find",
"spaceComplexity": "O(n)",
"code": "class MedianFinder:\n def __init__(self):\n self.small = [] # max heap, -ve\n self.large = [] # min heap, +ve\n \n def addNum(self, num):\n if len(self.small) == len(self.large):\n heapq.heappush(self.large, -heapq.heappushpop(self.small, -num))\n else:\n heapq.heappush(self.small, -heapq.heappushpop(self.large, num))\n \n def findMedian(self):\n if len(self.small) == len(self.large):\n return float(self.large[0] - self.small[0]) / 2.0\n return float(self.large[0])",
"explanation": "Keep two heaps balanced. Lower half max heap and upper half min heap. Median is either average of tops or top of larger heap.",
"relatedQuestions": [295, 480, 502]
},
{
"id": 38,
"title": "Insert Interval",
"slug": "insert-interval",
"difficulty": "Medium",
"category": "Intervals",
"tags": ["Array", "Intervals"],
"problem": "Given a set of non-overlapping intervals and a new interval, insert the new interval and merge if necessary.",
"solution": "Process intervals in three parts: before, overlapping, and after new interval.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def insert(intervals, newInterval):\n result = []\n i = 0\n n = len(intervals)\n \n # Add intervals that come before newInterval\n while i < n and intervals[i][1] < newInterval[0]:\n result.append(intervals[i])\n i += 1\n \n # Merge overlapping intervals\n while i < n and intervals[i][0] <= newInterval[1]:\n newInterval[0] = min(newInterval[0], intervals[i][0])\n newInterval[1] = max(newInterval[1], intervals[i][1])\n i += 1\n \n result.append(newInterval)\n \n # Add remaining intervals\n while i < n:\n result.append(intervals[i])\n i += 1\n \n return result",
"explanation": "Process intervals in three parts: those that end before new interval, those that overlap with it, and those that start after it.",
"relatedQuestions": [57, 56, 252]
},
{
"id": 39,
"title": "Merge Intervals",
"slug": "merge-intervals",
"difficulty": "Medium",
"category": "Intervals",
"tags": ["Array", "Intervals"],
"problem": "Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals.",
"solution": "Sort by start time, then merge overlapping intervals.",
"timeComplexity": "O(n log n)",
"spaceComplexity": "O(n)",
"code": "def merge(intervals):\n intervals.sort(key=lambda x: x[0])\n merged = []\n \n for interval in intervals:\n if not merged or merged[-1][1] < interval[0]:\n merged.append(interval)\n else:\n merged[-1][1] = max(merged[-1][1], interval[1])\n \n return merged",
"explanation": "Sort intervals by start time. For each interval, either add it as new interval or merge with previous interval.",
"relatedQuestions": [56, 57, 252]
},
{
"id": 40,
"title": "Non-overlapping Intervals",
"slug": "non-overlapping-intervals",
"difficulty": "Medium",
"category": "Intervals",
"tags": ["Array", "Greedy"],
"problem": "Given an array of intervals, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.",
"solution": "Sort by end time, greedily keep intervals that don't overlap.",
"timeComplexity": "O(n log n)",
"spaceComplexity": "O(1)",
"code": "def eraseOverlapIntervals(intervals):\n if not intervals:\n return 0\n \n intervals.sort(key=lambda x: x[1])\n non_overlap_end = intervals[0][1]\n count = 1\n \n for i in range(1, len(intervals)):\n if intervals[i][0] >= non_overlap_end:\n non_overlap_end = intervals[i][1]\n count += 1\n \n return len(intervals) - count",
"explanation": "Sort by end time. Greedily keep interval with earliest end time and skip overlapping intervals.",
"relatedQuestions": [435, 452, 646]
},
{
"id": 41,
"title": "Meeting Rooms",
"slug": "meeting-rooms",
"difficulty": "Easy",
"category": "Intervals",
"tags": ["Array", "Sorting"],
"problem": "Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.",
"solution": "Sort by start time and check for overlaps.",
"timeComplexity": "O(n log n)",
"spaceComplexity": "O(1)",
"code": "def canAttendMeetings(intervals):\n intervals.sort(key=lambda x: x[0])\n \n for i in range(1, len(intervals)):\n if intervals[i][0] < intervals[i-1][1]:\n return False\n \n return True",
"explanation": "Sort meetings by start time. If any meeting starts before previous ends, return false.",
"relatedQuestions": [252, 253, 56]
},
{
"id": 42,
"title": "Meeting Rooms II",
"slug": "meeting-rooms-ii",
"difficulty": "Medium",
"category": "Intervals",
"tags": ["Heap", "Greedy"],
"problem": "Given an array of meeting time intervals, find the minimum number of conference rooms required.",
"solution": "Use min heap to track end times of ongoing meetings.",
"timeComplexity": "O(n log n)",
"spaceComplexity": "O(n)",
"code": "def minMeetingRooms(intervals):\n if not intervals:\n return 0\n \n # Sort by start time\n intervals.sort(key=lambda x: x[0])\n \n # Min heap to store end times\n rooms = [intervals[0][1]]\n \n for interval in intervals[1:]:\n if rooms[0] <= interval[0]:\n heapq.heapreplace(rooms, interval[1])\n else:\n heapq.heappush(rooms, interval[1])\n \n return len(rooms)",
"explanation": "Track ongoing meetings using min heap of end times. New meeting needs new room if it starts before earliest end time.",
"relatedQuestions": [253, 731, 732]
},
{
"id": 43,
"title": "Minimum Window Substring",
"slug": "minimum-window-substring",
"difficulty": "Hard",
"category": "String",
"tags": ["String", "Hash Table", "Sliding Window"],
"problem": "Given strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window.",
"solution": "Use sliding window with character frequency counting.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(k) where k is size of charset",
"code": "def minWindow(s, t):\n if not t or not s:\n return ''\n \n dict_t = Counter(t)\n required = len(dict_t)\n \n # Filter s to include only chars in t\n filtered_s = [(i, c) for i, c in enumerate(s) if c in dict_t]\n \n l = 0\n formed = 0\n window_counts = {}\n ans = float('inf'), None, None\n \n for r, char in filtered_s:\n window_counts[char] = window_counts.get(char, 0) + 1\n if window_counts[char] == dict_t[char]:\n formed += 1\n \n while l <= r and formed == required:\n char = filtered_s[l][1]\n start = filtered_s[l][0]\n end = r\n \n if end - start + 1 < ans[0]:\n ans = (end - start + 1, start, end)\n \n window_counts[char] -= 1\n if window_counts[char] < dict_t[char]:\n formed -= 1\n l += 1\n \n return '' if ans[0] == float('inf') else s[ans[1]:ans[2] + 1]",
"explanation": "Use sliding window to maintain valid substring. Track character frequencies to determine when window contains all required characters.",
"relatedQuestions": [76, 567, 438]
},
{
"id": 44,
"title": "Group Anagrams",
"slug": "group-anagrams",
"difficulty": "Medium",
"category": "String",
"tags": ["String", "Hash Table"],
"problem": "Given an array of strings strs, group the anagrams together.",
"solution": "Use sorted string as key to group anagrams.",
"timeComplexity": "O(n * k log k) where k is max string length",
"spaceComplexity": "O(n * k)",
"code": "def groupAnagrams(strs):\n groups = defaultdict(list)\n for s in strs:\n key = ''.join(sorted(s))\n groups[key].append(s)\n return list(groups.values())",
"explanation": "Sort each string to create key. Group strings with same sorted form together.",
"relatedQuestions": [49, 242, 438]
},
{
"id": 45,
"title": "Valid Anagram",
"slug": "valid-anagram",
"difficulty": "Easy",
"category": "String",
"tags": ["String", "Hash Table"],
"problem": "Given two strings s and t, return true if t is an anagram of s, and false otherwise.",
"solution": "Compare character frequencies.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def isAnagram(s, t):\n if len(s) != len(t):\n return False\n return Counter(s) == Counter(t)",
"explanation": "Two strings are anagrams if they have same character frequencies.",
"relatedQuestions": [242, 49, 438]
},
{
"id": 46,
"title": "Valid Parentheses",
"slug": "valid-parentheses",
"difficulty": "Easy",
"category": "String",
"tags": ["String", "Stack"],
"problem": "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.",
"solution": "Use stack to match brackets.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def isValid(s):\n stack = []\n pairs = {')': '(', '}': '{', ']': '['}\n \n for char in s:\n if char in '({[':\n stack.append(char)\n elif not stack or stack.pop() != pairs[char]:\n return False\n \n return len(stack) == 0",
"explanation": "Push opening brackets onto stack. For closing brackets, check if matching opening bracket is at top of stack.",
"relatedQuestions": [20, 22, 32]
},
{
"id": 47,
"title": "Valid Palindrome",
"slug": "valid-palindrome",
"difficulty": "Easy",
"category": "String",
"tags": ["String", "Two Pointers"],
"problem": "Given a string s, return true if it is a palindrome, considering only alphanumeric characters and ignoring cases.",
"solution": "Use two pointers from both ends.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def isPalindrome(s):\n l, r = 0, len(s) - 1\n \n while l < r:\n while l < r and not s[l].isalnum():\n l += 1\n while l < r and not s[r].isalnum():\n r -= 1\n \n if s[l].lower() != s[r].lower():\n return False\n \n l += 1\n r -= 1\n \n return True",
"explanation": "Compare characters from both ends, skipping non-alphanumeric characters.",
"relatedQuestions": [125, 680, 234]
},
{
"id": 48,
"title": "Longest Palindromic Substring",
"slug": "longest-palindromic-substring",
"difficulty": "Medium",
"category": "String",
"tags": ["String", "Dynamic Programming"],
"problem": "Given a string s, return the longest palindromic substring in s.",
"solution": "Expand around centers for each possible palindrome center.",
"timeComplexity": "O(n²)",
"spaceComplexity": "O(1)",
"code": "def longestPalindrome(s):\n def expand_around_center(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n l -= 1\n r += 1\n return s[l+1:r]\n \n result = ''\n for i in range(len(s)):\n # Odd length palindromes\n palindrome1 = expand_around_center(i, i)\n if len(palindrome1) > len(result):\n result = palindrome1\n \n # Even length palindromes\n palindrome2 = expand_around_center(i, i+1)\n if len(palindrome2) > len(result):\n result = palindrome2\n \n return result",
"explanation": "For each position, try to expand palindrome with that position as center. Consider both odd and even length palindromes.",
"relatedQuestions": [5, 516, 647]
},
{
"id": 49,
"title": "Palindromic Substrings",
"slug": "palindromic-substrings",
"difficulty": "Medium",
"category": "String",
"tags": ["String", "Dynamic Programming"],
"problem": "Given a string s, return the number of palindromic substrings in it.",
"solution": "Count palindromes by expanding around centers.",
"timeComplexity": "O(n²)",
"spaceComplexity": "O(1)",
"code": "def countSubstrings(s):\n def count_palindromes(l, r):\n count = 0\n while l >= 0 and r < len(s) and s[l] == s[r]:\n count += 1\n l -= 1\n r += 1\n return count\n \n result = 0\n for i in range(len(s)):\n # Odd length palindromes\n result += count_palindromes(i, i)\n # Even length palindromes\n result += count_palindromes(i, i+1)\n \n return result",
"explanation": "Similar to longest palindromic substring, but count all palindromes instead of finding longest.",
"relatedQuestions": [647, 5, 516]
},
{
"id": 50,
"title": "Encode and Decode Strings",
"slug": "encode-and-decode-strings",
"difficulty": "Medium",
"category": "String",
"tags": ["String", "Design"],
"problem": "Design an algorithm to encode a list of strings to a string and decode a single string to a list of strings.",
"solution": "Use length prefixing with delimiter.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "class Codec:\n def encode(self, strs):\n return ''.join(f'{len(s)}#{s}' for s in strs)\n \n def decode(self, s):\n result, i = [], 0\n while i < len(s):\n j = s.find('#', i)\n length = int(s[i:j])\n result.append(s[j+1:j+1+length])\n i = j + 1 + length\n return result",
"explanation": "Encode each string as 'length#string'. Decode by reading length, then extracting that many characters.",
"relatedQuestions": [271, 297, 449]
},
{
"id": 51,
"title": "Maximum Subarray Sum",
"slug": "maximum-subarray-sum",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming", "Divide and Conquer"],
"problem": "Given an integer array nums, find the contiguous subarray with the largest sum and return its sum.",
"solution": "Use Kadane's algorithm to track maximum sum ending at each position.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def maxSubArray(nums):\n max_sum = curr_sum = nums[0]\n \n for num in nums[1:]:\n curr_sum = max(num, curr_sum + num)\n max_sum = max(max_sum, curr_sum)\n \n return max_sum",
"explanation": "At each position, either start new subarray or extend current one. Keep track of global maximum.",
"relatedQuestions": [53, 152, 918]
},
{
"id": 52,
"title": "Maximum Product Subarray",
"slug": "maximum-product-subarray",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming"],
"problem": "Given an integer array nums, find a contiguous subarray that has the largest product, and return the product.",
"solution": "Track both maximum and minimum products due to negative numbers.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def maxProduct(nums):\n if not nums:\n return 0\n \n max_so_far = min_so_far = result = nums[0]\n \n for num in nums[1:]:\n candidates = (num, max_so_far * num, min_so_far * num)\n max_so_far = max(candidates)\n min_so_far = min(candidates)\n result = max(result, max_so_far)\n \n return result",
"explanation": "Keep track of both max and min products because negative numbers can make min product become max product.",
"relatedQuestions": [152, 53, 628]
},
{
"id": 53,
"title": "Longest Increasing Subsequence",
"slug": "longest-increasing-subsequence",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming", "Binary Search"],
"problem": "Given an integer array nums, return the length of the longest strictly increasing subsequence.",
"solution": "Use dynamic programming or binary search approach.",
"timeComplexity": "O(n log n)",
"spaceComplexity": "O(n)",
"code": "def lengthOfLIS(nums):\n if not nums:\n return 0\n \n # tails[i] = smallest value that ends an increasing subsequence of length i+1\n tails = [0] * len(nums)\n size = 0\n \n for num in nums:\n i, j = 0, size\n while i != j:\n m = (i + j) // 2\n if tails[m] < num:\n i = m + 1\n else:\n j = m\n tails[i] = num\n size = max(i + 1, size)\n \n return size",
"explanation": "Maintain array of smallest values that can end increasing subsequences of each length. Use binary search to update efficiently.",
"relatedQuestions": [300, 673, 674]
},
{
"id": 54,
"title": "Word Break",
"slug": "word-break",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["String", "Dynamic Programming", "Trie"],
"problem": "Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.",
"solution": "Use dynamic programming to build solution from smaller subproblems.",
"timeComplexity": "O(n²)",
"spaceComplexity": "O(n)",
"code": "def wordBreak(s, wordDict):\n dp = [False] * (len(s) + 1)\n dp[0] = True\n word_set = set(wordDict)\n \n for i in range(1, len(s) + 1):\n for j in range(i):\n if dp[j] and s[j:i] in word_set:\n dp[i] = True\n break\n \n return dp[len(s)]",
"explanation": "For each position, check if any prefix up to that position is in dictionary and remaining substring can be broken.",
"relatedQuestions": [139, 140, 472]
},
{
"id": 55,
"title": "Combination Sum",
"slug": "combination-sum",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Backtracking"],
"problem": "Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.",
"solution": "Use backtracking to try all possible combinations.",
"timeComplexity": "O(N^(T/M)) where T is target and M is minimum value",
"spaceComplexity": "O(T/M)",
"code": "def combinationSum(candidates, target):\n def backtrack(remain, combo, start):\n if remain == 0:\n result.append(list(combo))\n return\n \n for i in range(start, len(candidates)):\n if candidates[i] > remain:\n continue\n \n combo.append(candidates[i])\n backtrack(remain - candidates[i], combo, i)\n combo.pop()\n \n result = []\n candidates.sort()\n backtrack(target, [], 0)\n return result",
"explanation": "Use backtracking to try different combinations. Sort candidates first to optimize and avoid duplicates.",
"relatedQuestions": [39, 40, 216]
},
{
"id": 56,
"title": "House Robber",
"slug": "house-robber",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming"],
"problem": "Given an integer array nums representing the amount of money in each house, return the maximum amount you can rob without alerting the police (can't rob adjacent houses).",
"solution": "Use dynamic programming to consider rob or skip current house.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n \n prev2, prev1 = nums[0], max(nums[0], nums[1])\n \n for i in range(2, len(nums)):\n current = max(prev2 + nums[i], prev1)\n prev2, prev1 = prev1, current\n \n return prev1",
"explanation": "At each house, either rob it and add to money from two houses before, or skip it and keep money from previous house.",
"relatedQuestions": [198, 213, 337]
},
{
"id": 57,
"title": "House Robber II",
"slug": "house-robber-ii",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming"],
"problem": "Same as House Robber, but first and last houses are adjacent. Return maximum amount you can rob.",
"solution": "Run House Robber algorithm twice: once excluding first house, once excluding last house.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def rob(nums):\n def rob_line(nums):\n prev2 = prev1 = 0\n for num in nums:\n prev2, prev1 = prev1, max(prev2 + num, prev1)\n return prev1\n \n if len(nums) <= 3:\n return max(nums) if nums else 0\n \n return max(rob_line(nums[:-1]), rob_line(nums[1:]))",
"explanation": "Since first and last houses are adjacent, we can't rob both. Try two scenarios: rob houses 1 to n-1, or rob houses 2 to n.",
"relatedQuestions": [213, 198, 337]
},
{
"id": 58,
"title": "Decode Ways",
"slug": "decode-ways",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["String", "Dynamic Programming"],
"problem": "Given a string s containing only digits, return the number of ways to decode it. A message can be encoded into numbers using A->1, B->2, ..., Z->26.",
"solution": "Use dynamic programming to build solution from smaller subproblems.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def numDecodings(s):\n if not s or s[0] == '0':\n return 0\n \n prev2, prev1 = 1, 1\n \n for i in range(1, len(s)):\n current = 0\n if s[i] != '0':\n current += prev1\n if '10' <= s[i-1:i+1] <= '26':\n current += prev2\n prev2, prev1 = prev1, current\n \n return prev1",
"explanation": "At each digit, it can either be decoded alone (if not '0') or with previous digit (if forms valid number).",
"relatedQuestions": [91, 639, 2266]
},
{
"id": 59,
"title": "Unique Paths",
"slug": "unique-paths",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming", "Math"],
"problem": "A robot is located at (0,0) in an m x n grid. It can only move right or down. How many unique paths are there to reach (m-1,n-1)?",
"solution": "Use dynamic programming to build paths or use combination formula.",
"timeComplexity": "O(m*n)",
"spaceComplexity": "O(min(m,n))",
"code": "def uniquePaths(m, n):\n dp = [1] * n\n \n for i in range(1, m):\n for j in range(1, n):\n dp[j] += dp[j-1]\n \n return dp[n-1]",
"explanation": "Each cell's paths is sum of paths from above and left. Optimize space by using 1D array.",
"relatedQuestions": [62, 63, 64]
},
{
"id": 60,
"title": "Jump Game",
"slug": "jump-game",
"difficulty": "Medium",
"category": "Dynamic Programming",
"tags": ["Array", "Dynamic Programming", "Greedy"],
"problem": "Given an array of non-negative integers nums where each element represents maximum jump length at that position, return true if you can reach the last index.",
"solution": "Use greedy approach tracking furthest reachable position.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(1)",
"code": "def canJump(nums):\n max_reach = 0\n \n for i in range(len(nums)):\n if i > max_reach:\n return False\n max_reach = max(max_reach, i + nums[i])\n if max_reach >= len(nums) - 1:\n return True\n \n return True",
"explanation": "Keep track of furthest index we can reach. If current index is beyond that, we can't reach end.",
"relatedQuestions": [55, 45, 1306]
},
{
"id": 61,
"title": "Clone Graph",
"slug": "clone-graph",
"difficulty": "Medium",
"category": "Graph",
"tags": ["Graph", "DFS", "BFS"],
"problem": "Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.",
"solution": "Use DFS/BFS with hash map to track cloned nodes.",
"timeComplexity": "O(V + E)",
"spaceComplexity": "O(V)",
"code": "def cloneGraph(node):\n if not node:\n return None\n \n visited = {}\n \n def dfs(node):\n if node in visited:\n return visited[node]\n \n clone = Node(node.val)\n visited[node] = clone\n \n for neighbor in node.neighbors:\n clone.neighbors.append(dfs(neighbor))\n \n return clone\n \n return dfs(node)",
"explanation": "Use hash map to track original to clone mapping. DFS to create new nodes and connect them.",
"relatedQuestions": [133, 138, 332]
},
{
"id": 62,
"title": "Course Schedule",
"slug": "course-schedule",
"difficulty": "Medium",
"category": "Graph",
"tags": ["Graph", "DFS", "BFS", "Topological Sort"],
"problem": "Given numCourses and prerequisites where prerequisites[i] = [ai, bi] indicates bi must be taken before ai, return true if you can finish all courses.",
"solution": "Use topological sort to detect cycles.",
"timeComplexity": "O(V + E)",
"spaceComplexity": "O(V + E)",
"code": "def canFinish(numCourses, prerequisites):\n graph = [[] for _ in range(numCourses)]\n visited = [0] * numCourses\n \n # Build graph\n for x, y in prerequisites:\n graph[x].append(y)\n \n def dfs(course):\n if visited[course] == -1:\n return False\n if visited[course] == 1:\n return True\n \n visited[course] = -1\n for prereq in graph[course]:\n if not dfs(prereq):\n return False\n visited[course] = 1\n return True\n \n for course in range(numCourses):\n if not dfs(course):\n return False\n return True",
"explanation": "Build adjacency list and use DFS with visited states to detect cycles. If cycle exists, return false.",
"relatedQuestions": [207, 210, 630]
},
{
"id": 63,
"title": "Pacific Atlantic Water Flow",
"slug": "pacific-atlantic-water-flow",
"difficulty": "Medium",
"category": "Graph",
"tags": ["Array", "DFS", "BFS", "Matrix"],
"problem": "Given an m x n matrix of heights, return a list of all cells from which water can flow to both the Pacific and Atlantic oceans.",
"solution": "Use DFS from ocean boundaries inward.",
"timeComplexity": "O(m*n)",
"spaceComplexity": "O(m*n)",
"code": "def pacificAtlantic(heights):\n if not heights:\n return []\n \n m, n = len(heights), len(heights[0])\n pacific = set()\n atlantic = set()\n \n def dfs(i, j, visited):\n visited.add((i, j))\n for ni, nj in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]:\n if (0 <= ni < m and 0 <= nj < n and\n (ni, nj) not in visited and\n heights[ni][nj] >= heights[i][j]):\n dfs(ni, nj, visited)\n \n for i in range(m):\n dfs(i, 0, pacific)\n dfs(i, n-1, atlantic)\n for j in range(n):\n dfs(0, j, pacific)\n dfs(m-1, j, atlantic)\n \n return list(pacific & atlantic)",
"explanation": "Start from ocean edges and DFS inward, keeping track of cells reachable from each ocean.",
"relatedQuestions": [417, 695, 1162]
},
{
"id": 64,
"title": "Number of Islands",
"slug": "number-of-islands",
"difficulty": "Medium",
"category": "Graph",
"tags": ["Array", "DFS", "BFS", "Union Find", "Matrix"],
"problem": "Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return the number of islands.",
"solution": "Use DFS/BFS to explore and mark connected land cells.",
"timeComplexity": "O(m*n)",
"spaceComplexity": "O(m*n)",
"code": "def numIslands(grid):\n if not grid:\n return 0\n \n m, n = len(grid), len(grid[0])\n count = 0\n \n def dfs(i, j):\n if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != '1':\n return\n \n grid[i][j] = '#' # mark as visited\n dfs(i+1, j)\n dfs(i-1, j)\n dfs(i, j+1)\n dfs(i, j-1)\n \n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n dfs(i, j)\n count += 1\n \n return count",
"explanation": "For each unvisited land cell, use DFS to mark all connected land cells and increment island count.",
"relatedQuestions": [200, 695, 1254]
},
{
"id": 65,
"title": "Longest Consecutive Sequence",
"slug": "longest-consecutive-sequence",
"difficulty": "Medium",
"category": "Graph",
"tags": ["Array", "Union Find", "Hash Table"],
"problem": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.",
"solution": "Use hash set to check sequence boundaries.",
"timeComplexity": "O(n)",
"spaceComplexity": "O(n)",
"code": "def longestConsecutive(nums):\n num_set = set(nums)\n longest = 0\n \n for num in num_set:\n if num - 1 not in num_set:\n current = num\n streak = 1\n \n while current + 1 in num_set:\n current += 1\n streak += 1\n \n longest = max(longest, streak)\n \n return longest",
"explanation": "Convert array to set. For each number that could start a sequence, count length of consecutive sequence.",
"relatedQuestions": [128, 298, 674]
},
{
"id": 66,
"title": "Alien Dictionary",
"slug": "alien-dictionary",
"difficulty": "Hard",
"category": "Graph",
"tags": ["Graph", "Topological Sort", "String"],
"problem": "Given a list of words in an alien language, find the order of characters in the alphabet.",
"solution": "Build graph from adjacent words and use topological sort.",
"timeComplexity": "O(C) where C is total length of all words",
"spaceComplexity": "O(1) since only lowercase letters",
"code": "def alienOrder(words):\n # Build graph\n graph = {c: set() for word in words for c in word}\n \n for i in range(len(words) - 1):\n w1, w2 = words[i], words[i + 1]\n if len(w1) > len(w2) and w1[:len(w2)] == w2:\n return ''\n for c1, c2 in zip(w1, w2):\n if c1 != c2:\n graph[c1].add(c2)\n break\n \n # Topological sort\n visited = {}\n result = []\n \n def dfs(c):\n if c in visited:\n return visited[c]\n \n visited[c] = False\n for next_char in graph[c]:\n if not dfs(next_char):\n return False\n visited[c] = True\n result.append(c)\n return True\n \n for c in graph:\n if not dfs(c):\n return ''\n \n return ''.join(result[::-1])",
"explanation": "Compare adjacent words to build character order graph. Use topological sort to find order.",
"relatedQuestions": [269, 953, 1203]
},
{
"id": 67,
"title": "Graph Valid Tree",
"slug": "graph-valid-tree",
"difficulty": "Medium",
"category": "Graph",
"tags": ["Graph", "DFS", "Union Find"],
"problem": "Given n nodes labeled from 0 to n-1 and a list of undirected edges, check if these edges form a valid tree.",
"solution": "Use Union-Find or DFS to detect cycles and check connectivity.",