├── Add Digits ├── README.md └── add-digits.py ├── Add Two Numbers ├── README.md └── add-two-numbers.cpp ├── Allow One Function Call ├── README.md └── allow-one-function-call ├── Apply Transform Over Each Element in Array ├── README.md └── apply-transform-over-each-element-in-array.java ├── Array Partition ├── README.md └── array-partition.py ├── Array Prototype Last ├── README.md └── array-prototype-last ├── Array Reduce Transformation ├── README.md └── array-reduce-transformation ├── Array Wrapper ├── README.md └── array-wrapper ├── Array of Objects to Matrix ├── README.md └── array-of-objects-to-matrix.cpp ├── Best Time to Buy and Sell Stock ├── README.md └── best-time-to-buy-and-sell-stock.java ├── Bulb Switcher ├── README.md └── bulb-switcher.py ├── Cache With Time Limit ├── README.md └── cache-with-time-limit ├── Call Function with Custom Context ├── README.md └── call-function-with-custom-context ├── Can Place Flowers ├── README.md └── can-place-flowers.py ├── Check if Object Instance of Class ├── README.md └── check-if-object-instance-of-class ├── Check if One String Swap Can Make Strings Equal ├── README.md └── check-if-one-string-swap-can-make-strings-equal.py ├── Check if the Sentence Is Pangram ├── README.md └── check-if-the-sentence-is-pangram.cpp ├── Checking Existence of Edge Length Limited Paths ├── README.md └── checking-existence-of-edge-length-limited-paths.py ├── Chunk Array ├── README.md └── chunk-array ├── Clone Graph ├── README.md └── clone-graph.py ├── Construct Binary Tree from Inorder and Postorder Traversal ├── README.md └── construct-binary-tree-from-inorder-and-postorder-traversal.py ├── Construct Quad Tree ├── README.md └── construct-quad-tree.py ├── Contains Duplicate ├── README.md └── contains-duplicate.py ├── Convert Object to JSON String ├── README.md └── convert-object-to-json-string ├── Convert Sorted List to Binary Search Tree ├── README.md └── convert-sorted-list-to-binary-search-tree.py ├── Count Items Matching a Rule ├── README.md └── count-items-matching-a-rule.cpp ├── Count Numbers with Unique Digits ├── README.md └── count-numbers-with-unique-digits.cpp ├── Count Subarrays With Fixed Bounds ├── README.md └── count-subarrays-with-fixed-bounds.py ├── Count Unreachable Pairs of Nodes in an Undirected Graph ├── README.md └── count-unreachable-pairs-of-nodes-in-an-undirected-graph.py ├── Count Ways To Build Good Strings ├── README.md └── count-ways-to-build-good-strings.py ├── Counter II ├── README.md └── counter-ii.java ├── Counter ├── README.md └── counter.java ├── Create Hello World Function ├── README.md └── create-hello-world-function.java ├── Curry ├── README.md └── curry ├── Debounce ├── README.md └── debounce ├── Design Add and Search Words Data Structure ├── README.md └── design-add-and-search-words-data-structure.py ├── Design Parking System ├── README.md └── design-parking-system.py ├── Differences Between Two Objects ├── README.md └── differences-between-two-objects ├── Divide Two Integers ├── README.md └── divide-two-integers.c ├── Edit Distance ├── README.md └── edit-distance.py ├── Evaluate Division ├── README.md └── evaluate-division.py ├── Event Emitter ├── README.md └── event-emitter ├── Filter Elements from Array ├── README.md └── filter-elements-from-array ├── Find Nearest Point That Has the Same X or Y Coordinate ├── README.md └── find-nearest-point-that-has-the-same-x-or-y-coordinate.py ├── Find the Difference of Two Arrays ├── README.md └── find-the-difference-of-two-arrays.py ├── Find the Difference ├── README.md └── find-the-difference.py ├── Find the Index of the First Occurrence in a String ├── README.md └── find-the-index-of-the-first-occurrence-in-a-string.py ├── Find the Longest Valid Obstacle Course at Each Position ├── README.md └── find-the-longest-valid-obstacle-course-at-each-position.py ├── Fizz Buzz ├── README.md └── fizz-buzz.c ├── Flatten Binary Tree to Linked List ├── README.md └── flatten-binary-tree-to-linked-list.py ├── Flatten Deeply Nested Array ├── README.md └── flatten-deeply-nested-array ├── Function Composition ├── README.md └── function-composition ├── Generate Fibonacci Sequence ├── README.md └── generate-fibonacci-sequence ├── Goal Parser Interpretation ├── README.md └── goal-parser-interpretation.py ├── Group By ├── README.md └── group-by ├── Happy Number ├── README.md └── happy-number.py ├── Implement Queue using Stacks ├── README.md └── implement-queue-using-stacks.py ├── Implement Trie (Prefix Tree) ├── README.md └── implement-trie-(prefix-tree).py ├── JSON Deep Equal ├── README.md └── json-deep-equal ├── Largest Color Value in a Directed Graph ├── README.md └── largest-color-value-in-a-directed-graph.py ├── Linked List Cycle II ├── README.md └── linked-list-cycle-ii.py ├── Linked List Random Node ├── README.md └── linked-list-random-node.py ├── Longest Cycle in a Graph ├── README.md └── longest-cycle-in-a-graph.py ├── Longest Palindromic Subsequence ├── README.md └── longest-palindromic-subsequence.py ├── Longest Palindromic Substring ├── README.md └── longest-palindromic-substring.py ├── Maximum Depth of Binary Tree ├── README.md └── maximum-depth-of-binary-tree.py ├── Maximum Depth of N-ary Tree ├── README.md └── maximum-depth-of-n-ary-tree.py ├── Maximum Subsequence Score ├── README.md └── maximum-subsequence-score.cpp ├── Maximum Value of K Coins From Piles ├── README.md └── maximum-value-of-k-coins-from-piles.py ├── Median of Two Sorted Arrays ├── README.md └── median-of-two-sorted-arrays.py ├── Memoize ├── README.md └── memoize ├── Merge Strings Alternately ├── README.md └── merge-strings-alternately.py ├── Merge k Sorted Lists ├── README.md └── merge-k-sorted-lists.py ├── Minimize Maximum of Array ├── README.md └── minimize-maximum-of-array.py ├── Minimum Number of Removals to Make Mountain Array ├── README.md └── minimum-number-of-removals-to-make-mountain-array.py ├── Minimum Path Sum ├── README.md └── minimum-path-sum.py ├── Minimum Score of a Path Between Two Cities ├── README.md └── minimum-score-of-a-path-between-two-cities.py ├── Minimum Time to Complete Trips ├── README.md └── minimum-time-to-complete-trips.py ├── Move Zeroes ├── README.md └── move-zeroes.py ├── N-ary Tree Preorder Traversal ├── README.md └── n-ary-tree-preorder-traversal.py ├── Nested Array Generator ├── README.md └── nested-array-generator ├── Next Greater Element I ├── README.md └── next-greater-element-i.java ├── Number of 1 Bits ├── README.md └── number-of-1-bits.py ├── Number of Ways to Form a Target String Given a Dictionary ├── README.md └── number-of-ways-to-form-a-target-string-given-a-dictionary.py ├── Number of Zero-Filled Subarrays ├── README.md └── number-of-zero-filled-subarrays.py ├── Optimal Partition of String ├── README.md └── optimal-partition-of-string.py ├── Palindrome Linked List ├── README.md └── palindrome-linked-list.c ├── Problems └── Readme.md ├── Promise Pool ├── README.md └── promise-pool ├── Promise Time Limit ├── README.md └── promise-time-limit ├── Range Sum Query - Immutable ├── README.md └── range-sum-query---immutable.py ├── Ransom Note ├── README.md └── ransom-note.c ├── Readme.md ├── Remove Max Number of Edges to Keep Graph Fully Traversable ├── README.md └── remove-max-number-of-edges-to-keep-graph-fully-traversable.py ├── Removing Stars From a String ├── README.md └── removing-stars-from-a-string.py ├── Repeated Substring Pattern ├── README.md └── repeated-substring-pattern.java ├── Reshape the Matrix ├── README.md └── reshape-the-matrix.py ├── Reverse Integer ├── README.md └── reverse-integer.py ├── Richest Customer Wealth ├── README.md └── richest-customer-wealth.py ├── Roman to Integer ├── README.md └── roman-to-integer.c ├── Scramble String ├── README.md └── scramble-string.py ├── Sign of the Product of an Array ├── README.md └── sign-of-the-product-of-an-array.cpp ├── Simplify Path ├── README.md └── simplify-path.py ├── Sleep ├── README.md └── sleep.java ├── Smallest Number in Infinite Set ├── README.md └── smallest-number-in-infinite-set.py ├── Spiral Matrix II ├── README.md └── spiral-matrix-ii.py ├── Spiral Matrix ├── README.md └── spiral-matrix.py ├── String Compression ├── README.md └── string-compression.py ├── Student Attendance Record I ├── README.md └── student-attendance-record-i.py ├── Successful Pairs of Spells and Potions ├── README.md └── successful-pairs-of-spells-and-potions.py ├── Sudoku Solver ├── README.md └── sudoku-solver.py ├── Sum Root to Leaf Numbers ├── README.md └── sum-root-to-leaf-numbers.py ├── Sum of All Odd Length Subarrays ├── README.md └── sum-of-all-odd-length-subarrays.py ├── Sum of Left Leaves ├── README.md └── sum-of-left-leaves.py ├── Swap Nodes in Pairs ├── README.md └── swap-nodes-in-pairs.py ├── Symmetric Tree ├── README.md └── symmetric-tree.py ├── Throttle ├── README.md └── throttle ├── Top K Frequent Elements ├── README.md └── top-k-frequent-elements.py ├── Two Sum ├── README.md └── two-sum.cpp ├── Valid Anagram ├── README.md └── valid-anagram.py └── Valid Parentheses ├── README.md └── valid-parentheses.cpp /Add Digits/README.md: -------------------------------------------------------------------------------- 1 | # [Add Digits](https://leetcode.com/problems/add-digits/) 2 |

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: num = 38
 8 | Output: 2
 9 | Explanation: The process is
10 | 38 --> 3 + 8 --> 11
11 | 11 --> 1 + 1 --> 2 
12 | Since 2 has only one digit, return it.
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: num = 0
18 | Output: 0
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 | 27 | 28 |

 

29 |

Follow up: Could you do it without any loop/recursion in O(1) runtime?

30 | -------------------------------------------------------------------------------- /Add Digits/add-digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | if num == 0 : return 0 4 | if num % 9 == 0 : return 9 5 | else : return (num % 9) -------------------------------------------------------------------------------- /Add Two Numbers/README.md: -------------------------------------------------------------------------------- 1 | # [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) 2 |

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

3 | 4 |

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: l1 = [2,4,3], l2 = [5,6,4]
10 | Output: [7,0,8]
11 | Explanation: 342 + 465 = 807.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: l1 = [0], l2 = [0]
17 | Output: [0]
18 | 
19 | 20 |

Example 3:

21 | 22 |
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
23 | Output: [8,9,9,9,0,0,0,1]
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 | 34 | -------------------------------------------------------------------------------- /Add Two Numbers/add-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | 13 | public: 14 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 15 | int x=0, y=0, carry=0, sum=0; 16 | ListNode *h=NULL, **t=&h; 17 | 18 | while (l1!=NULL || l2!=NULL){ 19 | x = getValueAndMoveNext(l1); 20 | y = getValueAndMoveNext(l2); 21 | 22 | sum = carry + x + y; 23 | 24 | ListNode *node = new ListNode(sum%10); 25 | *t = node; 26 | t = (&node->next); 27 | 28 | carry = sum/10; 29 | } 30 | 31 | if (carry > 0) { 32 | ListNode *node = new ListNode(carry%10); 33 | *t = node; 34 | } 35 | 36 | return h; 37 | } 38 | private: 39 | int getValueAndMoveNext(ListNode* &l){ 40 | int x = 0; 41 | if (l != NULL){ 42 | x = l->val; 43 | l = l->next; 44 | } 45 | return x; 46 | } 47 | }; -------------------------------------------------------------------------------- /Allow One Function Call/README.md: -------------------------------------------------------------------------------- 1 | # [Allow One Function Call](https://leetcode.com/problems/allow-one-function-call/) 2 |

Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.

3 | 4 | 8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
13 | Output: [{"calls":1,"value":6}]
14 | Explanation:
15 | const onceFn = once(fn);
16 | onceFn(1, 2, 3); // 6
17 | onceFn(2, 3, 6); // undefined, fn was not called
18 | 
19 | 20 |

Example 2:

21 | 22 |
Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
23 | Output: [{"calls":1,"value":140}]
24 | Explanation:
25 | const onceFn = once(fn);
26 | onceFn(5, 7, 4); // 140
27 | onceFn(2, 3, 6); // undefined, fn was not called
28 | onceFn(4, 6, 8); // undefined, fn was not called
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 | 39 | -------------------------------------------------------------------------------- /Allow One Function Call/allow-one-function-call: -------------------------------------------------------------------------------- 1 | function once any>(fn: T): 2 | ((...args: Parameters) => ReturnType | undefined) { 3 | let isCalled = false; 4 | return function (...args) { 5 | if (isCalled) { 6 | return undefined; 7 | } else { 8 | isCalled = true; 9 | return fn(...args); 10 | } 11 | }; 12 | } -------------------------------------------------------------------------------- /Apply Transform Over Each Element in Array/README.md: -------------------------------------------------------------------------------- 1 | # [Apply Transform Over Each Element in Array](https://leetcode.com/problems/apply-transform-over-each-element-in-array/) 2 |

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

3 | 4 |

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

5 | 6 |

Please solve it without the built-in Array.map method.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
12 | Output: [2,3,4]
13 | Explanation:
14 | const newArray = map(arr, plusone); // [2,3,4]
15 | The function increases each value in the array by one. 
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
21 | Output: [1,3,5]
22 | Explanation: The function increases each value by the index it resides in.
23 | 
24 | 25 |

Example 3:

26 | 27 |
Input: arr = [10,20,30], fn = function constant() { return 42; }
28 | Output: [42,42,42]
29 | Explanation: The function always returns 42.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 0 <= arr.length <= 1000
  • 37 |
  • -109 <= arr[i] <= 109
  • 38 |
  • fn returns a number
  • 39 |
40 | -------------------------------------------------------------------------------- /Apply Transform Over Each Element in Array/apply-transform-over-each-element-in-array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {Function} fn 4 | * @return {number[]} 5 | */ 6 | var map = function(arr, fn) { 7 | for(let i=0;iGiven an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: nums = [1,4,3,2]
 8 | Output: 4
 9 | Explanation: All possible pairings (ignoring the ordering of elements) are:
10 | 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
11 | 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
12 | 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
13 | So the maximum possible sum is 4.
14 | 15 |

Example 2:

16 | 17 |
Input: nums = [6,2,6,5,1,2]
18 | Output: 9
19 | Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= n <= 104
  • 27 |
  • nums.length == 2 * n
  • 28 |
  • -104 <= nums[i] <= 104
  • 29 |
30 | -------------------------------------------------------------------------------- /Array Partition/array-partition.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayPairSum(self, nums: List[int]) -> int: 3 | nums.sort() # sort the array 4 | result = 0 5 | for i in range(0, len(nums), 2): 6 | result += min(nums[i], nums[i+1]) # add the minimum of each pair to the result 7 | return result -------------------------------------------------------------------------------- /Array Prototype Last/README.md: -------------------------------------------------------------------------------- 1 | # [Array Prototype Last](https://leetcode.com/problems/array-prototype-last/) 2 | Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1. 3 |

 

4 |

Example 1:

5 | 6 |
Input: nums = [1,2,3]
 7 | Output: 3
 8 | Explanation: Calling nums.last() should return the last element: 3.
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: nums = []
14 | Output: -1
15 | Explanation: Because there are no elements, return -1.
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 0 <= arr.length <= 1000
  • 23 |
  • 0 <= arr[i] <= 1000
  • 24 |
25 | -------------------------------------------------------------------------------- /Array Prototype Last/array-prototype-last: -------------------------------------------------------------------------------- 1 | declare global { 2 | interface Array { 3 | last(): T | -1; 4 | } 5 | } 6 | 7 | Array.prototype.last = function() { 8 | return !this.length ? -1 : this[this.length-1]; 9 | }; 10 | 11 | 12 | export {}; -------------------------------------------------------------------------------- /Array Reduce Transformation/array-reduce-transformation: -------------------------------------------------------------------------------- 1 | type Fn = (accum: number, curr: number) => number; 2 | 3 | function reduce(nums: number[], fn: Fn, init: number): number { 4 | let result = init; 5 | for (const num of nums) { 6 | result = fn(result, num); 7 | } 8 | return result; 9 | } -------------------------------------------------------------------------------- /Array Wrapper/README.md: -------------------------------------------------------------------------------- 1 | # [Array Wrapper](https://leetcode.com/problems/array-wrapper/) 2 |

Create a class ArrayWrapper that accepts an array of integers in it's constructor. This class should have two features:

3 | 4 |
    5 |
  • When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
  • 6 |
  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].
  • 7 |
8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: nums = [[1,2],[3,4]], operation = "Add"
13 | Output: 10
14 | Explanation:
15 | const obj1 = new ArrayWrapper([1,2]);
16 | const obj2 = new ArrayWrapper([3,4]);
17 | obj1 + obj2; // 10
18 | 
19 | 20 |

Example 2:

21 | 22 |
Input: nums = [[23,98,42,70]], operation = "String"
23 | Output: "[23,98,42,70]"
24 | Explanation:
25 | const obj = new ArrayWrapper([23,98,42,70]);
26 | String(obj); // "[23,98,42,70]"
27 | 
28 | 29 |

Example 3:

30 | 31 |
Input: nums = [[],[]], operation = "Add"
32 | Output: 0
33 | Explanation:
34 | const obj1 = new ArrayWrapper([]);
35 | const obj2 = new ArrayWrapper([]);
36 | obj1 + obj2; // 0
37 | 
38 | 39 |

 

40 |

Constraints:

41 | 42 |
    43 |
  • 0 <= nums.length <= 1000
  • 44 |
  • 0 <= nums[i] <= 1000
  • 45 |
  • Note: nums is the array passed to the constructor
  • 46 |
47 | -------------------------------------------------------------------------------- /Array Wrapper/array-wrapper: -------------------------------------------------------------------------------- 1 | class ArrayWrapper { 2 | private nums: number[]; 3 | 4 | constructor(nums: number[]) { 5 | this.nums = nums; 6 | } 7 | 8 | valueOf(): number { 9 | return this.nums.reduce((acc, curr) => acc + curr, 0); 10 | } 11 | 12 | toString(): string { 13 | return JSON.stringify(this.nums); 14 | } 15 | } 16 | 17 | const obj1 = new ArrayWrapper([1, 2]); 18 | const obj2 = new ArrayWrapper([3, 4]); -------------------------------------------------------------------------------- /Array of Objects to Matrix/README.md: -------------------------------------------------------------------------------- 1 | # [Array of Objects to Matrix](https://leetcode.com/problems/array-of-objects-to-matrix/) 2 |

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

3 | 4 |

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

5 | 6 |

You can return the answer in any order.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: nums = [2,7,11,15], target = 9
12 | Output: [0,1]
13 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: nums = [3,2,4], target = 6
19 | Output: [1,2]
20 | 
21 | 22 |

Example 3:

23 | 24 |
Input: nums = [3,3], target = 6
25 | Output: [0,1]
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 2 <= nums.length <= 104
  • 33 |
  • -109 <= nums[i] <= 109
  • 34 |
  • -109 <= target <= 109
  • 35 |
  • Only one valid answer exists.
  • 36 |
37 | 38 |

 

39 | Follow-up: Can you come up with an algorithm that is less than O(n2time complexity? -------------------------------------------------------------------------------- /Array of Objects to Matrix/array-of-objects-to-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | for (int i = 0; i < nums.size(); i++) 5 | { 6 | for (int j = i+1; j < nums.size(); j++) 7 | { 8 | if ((nums[i] + nums[j])==target) 9 | { 10 | return {i, j}; 11 | } 12 | } 13 | } 14 | return {}; 15 | } 16 | }; -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock/README.md: -------------------------------------------------------------------------------- 1 | # [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) 2 |

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

3 | 4 |

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

5 | 6 |

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

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: prices = [7,1,5,3,6,4]
12 | Output: 5
13 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
14 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: prices = [7,6,4,3,1]
20 | Output: 0
21 | Explanation: In this case, no transactions are done and the max profit = 0.
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • 1 <= prices.length <= 105
  • 29 |
  • 0 <= prices[i] <= 104
  • 30 |
31 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock/best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | function maxProfit(prices) { 2 | let minPrice = prices[0]; 3 | let maxProfit = 0; 4 | 5 | for (let i = 1; i < prices.length; i++) { 6 | if (prices[i] < minPrice) { 7 | minPrice = prices[i]; 8 | } else if (prices[i] - minPrice > maxProfit) { 9 | maxProfit = prices[i] - minPrice; 10 | } 11 | } 12 | 13 | return maxProfit; 14 | } 15 | 16 | // Example usage 17 | const prices = [7, 1, 5, 3, 6, 4]; 18 | console.log(maxProfit(prices)); // expected output: 5 -------------------------------------------------------------------------------- /Bulb Switcher/README.md: -------------------------------------------------------------------------------- 1 | # [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) 2 |

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.

3 | 4 |

On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.

5 | 6 |

Return the number of bulbs that are on after n rounds.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: n = 3
12 | Output: 1
13 | Explanation: At first, the three bulbs are [off, off, off].
14 | After the first round, the three bulbs are [on, on, on].
15 | After the second round, the three bulbs are [on, off, on].
16 | After the third round, the three bulbs are [on, off, off]. 
17 | So you should return 1 because there is only one bulb is on.
18 | 19 |

Example 2:

20 | 21 |
Input: n = 0
22 | Output: 0
23 | 
24 | 25 |

Example 3:

26 | 27 |
Input: n = 1
28 | Output: 1
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 0 <= n <= 109
  • 36 |
37 | -------------------------------------------------------------------------------- /Bulb Switcher/bulb-switcher.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bulbSwitch(self, n: int) -> int: 3 | 4 | return isqrt(n) -------------------------------------------------------------------------------- /Cache With Time Limit/cache-with-time-limit: -------------------------------------------------------------------------------- 1 | class TimeLimitedCache { 2 | // internal caches 3 | cache: Map; 4 | timeouts: Map>; 5 | 6 | 7 | constructor() { 8 | this.cache = new Map(); 9 | this.timeouts = new Map(); 10 | } 11 | 12 | set(key: number, value: number, duration: number): boolean { 13 | const result = this.cache.has(key) 14 | this.cache.set(key, value) 15 | clearTimeout(this.timeouts.get(key)) // don't need to check if it exists ourselves 16 | // set a timeout to clear the value 17 | this.timeouts.set(key, setTimeout(() => this.cache.delete(key), duration)) 18 | return result 19 | } 20 | 21 | get(key: number): number { 22 | return this.cache.get(key) ?? -1 23 | } 24 | 25 | count(): number { 26 | return [...this.cache].length 27 | } 28 | } -------------------------------------------------------------------------------- /Call Function with Custom Context/call-function-with-custom-context: -------------------------------------------------------------------------------- 1 | declare global { 2 | interface Function { 3 | callPolyfill(context: Record, ...args: any[]): any; 4 | } 5 | } 6 | 7 | Function.prototype.callPolyfill = function(context, ...args): any { 8 | let fn = this.bind(context); 9 | return fn(...args); 10 | } -------------------------------------------------------------------------------- /Can Place Flowers/README.md: -------------------------------------------------------------------------------- 1 | # [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) 2 |

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

3 | 4 |

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

5 | 6 |

 

7 |

Example 1:

8 |
Input: flowerbed = [1,0,0,0,1], n = 1
 9 | Output: true
10 | 

Example 2:

11 |
Input: flowerbed = [1,0,0,0,1], n = 2
12 | Output: false
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= flowerbed.length <= 2 * 104
  • 19 |
  • flowerbed[i] is 0 or 1.
  • 20 |
  • There are no two adjacent flowers in flowerbed.
  • 21 |
  • 0 <= n <= flowerbed.length
  • 22 |
23 | -------------------------------------------------------------------------------- /Can Place Flowers/can-place-flowers.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: 4 | count = 0 5 | i = 0 6 | while i < len(flowerbed): 7 | if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and (i == len(flowerbed)-1 or flowerbed[i+1] == 0): 8 | flowerbed[i] = 1 9 | count += 1 10 | i += 1 11 | return count >= n -------------------------------------------------------------------------------- /Check if Object Instance of Class/README.md: -------------------------------------------------------------------------------- 1 | # [Check if Object Instance of Class](https://leetcode.com/problems/check-if-object-instance-of-class/) 2 |

Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.

3 | 4 |

There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: func = () => checkIfInstanceOf(new Date(), Date)
10 | Output: true
11 | Explanation: The object returned by the Date constructor is, by definition, an instance of Date.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
17 | Output: true
18 | Explanation:
19 | class Animal {};
20 | class Dog extends Animal {};
21 | checkIfInstanceOf(new Dog(), Animal); // true
22 | 
23 | Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.
24 | 25 |

Example 3:

26 | 27 |
Input: func = () => checkIfInstanceOf(Date, Date)
28 | Output: false
29 | Explanation: A date constructor cannot logically be an instance of itself.
30 | 
31 | 32 |

Example 4:

33 | 34 |
Input: func = () => checkIfInstanceOf(5, Number)
35 | Output: true
36 | Explanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()".
37 | 
38 | -------------------------------------------------------------------------------- /Check if Object Instance of Class/check-if-object-instance-of-class: -------------------------------------------------------------------------------- 1 | function checkIfInstanceOf(obj: any, classFunction: any): boolean { 2 | while (obj != null) { 3 | if (obj.constructor === classFunction) { 4 | return true; 5 | } 6 | 7 | obj = Object.getPrototypeOf(obj) 8 | } 9 | 10 | return false 11 | }; -------------------------------------------------------------------------------- /Check if One String Swap Can Make Strings Equal/README.md: -------------------------------------------------------------------------------- 1 | # [Check if One String Swap Can Make Strings Equal](https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/) 2 |

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.

3 | 4 |

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: s1 = "bank", s2 = "kanb"
10 | Output: true
11 | Explanation: For example, swap the first character with the last character of s2 to make "bank".
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: s1 = "attack", s2 = "defend"
17 | Output: false
18 | Explanation: It is impossible to make them equal with one string swap.
19 | 
20 | 21 |

Example 3:

22 | 23 |
Input: s1 = "kelb", s2 = "kelb"
24 | Output: true
25 | Explanation: The two strings are already equal, so no string swap operation is required.
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 1 <= s1.length, s2.length <= 100
  • 33 |
  • s1.length == s2.length
  • 34 |
  • s1 and s2 consist of only lowercase English letters.
  • 35 |
36 | -------------------------------------------------------------------------------- /Check if One String Swap Can Make Strings Equal/check-if-one-string-swap-can-make-strings-equal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def areAlmostEqual(self, s1: str, s2: str) -> bool: 3 | if s1 == s2: 4 | return True 5 | 6 | # find the first index where s1 and s2 differ 7 | index_diff = -1 8 | for i in range(len(s1)): 9 | if s1[i] != s2[i]: 10 | index_diff = i 11 | break 12 | 13 | # if there is no difference, or more than one difference, we can't make them equal with a single swap 14 | if index_diff == -1 or sum(1 for i in range(len(s1)) if s1[i] != s2[i]) > 2: 15 | return False 16 | 17 | # check if swapping the characters at index_diff in s1 would make s1 equal to s2 18 | index_swap = -1 19 | for i in range(index_diff+1, len(s1)): 20 | if s1[i] == s2[index_diff] and s2[i] == s1[index_diff]: 21 | index_swap = i 22 | break 23 | 24 | return index_swap != -1 25 | -------------------------------------------------------------------------------- /Check if the Sentence Is Pangram/README.md: -------------------------------------------------------------------------------- 1 | # [Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram/) 2 |

A pangram is a sentence where every letter of the English alphabet appears at least once.

3 | 4 |

Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
10 | Output: true
11 | Explanation: sentence contains at least one of every letter of the English alphabet.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: sentence = "leetcode"
17 | Output: false
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= sentence.length <= 1000
  • 25 |
  • sentence consists of lowercase English letters.
  • 26 |
27 | -------------------------------------------------------------------------------- /Check if the Sentence Is Pangram/check-if-the-sentence-is-pangram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkIfPangram(string sentence) { 4 | if(sentence.size()<26){ return false;} 5 | vector arr(26,false); 6 | for(int i=0;i self.rank[py]: 17 | self.parent[py] = px 18 | else: 19 | self.parent[py] = px 20 | self.rank[px] += 1 21 | 22 | def connected(self, x, y): 23 | return self.find(x) == self.find(y) 24 | 25 | class Solution: 26 | def distanceLimitedPathsExist(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[bool]: 27 | edges = sorted(edges, key=lambda x: x[2]) 28 | ans = [False] * len(queries) 29 | uf = UnionFind(n) 30 | i = 0 31 | sorted_queries = sorted(enumerate(queries), key=lambda x: x[1][2]) 32 | for q_idx, (u, v, limit) in sorted_queries: 33 | while i < len(edges) and edges[i][2] < limit: 34 | uf.union(edges[i][0], edges[i][1]) 35 | i += 1 36 | ans[q_idx] = uf.connected(u, v) 37 | return ans -------------------------------------------------------------------------------- /Chunk Array/chunk-array: -------------------------------------------------------------------------------- 1 | function chunk(arr: any[], size: number): any[][] { 2 | var ans:any[] = []; 3 | var index:number = 0; 4 | 5 | while (index < arr.length) { 6 | ans.push(arr.slice(index, index + size)); 7 | index += size; 8 | } 9 | 10 | return ans; 11 | }; -------------------------------------------------------------------------------- /Clone Graph/clone-graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cloneGraph(self, node: 'Node') -> 'Node': 3 | if not node: return node 4 | 5 | q, clones = deque([node]), {node.val: Node(node.val, [])} 6 | while q: 7 | cur = q.popleft() 8 | cur_clone = clones[cur.val] 9 | 10 | for ngbr in cur.neighbors: 11 | if ngbr.val not in clones: 12 | clones[ngbr.val] = Node(ngbr.val, []) 13 | q.append(ngbr) 14 | 15 | cur_clone.neighbors.append(clones[ngbr.val]) 16 | 17 | return clones[node.val] -------------------------------------------------------------------------------- /Construct Binary Tree from Inorder and Postorder Traversal/README.md: -------------------------------------------------------------------------------- 1 | # [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) 2 |

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
 8 | Output: [3,9,20,null,null,15,7]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: inorder = [-1], postorder = [-1]
14 | Output: [-1]
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • 1 <= inorder.length <= 3000
  • 22 |
  • postorder.length == inorder.length
  • 23 |
  • -3000 <= inorder[i], postorder[i] <= 3000
  • 24 |
  • inorder and postorder consist of unique values.
  • 25 |
  • Each value of postorder also appears in inorder.
  • 26 |
  • inorder is guaranteed to be the inorder traversal of the tree.
  • 27 |
  • postorder is guaranteed to be the postorder traversal of the tree.
  • 28 |
29 | -------------------------------------------------------------------------------- /Construct Binary Tree from Inorder and Postorder Traversal/construct-binary-tree-from-inorder-and-postorder-traversal.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional 2 | 3 | class TreeNode: 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution: 10 | def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: 11 | # base case 12 | if not inorder or not postorder: 13 | return None 14 | 15 | # find the root node in the postorder traversal array 16 | root_val = postorder[-1] 17 | root = TreeNode(root_val) 18 | 19 | # find the index of the root node in the inorder traversal array 20 | root_idx = inorder.index(root_val) 21 | 22 | # recursively construct the left and right subtrees 23 | root.left = self.buildTree(inorder[:root_idx], postorder[:root_idx]) 24 | root.right = self.buildTree(inorder[root_idx+1:], postorder[root_idx:-1]) 25 | 26 | return root -------------------------------------------------------------------------------- /Construct Quad Tree/construct-quad-tree.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): 3 | self.val = val 4 | self.isLeaf = isLeaf 5 | self.topLeft = topLeft 6 | self.topRight = topRight 7 | self.bottomLeft = bottomLeft 8 | self.bottomRight = bottomRight 9 | 10 | 11 | class Solution: 12 | def construct(self, grid: List[List[int]]) -> 'Node': 13 | # Define a recursive helper function to build the quad tree 14 | def build_quad_tree(grid, top, left, bottom, right): 15 | # Check if the sub-matrix is homogeneous (i.e., all values are the same) 16 | is_homogeneous = True 17 | val = grid[top][left] 18 | for i in range(top, bottom): 19 | for j in range(left, right): 20 | if grid[i][j] != val: 21 | is_homogeneous = False 22 | break 23 | if not is_homogeneous: 24 | break 25 | 26 | # If the sub-matrix is homogeneous, create a leaf node 27 | if is_homogeneous: 28 | return Node(val, True, None, None, None, None) 29 | 30 | # Otherwise, recursively build the quad tree 31 | mid_row = (top + bottom) // 2 32 | mid_col = (left + right) // 2 33 | topLeft = build_quad_tree(grid, top, left, mid_row, mid_col) 34 | topRight = build_quad_tree(grid, top, mid_col, mid_row, right) 35 | bottomLeft = build_quad_tree(grid, mid_row, left, bottom, mid_col) 36 | bottomRight = build_quad_tree(grid, mid_row, mid_col, bottom, right) 37 | 38 | return Node(None, False, topLeft, topRight, bottomLeft, bottomRight) 39 | 40 | # Call the recursive helper function to build the quad tree 41 | n = len(grid) 42 | return build_quad_tree(grid, 0, 0, n, n) -------------------------------------------------------------------------------- /Contains Duplicate/README.md: -------------------------------------------------------------------------------- 1 | # [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) 2 |

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

3 | 4 |

 

5 |

Example 1:

6 |
Input: nums = [1,2,3,1]
 7 | Output: true
 8 | 

Example 2:

9 |
Input: nums = [1,2,3,4]
10 | Output: false
11 | 

Example 3:

12 |
Input: nums = [1,1,1,3,3,4,3,2,4,2]
13 | Output: true
14 | 
15 |

 

16 |

Constraints:

17 | 18 |
    19 |
  • 1 <= nums.length <= 105
  • 20 |
  • -109 <= nums[i] <= 109
  • 21 |
22 | -------------------------------------------------------------------------------- /Contains Duplicate/contains-duplicate.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def containsDuplicate(self, nums: List[int]) -> bool: 5 | # Create an empty set to store the unique elements of nums 6 | unique_nums = set() 7 | 8 | # Iterate over each element in nums 9 | for num in nums: 10 | # If the element is already in the set, it means it has occurred before 11 | # so we return True 12 | if num in unique_nums: 13 | return True 14 | 15 | # Otherwise, add the element to the set 16 | unique_nums.add(num) 17 | 18 | # If we have iterated over all elements and none of them have occurred before, 19 | # we return False 20 | return False -------------------------------------------------------------------------------- /Convert Object to JSON String/README.md: -------------------------------------------------------------------------------- 1 | # [Convert Object to JSON String](https://leetcode.com/problems/convert-object-to-json-string/) 2 |

Given an object, return a valid JSON string of that object. You may assume the object only includes strings, integers, arrays, objects, booleans, and null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by Object.keys().

3 | 4 |

Please solve it without using the built-in JSON.stringify method.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: object = {"y":1,"x":2}
10 | Output: {"y":1,"x":2}
11 | Explanation: 
12 | Return the JSON representation.
13 | Note that the order of keys should be the same as the order returned by Object.keys().
14 | 15 |

Example 2:

16 | 17 |
Input: object = {"a":"str","b":-12,"c":true,"d":null}
18 | Output: {"a":"str","b":-12,"c":true,"d":null}
19 | Explanation:
20 | The primitives of JSON are strings, numbers, booleans, and null.
21 | 
22 | 23 |

Example 3:

24 | 25 |
Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}}
26 | Output: {"key":{"a":1,"b":[{},null,"Hello"]}}
27 | Explanation:
28 | Objects and arrays can include other objects and arrays.
29 | 
30 | 31 |

Example 4:

32 | 33 |
Input: object = true
34 | Output: true
35 | Explanation:
36 | Primitive types are valid inputs.
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • object includes strings, integers, booleans, arrays, objects, and null
  • 43 |
  • 1 <= JSON.stringify(object).length <= 105
  • 44 |
  • maxNestingLevel <= 1000
  • 45 |
  • all strings will only contain alphanumeric characters
  • 46 |
47 | -------------------------------------------------------------------------------- /Convert Object to JSON String/convert-object-to-json-string: -------------------------------------------------------------------------------- 1 | function jsonStringify(object: any): string { 2 | if (typeof object === 'string') 3 | return '"' + object + '"'; 4 | if (!object || typeof object !== 'object') 5 | return String(object); 6 | if (Array.isArray(object)) 7 | return '[' + object.map((item) => jsonStringify(item)) + ']'; 8 | var ans = '' 9 | for (const key in object) 10 | ans += '"' + key + '":' + jsonStringify(object[key]) + ','; 11 | return '{' + ans.slice(0, -1) + '}' 12 | }; -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree/README.md: -------------------------------------------------------------------------------- 1 | # [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) 2 |

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a

binary search tree.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: head = [-10,-3,0,5,9]
 8 | Output: [0,-3,9,-10,null,5]
 9 | Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: head = []
15 | Output: []
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • The number of nodes in head is in the range [0, 2 * 104].
  • 23 |
  • -105 <= Node.val <= 105
  • 24 |
25 | -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree/convert-sorted-list-to-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | # Definition for a binary tree node. 8 | # class TreeNode: 9 | # def __init__(self, val=0, left=None, right=None): 10 | # self.val = val 11 | # self.left = left 12 | # self.right = right 13 | 14 | class Solution: 15 | def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: 16 | # Base case 17 | if not head: 18 | return None 19 | 20 | # Find the middle node of the linked list 21 | slow, fast = head, head 22 | prev = None 23 | while fast and fast.next: 24 | prev = slow 25 | slow = slow.next 26 | fast = fast.next.next 27 | 28 | # Create a new TreeNode with the value of the middle node 29 | node = TreeNode(slow.val) 30 | 31 | # Split the linked list into two halves 32 | if prev: 33 | prev.next = None 34 | left = head 35 | right = slow.next 36 | else: 37 | left = None 38 | right = slow.next 39 | 40 | # Recursively build the left and right subtrees 41 | node.left = self.sortedListToBST(left) 42 | node.right = self.sortedListToBST(right) 43 | 44 | return node -------------------------------------------------------------------------------- /Count Items Matching a Rule/count-items-matching-a-rule.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countMatches(vector>& items, string ruleKey, string ruleValue) { 4 | int x; int c=0; 5 | if(ruleKey=="type"){x=0;} 6 | if(ruleKey=="color"){x=1;} 7 | if(ruleKey=="name"){x=2;} 8 | for(int i=0; iGiven an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: n = 2
 8 | Output: 91
 9 | Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: n = 0
15 | Output: 1
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 0 <= n <= 8
  • 23 |
24 | -------------------------------------------------------------------------------- /Count Numbers with Unique Digits/count-numbers-with-unique-digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNumbersWithUniqueDigits( int n, int p = 9, int f = 9 ) 4 | { 5 | return n>1?p*f+countNumbersWithUniqueDigits(n<=10?n-1:10,p*f,f-1):pow(10,n); 6 | } 7 | }; -------------------------------------------------------------------------------- /Count Subarrays With Fixed Bounds/README.md: -------------------------------------------------------------------------------- 1 | # [Count Subarrays With Fixed Bounds](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/) 2 |

You are given an integer array nums and two integers minK and maxK.

3 | 4 |

A fixed-bound subarray of nums is a subarray that satisfies the following conditions:

5 | 6 |
    7 |
  • The minimum value in the subarray is equal to minK.
  • 8 |
  • The maximum value in the subarray is equal to maxK.
  • 9 |
10 | 11 |

Return the number of fixed-bound subarrays.

12 | 13 |

A subarray is a contiguous part of an array.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
19 | Output: 2
20 | Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
21 | 
22 | 23 |

Example 2:

24 | 25 |
Input: nums = [1,1,1,1], minK = 1, maxK = 1
26 | Output: 10
27 | Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • 2 <= nums.length <= 105
  • 35 |
  • 1 <= nums[i], minK, maxK <= 106
  • 36 |
37 | -------------------------------------------------------------------------------- /Count Subarrays With Fixed Bounds/count-subarrays-with-fixed-bounds.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int: 3 | # find the subarray with min value is minK and max value is maxK 4 | # find the index of the min value and max value. 5 | # first, find the longest subarrays with minK and maxK 6 | # then, find each number of subarrays for each array 7 | def findArrays(nums, minK, maxK): 8 | nums.append(0) 9 | res = [] 10 | arr = [] 11 | for i in range(len(nums)): 12 | if nums[i] >= minK and nums[i] <= maxK: 13 | arr.append(nums[i]) 14 | else: 15 | if arr and min(arr)==minK and max(arr)==maxK: 16 | res.append(arr) 17 | arr = [] 18 | return res 19 | 20 | def calculateSubarrays(arr, minK, maxK): 21 | res = 0 22 | # use queue tostore the index of the minK and max K 23 | queue = [] 24 | prev = 0 25 | n = len(arr) 26 | if minK==maxK: 27 | return n//2*(n+1) if n%2==0 else (n+1)//2*n 28 | for i in range(len(arr)): 29 | if i>=prev and (arr[i] == minK or arr[i] == maxK): 30 | # print(queue) 31 | while len(queue)>0 and arr[queue[len(queue)-1]] !=arr[i]: 32 | index = queue.pop(0) 33 | beforeCount = index -prev+1 34 | afterCount = n - i 35 | res += beforeCount*afterCount 36 | # print(prev,index,i,beforeCount,afterCount) 37 | prev = index+1 38 | queue.append(i) 39 | return res 40 | 41 | # main body 42 | arrs = findArrays(nums, minK, maxK) 43 | ans = 0 44 | for arr in arrs: 45 | ans+=calculateSubarrays(arr, minK, maxK) 46 | return ans -------------------------------------------------------------------------------- /Count Unreachable Pairs of Nodes in an Undirected Graph/README.md: -------------------------------------------------------------------------------- 1 | # [Count Unreachable Pairs of Nodes in an Undirected Graph](https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/) 2 |

You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

3 | 4 |

Return the number of pairs of different nodes that are unreachable from each other.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
10 | Output: 0
11 | Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
17 | Output: 14
18 | Explanation: There are 14 pairs of nodes that are unreachable from each other:
19 | [[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
20 | Therefore, we return 14.
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 1 <= n <= 105
  • 28 |
  • 0 <= edges.length <= 2 * 105
  • 29 |
  • edges[i].length == 2
  • 30 |
  • 0 <= ai, bi < n
  • 31 |
  • ai != bi
  • 32 |
  • There are no repeated edges.
  • 33 |
34 | -------------------------------------------------------------------------------- /Count Unreachable Pairs of Nodes in an Undirected Graph/count-unreachable-pairs-of-nodes-in-an-undirected-graph.py: -------------------------------------------------------------------------------- 1 | class UnionFind: 2 | def __init__(self, size): 3 | self.root = [i for i in range(size)] 4 | self.rank = [1] * size 5 | 6 | def find(self, node): 7 | if node != self.root[node]: 8 | self.root[node] = self.find(self.root[node]) 9 | return self.root[node] 10 | 11 | def union(self, node1, node2): 12 | root1 = self.find(node1) 13 | root2 = self.find(node2) 14 | if root1 != root2: 15 | if self.rank[root1] > self.rank[root2]: 16 | self.root[root2] = root1 17 | elif self.rank[root1] < self.rank[root2]: 18 | self.root[root1] = root2 19 | else: 20 | self.root[root2] = root1 21 | self.rank[root1] += 1 22 | 23 | class Solution: 24 | def countPairs(self, n: int, edges: List[List[int]]) -> int: 25 | uf = UnionFind(n) 26 | for node1, node2 in edges: 27 | uf.union(node1 - 1, node2 - 1) 28 | group_sizes = list(Counter([uf.find(i) for i in range(n)]).values()) 29 | ans = 0 30 | first_group_size = group_sizes[0] 31 | for i in range(1, len(group_sizes)): 32 | ans += first_group_size * group_sizes[i] 33 | first_group_size += group_sizes[i] 34 | return ans -------------------------------------------------------------------------------- /Count Ways To Build Good Strings/README.md: -------------------------------------------------------------------------------- 1 | # [Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/) 2 |

Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:

3 | 4 |
    5 |
  • Append the character '0' zero times.
  • 6 |
  • Append the character '1' one times.
  • 7 |
8 | 9 |

This can be performed any number of times.

10 | 11 |

A good string is a string constructed by the above process having a length between low and high (inclusive).

12 | 13 |

Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
Input: low = 3, high = 3, zero = 1, one = 1
19 | Output: 8
20 | Explanation: 
21 | One possible valid good string is "011". 
22 | It can be constructed as follows: "" -> "0" -> "01" -> "011". 
23 | All binary strings from "000" to "111" are good strings in this example.
24 | 
25 | 26 |

Example 2:

27 | 28 |
Input: low = 2, high = 3, zero = 1, one = 2
29 | Output: 5
30 | Explanation: The good strings are "00", "11", "000", "110", and "011".
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • 1 <= low <= high <= 105
  • 38 |
  • 1 <= zero, one <= low
  • 39 |
40 | -------------------------------------------------------------------------------- /Count Ways To Build Good Strings/count-ways-to-build-good-strings.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: 5 | dp = Counter({0: 1}) 6 | mod = 10 ** 9 + 7 7 | for i in range(1, high + 1): 8 | 9 | z = dp[i - zero] 10 | 11 | o = dp[i - one] 12 | 13 | n = (z + o) % mod 14 | 15 | dp[i] = n 16 | 17 | 18 | ans = sum(dp[i] for i in range(low, high + 1)) % mod 19 | 20 | 21 | return ans -------------------------------------------------------------------------------- /Counter II/README.md: -------------------------------------------------------------------------------- 1 | # [Counter II](https://leetcode.com/problems/counter-ii/) 2 |

Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.

3 | 4 |

The three functions are:

5 | 6 |
    7 |
  • increment() increases the current value by 1 and then returns it.
  • 8 |
  • decrement() reduces the current value by 1 and then returns it.
  • 9 |
  • reset() sets the current value to init and then returns it.
  • 10 |
11 | 12 |

 

13 |

Example 1:

14 | 15 |
Input: init = 5, calls = ["increment","reset","decrement"]
16 | Output: [6,5,4]
17 | Explanation:
18 | const counter = createCounter(5);
19 | counter.increment(); // 6
20 | counter.reset(); // 5
21 | counter.decrement(); // 4
22 | 
23 | 24 |

Example 2:

25 | 26 |
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]
27 | Output: [1,2,1,0,0]
28 | Explanation:
29 | const counter = createCounter(0);
30 | counter.increment(); // 1
31 | counter.increment(); // 2
32 | counter.decrement(); // 1
33 | counter.reset(); // 0
34 | counter.reset(); // 0
35 | 
36 | 37 |

 

38 |

Constraints:

39 | 40 |
    41 |
  • -1000 <= init <= 1000
  • 42 |
  • total calls not to exceed 1000
  • 43 |
44 | -------------------------------------------------------------------------------- /Counter II/counter-ii.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {integer} init 3 | * @return { increment: Function, decrement: Function, reset: Function } 4 | */ 5 | var createCounter = function(init) { 6 | let counter = init; 7 | let resetVal = init; 8 | 9 | let obj = { 10 | increment : () => ++counter, 11 | decrement : () => --counter, 12 | reset : () => counter = resetVal 13 | } 14 | 15 | return obj; 16 | }; -------------------------------------------------------------------------------- /Counter/README.md: -------------------------------------------------------------------------------- 1 | # [Counter](https://leetcode.com/problems/counter/) 2 |

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: 
 8 | n = 10 
 9 | ["call","call","call"]
10 | Output: [10,11,12]
11 | Explanation: 
12 | counter() = 10 // The first time counter() is called, it returns n.
13 | counter() = 11 // Returns 1 more than the previous time.
14 | counter() = 12 // Returns 1 more than the previous time.
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: 
20 | n = -2
21 | ["call","call","call","call","call"]
22 | Output: [-2,-1,0,1,2]
23 | Explanation: counter() initially returns -2. Then increases after each sebsequent call.
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • -1000 <= n <= 1000
  • 31 |
  • At most 1000 calls to counter() will be made
  • 32 |
33 | -------------------------------------------------------------------------------- /Counter/counter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {Function} counter 4 | */ 5 | var createCounter = function(n) { 6 | return function() { 7 | return n++; 8 | }; 9 | }; -------------------------------------------------------------------------------- /Create Hello World Function/README.md: -------------------------------------------------------------------------------- 1 | # [Create Hello World Function](https://leetcode.com/problems/create-hello-world-function/) 2 | Write a function createHelloWorld. It should return a new function that always returns "Hello World". 3 |

 

4 |

Example 1:

5 | 6 |
Input: args = []
 7 | Output: "Hello World"
 8 | Explanation:
 9 | const f = createHelloWorld();
10 | f(); // "Hello World"
11 | 
12 | The function returned by createHelloWorld should always return "Hello World".
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: args = [{},null,42]
18 | Output: "Hello World"
19 | Explanation:
20 | const f = createHelloWorld();
21 | f({}, null, 42); // "Hello World"
22 | 
23 | Any arguments could be passed to the function but it should still always return "Hello World".
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 0 <= args.length <= 10
  • 31 |
32 | -------------------------------------------------------------------------------- /Create Hello World Function/create-hello-world-function.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @return {Function} 3 | */ 4 | var createHelloWorld = function() { 5 | return function(...args) { 6 | return "Hello World"; 7 | } 8 | }; -------------------------------------------------------------------------------- /Curry/curry: -------------------------------------------------------------------------------- 1 | function curry(fn: Function): Function { 2 | const res = []; 3 | return function curried(...args) { 4 | res.push(...args) 5 | if (res.length === fn.length) { 6 | return fn(...res); 7 | } 8 | return (...args2) => curried(...args2); 9 | }; 10 | }; -------------------------------------------------------------------------------- /Debounce/debounce: -------------------------------------------------------------------------------- 1 | type F = (...p: any[]) => any 2 | 3 | function debounce(fn: F, t: number): F { 4 | let timeout: NodeJS.Timeout = null; 5 | return function(...args) { 6 | if (timeout != null) { 7 | clearTimeout(timeout); 8 | } 9 | timeout = setTimeout(() => { 10 | fn(...args); 11 | timeout = null; 12 | }, t); 13 | } 14 | }; -------------------------------------------------------------------------------- /Design Add and Search Words Data Structure/README.md: -------------------------------------------------------------------------------- 1 | # [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/) 2 |

Design a data structure that supports adding new words and finding if a string matches any previously added string.

3 | 4 |

Implement the WordDictionary class:

5 | 6 |
    7 |
  • WordDictionary() Initializes the object.
  • 8 |
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • 9 |
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
  • 10 |
11 | 12 |

 

13 |

Example:

14 | 15 |
Input
16 | ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
17 | [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
18 | Output
19 | [null,null,null,null,false,true,true,true]
20 | 
21 | Explanation
22 | WordDictionary wordDictionary = new WordDictionary();
23 | wordDictionary.addWord("bad");
24 | wordDictionary.addWord("dad");
25 | wordDictionary.addWord("mad");
26 | wordDictionary.search("pad"); // return False
27 | wordDictionary.search("bad"); // return True
28 | wordDictionary.search(".ad"); // return True
29 | wordDictionary.search("b.."); // return True
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= word.length <= 25
  • 37 |
  • word in addWord consists of lowercase English letters.
  • 38 |
  • word in search consist of '.' or lowercase English letters.
  • 39 |
  • There will be at most 2 dots in word for search queries.
  • 40 |
  • At most 104 calls will be made to addWord and search.
  • 41 |
42 | -------------------------------------------------------------------------------- /Design Add and Search Words Data Structure/design-add-and-search-words-data-structure.py: -------------------------------------------------------------------------------- 1 | class TrieNode: 2 | def __init__(self): 3 | self.children = {} 4 | self.is_word = False 5 | 6 | class WordDictionary: 7 | def __init__(self): 8 | self.root = TrieNode() 9 | 10 | def addWord(self, word: str) -> None: 11 | node = self.root 12 | for c in word: 13 | if c not in node.children: 14 | node.children[c] = TrieNode() 15 | node = node.children[c] 16 | node.is_word = True 17 | 18 | def search(self, word: str) -> bool: 19 | def search_in_node(word, node): 20 | for i, c in enumerate(word): 21 | if c not in node.children: 22 | if c == '.': 23 | for child in node.children: 24 | if search_in_node(word[i+1:], node.children[child]): 25 | return True 26 | return False 27 | else: 28 | node = node.children[c] 29 | return node.is_word 30 | 31 | return search_in_node(word, self.root) -------------------------------------------------------------------------------- /Design Parking System/design-parking-system.py: -------------------------------------------------------------------------------- 1 | class ParkingSystem: 2 | def __init__(self, big: int, medium: int, small: int): 3 | self.slots = [0, big, medium, small] 4 | 5 | def addCar(self, carType: int) -> bool: 6 | if self.slots[carType] > 0: 7 | self.slots[carType] -= 1 8 | return True 9 | else: 10 | return False -------------------------------------------------------------------------------- /Differences Between Two Objects/README.md: -------------------------------------------------------------------------------- 1 | # [Differences Between Two Objects](https://leetcode.com/problems/differences-between-two-objects/) 2 | -------------------------------------------------------------------------------- /Differences Between Two Objects/differences-between-two-objects: -------------------------------------------------------------------------------- 1 | function objDiff(obj1: any, obj2: any): any { 2 | if (obj1 === obj2) return {}; 3 | if (obj1 === null || obj2 === null) return [obj1, obj2]; 4 | if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return [obj1, obj2]; 5 | if (Array.isArray(obj1) !== Array.isArray(obj2)) return [obj1, obj2]; 6 | 7 | const returnObject = {}; 8 | for (const key in obj1) { 9 | if (key in obj2) { 10 | const subDiff = objDiff(obj1[key], obj2[key]); 11 | if (Object.keys(subDiff).length > 0) { 12 | returnObject[key] = subDiff; 13 | } 14 | } 15 | } 16 | return returnObject; 17 | }; -------------------------------------------------------------------------------- /Divide Two Integers/README.md: -------------------------------------------------------------------------------- 1 | # [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) 2 |

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

3 | 4 |

The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.

5 | 6 |

Return the quotient after dividing dividend by divisor.

7 | 8 |

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.

9 | 10 |

 

11 |

Example 1:

12 | 13 |
Input: dividend = 10, divisor = 3
14 | Output: 3
15 | Explanation: 10/3 = 3.33333.. which is truncated to 3.
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: dividend = 7, divisor = -3
21 | Output: -2
22 | Explanation: 7/-3 = -2.33333.. which is truncated to -2.
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • -231 <= dividend, divisor <= 231 - 1
  • 30 |
  • divisor != 0
  • 31 |
32 | -------------------------------------------------------------------------------- /Divide Two Integers/divide-two-integers.c: -------------------------------------------------------------------------------- 1 | int divide( int dividend, int divisor ) 2 | { 3 | long int cnt, ans = 0 ; 4 | long int x = dividend, y = divisor ; 5 | bool flag = 0 ; 6 | 7 | if( x == INT_MIN && y == -1 ) return INT_MAX ; 8 | if( x == INT_MIN && y == 1 ) return INT_MIN ; 9 | 10 | if( x < 0 ) 11 | { 12 | x *= -1 ; 13 | flag = 1 ; 14 | } 15 | 16 | if( y < 0 ) 17 | { 18 | if( flag == 1 ) 19 | { 20 | flag = 0 ; 21 | } 22 | 23 | else 24 | { 25 | flag = 1 ; 26 | } 27 | y *= -1 ; 28 | } 29 | 30 | while( x >= y ) 31 | { 32 | int tmp = 0 ; 33 | while( x >= ( y << tmp ) ) 34 | { 35 | tmp++ ; 36 | } 37 | x -= ( y << tmp-1 ) ; 38 | ans += 1< INT_MAX ) return INT_MAX ; 48 | else return ans ; 49 | } -------------------------------------------------------------------------------- /Edit Distance/README.md: -------------------------------------------------------------------------------- 1 | # [Edit Distance](https://leetcode.com/problems/edit-distance/) 2 |

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

3 | 4 |

You have the following three operations permitted on a word:

5 | 6 |
    7 |
  • Insert a character
  • 8 |
  • Delete a character
  • 9 |
  • Replace a character
  • 10 |
11 | 12 |

 

13 |

Example 1:

14 | 15 |
Input: word1 = "horse", word2 = "ros"
16 | Output: 3
17 | Explanation: 
18 | horse -> rorse (replace 'h' with 'r')
19 | rorse -> rose (remove 'r')
20 | rose -> ros (remove 'e')
21 | 
22 | 23 |

Example 2:

24 | 25 |
Input: word1 = "intention", word2 = "execution"
26 | Output: 5
27 | Explanation: 
28 | intention -> inention (remove 't')
29 | inention -> enention (replace 'i' with 'e')
30 | enention -> exention (replace 'n' with 'x')
31 | exention -> exection (replace 'n' with 'c')
32 | exection -> execution (insert 'u')
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 0 <= word1.length, word2.length <= 500
  • 40 |
  • word1 and word2 consist of lowercase English letters.
  • 41 |
42 | -------------------------------------------------------------------------------- /Edit Distance/edit-distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDistance(self, word1: str, word2: str) -> int: 3 | m, n = len(word1), len(word2) 4 | # Create a table to store the minimum edit distances 5 | dp = [[0] * (n+1) for _ in range(m+1)] 6 | # Initialize the first row and column of the table 7 | for i in range(m+1): 8 | dp[i][0] = i 9 | for j in range(n+1): 10 | dp[0][j] = j 11 | # Fill in the rest of the table 12 | for i in range(1, m+1): 13 | for j in range(1, n+1): 14 | if word1[i-1] == word2[j-1]: 15 | dp[i][j] = dp[i-1][j-1] 16 | else: 17 | dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) 18 | # Return the minimum edit distance 19 | return dp[m][n] -------------------------------------------------------------------------------- /Evaluate Division/evaluate-division.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | class Solution: 4 | def calcEquation(self, equations, values, queries): 5 | graph = self.buildGraph(equations, values) 6 | results = [] 7 | 8 | for dividend, divisor in queries: 9 | if dividend not in graph or divisor not in graph: 10 | results.append(-1.0) 11 | else: 12 | result = self.bfs(dividend, divisor, graph) 13 | results.append(result) 14 | 15 | return results 16 | 17 | def buildGraph(self, equations, values): 18 | graph = defaultdict(dict) 19 | 20 | for (dividend, divisor), value in zip(equations, values): 21 | graph[dividend][divisor] = value 22 | graph[divisor][dividend] = 1.0 / value 23 | 24 | return graph 25 | 26 | def bfs(self, start, end, graph): 27 | queue = deque([(start, 1.0)]) 28 | visited = set() 29 | 30 | while queue: 31 | node, value = queue.popleft() 32 | 33 | if node == end: 34 | return value 35 | 36 | visited.add(node) 37 | 38 | for neighbor, weight in graph[node].items(): 39 | if neighbor not in visited: 40 | queue.append((neighbor, value * weight)) 41 | 42 | return -1.0 -------------------------------------------------------------------------------- /Event Emitter/event-emitter: -------------------------------------------------------------------------------- 1 | type Callback = (...args: any[]) => any; 2 | type Subscription = { 3 | unsubscribe: () => void 4 | } 5 | 6 | class EventEmitter { 7 | subs: any; 8 | constructor(){ 9 | this.subs = {}; 10 | } 11 | subscribe(eventName: string, callback: Callback): Subscription { 12 | if(this.subs[eventName] === undefined) this.subs[eventName] = []; 13 | let curIdx = this.subs[eventName].length; 14 | this.subs[eventName].push(callback); 15 | return { 16 | unsubscribe: () => { 17 | this.subs[eventName][curIdx] = null; 18 | } 19 | }; 20 | } 21 | 22 | emit(eventName: string, args: any[] = []): any { 23 | if(this.subs[eventName] === undefined) return []; 24 | let res = []; 25 | for(let cbFn of this.subs[eventName]) { 26 | if(cbFn === null) continue; 27 | res.push(cbFn(...args)); 28 | } 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /Filter Elements from Array/README.md: -------------------------------------------------------------------------------- 1 | # [Filter Elements from Array](https://leetcode.com/problems/filter-elements-from-array/) 2 |

Given an integer array arr and a filtering function fn, return a new array with a fewer or equal number of elements.

3 | 4 |

The returned array should only contain elements where fn(arr[i], i) evaluated to a truthy value.

5 | 6 |

Please solve it without the built-in Array.filter method.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
12 | Output: [20,30]
13 | Explanation:
14 | const newArray = filter(arr, fn); // [20, 30]
15 | The function filters out values that are not greater than 10
16 | 17 |

Example 2:

18 | 19 |
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
20 | Output: [1]
21 | Explanation:
22 | fn can also accept the index of each element
23 | In this case, the function removes elements not at index 0
24 | 
25 | 26 |

Example 3:

27 | 28 |
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
29 | Output: [-2,0,1,2]
30 | Explanation:
31 | Falsey values such as 0 should be filtered out
32 | 
33 | 34 |

 

35 |

Constraints:

36 | 37 |
    38 |
  • 0 <= arr.length <= 1000
  • 39 |
  • -109 <= arr[i] <= 109
  • 40 |
41 | -------------------------------------------------------------------------------- /Filter Elements from Array/filter-elements-from-array: -------------------------------------------------------------------------------- 1 | function filter(arr: T[], fn: (val: T, index: number) => boolean): T[] { 2 | const result: T[] = []; 3 | for (let i = 0; i < arr.length; i++) { 4 | if (fn(arr[i], i)) { 5 | result.push(arr[i]); 6 | } 7 | } 8 | return result; 9 | } -------------------------------------------------------------------------------- /Find Nearest Point That Has the Same X or Y Coordinate/find-nearest-point-that-has-the-same-x-or-y-coordinate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: 3 | min_dist = float('inf') # Initialize minimum distance to infinity 4 | min_index = -1 # Initialize minimum index to -1 5 | for i in range(len(points)): 6 | if points[i][0] == x or points[i][1] == y: # Check if point is valid 7 | dist = abs(points[i][0] - x) + abs(points[i][1] - y) # Calculate Manhattan distance 8 | if dist < min_dist: # Update minimum distance and index if distance is smaller 9 | min_dist = dist 10 | min_index = i 11 | return min_index # Return index of the valid point with smallest Manhattan distance -------------------------------------------------------------------------------- /Find the Difference of Two Arrays/README.md: -------------------------------------------------------------------------------- 1 | # [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays/) 2 |

Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:

3 | 4 |
    5 |
  • answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
  • 6 |
  • answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
  • 7 |
8 | 9 |

Note that the integers in the lists may be returned in any order.

10 | 11 |

 

12 |

Example 1:

13 | 14 |
Input: nums1 = [1,2,3], nums2 = [2,4,6]
15 | Output: [[1,3],[4,6]]
16 | Explanation:
17 | For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
18 | For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].
19 | 20 |

Example 2:

21 | 22 |
Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
23 | Output: [[3],[]]
24 | Explanation:
25 | For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
26 | Every integer in nums2 is present in nums1. Therefore, answer[1] = [].
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 1 <= nums1.length, nums2.length <= 1000
  • 34 |
  • -1000 <= nums1[i], nums2[i] <= 1000
  • 35 |
36 | -------------------------------------------------------------------------------- /Find the Difference of Two Arrays/find-the-difference-of-two-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: 3 | set1=set(nums1) 4 | set2=set(nums2) 5 | res=[[],[]] 6 | 7 | for i in set1: 8 | if i not in set2: 9 | res[0].append(i) 10 | for i in set2: 11 | if i not in set1: 12 | res[1].append(i) 13 | return res 14 | 15 | #other possible answer for this problem 16 | class Solution: 17 | def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: 18 | set1,set2=set(nums1),set(nums2) 19 | return[set1-set2,set2-set1] -------------------------------------------------------------------------------- /Find the Difference/README.md: -------------------------------------------------------------------------------- 1 | # [Find the Difference](https://leetcode.com/problems/find-the-difference/) 2 |

You are given two strings s and t.

3 | 4 |

String t is generated by random shuffling string s and then add one more letter at a random position.

5 | 6 |

Return the letter that was added to t.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: s = "abcd", t = "abcde"
12 | Output: "e"
13 | Explanation: 'e' is the letter that was added.
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: s = "", t = "y"
19 | Output: "y"
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 0 <= s.length <= 1000
  • 27 |
  • t.length == s.length + 1
  • 28 |
  • s and t consist of lowercase English letters.
  • 29 |
30 | -------------------------------------------------------------------------------- /Find the Difference/find-the-difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | # initialize dictionaries to keep track of character frequency 4 | s_freq = {} 5 | t_freq = {} 6 | 7 | # count frequency of characters in s 8 | for char in s: 9 | s_freq[char] = s_freq.get(char, 0) + 1 10 | 11 | # count frequency of characters in t 12 | for char in t: 13 | t_freq[char] = t_freq.get(char, 0) + 1 14 | 15 | # compare the frequencies to find the extra character 16 | for char in t_freq: 17 | if char not in s_freq or t_freq[char] != s_freq[char]: 18 | return char -------------------------------------------------------------------------------- /Find the Index of the First Occurrence in a String/README.md: -------------------------------------------------------------------------------- 1 | # [Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/) 2 |

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: haystack = "sadbutsad", needle = "sad"
 8 | Output: 0
 9 | Explanation: "sad" occurs at index 0 and 6.
10 | The first occurrence is at index 0, so we return 0.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: haystack = "leetcode", needle = "leeto"
16 | Output: -1
17 | Explanation: "leeto" did not occur in "leetcode", so we return -1.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= haystack.length, needle.length <= 104
  • 25 |
  • haystack and needle consist of only lowercase English characters.
  • 26 |
27 | -------------------------------------------------------------------------------- /Find the Index of the First Occurrence in a String/find-the-index-of-the-first-occurrence-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | if not needle: 4 | return 0 5 | if not haystack: 6 | return -1 7 | if len(haystack) < len(needle): 8 | return -1 9 | 10 | for i in range(len(haystack) - len(needle) + 1): 11 | if haystack[i:i+len(needle)] == needle: 12 | return i 13 | return -1 -------------------------------------------------------------------------------- /Find the Longest Valid Obstacle Course at Each Position/find-the-longest-valid-obstacle-course-at-each-position.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]: 3 | stack,ans=[],[] 4 | 5 | for i in obstacles: 6 | br=bisect_right(stack,i) 7 | if br==len(stack): 8 | stack.append(i) 9 | else: 10 | stack[br]=i 11 | ans.append(br+1) 12 | 13 | return ans -------------------------------------------------------------------------------- /Fizz Buzz/README.md: -------------------------------------------------------------------------------- 1 | # [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) 2 |

Given an integer n, return a string array answer (1-indexed) where:

3 | 4 |
    5 |
  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • 6 |
  • answer[i] == "Fizz" if i is divisible by 3.
  • 7 |
  • answer[i] == "Buzz" if i is divisible by 5.
  • 8 |
  • answer[i] == i (as a string) if none of the above conditions are true.
  • 9 |
10 | 11 |

 

12 |

Example 1:

13 |
Input: n = 3
14 | Output: ["1","2","Fizz"]
15 | 

Example 2:

16 |
Input: n = 5
17 | Output: ["1","2","Fizz","4","Buzz"]
18 | 

Example 3:

19 |
Input: n = 15
20 | Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
21 | 
22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= n <= 104
  • 27 |
28 | -------------------------------------------------------------------------------- /Fizz Buzz/fizz-buzz.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Note: The returned array must be malloced, assume caller calls free(). 3 | */ 4 | char ** fizzBuzz(int n, int* returnSize){ 5 | 6 | char **res=(char**)calloc(n,sizeof(char *));int c=0; 7 | for(int i=1;i<=n;i++) 8 | { 9 | if(i%3==0&&i%5==0) 10 | { 11 | *(res+c)=(char *)calloc(9,sizeof(char)); 12 | res[c][0]='F';res[c][1]='i';res[c][2]='z'; 13 | res[c][3]='z';res[c][4]='B';res[c][5]='u'; 14 | res[c][6]='z';res[c][7]='z';res[c][8]='\0'; 15 | c++; 16 | } 17 | else if(i%3==0) 18 | { 19 | *(res+c)=(char *)calloc(5,sizeof(char)); 20 | res[c][0]='F';res[c][1]='i';res[c][2]='z'; 21 | res[c][3]='z';res[c][4]='\0'; 22 | c++; 23 | } 24 | else if(i%5==0) 25 | { 26 | *(res+c)=(char *)calloc(5,sizeof(char)); 27 | res[c][0]='B';res[c][1]='u';res[c][2]='z'; 28 | res[c][3]='z';res[c][4]='\0'; 29 | c++; 30 | } 31 | else 32 | { 33 | int x=0,y=i; 34 | while(y) 35 | { 36 | x++; 37 | y=y/10; 38 | } 39 | *(res+c)=(char *)calloc(x+1,sizeof(char)); 40 | res[c][x]='\0'; 41 | x--; 42 | y=i; 43 | while(y) 44 | { 45 | int m=y%10; 46 | res[c][x--]=48+m; 47 | y=y/10; 48 | } 49 | c++; 50 | } 51 | 52 | } 53 | *returnSize=c; 54 | return res; 55 | } -------------------------------------------------------------------------------- /Flatten Binary Tree to Linked List/README.md: -------------------------------------------------------------------------------- 1 | # [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) 2 |

Given the root of a binary tree, flatten the tree into a "linked list":

3 | 4 |
    5 |
  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • 6 |
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.
  • 7 |
8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: root = [1,2,5,3,4,null,6]
13 | Output: [1,null,2,null,3,null,4,null,5,null,6]
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

Example 3:

23 | 24 |
Input: root = [0]
25 | Output: [0]
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • The number of nodes in the tree is in the range [0, 2000].
  • 33 |
  • -100 <= Node.val <= 100
  • 34 |
35 | 36 |

 

37 | Follow up: Can you flatten the tree in-place (with O(1) extra space)? -------------------------------------------------------------------------------- /Flatten Binary Tree to Linked List/flatten-binary-tree-to-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def flatten(self, root: Optional[TreeNode]) -> None: 10 | """ 11 | Do not return anything, modify root in-place instead. 12 | """ 13 | if not root: 14 | return 15 | 16 | self.flatten(root.left) 17 | self.flatten(root.right) 18 | 19 | left = root.left 20 | right = root.right 21 | 22 | root.left = None 23 | root.right = left 24 | 25 | current = root 26 | while current.right: 27 | current = current.right 28 | current.right = right -------------------------------------------------------------------------------- /Flatten Deeply Nested Array/flatten-deeply-nested-array: -------------------------------------------------------------------------------- 1 | var flat = function (arr, n) { 2 | return arr.flat(n); 3 | }; -------------------------------------------------------------------------------- /Function Composition/function-composition: -------------------------------------------------------------------------------- 1 | type F = (x: number) => number; 2 | 3 | function compose(functions: F[]): F { 4 | return function(x) { 5 | let funcLen = functions.length; 6 | 7 | for(let idx = funcLen-1; idx >= 0; idx--){ 8 | x = functions[idx](x); 9 | } 10 | 11 | return x; 12 | } 13 | }; -------------------------------------------------------------------------------- /Generate Fibonacci Sequence/README.md: -------------------------------------------------------------------------------- 1 | # [Generate Fibonacci Sequence](https://leetcode.com/problems/generate-fibonacci-sequence/) 2 |

Write a generator function that returns a generator object which yields the fibonacci sequence.

3 | 4 |

The fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2.

5 | 6 |

The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: callCount = 5
12 | Output: [0,1,1,2,3]
13 | Explanation:
14 | const gen = fibGenerator();
15 | gen.next().value; // 0
16 | gen.next().value; // 1
17 | gen.next().value; // 1
18 | gen.next().value; // 2
19 | gen.next().value; // 3
20 | 
21 | 22 |

Example 2:

23 | 24 |
Input: callCount = 0
25 | Output: []
26 | Explanation: gen.next() is never called so nothing is outputted
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 0 <= callCount <= 50
  • 34 |
35 | -------------------------------------------------------------------------------- /Generate Fibonacci Sequence/generate-fibonacci-sequence: -------------------------------------------------------------------------------- 1 | function* fibGenerator(): Generator { 2 | const fib = [0, 1, 1]; 3 | while (true) { 4 | yield fib.shift()!; 5 | fib.push(fib[0] + fib[1]); 6 | } 7 | } -------------------------------------------------------------------------------- /Goal Parser Interpretation/README.md: -------------------------------------------------------------------------------- 1 | # [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/) 2 |

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.

3 | 4 |

Given the string command, return the Goal Parser's interpretation of command.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: command = "G()(al)"
10 | Output: "Goal"
11 | Explanation: The Goal Parser interprets the command as follows:
12 | G -> G
13 | () -> o
14 | (al) -> al
15 | The final concatenated result is "Goal".
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: command = "G()()()()(al)"
21 | Output: "Gooooal"
22 | 
23 | 24 |

Example 3:

25 | 26 |
Input: command = "(al)G(al)()()G"
27 | Output: "alGalooG"
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • 1 <= command.length <= 100
  • 35 |
  • command consists of "G", "()", and/or "(al)" in some order.
  • 36 |
37 | -------------------------------------------------------------------------------- /Goal Parser Interpretation/goal-parser-interpretation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def interpret(self, command: str) -> str: 3 | interpreted_str = "" 4 | i = 0 5 | 6 | while i < len(command): 7 | if command[i] == "G": 8 | interpreted_str += "G" 9 | i += 1 10 | elif command[i] == "(" and command[i+1] == ")": 11 | interpreted_str += "o" 12 | i += 2 13 | elif command[i] == "(" and command[i+1] == "a": 14 | interpreted_str += "al" 15 | i += 4 16 | 17 | return interpreted_str -------------------------------------------------------------------------------- /Group By/group-by: -------------------------------------------------------------------------------- 1 | declare global { 2 | interface Array { 3 | groupBy(fn: (item: T) => string): Record 4 | } 5 | } 6 | 7 | Array.prototype.groupBy = function(fn) { 8 | const groups = {} 9 | for (let element of this) { 10 | const key = fn(element) 11 | 12 | if (!(key in groups)) { 13 | groups[key] = [] 14 | } 15 | groups[key].push(element) 16 | } 17 | return groups 18 | } -------------------------------------------------------------------------------- /Happy Number/README.md: -------------------------------------------------------------------------------- 1 | # [Happy Number](https://leetcode.com/problems/happy-number/) 2 |

Write an algorithm to determine if a number n is happy.

3 | 4 |

A happy number is a number defined by the following process:

5 | 6 |
    7 |
  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • 8 |
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • 9 |
  • Those numbers for which this process ends in 1 are happy.
  • 10 |
11 | 12 |

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

13 | 14 |

 

15 |

Example 1:

16 | 17 |
Input: n = 19
18 | Output: true
19 | Explanation:
20 | 12 + 92 = 82
21 | 82 + 22 = 68
22 | 62 + 82 = 100
23 | 12 + 02 + 02 = 1
24 | 
25 | 26 |

Example 2:

27 | 28 |
Input: n = 2
29 | Output: false
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= n <= 231 - 1
  • 37 |
38 | -------------------------------------------------------------------------------- /Happy Number/happy-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | def sum_of_squares(num): 4 | sum_squares = 0 5 | while num > 0: 6 | digit = num % 10 7 | sum_squares += digit ** 2 8 | num //= 10 9 | return sum_squares 10 | 11 | seen = set() 12 | while n not in seen: 13 | seen.add(n) 14 | n = sum_of_squares(n) 15 | if n == 1: 16 | return True 17 | return False -------------------------------------------------------------------------------- /Implement Queue using Stacks/implement-queue-using-stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | 3 | def __init__(self): 4 | self.input_stack = [] # Stack to add elements 5 | self.output_stack = [] # Stack to remove elements 6 | 7 | def push(self, x: int) -> None: 8 | self.input_stack.append(x) 9 | 10 | def pop(self) -> int: 11 | self.peek() # Move elements from input to output stack if output stack is empty 12 | return self.output_stack.pop() 13 | 14 | def peek(self) -> int: 15 | if not self.output_stack: 16 | while self.input_stack: 17 | self.output_stack.append(self.input_stack.pop()) 18 | return self.output_stack[-1] 19 | 20 | def empty(self) -> bool: 21 | return not self.input_stack and not self.output_stack -------------------------------------------------------------------------------- /Implement Trie (Prefix Tree)/README.md: -------------------------------------------------------------------------------- 1 | # [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) 2 |

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

3 | 4 |

Implement the Trie class:

5 | 6 |
    7 |
  • Trie() Initializes the trie object.
  • 8 |
  • void insert(String word) Inserts the string word into the trie.
  • 9 |
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • 10 |
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
  • 11 |
12 | 13 |

 

14 |

Example 1:

15 | 16 |
Input
17 | ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
18 | [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
19 | Output
20 | [null, null, true, false, true, null, true]
21 | 
22 | Explanation
23 | Trie trie = new Trie();
24 | trie.insert("apple");
25 | trie.search("apple");   // return True
26 | trie.search("app");     // return False
27 | trie.startsWith("app"); // return True
28 | trie.insert("app");
29 | trie.search("app");     // return True
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= word.length, prefix.length <= 2000
  • 37 |
  • word and prefix consist only of lowercase English letters.
  • 38 |
  • At most 3 * 104 calls in total will be made to insert, search, and startsWith.
  • 39 |
40 | -------------------------------------------------------------------------------- /Implement Trie (Prefix Tree)/implement-trie-(prefix-tree).py: -------------------------------------------------------------------------------- 1 | class TrieNode: 2 | def __init__(self): 3 | self.children = {} 4 | self.is_end_of_word = False 5 | 6 | class Trie: 7 | def __init__(self): 8 | self.root = TrieNode() 9 | 10 | def insert(self, word: str) -> None: 11 | node = self.root 12 | for char in word: 13 | if char not in node.children: 14 | node.children[char] = TrieNode() 15 | node = node.children[char] 16 | node.is_end_of_word = True 17 | 18 | def search(self, word: str) -> bool: 19 | node = self.root 20 | for char in word: 21 | if char not in node.children: 22 | return False 23 | node = node.children[char] 24 | return node.is_end_of_word 25 | 26 | def startsWith(self, prefix: str) -> bool: 27 | node = self.root 28 | for char in prefix: 29 | if char not in node.children: 30 | return False 31 | node = node.children[char] 32 | return True -------------------------------------------------------------------------------- /JSON Deep Equal/README.md: -------------------------------------------------------------------------------- 1 | # [JSON Deep Equal](https://leetcode.com/problems/json-deep-equal/) 2 |

Given two objects o1 and o2, check if they are deeply equal.

3 | 4 |

For two objects to be deeply equal, they must contain the same keys, and the associated values must also be deeply equal. Two objects are also considered deeply equal if they pass the === equality check.

5 | 6 |

You may assume both objects are the output of JSON.parse. In other words, they are valid JSON.

7 | 8 |

Please solve it without using lodash's _.isEqual() function.

9 | 10 |

 

11 |

Example 1:

12 | 13 |
Input: o1 = {"x":1,"y":2}, o2 = {"x":1,"y":2}
14 | Output: true
15 | Explanation: The keys and values match exactly.
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: o1 = {"y":2,"x":1}, o2 = {"x":1,"y":2}
21 | Output: true
22 | Explanation: Although the keys are in a different order, they still match exactly.
23 | 
24 | 25 |

Example 3:

26 | 27 |
Input: o1 = {"x":null,"L":[1,2,3]}, o2 = {"x":null,"L":["1","2","3"]}
28 | Output: false
29 | Explanation: The array of numbers is different from the array of strings.
30 | 
31 | 32 |

Example 4:

33 | 34 |
Input: o1 = true, o2 = false
35 | Output: false
36 | Explanation: true !== false
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • 1 <= JSON.stringify(o1).length <= 105
  • 43 |
  • 1 <= JSON.stringify(o2).length <= 105
  • 44 |
  • maxNestingDepth <= 1000
  • 45 |
46 | -------------------------------------------------------------------------------- /JSON Deep Equal/json-deep-equal: -------------------------------------------------------------------------------- 1 | const areDeeplyEqual = (o1: any, o2: any): boolean => { 2 | if ((typeof o1) !== (typeof o2)) { 3 | return false 4 | } 5 | switch (typeof o1) { 6 | case "string": case "boolean": case "number": return o1 === o2 7 | } 8 | if ((o1 ?? o2) === null) { 9 | return o1 === o2 10 | } 11 | if (Array.isArray(o1) || Array.isArray(o2)) { 12 | if (!Array.isArray(o1) || !Array.isArray(o2) || o1.length !== o2.length) { 13 | return false 14 | } 15 | return o1.every((v: any, k: number) => areDeeplyEqual(v, o2[k])) 16 | } 17 | return Array.from(new Set([...Object.keys(o1), ...Object.keys(o2)])).every(k => areDeeplyEqual(o1[k], o2[k])) 18 | } -------------------------------------------------------------------------------- /Largest Color Value in a Directed Graph/largest-color-value-in-a-directed-graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPathValue(self, colors: str, edges: List[List[int]]) -> int: 3 | n = len(colors) 4 | graph = collections.defaultdict(list) 5 | indegree = [0] * len(colors) 6 | for u, v in edges: 7 | graph[v].append(u) 8 | indegree[u] += 1 9 | count = [collections.defaultdict(int) for _ in range(n)] 10 | q = collections.deque(filter(lambda i: not indegree[i], range(n))) 11 | seen = 0 12 | ans = 0 13 | while q: 14 | curr = q.popleft() 15 | count[curr][colors[curr]] += 1 16 | ans = max(ans, count[curr][colors[curr]]) 17 | seen += 1 18 | for v in graph[curr]: 19 | for c in count[curr]: 20 | count[v][c] = max(count[v][c], count[curr][c]) 21 | indegree[v] -= 1 22 | if indegree[v] == 0: 23 | q.append(v) 24 | if seen < n: 25 | return -1 26 | return ans -------------------------------------------------------------------------------- /Linked List Cycle II/linked-list-cycle-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | if head is None or head.next is None: 4 | return None 5 | 6 | slow = head 7 | fast = head 8 | 9 | while fast is not None and fast.next is not None: 10 | slow = slow.next 11 | fast = fast.next.next 12 | 13 | # If there is a cycle 14 | if slow == fast: 15 | # Move slow pointer back to head 16 | slow = head 17 | 18 | # Find the point where cycle starts 19 | while slow != fast: 20 | slow = slow.next 21 | fast = fast.next 22 | 23 | return slow 24 | 25 | # No cycle found 26 | return None -------------------------------------------------------------------------------- /Linked List Random Node/README.md: -------------------------------------------------------------------------------- 1 | # [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) 2 |

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

3 | 4 |

Implement the Solution class:

5 | 6 |
    7 |
  • Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
  • 8 |
  • int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
  • 9 |
10 | 11 |

 

12 |

Example 1:

13 | 14 |
Input
15 | ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
16 | [[[1, 2, 3]], [], [], [], [], []]
17 | Output
18 | [null, 1, 3, 2, 2, 3]
19 | 
20 | Explanation
21 | Solution solution = new Solution([1, 2, 3]);
22 | solution.getRandom(); // return 1
23 | solution.getRandom(); // return 3
24 | solution.getRandom(); // return 2
25 | solution.getRandom(); // return 2
26 | solution.getRandom(); // return 3
27 | // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • The number of nodes in the linked list will be in the range [1, 104].
  • 35 |
  • -104 <= Node.val <= 104
  • 36 |
  • At most 104 calls will be made to getRandom.
  • 37 |
38 | 39 |

 

40 |

Follow up:

41 | 42 |
    43 |
  • What if the linked list is extremely large and its length is unknown to you?
  • 44 |
  • Could you solve this efficiently without using extra space?
  • 45 |
46 | -------------------------------------------------------------------------------- /Linked List Random Node/linked-list-random-node.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | 3 | def __init__(self, head): 4 | """ 5 | :type head: Optional[ListNode] 6 | """ 7 | self.head = head 8 | 9 | def getRandom(self): 10 | """ 11 | :rtype: int 12 | """ 13 | count = 0 14 | result = None 15 | curr = self.head 16 | 17 | while curr: 18 | count += 1 19 | # generate a random number between 1 and the count 20 | # if the random number is 1, update the result with the current node's value 21 | if random.randint(1, count) == 1: 22 | result = curr.val 23 | curr = curr.next 24 | 25 | return result -------------------------------------------------------------------------------- /Longest Cycle in a Graph/README.md: -------------------------------------------------------------------------------- 1 | # [Longest Cycle in a Graph](https://leetcode.com/problems/longest-cycle-in-a-graph/) 2 |

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

3 | 4 |

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.

5 | 6 |

Return the length of the longest cycle in the graph. If no cycle exists, return -1.

7 | 8 |

A cycle is a path that starts and ends at the same node.

9 | 10 |

 

11 |

Example 1:

12 | 13 |
Input: edges = [3,3,4,2,3]
14 | Output: 3
15 | Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
16 | The length of this cycle is 3, so 3 is returned.
17 | 
18 | 19 |

Example 2:

20 | 21 |
Input: edges = [2,-1,3,1]
22 | Output: -1
23 | Explanation: There are no cycles in this graph.
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • n == edges.length
  • 31 |
  • 2 <= n <= 105
  • 32 |
  • -1 <= edges[i] < n
  • 33 |
  • edges[i] != i
  • 34 |
35 | -------------------------------------------------------------------------------- /Longest Cycle in a Graph/longest-cycle-in-a-graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCycle(self, edges: List[int]) -> int: 3 | longest_cycle_len = -1 4 | time_step = 1 5 | node_visited_at_time = [0] * len(edges) 6 | 7 | for current_node in range(len(edges)): 8 | if node_visited_at_time[current_node] > 0: 9 | continue 10 | start_time = time_step 11 | u = current_node 12 | while u != -1 and node_visited_at_time[u] == 0: 13 | node_visited_at_time[u] = time_step 14 | time_step += 1 15 | u = edges[u] 16 | if u != -1 and node_visited_at_time[u] >= start_time: 17 | longest_cycle_len = max(longest_cycle_len, time_step - node_visited_at_time[u]) 18 | 19 | return longest_cycle_len -------------------------------------------------------------------------------- /Longest Palindromic Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # [Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) 2 |

Given a string s, find the longest palindromic subsequence's length in s.

3 | 4 |

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: s = "bbbab"
10 | Output: 4
11 | Explanation: One possible longest palindromic subsequence is "bbbb".
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: s = "cbbd"
17 | Output: 2
18 | Explanation: One possible longest palindromic subsequence is "bb".
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= s.length <= 1000
  • 26 |
  • s consists only of lowercase English letters.
  • 27 |
28 | -------------------------------------------------------------------------------- /Longest Palindromic Subsequence/longest-palindromic-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindromeSubseq(self, s: str) -> int: 3 | n = len(s) 4 | dp = [0] * n 5 | for i in range(n-1, -1, -1): 6 | newdp = [0] * n 7 | newdp[i] = 1 8 | for j in range(i+1, n): 9 | if s[i] == s[j]: 10 | newdp[j] = 2 + dp[j-1] 11 | else: 12 | newdp[j] = max(dp[j], newdp[j-1]) 13 | dp = newdp 14 | return dp[-1] -------------------------------------------------------------------------------- /Longest Palindromic Substring/README.md: -------------------------------------------------------------------------------- 1 | # [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) 2 |

Given a string s, return the longest

in s.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: s = "babad"
 8 | Output: "bab"
 9 | Explanation: "aba" is also a valid answer.
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: s = "cbbd"
15 | Output: "bb"
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 1 <= s.length <= 1000
  • 23 |
  • s consist of only digits and English letters.
  • 24 |
25 | -------------------------------------------------------------------------------- /Longest Palindromic Substring/longest-palindromic-substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> str: 3 | n = len(s) 4 | dp = [[False] * n for _ in range(n)] 5 | ans = "" 6 | # Every substring of length 1 is a palindrome 7 | for i in range(n): 8 | dp[i][i] = True 9 | ans = s[i] 10 | 11 | # Check for substrings of length 2 12 | for i in range(n-1): 13 | if s[i] == s[i+1]: 14 | dp[i][i+1] = True 15 | ans = s[i:i+2] 16 | 17 | # Check for substrings of length greater than 2 18 | for l in range(3, n+1): 19 | for i in range(n-l+1): 20 | j = i+l-1 21 | if s[i] == s[j] and dp[i+1][j-1]: 22 | dp[i][j] = True 23 | ans = s[i:j+1] 24 | 25 | return ans -------------------------------------------------------------------------------- /Maximum Depth of Binary Tree/README.md: -------------------------------------------------------------------------------- 1 | # [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) 2 |

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

3 | 4 |

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

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: root = [3,9,20,null,null,15,7]
10 | Output: 3
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: root = [1,null,2]
16 | Output: 2
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • The number of nodes in the tree is in the range [0, 104].
  • 24 |
  • -100 <= Node.val <= 100
  • 25 |
26 | -------------------------------------------------------------------------------- /Maximum Depth of Binary Tree/maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, root: Optional[TreeNode]) -> int: 3 | # Base case: if the root is None, the depth is 0 4 | if root is None: 5 | return 0 6 | 7 | # Recursive case: calculate the depth of the left and right subtrees 8 | left_depth = self.maxDepth(root.left) 9 | right_depth = self.maxDepth(root.right) 10 | 11 | # Return the maximum depth of the two subtrees plus one for the root node 12 | return max(left_depth, right_depth) + 1 -------------------------------------------------------------------------------- /Maximum Depth of N-ary Tree/README.md: -------------------------------------------------------------------------------- 1 | # [Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/) 2 |

Given a n-ary tree, find its maximum depth.

3 | 4 |

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

5 | 6 |

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

7 | 8 |

 

9 |

Example 1:

10 | 11 |

12 | 13 |
Input: root = [1,null,3,2,4,null,5,6]
14 | Output: 3
15 | 
16 | 17 |

Example 2:

18 | 19 |

20 | 21 |
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
22 | Output: 5
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The total number of nodes is in the range [0, 104].
  • 30 |
  • The depth of the n-ary tree is less than or equal to 1000.
  • 31 |
32 | -------------------------------------------------------------------------------- /Maximum Depth of N-ary Tree/maximum-depth-of-n-ary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a Node. 2 | # class Node: 3 | # def __init__(self, val=None, children=None): 4 | # self.val = val 5 | # self.children = children 6 | 7 | class Solution: 8 | def maxDepth(self, root: 'Node') -> int: 9 | if not root: 10 | return 0 11 | 12 | max_depth = 0 13 | for child in root.children: 14 | depth = self.maxDepth(child) 15 | max_depth = max(max_depth, depth) 16 | 17 | return max_depth + 1 -------------------------------------------------------------------------------- /Maximum Subsequence Score/maximum-subsequence-score.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maxScore(vector& nums1, vector& nums2, int k) { 4 | vector> nums; 5 | int n = nums1.size(); 6 | for(int i=0; i maxk(n,0ll); 11 | long long ans = 0, sum = nums[n-1][1]; 12 | multiset st; 13 | st.insert(nums[n-1][1]); 14 | maxk[n-1] = nums[n-1][1]; 15 | for(int i=n-2; i>=0; --i){ 16 | int curr = nums[i][1]; 17 | if(st.size() < k-1){ 18 | st.insert(curr); 19 | sum += curr; 20 | } 21 | else{ 22 | if(*st.begin()<=curr){ 23 | sum += curr; 24 | sum -= *st.begin(); 25 | st.erase(st.begin()); 26 | st.insert(curr); 27 | } 28 | } 29 | maxk[i] = sum; 30 | } 31 | maxk.push_back(0); 32 | for(int i=0; i<=n-k; ++i){ 33 | if(k == 1) 34 | ans = max(ans,((long long)nums[i][1] * nums[i][0])); 35 | else 36 | ans = max(ans,(maxk[i+1]+nums[i][1])*nums[i][0]); 37 | } 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /Maximum Value of K Coins From Piles/README.md: -------------------------------------------------------------------------------- 1 | # [Maximum Value of K Coins From Piles](https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/) 2 |

There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.

3 | 4 |

In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.

5 | 6 |

Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: piles = [[1,100,3],[7,8,9]], k = 2
12 | Output: 101
13 | Explanation:
14 | The above diagram shows the different ways we can choose k coins.
15 | The maximum total we can obtain is 101.
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7
21 | Output: 706
22 | Explanation:
23 | The maximum total can be obtained if we choose all coins from the last pile.
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • n == piles.length
  • 31 |
  • 1 <= n <= 1000
  • 32 |
  • 1 <= piles[i][j] <= 105
  • 33 |
  • 1 <= k <= sum(piles[i].length) <= 2000
  • 34 |
35 | -------------------------------------------------------------------------------- /Maximum Value of K Coins From Piles/maximum-value-of-k-coins-from-piles.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxValueOfCoins(self, piles, k): 3 | """ 4 | :type piles: List[List[int]] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | dp = [[0] * (k + 1) for _ in range(len(piles) + 1)] 9 | for i in range(1, len(piles) + 1): 10 | for j in range(1, k + 1): 11 | cur = 0 12 | for x in range(min(len(piles[i - 1]), j)): 13 | cur += piles[i - 1][x] 14 | dp[i][j] = max(dp[i][j], cur + dp[i - 1][j - x - 1]) 15 | dp[i][j] = max(dp[i][j], dp[i - 1][j]) 16 | return dp[len(piles)][k] -------------------------------------------------------------------------------- /Median of Two Sorted Arrays/README.md: -------------------------------------------------------------------------------- 1 | # [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) 2 |

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

3 | 4 |

The overall run time complexity should be O(log (m+n)).

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: nums1 = [1,3], nums2 = [2]
10 | Output: 2.00000
11 | Explanation: merged array = [1,2,3] and median is 2.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: nums1 = [1,2], nums2 = [3,4]
17 | Output: 2.50000
18 | Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • nums1.length == m
  • 26 |
  • nums2.length == n
  • 27 |
  • 0 <= m <= 1000
  • 28 |
  • 0 <= n <= 1000
  • 29 |
  • 1 <= m + n <= 2000
  • 30 |
  • -106 <= nums1[i], nums2[i] <= 106
  • 31 |
32 | -------------------------------------------------------------------------------- /Median of Two Sorted Arrays/median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 3 | m, n = len(nums1), len(nums2) 4 | if m > n: 5 | nums1, nums2, m, n = nums2, nums1, n, m 6 | imin, imax, half_len = 0, m, (m + n + 1) // 2 7 | while imin <= imax: 8 | i = (imin + imax) // 2 9 | j = half_len - i 10 | if i < m and nums2[j-1] > nums1[i]: 11 | imin = i + 1 12 | elif i > 0 and nums1[i-1] > nums2[j]: 13 | imax = i - 1 14 | else: 15 | if i == 0: max_of_left = nums2[j-1] 16 | elif j == 0: max_of_left = nums1[i-1] 17 | else: max_of_left = max(nums1[i-1], nums2[j-1]) 18 | 19 | if (m + n) % 2 == 1: 20 | return max_of_left 21 | 22 | if i == m: min_of_right = nums2[j] 23 | elif j == n: min_of_right = nums1[i] 24 | else: min_of_right = min(nums1[i], nums2[j]) 25 | 26 | return (max_of_left + min_of_right) / 2.0 -------------------------------------------------------------------------------- /Memoize/memoize: -------------------------------------------------------------------------------- 1 | type Fn = (...params: any) => any 2 | 3 | function memoize(fn: Fn): Fn { 4 | const store : { 5 | [key: string | number] : number 6 | } = {}; 7 | 8 | return function(...args) { 9 | const key = args.join(); 10 | if (store[key] !== undefined) { 11 | return store[key]; 12 | } 13 | return store[key] = fn(...args); 14 | } 15 | } -------------------------------------------------------------------------------- /Merge Strings Alternately/README.md: -------------------------------------------------------------------------------- 1 | # [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) 2 |

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

3 | 4 |

Return the merged string.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: word1 = "abc", word2 = "pqr"
10 | Output: "apbqcr"
11 | Explanation: The merged string will be merged as so:
12 | word1:  a   b   c
13 | word2:    p   q   r
14 | merged: a p b q c r
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: word1 = "ab", word2 = "pqrs"
20 | Output: "apbqrs"
21 | Explanation: Notice that as word2 is longer, "rs" is appended to the end.
22 | word1:  a   b 
23 | word2:    p   q   r   s
24 | merged: a p b q   r   s
25 | 
26 | 27 |

Example 3:

28 | 29 |
Input: word1 = "abcd", word2 = "pq"
30 | Output: "apbqcd"
31 | Explanation: Notice that as word1 is longer, "cd" is appended to the end.
32 | word1:  a   b   c   d
33 | word2:    p   q 
34 | merged: a p b q c   d
35 | 
36 | 37 |

 

38 |

Constraints:

39 | 40 |
    41 |
  • 1 <= word1.length, word2.length <= 100
  • 42 |
  • word1 and word2 consist of lowercase English letters.
  • 43 |
-------------------------------------------------------------------------------- /Merge Strings Alternately/merge-strings-alternately.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | class Solution: 3 | def mergeAlternately(self, word1: str, word2: str) -> str: 4 | return "".join(a+b for a, b in itertools.zip_longest(word1, word2, fillvalue="")) -------------------------------------------------------------------------------- /Merge k Sorted Lists/README.md: -------------------------------------------------------------------------------- 1 | # [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) 2 |

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

3 | 4 |

Merge all the linked-lists into one sorted linked-list and return it.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: lists = [[1,4,5],[1,3,4],[2,6]]
10 | Output: [1,1,2,3,4,4,5,6]
11 | Explanation: The linked-lists are:
12 | [
13 |   1->4->5,
14 |   1->3->4,
15 |   2->6
16 | ]
17 | merging them into one sorted list:
18 | 1->1->2->3->4->4->5->6
19 | 
20 | 21 |

Example 2:

22 | 23 |
Input: lists = []
24 | Output: []
25 | 
26 | 27 |

Example 3:

28 | 29 |
Input: lists = [[]]
30 | Output: []
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • k == lists.length
  • 38 |
  • 0 <= k <= 104
  • 39 |
  • 0 <= lists[i].length <= 500
  • 40 |
  • -104 <= lists[i][j] <= 104
  • 41 |
  • lists[i] is sorted in ascending order.
  • 42 |
  • The sum of lists[i].length will not exceed 104.
  • 43 |
44 | -------------------------------------------------------------------------------- /Merge k Sorted Lists/merge-k-sorted-lists.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from typing import List, Optional 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, val=0, next=None): 7 | # self.val = val 8 | # self.next = next 9 | 10 | class Solution: 11 | def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: 12 | # Create a min-heap to store the heads of all k linked lists 13 | min_heap = [] 14 | 15 | # Add the head of each linked list to the min-heap 16 | for i in range(len(lists)): 17 | if lists[i]: 18 | heappush(min_heap, (lists[i].val, i, lists[i])) 19 | 20 | # Create a dummy node to serve as the head of the merged linked list 21 | dummy = ListNode(0) 22 | curr = dummy 23 | 24 | # While there are still nodes in the min-heap 25 | while min_heap: 26 | # Pop the node with the smallest value from the min-heap 27 | val, i, node = heappop(min_heap) 28 | 29 | # Add the popped node to the merged linked list 30 | curr.next = node 31 | curr = curr.next 32 | 33 | # If the popped node has a next node, add it to the min-heap 34 | if node.next: 35 | heappush(min_heap, (node.next.val, i, node.next)) 36 | 37 | return dummy.next -------------------------------------------------------------------------------- /Minimize Maximum of Array/README.md: -------------------------------------------------------------------------------- 1 | # [Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array/) 2 |

You are given a 0-indexed array nums comprising of n non-negative integers.

3 | 4 |

In one operation, you must:

5 | 6 |
    7 |
  • Choose an integer i such that 1 <= i < n and nums[i] > 0.
  • 8 |
  • Decrease nums[i] by 1.
  • 9 |
  • Increase nums[i - 1] by 1.
  • 10 |
11 | 12 |

Return the minimum possible value of the maximum integer of nums after performing any number of operations.

13 | 14 |

 

15 |

Example 1:

16 | 17 |
Input: nums = [3,7,1,6]
18 | Output: 5
19 | Explanation:
20 | One set of optimal operations is as follows:
21 | 1. Choose i = 1, and nums becomes [4,6,1,6].
22 | 2. Choose i = 3, and nums becomes [4,6,2,5].
23 | 3. Choose i = 1, and nums becomes [5,5,2,5].
24 | The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
25 | Therefore, we return 5.
26 | 
27 | 28 |

Example 2:

29 | 30 |
Input: nums = [10,1]
31 | Output: 10
32 | Explanation:
33 | It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
34 | 
35 | 36 |

 

37 |

Constraints:

38 | 39 |
    40 |
  • n == nums.length
  • 41 |
  • 2 <= n <= 105
  • 42 |
  • 0 <= nums[i] <= 109
  • 43 |
44 | -------------------------------------------------------------------------------- /Minimize Maximum of Array/minimize-maximum-of-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimizeArrayValue(self, nums): 3 | total_sum = 0 4 | result = 0 5 | for index in range(len(nums)): 6 | total_sum += nums[index] 7 | result = max(result, (total_sum + index) // (index + 1)) 8 | return int(result) -------------------------------------------------------------------------------- /Minimum Number of Removals to Make Mountain Array/README.md: -------------------------------------------------------------------------------- 1 | # [Minimum Number of Removals to Make Mountain Array](https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/) 2 |

You may recall that an array arr is a mountain array if and only if:

3 | 4 |
    5 |
  • arr.length >= 3
  • 6 |
  • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: 7 |
      8 |
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • 9 |
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
    • 10 |
    11 |
  • 12 |
13 | 14 |

Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array.

15 | 16 |

 

17 |

Example 1:

18 | 19 |
Input: nums = [1,3,1]
20 | Output: 0
21 | Explanation: The array itself is a mountain array so we do not need to remove any elements.
22 | 
23 | 24 |

Example 2:

25 | 26 |
Input: nums = [2,1,1,5,6,2,3,1]
27 | Output: 3
28 | Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 3 <= nums.length <= 1000
  • 36 |
  • 1 <= nums[i] <= 109
  • 37 |
  • It is guaranteed that you can make a mountain array out of nums.
  • 38 |
39 | -------------------------------------------------------------------------------- /Minimum Number of Removals to Make Mountain Array/minimum-number-of-removals-to-make-mountain-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def minimumMountainRemovals(self, nums: List[int]) -> int: 5 | n = len(nums) 6 | left = [1] * n 7 | right = [1] * n 8 | 9 | for i in range(n): 10 | for j in range(i): 11 | if nums[i] > nums[j]: 12 | left[i] = max(left[i], left[j] + 1) 13 | 14 | for i in range(n - 1, -1, -1): 15 | for j in range(i + 1, n): 16 | if nums[i] > nums[j]: 17 | right[i] = max(right[i], right[j] + 1) 18 | 19 | res = 0 20 | for i in range(1, n - 1): 21 | if left[i] > 1 and right[i] > 1: 22 | res = max(res, left[i] + right[i] - 1) 23 | 24 | return n - res -------------------------------------------------------------------------------- /Minimum Path Sum/README.md: -------------------------------------------------------------------------------- 1 | # [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) 2 |

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

3 | 4 |

Note: You can only move either down or right at any point in time.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
10 | Output: 7
11 | Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: grid = [[1,2,3],[4,5,6]]
17 | Output: 12
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • m == grid.length
  • 25 |
  • n == grid[i].length
  • 26 |
  • 1 <= m, n <= 200
  • 27 |
  • 0 <= grid[i][j] <= 100
  • 28 |
29 | -------------------------------------------------------------------------------- /Minimum Path Sum/minimum-path-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPathSum(self, grid: List[List[int]]) -> int: 3 | n=len(grid) 4 | m=len(grid[0]) 5 | for i in range(n): 6 | for j in range(m): 7 | if i==0: 8 | if j!=0: 9 | grid[i][j]+=grid[i][j-1] 10 | elif j==0: 11 | if i!=0: 12 | grid[i][j]+=grid[i-1][j] 13 | else: 14 | grid[i][j]+=min(grid[i-1][j],grid[i][j-1]) 15 | return grid[n-1][m-1] -------------------------------------------------------------------------------- /Minimum Score of a Path Between Two Cities/minimum-score-of-a-path-between-two-cities.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minScore(self, n: int, roads: List[List[int]]) -> int: 3 | graph = defaultdict(dict) 4 | for u, v, w in roads: 5 | graph[u][v] = graph[v][u] = w 6 | min_score = float('inf') 7 | visited = set() 8 | queue = deque([1]) 9 | while queue: 10 | node = queue.popleft() 11 | for adj, score in graph[node].items(): 12 | if adj not in visited: 13 | queue.append(adj) 14 | visited.add(adj) 15 | min_score = min(min_score, score) 16 | return min_score -------------------------------------------------------------------------------- /Minimum Time to Complete Trips/README.md: -------------------------------------------------------------------------------- 1 | # [Minimum Time to Complete Trips](https://leetcode.com/problems/minimum-time-to-complete-trips/) 2 |

You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.

3 | 4 |

Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.

5 | 6 |

You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: time = [1,2,3], totalTrips = 5
12 | Output: 3
13 | Explanation:
14 | - At time t = 1, the number of trips completed by each bus are [1,0,0]. 
15 |   The total number of trips completed is 1 + 0 + 0 = 1.
16 | - At time t = 2, the number of trips completed by each bus are [2,1,0]. 
17 |   The total number of trips completed is 2 + 1 + 0 = 3.
18 | - At time t = 3, the number of trips completed by each bus are [3,1,1]. 
19 |   The total number of trips completed is 3 + 1 + 1 = 5.
20 | So the minimum time needed for all buses to complete at least 5 trips is 3.
21 | 
22 | 23 |

Example 2:

24 | 25 |
Input: time = [2], totalTrips = 1
26 | Output: 2
27 | Explanation:
28 | There is only one bus, and it will complete its first trip at t = 2.
29 | So the minimum time needed to complete 1 trip is 2.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= time.length <= 105
  • 37 |
  • 1 <= time[i], totalTrips <= 107
  • 38 |
39 | -------------------------------------------------------------------------------- /Minimum Time to Complete Trips/minimum-time-to-complete-trips.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def minimumTime(self, time: List[int], totalTrips: int) -> int: 5 | left, right = 0, max(time) * totalTrips # initialize left and right pointers 6 | while left < right: 7 | mid = (left + right) // 2 # calculate midpoint 8 | trips = 0 9 | for t in time: 10 | trips += mid // t # calculate number of trips for each bus at time 'mid' 11 | if trips >= totalTrips: 12 | break # stop the loop if the total number of trips is reached 13 | if trips >= totalTrips: 14 | right = mid # update right pointer if totalTrips is reached 15 | else: 16 | left = mid + 1 # update left pointer if totalTrips is not reached 17 | return left -------------------------------------------------------------------------------- /Move Zeroes/README.md: -------------------------------------------------------------------------------- 1 | # [Move Zeroes](https://leetcode.com/problems/move-zeroes/) 2 |

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

3 | 4 |

Note that you must do this in-place without making a copy of the array.

5 | 6 |

 

7 |

Example 1:

8 |
Input: nums = [0,1,0,3,12]
 9 | Output: [1,3,12,0,0]
10 | 

Example 2:

11 |
Input: nums = [0]
12 | Output: [0]
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= nums.length <= 104
  • 19 |
  • -231 <= nums[i] <= 231 - 1
  • 20 |
21 | 22 |

 

23 | Follow up: Could you minimize the total number of operations done? -------------------------------------------------------------------------------- /Move Zeroes/move-zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | left = 0 7 | right = 0 8 | 9 | while right < len(nums): 10 | if nums[right] != 0: 11 | nums[left], nums[right] = nums[right], nums[left] 12 | left += 1 13 | right += 1 -------------------------------------------------------------------------------- /N-ary Tree Preorder Traversal/README.md: -------------------------------------------------------------------------------- 1 | # [N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/) 2 |

Given the root of an n-ary tree, return the preorder traversal of its nodes' values.

3 | 4 |

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

5 | 6 |

 

7 |

Example 1:

8 | 9 |

10 | 11 |
Input: root = [1,null,3,2,4,null,5,6]
12 | Output: [1,3,5,6,2,4]
13 | 
14 | 15 |

Example 2:

16 | 17 |

18 | 19 |
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
20 | Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • The number of nodes in the tree is in the range [0, 104].
  • 28 |
  • 0 <= Node.val <= 104
  • 29 |
  • The height of the n-ary tree is less than or equal to 1000.
  • 30 |
31 | 32 |

 

33 |

Follow up: Recursive solution is trivial, could you do it iteratively?

34 | -------------------------------------------------------------------------------- /N-ary Tree Preorder Traversal/n-ary-tree-preorder-traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def preorder(self, root: 'Node') -> List[int]: 3 | ans = [] 4 | def helper(curr=root): 5 | nonlocal ans 6 | if curr: 7 | ans.append(curr.val) 8 | for i in curr.children: 9 | helper(i) 10 | helper() 11 | return ans -------------------------------------------------------------------------------- /Nested Array Generator/README.md: -------------------------------------------------------------------------------- 1 | # [Nested Array Generator](https://leetcode.com/problems/nested-array-generator/) 2 |

Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal.

3 | 4 |

multi-dimensional array is a recursive data structure that contains both integers and other multi-dimensional arrays.

5 | 6 |

inorder traversal iterates over each array from left to right, yielding any integers it encounters or applying inorder traversal to any arrays it encounters.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: arr = [[[6]],[1,3],[]]
12 | Output: [6,1,3]
13 | Explanation:
14 | const generator = inorderTraversal(arr);
15 | generator.next().value; // 6
16 | generator.next().value; // 1
17 | generator.next().value; // 3
18 | generator.next().done; // true
19 | 
20 | 21 |

Example 2:

22 | 23 |
Input: arr = []
24 | Output: []
25 | Explanation: There are no integers so the generator doesn't yield anything.
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 0 <= arr.flat().length <= 105
  • 33 |
  • 0 <= arr.flat()[i] <= 105
  • 34 |
  • maxNestingDepth <= 105
  • 35 |
36 | 37 |

 

38 | Can you solve this without creating a new flattened version of the array? -------------------------------------------------------------------------------- /Nested Array Generator/nested-array-generator: -------------------------------------------------------------------------------- 1 | type MultidimensionalArray = (MultidimensionalArray | number)[] 2 | 3 | function* inorderTraversal(arr: MultidimensionalArray): Generator { 4 | for (const v of arr) { 5 | if (Array.isArray(v)) yield* inorderTraversal(v); 6 | else yield v; 7 | } 8 | }; 9 | 10 | /** 11 | * const gen = inorderTraversal([1, [2, 3]]); 12 | * gen.next().value; // 1 13 | * gen.next().value; // 2 14 | * gen.next().value; // 3 15 | */ -------------------------------------------------------------------------------- /Next Greater Element I/next-greater-element-i.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number[]} nums2 4 | * @return {number[]} 5 | */ 6 | var nextGreaterElement = function(nums1, nums2) { 7 | let result = []; 8 | for(let num of nums1) 9 | { 10 | let flag=-1; 11 | for(let i=nums2.indexOf(num)+1;inum) 14 | { 15 | flag=nums2[i]; 16 | break; 17 | } 18 | } 19 | result.push(flag); 20 | } 21 | return result; 22 | }; -------------------------------------------------------------------------------- /Number of 1 Bits/number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | # Initialize count to zero 4 | count = 0 5 | 6 | # Loop through all the bits in the binary representation of n 7 | while n > 0: 8 | # If the rightmost bit is 1, increment count 9 | if n & 1 == 1: 10 | count += 1 11 | # Shift n one bit to the right 12 | n = n >> 1 13 | 14 | # Return the count of '1' bits 15 | return count -------------------------------------------------------------------------------- /Number of Ways to Form a Target String Given a Dictionary/number-of-ways-to-form-a-target-string-given-a-dictionary.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numWays(self, words, target): 3 | """ 4 | :type words: List[str] 5 | :type target: str 6 | :rtype: int 7 | """ 8 | mod = 10**9 + 7 9 | m, n = len(words), len(words[0]) 10 | 11 | # frequency array for each character in each column 12 | freq = [[0] * 26 for _ in range(n)] 13 | for j in range(n): 14 | for i in range(m): 15 | freq[j][ord(words[i][j]) - ord('a')] += 1 16 | 17 | # dp array to store the number of ways to form the prefix of target 18 | dp = [1] + [0] * len(target) 19 | 20 | # fill dp array from left to right 21 | for j in range(n): 22 | for i in range(len(target), 0, -1): 23 | dp[i] += dp[i-1] * freq[j][ord(target[i-1]) - ord('a')] 24 | dp[i] %= mod 25 | 26 | return dp[len(target)] -------------------------------------------------------------------------------- /Number of Zero-Filled Subarrays/README.md: -------------------------------------------------------------------------------- 1 | # [Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/) 2 |

Given an integer array nums, return the number of subarrays filled with 0.

3 | 4 |

A subarray is a contiguous non-empty sequence of elements within an array.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: nums = [1,3,0,0,2,0,0,4]
10 | Output: 6
11 | Explanation: 
12 | There are 4 occurrences of [0] as a subarray.
13 | There are 2 occurrences of [0,0] as a subarray.
14 | There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
15 | 16 |

Example 2:

17 | 18 |
Input: nums = [0,0,0,2,0,0]
19 | Output: 9
20 | Explanation:
21 | There are 5 occurrences of [0] as a subarray.
22 | There are 3 occurrences of [0,0] as a subarray.
23 | There is 1 occurrence of [0,0,0] as a subarray.
24 | There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
25 | 
26 | 27 |

Example 3:

28 | 29 |
Input: nums = [2,10,2019]
30 | Output: 0
31 | Explanation: There is no subarray filled with 0. Therefore, we return 0.
32 | 
33 | 34 |

 

35 |

Constraints:

36 | 37 |
    38 |
  • 1 <= nums.length <= 105
  • 39 |
  • -109 <= nums[i] <= 109
  • 40 |
41 | -------------------------------------------------------------------------------- /Number of Zero-Filled Subarrays/number-of-zero-filled-subarrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def zeroFilledSubarray(self, nums: List[int]) -> int: 4 | count = 0 5 | zero_count = 0 6 | for num in nums: 7 | if num == 0: 8 | zero_count += 1 9 | else: 10 | count += (zero_count * (zero_count + 1)) // 2 11 | zero_count = 0 12 | count += (zero_count * (zero_count + 1)) // 2 13 | return count -------------------------------------------------------------------------------- /Optimal Partition of String/README.md: -------------------------------------------------------------------------------- 1 | # [Optimal Partition of String](https://leetcode.com/problems/optimal-partition-of-string/) 2 |

Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.

3 | 4 |

Return the minimum number of substrings in such a partition.

5 | 6 |

Note that each character should belong to exactly one substring in a partition.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: s = "abacaba"
12 | Output: 4
13 | Explanation:
14 | Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
15 | It can be shown that 4 is the minimum number of substrings needed.
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: s = "ssssss"
21 | Output: 6
22 | Explanation:
23 | The only valid partition is ("s","s","s","s","s","s").
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 1 <= s.length <= 105
  • 31 |
  • s consists of only English lowercase letters.
  • 32 |
33 | -------------------------------------------------------------------------------- /Optimal Partition of String/optimal-partition-of-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def partitionString(self, s): 3 | idx = 0 4 | count = 0 5 | mp = {} # use a dictionary instead of a HashMap 6 | while idx < len(s): 7 | if s[idx] in mp: # if current character has already appeared in current substring 8 | count += 1 # increment count 9 | mp.clear() # clear dictionary to start a new substring 10 | mp[s[idx]] = True # mark current character as seen 11 | idx += 1 # move to next character 12 | return count + 1 # return number of substrings (add 1 because we need to count the last substring as well) -------------------------------------------------------------------------------- /Palindrome Linked List/README.md: -------------------------------------------------------------------------------- 1 | # [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) 2 |

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

or false otherwise.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: head = [1,2,2,1]
 8 | Output: true
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: head = [1,2]
14 | Output: false
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • The number of nodes in the list is in the range [1, 105].
  • 22 |
  • 0 <= Node.val <= 9
  • 23 |
24 | 25 |

 

26 | Follow up: Could you do it in O(n) time and O(1) space? -------------------------------------------------------------------------------- /Palindrome Linked List/palindrome-linked-list.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | 9 | 10 | bool isPalindrome(struct ListNode* head){ 11 | if(head==NULL){ 12 | return true; 13 | } 14 | struct ListNode* p1=head; 15 | struct ListNode* p2=head->next; 16 | while(p2 && p2->next){ 17 | p1 = p1->next; 18 | p2 = p2->next->next; 19 | } 20 | 21 | struct ListNode *prev, *curr, *n, *h2; 22 | prev = NULL; 23 | curr = p1->next; 24 | h2 = curr; 25 | while(curr){ 26 | n = curr->next; 27 | curr->next = prev; 28 | prev = curr; 29 | curr = n; 30 | } 31 | p2 = head; 32 | p1 = prev; 33 | while(p1){ 34 | if(p1->val!=p2->val){ 35 | return false; 36 | } 37 | p1 = p1->next; 38 | p2 = p2->next; 39 | } 40 | 41 | return true; 42 | 43 | } -------------------------------------------------------------------------------- /Problems/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdityaSeth777/LeetCode-Adi/c801e3ebb7951579aae87f7cf61f60ad28f3b22e/Problems/Readme.md -------------------------------------------------------------------------------- /Promise Pool/promise-pool: -------------------------------------------------------------------------------- 1 | type F = () => Promise 2 | 3 | const promisePool = (fn: F[], n: number): Promise => { 4 | let next = () => fn[n++]?.().then(next) 5 | return Promise.all(fn.slice(0, n).map(f => f().then(next))) 6 | } -------------------------------------------------------------------------------- /Promise Time Limit/promise-time-limit: -------------------------------------------------------------------------------- 1 | type Fn = (...params: any[]) => Promise; 2 | 3 | function timeLimit(fn: Fn, t: number): Fn { 4 | return async function(...args) { 5 | return Promise.race([ 6 | fn(...args), 7 | new Promise((_, reject) => { 8 | setTimeout( 9 | () => reject('Time Limit Exceeded'), 10 | t 11 | ) 12 | }) 13 | ]); 14 | } 15 | }; -------------------------------------------------------------------------------- /Range Sum Query - Immutable/README.md: -------------------------------------------------------------------------------- 1 | # [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/) 2 |

Given an integer array nums, handle multiple queries of the following type:

3 | 4 |
    5 |
  1. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
  2. 6 |
7 | 8 |

Implement the NumArray class:

9 | 10 |
    11 |
  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • 12 |
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
  • 13 |
14 | 15 |

 

16 |

Example 1:

17 | 18 |
Input
19 | ["NumArray", "sumRange", "sumRange", "sumRange"]
20 | [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
21 | Output
22 | [null, 1, -1, -3]
23 | 
24 | Explanation
25 | NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
26 | numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
27 | numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
28 | numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 1 <= nums.length <= 104
  • 36 |
  • -105 <= nums[i] <= 105
  • 37 |
  • 0 <= left <= right < nums.length
  • 38 |
  • At most 104 calls will be made to sumRange.
  • 39 |
40 | -------------------------------------------------------------------------------- /Range Sum Query - Immutable/range-sum-query---immutable.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | def __init__(self, nums: List[int]): 3 | self.prefix_sum = [0] * (len(nums) + 1) 4 | for i in range(len(nums)): 5 | self.prefix_sum[i+1] = self.prefix_sum[i] + nums[i] 6 | 7 | def sumRange(self, left: int, right: int) -> int: 8 | return self.prefix_sum[right+1] - self.prefix_sum[left] -------------------------------------------------------------------------------- /Ransom Note/README.md: -------------------------------------------------------------------------------- 1 | # [Ransom Note](https://leetcode.com/problems/ransom-note/) 2 |

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

3 | 4 |

Each letter in magazine can only be used once in ransomNote.

5 | 6 |

 

7 |

Example 1:

8 |
Input: ransomNote = "a", magazine = "b"
 9 | Output: false
10 | 

Example 2:

11 |
Input: ransomNote = "aa", magazine = "ab"
12 | Output: false
13 | 

Example 3:

14 |
Input: ransomNote = "aa", magazine = "aab"
15 | Output: true
16 | 
17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • 1 <= ransomNote.length, magazine.length <= 105
  • 22 |
  • ransomNote and magazine consist of lowercase English letters.
  • 23 |
24 | -------------------------------------------------------------------------------- /Ransom Note/ransom-note.c: -------------------------------------------------------------------------------- 1 | bool canConstruct(char * ransomNote, char * magazine){ 2 | 3 | int t[26] = {0}; 4 | 5 | for(char *str = magazine; *str; str++ ) { 6 | if(*str >= 97 && *str <= 122) { 7 | t[*str - 97] += 1; 8 | } 9 | } 10 | 11 | for(char *str = ransomNote; *str; str++) { 12 | if(t[*str -97] == 0) 13 | return false; 14 | else if (t[*str -97] > 0) 15 | t[*str -97] -= 1; 16 | } 17 | 18 | return true; 19 | } -------------------------------------------------------------------------------- /Remove Max Number of Edges to Keep Graph Fully Traversable/remove-max-number-of-edges-to-keep-graph-fully-traversable.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxNumEdgesToRemove(self, n, edges): 3 | 4 | def find(i, root): 5 | if i != root[i]: 6 | root[i] = find(root[i], root) 7 | return root[i] 8 | 9 | def uni(x, y, root): 10 | x, y = find(x, root), find(y, root) 11 | if x == y: return 0 12 | root[x] = y 13 | return 1 14 | 15 | res = alice_edges = bob_edges = 0 16 | 17 | 18 | root = list(range(n + 1)) 19 | for t, i, j in edges: 20 | if t == 3: 21 | if uni(i, j, root): 22 | alice_edges += 1 23 | bob_edges += 1 24 | else: 25 | res += 1 26 | root0 = root[:] 27 | 28 | 29 | for t, i, j in edges: 30 | if t == 1: 31 | if uni(i, j, root): 32 | alice_edges += 1 33 | else: 34 | res += 1 35 | 36 | 37 | root = root0 38 | for t, i, j in edges: 39 | if t == 2: 40 | if uni(i, j, root): 41 | bob_edges += 1 42 | else: 43 | res += 1 44 | 45 | return res if alice_edges == bob_edges == n - 1 else -1 -------------------------------------------------------------------------------- /Removing Stars From a String/README.md: -------------------------------------------------------------------------------- 1 | # [Removing Stars From a String](https://leetcode.com/problems/removing-stars-from-a-string/) 2 |

You are given a string s, which contains stars *.

3 | 4 |

In one operation, you can:

5 | 6 |
    7 |
  • Choose a star in s.
  • 8 |
  • Remove the closest non-star character to its left, as well as remove the star itself.
  • 9 |
10 | 11 |

Return the string after all stars have been removed.

12 | 13 |

Note:

14 | 15 |
    16 |
  • The input will be generated such that the operation is always possible.
  • 17 |
  • It can be shown that the resulting string will always be unique.
  • 18 |
19 | 20 |

 

21 |

Example 1:

22 | 23 |
Input: s = "leet**cod*e"
24 | Output: "lecoe"
25 | Explanation: Performing the removals from left to right:
26 | - The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
27 | - The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
28 | - The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
29 | There are no more stars, so we return "lecoe".
30 | 31 |

Example 2:

32 | 33 |
Input: s = "erase*****"
34 | Output: ""
35 | Explanation: The entire string is removed, so we return an empty string.
36 | 
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • 1 <= s.length <= 105
  • 43 |
  • s consists of lowercase English letters and stars *.
  • 44 |
  • The operation above can be performed on s.
  • 45 |
46 | -------------------------------------------------------------------------------- /Removing Stars From a String/removing-stars-from-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeStars(self, s: str) -> str: 3 | res = [] 4 | for i in s: 5 | if i != '*': 6 | res.append(i) 7 | elif res: 8 | res.pop() 9 | return ''.join(res) -------------------------------------------------------------------------------- /Repeated Substring Pattern/README.md: -------------------------------------------------------------------------------- 1 | # [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) 2 |

Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: s = "abab"
 8 | Output: true
 9 | Explanation: It is the substring "ab" twice.
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: s = "aba"
15 | Output: false
16 | 
17 | 18 |

Example 3:

19 | 20 |
Input: s = "abcabcabcabc"
21 | Output: true
22 | Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= s.length <= 104
  • 30 |
  • s consists of lowercase English letters.
  • 31 |
32 | -------------------------------------------------------------------------------- /Repeated Substring Pattern/repeated-substring-pattern.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static boolean repeatedSubstringPattern(String s) { 3 | String str = s + s; 4 | String str1 = str.substring(1, str.length() - 1); 5 | return str1.contains(s); 6 | } 7 | } -------------------------------------------------------------------------------- /Reshape the Matrix/README.md: -------------------------------------------------------------------------------- 1 | # [Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) 2 |

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

3 | 4 |

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

5 | 6 |

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

7 | 8 |

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

9 | 10 |

 

11 |

Example 1:

12 | 13 |
Input: mat = [[1,2],[3,4]], r = 1, c = 4
14 | Output: [[1,2,3,4]]
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: mat = [[1,2],[3,4]], r = 2, c = 4
20 | Output: [[1,2],[3,4]]
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • m == mat.length
  • 28 |
  • n == mat[i].length
  • 29 |
  • 1 <= m, n <= 100
  • 30 |
  • -1000 <= mat[i][j] <= 1000
  • 31 |
  • 1 <= r, c <= 300
  • 32 |
33 | -------------------------------------------------------------------------------- /Reshape the Matrix/reshape-the-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: 3 | m = len(mat) 4 | n = len(mat[0]) 5 | 6 | if m * n != r * c: 7 | return mat 8 | 9 | flat_mat = [elem for row in mat for elem in row] 10 | 11 | reshaped_mat = [] 12 | for i in range(r): 13 | row = flat_mat[i*c : (i+1)*c] 14 | reshaped_mat.append(row) 15 | 16 | return reshaped_mat 17 | class Solution: 18 | def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: 19 | m = len(mat) 20 | n = len(mat[0]) 21 | 22 | if m * n != r * c: 23 | return mat 24 | 25 | flat_mat = [elem for row in mat for elem in row] 26 | 27 | reshaped_mat = [] 28 | for i in range(r): 29 | row = flat_mat[i*c : (i+1)*c] 30 | reshaped_mat.append(row) 31 | 32 | return reshaped_mat -------------------------------------------------------------------------------- /Reverse Integer/README.md: -------------------------------------------------------------------------------- 1 | # [Reverse Integer](https://leetcode.com/problems/reverse-integer/) 2 |

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

3 | 4 |

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

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: x = 123
10 | Output: 321
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: x = -123
16 | Output: -321
17 | 
18 | 19 |

Example 3:

20 | 21 |
Input: x = 120
22 | Output: 21
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • -231 <= x <= 231 - 1
  • 30 |
31 | -------------------------------------------------------------------------------- /Reverse Integer/reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | # check if x is negative 4 | negative = x < 0 5 | 6 | # convert x to positive 7 | x = abs(x) 8 | 9 | # reverse the digits 10 | reversed_x = 0 11 | while x > 0: 12 | reversed_x = reversed_x * 10 + x % 10 13 | x //= 10 14 | 15 | # check for overflow condition 16 | if reversed_x > 2**31 - 1: 17 | return 0 18 | 19 | # convert back to negative if necessary 20 | if negative: 21 | reversed_x *= -1 22 | 23 | return reversed_x -------------------------------------------------------------------------------- /Richest Customer Wealth/README.md: -------------------------------------------------------------------------------- 1 | # [Richest Customer Wealth](https://leetcode.com/problems/richest-customer-wealth/) 2 |

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.

3 | 4 |

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.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: accounts = [[1,2,3],[3,2,1]]
10 | Output: 6
11 | Explanation:
12 | 1st customer has wealth = 1 + 2 + 3 = 6
13 | 2nd customer has wealth = 3 + 2 + 1 = 6
14 | Both customers are considered the richest with a wealth of 6 each, so return 6.
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: accounts = [[1,5],[7,3],[3,5]]
20 | Output: 10
21 | Explanation: 
22 | 1st customer has wealth = 6
23 | 2nd customer has wealth = 10 
24 | 3rd customer has wealth = 8
25 | The 2nd customer is the richest with a wealth of 10.
26 | 27 |

Example 3:

28 | 29 |
Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]
30 | Output: 17
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • m == accounts.length
  • 38 |
  • n == accounts[i].length
  • 39 |
  • 1 <= m, n <= 50
  • 40 |
  • 1 <= accounts[i][j] <= 100
  • 41 |
42 | -------------------------------------------------------------------------------- /Richest Customer Wealth/richest-customer-wealth.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumWealth(self, accounts: List[List[int]]) -> int: 3 | max_wealth = 0 4 | 5 | for customer in accounts: 6 | wealth = sum(customer) 7 | max_wealth = max(max_wealth, wealth) 8 | 9 | return max_wealth -------------------------------------------------------------------------------- /Roman to Integer/roman-to-integer.c: -------------------------------------------------------------------------------- 1 | int getValue(const char * s){ 2 | switch(*s) { 3 | case 'I': return (s[1] == 'V' || s[1] == 'X') ? -1 : 1; 4 | case 'X': return (s[1] == 'L' || s[1] == 'C') ? -10 : 10; 5 | case 'C': return (s[1] == 'D' || s[1] == 'M') ? -100 : 100; 6 | case 'V': return 5; 7 | case 'L': return 50; 8 | case 'D': return 500; 9 | case 'M': return 1000; 10 | } 11 | return 0; 12 | } 13 | 14 | int romanToInt(char * s){ 15 | int result = 0; 16 | 17 | for(;*s != '\0'; ++s) { 18 | result += getValue(s); 19 | } 20 | return result; 21 | } -------------------------------------------------------------------------------- /Scramble String/scramble-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # dictionary to store previously computed substrings 3 | map = {} 4 | 5 | def isScramble(self, s1: str, s2: str) -> bool: 6 | n = len(s1) 7 | # check if the two strings are equal 8 | if s1 == s2: 9 | return True 10 | # initialize frequency lists for s1, s2, and current substring 11 | a, b, c = [0] * 26, [0] * 26, [0] * 26 12 | # check if the current substring has already been computed 13 | if (s1 + s2) in self.map: 14 | return self.map[s1 + s2] 15 | # check all possible splits of the two strings 16 | for i in range(1, n): 17 | j = n - i 18 | # update frequency lists for s1, s2, and current substring 19 | a[ord(s1[i - 1]) - ord('a')] += 1 20 | b[ord(s2[i - 1]) - ord('a')] += 1 21 | c[ord(s2[j]) - ord('a')] += 1 22 | # check if the current substring has the same characters 23 | if a == b and self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]): 24 | # if the substrings are scrambled versions of each other, return True 25 | self.map[s1 + s2] = True 26 | return True 27 | # check if the current substring and its complement have the same characters 28 | if a == c and self.isScramble(s1[:i], s2[j:]) and self.isScramble(s1[i:], s2[:j]): 29 | # if the substrings are scrambled versions of each other, return True 30 | self.map[s1 + s2] = True 31 | return True 32 | # if none of the splits result in scrambled versions, return False 33 | self.map[s1 + s2] = False 34 | return False -------------------------------------------------------------------------------- /Sign of the Product of an Array/README.md: -------------------------------------------------------------------------------- 1 | # [Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) 2 |

There is a function signFunc(x) that returns:

3 | 4 |
    5 |
  • 1 if x is positive.
  • 6 |
  • -1 if x is negative.
  • 7 |
  • 0 if x is equal to 0.
  • 8 |
9 | 10 |

You are given an integer array nums. Let product be the product of all values in the array nums.

11 | 12 |

Return signFunc(product).

13 | 14 |

 

15 |

Example 1:

16 | 17 |
Input: nums = [-1,-2,-3,-4,3,2,1]
18 | Output: 1
19 | Explanation: The product of all values in the array is 144, and signFunc(144) = 1
20 | 
21 | 22 |

Example 2:

23 | 24 |
Input: nums = [1,5,0,2,-3]
25 | Output: 0
26 | Explanation: The product of all values in the array is 0, and signFunc(0) = 0
27 | 
28 | 29 |

Example 3:

30 | 31 |
Input: nums = [-1,1,-1,1,-1]
32 | Output: -1
33 | Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
34 | 
35 | 36 |

 

37 |

Constraints:

38 | 39 |
    40 |
  • 1 <= nums.length <= 1000
  • 41 |
  • -100 <= nums[i] <= 100
  • 42 |
43 | -------------------------------------------------------------------------------- /Sign of the Product of an Array/sign-of-the-product-of-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arraySign(vector& a) { 4 | int cnt = 0; 5 | for(int i = 0; i < a.size(); i++) 6 | { 7 | if(a[i] == 0) return 0; 8 | if(a[i] < 0) cnt++; 9 | } 10 | return cnt%2 ? -1 : 1; 11 | } 12 | }; -------------------------------------------------------------------------------- /Simplify Path/simplify-path.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path): 3 | dirOrFiles = [] 4 | path = path.split("/") 5 | for elem in path: 6 | if dirOrFiles and elem == "..": 7 | dirOrFiles.pop() 8 | elif elem not in [".", "", ".."]: 9 | dirOrFiles.append(elem) 10 | 11 | return "/" + "/".join(dirOrFiles) -------------------------------------------------------------------------------- /Sleep/README.md: -------------------------------------------------------------------------------- 1 | # [Sleep](https://leetcode.com/problems/sleep/) 2 |

Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: millis = 100
 8 | Output: 100
 9 | Explanation: It should return a promise that resolves after 100ms.
10 | let t = Date.now();
11 | sleep(100).then(() => {
12 |   console.log(Date.now() - t); // 100
13 | });
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: millis = 200
19 | Output: 200
20 | Explanation: It should return a promise that resolves after 200ms.
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 1 <= millis <= 1000
  • 28 |
29 | -------------------------------------------------------------------------------- /Sleep/sleep.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} millis 3 | */ 4 | async function sleep(millis) { 5 | await new Promise(resolve => setTimeout(resolve , millis)); 6 | return millis; 7 | } 8 | 9 | /** 10 | * let t = Date.now() 11 | * sleep(100).then(() => console.log(Date.now() - t)) // 100 12 | */ -------------------------------------------------------------------------------- /Smallest Number in Infinite Set/smallest-number-in-infinite-set.py: -------------------------------------------------------------------------------- 1 | class SmallestInfiniteSet: 2 | def __init__(self): 3 | self.cur = 1 4 | self.s = set() 5 | 6 | def popSmallest(self): 7 | if self.s: 8 | res = min(self.s) 9 | self.s.remove(res) 10 | return res 11 | else: 12 | self.cur += 1 13 | return self.cur - 1 14 | 15 | def addBack(self, num): 16 | if self.cur > num: 17 | self.s.add(num) -------------------------------------------------------------------------------- /Spiral Matrix II/README.md: -------------------------------------------------------------------------------- 1 | # [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) 2 |

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

3 | 4 |

 

5 |

Example 1:

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

Example 2:

12 | 13 |
Input: n = 1
14 | Output: [[1]]
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • 1 <= n <= 20
  • 22 |
23 | -------------------------------------------------------------------------------- /Spiral Matrix II/spiral-matrix-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n: int) -> List[List[int]]: 3 | if not n: 4 | return [] 5 | matrix = [[0 for _ in range(n)] for _ in range(n)] 6 | left, right, top, bottom, num = 0, n-1, 0, n-1, 1 7 | while left <= right and top <= bottom: 8 | for i in range(left, right+1): 9 | matrix[top][i] = num 10 | num += 1 11 | top += 1 12 | for i in range(top, bottom+1): 13 | matrix[i][right] = num 14 | num += 1 15 | right -= 1 16 | if top <= bottom: 17 | for i in range(right, left-1, -1): 18 | matrix[bottom][i] = num 19 | num += 1 20 | bottom -= 1 21 | if left <= right: 22 | for i in range(bottom, top-1, -1): 23 | matrix[i][left] = num 24 | num += 1 25 | left += 1 26 | return matrix -------------------------------------------------------------------------------- /Spiral Matrix/README.md: -------------------------------------------------------------------------------- 1 | # [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) 2 |

Given an m x n matrix, return all elements of the matrix in spiral order.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
 8 | Output: [1,2,3,6,9,8,7,4,5]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
14 | Output: [1,2,3,4,8,12,11,10,9,5,6,7]
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • m == matrix.length
  • 22 |
  • n == matrix[i].length
  • 23 |
  • 1 <= m, n <= 10
  • 24 |
  • -100 <= matrix[i][j] <= 100
  • 25 |
26 | -------------------------------------------------------------------------------- /Spiral Matrix/spiral-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | if not matrix: 4 | return [] 5 | 6 | rows, cols = len(matrix), len(matrix[0]) 7 | top, bottom, left, right = 0, rows-1, 0, cols-1 8 | result = [] 9 | 10 | while len(result) < rows * cols: 11 | for i in range(left, right+1): 12 | result.append(matrix[top][i]) 13 | top += 1 14 | 15 | for i in range(top, bottom+1): 16 | result.append(matrix[i][right]) 17 | right -= 1 18 | 19 | if top <= bottom: 20 | for i in range(right, left-1, -1): 21 | result.append(matrix[bottom][i]) 22 | bottom -= 1 23 | 24 | if left <= right: 25 | for i in range(bottom, top-1, -1): 26 | result.append(matrix[i][left]) 27 | left += 1 28 | 29 | return result -------------------------------------------------------------------------------- /String Compression/string-compression.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def compress(self, chars: List[str]) -> int: 5 | # Initialize pointers 6 | write = 0 7 | start = 0 8 | 9 | # Iterate through the input array 10 | for i in range(len(chars)): 11 | # If the current character is different from the previous one 12 | if i + 1 == len(chars) or chars[i + 1] != chars[i]: 13 | # Write the current character 14 | chars[write] = chars[start] 15 | write += 1 16 | 17 | # If there is more than one occurrence of the current character 18 | if i > start: 19 | # Compute the length of the group and write it 20 | for digit in str(i - start + 1): 21 | chars[write] = digit 22 | write += 1 23 | 24 | # Move the start pointer to the next group 25 | start = i + 1 26 | 27 | # Return the new length of the array 28 | return write -------------------------------------------------------------------------------- /Student Attendance Record I/README.md: -------------------------------------------------------------------------------- 1 | # [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) 2 |

You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:

3 | 4 |
    5 |
  • 'A': Absent.
  • 6 |
  • 'L': Late.
  • 7 |
  • 'P': Present.
  • 8 |
9 | 10 |

The student is eligible for an attendance award if they meet both of the following criteria:

11 | 12 |
    13 |
  • The student was absent ('A') for strictly fewer than 2 days total.
  • 14 |
  • The student was never late ('L') for 3 or more consecutive days.
  • 15 |
16 | 17 |

Return true if the student is eligible for an attendance award, or false otherwise.

18 | 19 |

 

20 |

Example 1:

21 | 22 |
Input: s = "PPALLP"
23 | Output: true
24 | Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.
25 | 
26 | 27 |

Example 2:

28 | 29 |
Input: s = "PPALLL"
30 | Output: false
31 | Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.
32 | 
33 | 34 |

 

35 |

Constraints:

36 | 37 |
    38 |
  • 1 <= s.length <= 1000
  • 39 |
  • s[i] is either 'A', 'L', or 'P'.
  • 40 |
41 | -------------------------------------------------------------------------------- /Student Attendance Record I/student-attendance-record-i.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkRecord(self, s: str) -> bool: 3 | absences = 0 4 | consecutive_lates = 0 5 | 6 | for day in s: 7 | if day == 'A': 8 | absences += 1 9 | consecutive_lates = 0 10 | if absences >= 2: 11 | return False 12 | elif day == 'L': 13 | consecutive_lates += 1 14 | if consecutive_lates >= 3: 15 | return False 16 | else: 17 | consecutive_lates = 0 18 | 19 | return True -------------------------------------------------------------------------------- /Successful Pairs of Spells and Potions/successful-pairs-of-spells-and-potions.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def successfulPairs(self, spells, potions, success): 3 | n = len(spells) 4 | m = len(potions) 5 | pairs = [0] * n 6 | potions.sort() 7 | for i in range(n): 8 | spell = spells[i] 9 | left = 0 10 | right = m - 1 11 | while left <= right: 12 | mid = left + (right - left) // 2 13 | product = spell * potions[mid] 14 | if product >= success: 15 | right = mid - 1 16 | else: 17 | left = mid + 1 18 | pairs[i] = m - left 19 | return pairs -------------------------------------------------------------------------------- /Sudoku Solver/sudoku-solver.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solveSudoku(self, board: List[List[str]]) -> None: 3 | """ 4 | Do not return anything, modify board in-place instead. 5 | """ 6 | def isValid(x: int, y: int, c: str) -> bool: 7 | for i in range(9): 8 | if board[i][y] == c: 9 | return False 10 | if board[x][i] == c: 11 | return False 12 | if board[3 * (x // 3) + i // 3][3 * (y // 3) + i % 3] == c: 13 | return False 14 | return True 15 | 16 | def solveHelper() -> bool: 17 | for i in range(9): 18 | for j in range(9): 19 | if board[i][j] == '.': 20 | for c in '123456789': 21 | if isValid(i, j, c): 22 | board[i][j] = c 23 | if solveHelper(): 24 | return True 25 | board[i][j] = '.' 26 | return False 27 | return True 28 | 29 | solveHelper() -------------------------------------------------------------------------------- /Sum Root to Leaf Numbers/README.md: -------------------------------------------------------------------------------- 1 | # [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) 2 |

You are given the root of a binary tree containing digits from 0 to 9 only.

3 | 4 |

Each root-to-leaf path in the tree represents a number.

5 | 6 |
    7 |
  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
  • 8 |
9 | 10 |

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

11 | 12 |

A leaf node is a node with no children.

13 | 14 |

 

15 |

Example 1:

16 | 17 |
Input: root = [1,2,3]
18 | Output: 25
19 | Explanation:
20 | The root-to-leaf path 1->2 represents the number 12.
21 | The root-to-leaf path 1->3 represents the number 13.
22 | Therefore, sum = 12 + 13 = 25.
23 | 
24 | 25 |

Example 2:

26 | 27 |
Input: root = [4,9,0,5,1]
28 | Output: 1026
29 | Explanation:
30 | The root-to-leaf path 4->9->5 represents the number 495.
31 | The root-to-leaf path 4->9->1 represents the number 491.
32 | The root-to-leaf path 4->0 represents the number 40.
33 | Therefore, sum = 495 + 491 + 40 = 1026.
34 | 
35 | 36 |

 

37 |

Constraints:

38 | 39 |
    40 |
  • The number of nodes in the tree is in the range [1, 1000].
  • 41 |
  • 0 <= Node.val <= 9
  • 42 |
  • The depth of the tree will not exceed 10.
  • 43 |
44 | -------------------------------------------------------------------------------- /Sum Root to Leaf Numbers/sum-root-to-leaf-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumNumbers(self, root: Optional[TreeNode]) -> int: 3 | # Define a helper function to recursively traverse the tree and compute the sum 4 | def traverse(node, path_sum): 5 | if not node: 6 | return 0 7 | path_sum = path_sum * 10 + node.val 8 | if not node.left and not node.right: # Leaf node 9 | return path_sum 10 | left_sum = traverse(node.left, path_sum) 11 | right_sum = traverse(node.right, path_sum) 12 | return left_sum + right_sum 13 | 14 | # Call the helper function on the root node 15 | return traverse(root, 0) -------------------------------------------------------------------------------- /Sum of All Odd Length Subarrays/README.md: -------------------------------------------------------------------------------- 1 | # [Sum of All Odd Length Subarrays](https://leetcode.com/problems/sum-of-all-odd-length-subarrays/) 2 |

Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.

3 | 4 |

A subarray is a contiguous subsequence of the array.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: arr = [1,4,2,5,3]
10 | Output: 58
11 | Explanation: The odd-length subarrays of arr and their sums are:
12 | [1] = 1
13 | [4] = 4
14 | [2] = 2
15 | [5] = 5
16 | [3] = 3
17 | [1,4,2] = 7
18 | [4,2,5] = 11
19 | [2,5,3] = 10
20 | [1,4,2,5,3] = 15
21 | If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
22 | 23 |

Example 2:

24 | 25 |
Input: arr = [1,2]
26 | Output: 3
27 | Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
28 | 29 |

Example 3:

30 | 31 |
Input: arr = [10,11,12]
32 | Output: 66
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 1 <= arr.length <= 100
  • 40 |
  • 1 <= arr[i] <= 1000
  • 41 |
42 | 43 |

 

44 |

Follow up:

45 | 46 |

Could you solve this problem in O(n) time complexity?

47 | -------------------------------------------------------------------------------- /Sum of All Odd Length Subarrays/sum-of-all-odd-length-subarrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOddLengthSubarrays(self, arr: List[int]) -> int: 3 | n = len(arr) 4 | result = 0 5 | 6 | for length in range(1, n+1, 2): 7 | for i in range(n-length+1): 8 | j = i + length - 1 9 | result += sum(arr[i:j+1]) 10 | 11 | return result -------------------------------------------------------------------------------- /Sum of Left Leaves/README.md: -------------------------------------------------------------------------------- 1 | # [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) 2 |

Given the root of a binary tree, return the sum of all left leaves.

3 | 4 |

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

5 | 6 |

 

7 |

Example 1:

8 | 9 |
Input: root = [3,9,20,null,null,15,7]
10 | Output: 24
11 | Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: root = [1]
17 | Output: 0
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • The number of nodes in the tree is in the range [1, 1000].
  • 25 |
  • -1000 <= Node.val <= 1000
  • 26 |
27 | -------------------------------------------------------------------------------- /Sum of Left Leaves/sum-of-left-leaves.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: 3 | # Base case: if the root is None, the sum is 0 4 | if root is None: 5 | return 0 6 | 7 | # Recursive case: check if the left child is a left leaf and add its value to the sum 8 | if root.left is not None and root.left.left is None and root.left.right is None: 9 | left_leaf_value = root.left.val 10 | else: 11 | left_leaf_value = 0 12 | 13 | # Recursively calculate the sum of left leaves in the left and right subtrees 14 | left_sum = self.sumOfLeftLeaves(root.left) 15 | right_sum = self.sumOfLeftLeaves(root.right) 16 | 17 | # Return the sum of left leaves in the current subtree 18 | return left_leaf_value + left_sum + right_sum -------------------------------------------------------------------------------- /Swap Nodes in Pairs/README.md: -------------------------------------------------------------------------------- 1 | # [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) 2 |

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

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: head = [1,2,3,4]
 8 | Output: [2,1,4,3]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: head = []
14 | Output: []
15 | 
16 | 17 |

Example 3:

18 | 19 |
Input: head = [1]
20 | Output: [1]
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • The number of nodes in the list is in the range [0, 100].
  • 28 |
  • 0 <= Node.val <= 100
  • 29 |
30 | -------------------------------------------------------------------------------- /Swap Nodes in Pairs/swap-nodes-in-pairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | if not head or not head.next: 4 | return head 5 | 6 | ans = ListNode(0) 7 | ans.next = head 8 | curr = ans 9 | 10 | while curr.next and curr.next.next: 11 | t1 = curr.next 12 | t2 = curr.next.next 13 | curr.next = t2 14 | t1.next = t2.next 15 | t2.next = t1 16 | curr = curr.next.next 17 | 18 | return ans.next -------------------------------------------------------------------------------- /Symmetric Tree/README.md: -------------------------------------------------------------------------------- 1 | # [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) 2 |

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

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: root = [1,2,2,3,4,4,3]
 8 | Output: true
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: root = [1,2,2,null,3,null,3]
14 | Output: false
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • The number of nodes in the tree is in the range [1, 1000].
  • 22 |
  • -100 <= Node.val <= 100
  • 23 |
24 | 25 |

 

26 | Follow up: Could you solve it both recursively and iteratively? -------------------------------------------------------------------------------- /Symmetric Tree/symmetric-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSymmetric(self, root: Optional[TreeNode]) -> bool: 3 | if root is None: 4 | return True 5 | else: 6 | return self.isMirror(root.left, root.right) 7 | 8 | def isMirror(self, left: TreeNode, right: TreeNode) -> bool: 9 | if left is None and right is None: 10 | return True 11 | elif left is None or right is None: 12 | return False 13 | elif left.val != right.val: 14 | return False 15 | else: 16 | return self.isMirror(left.left, right.right) and self.isMirror(left.right, right.left) -------------------------------------------------------------------------------- /Throttle/throttle: -------------------------------------------------------------------------------- 1 | type F = (...args: any[]) => void 2 | 3 | function throttle(fn: F, t: number): F { 4 | let canExecute = true 5 | let cachedArgs: Parameters | undefined 6 | 7 | const tryExecute = () => { 8 | if (!cachedArgs || !canExecute) { 9 | return 10 | } 11 | 12 | canExecute = false 13 | fn(...cachedArgs) 14 | cachedArgs = undefined 15 | 16 | setTimeout(() => { 17 | canExecute = true 18 | tryExecute() 19 | }, t) 20 | } 21 | 22 | return function (...args) { 23 | cachedArgs = args 24 | 25 | tryExecute() 26 | } 27 | }; -------------------------------------------------------------------------------- /Top K Frequent Elements/README.md: -------------------------------------------------------------------------------- 1 | # [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) 2 |

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

3 | 4 |

 

5 |

Example 1:

6 |
Input: nums = [1,1,1,2,2,3], k = 2
 7 | Output: [1,2]
 8 | 

Example 2:

9 |
Input: nums = [1], k = 1
10 | Output: [1]
11 | 
12 |

 

13 |

Constraints:

14 | 15 |
    16 |
  • 1 <= nums.length <= 105
  • 17 |
  • -104 <= nums[i] <= 104
  • 18 |
  • k is in the range [1, the number of unique elements in the array].
  • 19 |
  • It is guaranteed that the answer is unique.
  • 20 |
21 | 22 |

 

23 |

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

24 | -------------------------------------------------------------------------------- /Top K Frequent Elements/top-k-frequent-elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self,nums:List[int],k:int)->List[int]: 3 | return [x[0] for x in Counter(nums).most_common(k)] -------------------------------------------------------------------------------- /Two Sum/README.md: -------------------------------------------------------------------------------- 1 | # [Two Sum](https://leetcode.com/problems/two-sum/) 2 |

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

3 | 4 |

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

5 | 6 |

You can return the answer in any order.

7 | 8 |

 

9 |

Example 1:

10 | 11 |
Input: nums = [2,7,11,15], target = 9
12 | Output: [0,1]
13 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: nums = [3,2,4], target = 6
19 | Output: [1,2]
20 | 
21 | 22 |

Example 3:

23 | 24 |
Input: nums = [3,3], target = 6
25 | Output: [0,1]
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 2 <= nums.length <= 104
  • 33 |
  • -109 <= nums[i] <= 109
  • 34 |
  • -109 <= target <= 109
  • 35 |
  • Only one valid answer exists.
  • 36 |
37 | 38 |

 

39 | Follow-up: Can you come up with an algorithm that is less than O(n2time complexity? -------------------------------------------------------------------------------- /Two Sum/two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | for (int i = 0; i < nums.size(); i++) 5 | { 6 | for (int j = i+1; j < nums.size(); j++) 7 | { 8 | if ((nums[i] + nums[j])==target) 9 | { 10 | return {i, j}; 11 | } 12 | } 13 | } 14 | return {}; 15 | } 16 | }; -------------------------------------------------------------------------------- /Valid Anagram/README.md: -------------------------------------------------------------------------------- 1 | # [Valid Anagram](https://leetcode.com/problems/valid-anagram/) 2 |

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

3 | 4 |

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

5 | 6 |

 

7 |

Example 1:

8 |
Input: s = "anagram", t = "nagaram"
 9 | Output: true
10 | 

Example 2:

11 |
Input: s = "rat", t = "car"
12 | Output: false
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= s.length, t.length <= 5 * 104
  • 19 |
  • s and t consist of lowercase English letters.
  • 20 |
21 | 22 |

 

23 |

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

24 | -------------------------------------------------------------------------------- /Valid Anagram/valid-anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | # If the length of s and t are not equal, they cannot be anagrams 4 | if len(s) != len(t): 5 | return False 6 | 7 | # Create a dictionary to count the frequency of characters in s 8 | freq = {} 9 | for char in s: 10 | freq[char] = freq.get(char, 0) + 1 11 | 12 | # Check if the frequency of characters in t matches that of s 13 | for char in t: 14 | if char not in freq or freq[char] == 0: 15 | return False 16 | freq[char] -= 1 17 | 18 | return True -------------------------------------------------------------------------------- /Valid Parentheses/README.md: -------------------------------------------------------------------------------- 1 | # [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) 2 |

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

3 | 4 |

An input string is valid if:

5 | 6 |
    7 |
  1. Open brackets must be closed by the same type of brackets.
  2. 8 |
  3. Open brackets must be closed in the correct order.
  4. 9 |
  5. Every close bracket has a corresponding open bracket of the same type.
  6. 10 |
11 | 12 |

 

13 |

Example 1:

14 | 15 |
Input: s = "()"
16 | Output: true
17 | 
18 | 19 |

Example 2:

20 | 21 |
Input: s = "()[]{}"
22 | Output: true
23 | 
24 | 25 |

Example 3:

26 | 27 |
Input: s = "(]"
28 | Output: false
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 1 <= s.length <= 104
  • 36 |
  • s consists of parentheses only '()[]{}'.
  • 37 |
38 | -------------------------------------------------------------------------------- /Valid Parentheses/valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack st; 5 | for(auto i:s) 6 | { 7 | // if element is open parantheses, push it in stack 8 | if(i=='(' or i=='{' or i=='[') 9 | st.push(i); 10 | else 11 | { 12 | // checking if top element is opening parantheses 13 | // of same kind as closing parantheses 14 | if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or (st.top()=='[' and i!=']')) return false; 15 | st.pop(); 16 | } 17 | } 18 | // If the stack is not empty,that is there is an opening 19 | // parentheses without a corresponding closing parentheses and we can return False, else return true. 20 | return st.empty(); 21 | } 22 | }; --------------------------------------------------------------------------------