├── 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.
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 |0 <= num <= 231 - 1
29 |
Follow up: Could you do it without any loop/recursion in O(1)
runtime?
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 |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 |[1, 100]
.0 <= Node.val <= 9
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.
fn
.undefined
.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 |1 <= calls.length <= 10
1 <= calls[i].length <= 100
2 <= JSON.stringify(calls).length <= 1000
Given an integer array arr
and a mapping function fn
, return a new array with a transformation applied to each element.
The returned array should be created such that returnedArray[i] = fn(arr[i], i)
.
Please solve it without the built-in Array.map
method.
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 |0 <= arr.length <= 1000
-109 <= arr[i] <= 109
fn returns a number
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 |1 <= n <= 104
nums.length == 2 * n
-104 <= nums[i] <= 104
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 |0 <= arr.length <= 1000
0 <= arr[i] <= 1000
Create a class ArrayWrapper
that accepts an array of integers in it's constructor. This class should have two features:
+
operator, the resulting value is the sum of all the elements in both arrays.String()
function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3]
.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 |0 <= nums.length <= 1000
0 <= nums[i] <= 1000
Note: nums is the array passed to the constructor
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
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 |2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
39 | Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?
--------------------------------------------------------------------------------
/Array of Objects to Matrix/array-of-objects-to-matrix.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vectorYou are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
5 | 6 |Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
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 |1 <= prices.length <= 105
0 <= prices[i] <= 104
There are n
bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
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.
Return the number of bulbs that are on after n
rounds.
9 |
Example 1:
10 |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 |0 <= n <= 109
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.
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 |1 <= flowerbed.length <= 2 * 104
flowerbed[i]
is 0
or 1
.flowerbed
.0 <= n <= flowerbed.length
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
.
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.
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
.
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 |1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1
and s2
consist of only lowercase English letters.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.
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 |1 <= sentence.length <= 1000
sentence
consists of lowercase English letters.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.
5 |
Example 1:
6 |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 |1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder
and postorder
consist of unique values.postorder
also appears in inorder
.inorder
is guaranteed to be the inorder traversal of the tree.postorder
is guaranteed to be the postorder traversal of the tree.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.
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 |1 <= nums.length <= 105
-109 <= nums[i] <= 109
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()
.
Please solve it without using the built-in JSON.stringify
method.
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 |object includes strings, integers, booleans, arrays, objects, and null
1 <= JSON.stringify(object).length <= 105
maxNestingLevel <= 1000
all strings will only contain alphanumeric characters
Given the head
of a singly linked list where elements are sorted in ascending order, convert it to a
5 |
Example 1:
6 |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 |head
is in the range [0, 2 * 104]
.-105 <= Node.val <= 105
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 |0 <= n <= 8
You are given an integer array nums
and two integers minK
and maxK
.
A fixed-bound subarray of nums
is a subarray that satisfies the following conditions:
minK
.maxK
.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 |2 <= nums.length <= 105
1 <= nums[i], minK, maxK <= 106
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
.
Return the number of pairs of different nodes that are unreachable from each other.
5 | 6 |7 |
Example 1:
8 |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 |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 |1 <= n <= 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ai, bi < n
ai != bi
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:
'0'
zero
times.'1'
one
times.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).
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
.
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 |1 <= low <= high <= 105
1 <= zero, one <= low
Write a function createCounter
. It should accept an initial integer init
. It should return an object with three functions.
The three functions are:
5 | 6 |increment()
increases the current value by 1 and then returns it.decrement()
reduces the current value by 1 and then returns it.reset()
sets the current value to init
and then returns it.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 |-1000 <= init <= 1000
total calls not to exceed 1000
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).
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 |-1000 <= n <= 1000
At most 1000 calls to counter() will be made
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 |0 <= args.length <= 10
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:
WordDictionary()
Initializes the object.void addWord(word)
Adds word
to the data structure, it can be matched later.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.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 |1 <= word.length <= 25
word
in addWord
consists of lowercase English letters.word
in search
consist of '.'
or lowercase English letters.2
dots in word
for search
queries.104
calls will be made to addWord
and search
.Given two integers dividend
and divisor
, divide two integers without using multiplication, division, and mod operator.
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
.
Return the quotient after dividing dividend
by divisor
.
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
.
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 |-231 <= dividend, divisor <= 231 - 1
divisor != 0
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
5 | 6 |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 |0 <= word1.length, word2.length <= 500
word1
and word2
consist of lowercase English letters.Given an integer array arr
and a filtering function fn
, return a new array with a fewer or equal number of elements.
The returned array should only contain elements where fn(arr[i], i)
evaluated to a truthy value.
Please solve it without the built-in Array.filter
method.
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 1016 | 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 |0 <= arr.length <= 1000
-109 <= arr[i] <= 109
Given two 0-indexed integer arrays nums1
and nums2
, return a list answer
of size 2
where:
answer[0]
is a list of all distinct integers in nums1
which are not present in nums2
.answer[1]
is a list of all distinct integers in nums2
which are not present in nums1
.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 |1 <= nums1.length, nums2.length <= 1000
-1000 <= nums1[i], nums2[i] <= 1000
You are given two strings s
and t
.
String t
is generated by random shuffling string s
and then add one more letter at a random position.
Return the letter that was added to t
.
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 |0 <= s.length <= 1000
t.length == s.length + 1
s
and t
consist of lowercase English letters.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
.
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 |1 <= haystack.length, needle.length <= 104
haystack
and needle
consist of only lowercase English characters.Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
if i
is divisible by 3
and 5
.answer[i] == "Fizz"
if i
is divisible by 3
.answer[i] == "Buzz"
if i
is divisible by 5
.answer[i] == i
(as a string) if none of the above conditions are true.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 |1 <= n <= 104
Given the root
of a binary tree, flatten the tree into a "linked list":
TreeNode
class where the right
child pointer points to the next node in the list and the left
child pointer is always null
.10 |
Example 1:
11 |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 |[0, 2000]
.-100 <= Node.val <= 100
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
.
The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13
.
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 |0 <= callCount <= 50
You own a Goal Parser that can interpret a string command
. The command
consists of an alphabet of "G"
, "()"
and/or "(al)"
in some order. The Goal Parser will interpret "G"
as the string "G"
, "()"
as the string "o"
, and "(al)"
as the string "al"
. The interpreted strings are then concatenated in the original order.
Given the string command
, return the Goal Parser's interpretation of command
.
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 |1 <= command.length <= 100
command
consists of "G"
, "()"
, and/or "(al)"
in some order.Write an algorithm to determine if a number n
is happy.
A happy number is a number defined by the following process:
5 | 6 |Return true
if n
is a happy number, and false
if not.
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 |1 <= n <= 231 - 1
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 |Trie()
Initializes the trie object.void insert(String word)
Inserts the string word
into the trie.boolean search(String word)
Returns true
if the string word
is in the trie (i.e., was inserted before), and false
otherwise.boolean startsWith(String prefix)
Returns true
if there is a previously inserted string word
that has the prefix prefix
, and false
otherwise.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 |1 <= word.length, prefix.length <= 2000
word
and prefix
consist only of lowercase English letters.3 * 104
calls in total will be made to insert
, search
, and startsWith
.Given two objects o1
and o2
, check if they are deeply equal.
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.
You may assume both objects are the output of JSON.parse
. In other words, they are valid JSON.
Please solve it without using lodash's _.isEqual()
function.
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 !== false37 | 38 |
39 |
Constraints:
40 | 41 |1 <= JSON.stringify(o1).length <= 105
1 <= JSON.stringify(o2).length <= 105
maxNestingDepth <= 1000
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:
Solution(ListNode head)
Initializes the object with the head of the singly-linked list head
.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.12 |
Example 1:
13 |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 |[1, 104]
.-104 <= Node.val <= 104
104
calls will be made to getRandom
.40 |
Follow up:
41 | 42 |You are given a directed graph of n
nodes numbered from 0
to n - 1
, where each node has at most one outgoing edge.
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
.
Return the length of the longest cycle in the graph. If no cycle exists, return -1
.
A cycle is a path that starts and ends at the same node.
9 | 10 |11 |
Example 1:
12 |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 |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 |n == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
Given a string s
, find the longest palindromic subsequence's length in s
.
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 |1 <= s.length <= 1000
s
consists only of lowercase English letters.Given a string s
, return the longest s
.
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 |1 <= s.length <= 1000
s
consist of only digits and English letters.Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
5 | 6 |7 |
Example 1:
8 |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 |[0, 104]
.-100 <= Node.val <= 100
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 |Input: root = [1,null,3,2,4,null,5,6] 14 | Output: 3 15 |16 | 17 |
Example 2:
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] 22 | Output: 5 23 |24 | 25 |
26 |
Constraints:
27 | 28 |[0, 104]
.1000
.There are n
piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.
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.
9 |
Example 1:
10 |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 |n == piles.length
1 <= n <= 1000
1 <= piles[i][j] <= 105
1 <= k <= sum(piles[i].length) <= 2000
Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))
.
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 |nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
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.
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 |1 <= word1.length, word2.length <= 100
word1
and word2
consist of lowercase English letters.You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
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 |k == lists.length
0 <= k <= 104
0 <= lists[i].length <= 500
-104 <= lists[i][j] <= 104
lists[i]
is sorted in ascending order.lists[i].length
will not exceed 104
.You are given a 0-indexed array nums
comprising of n
non-negative integers.
In one operation, you must:
5 | 6 |i
such that 1 <= i < n
and nums[i] > 0
.nums[i]
by 1.nums[i - 1]
by 1.Return the minimum possible value of the maximum integer of nums
after performing any number of operations.
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 |n == nums.length
2 <= n <= 105
0 <= nums[i] <= 109
You may recall that an array arr
is a mountain array if and only if:
arr.length >= 3
i
(0-indexed) with 0 < i < arr.length - 1
such that:
7 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array nums
, return the minimum number of elements to remove to make nums
a mountain array.
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 |3 <= nums.length <= 1000
1 <= nums[i] <= 109
nums
.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.
Note: You can only move either down or right at any point in time.
5 | 6 |7 |
Example 1:
8 |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 |m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100
You are given an array time
where time[i]
denotes the time taken by the ith
bus to complete one trip.
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.
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 |1 <= time.length <= 105
1 <= time[i], totalTrips <= 107
Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
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 |1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
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.
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 |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 |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 |[0, 104]
.0 <= Node.val <= 104
1000
.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 |A 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 |0 <= arr.flat().length <= 105
0 <= arr.flat()[i] <= 105
maxNestingDepth <= 105
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
Given an integer array nums
, return the number of subarrays filled with 0
.
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 |1 <= nums.length <= 105
-109 <= nums[i] <= 109
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.
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 |1 <= s.length <= 105
s
consists of only English lowercase letters.Given the head
of a singly linked list, return true
if it is a false
otherwise.
5 |
Example 1:
6 |Input: head = [1,2,2,1] 8 | Output: true 9 |10 | 11 |
Example 2:
12 |Input: head = [1,2] 14 | Output: false 15 |16 | 17 |
18 |
Constraints:
19 | 20 |[1, 105]
.0 <= Node.val <= 9
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 = () => PromiseGiven an integer array nums
, handle multiple queries of the following type:
nums
between indices left
and right
inclusive where left <= right
.Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer array nums
.int sumRange(int left, int right)
Returns the sum of the elements of nums
between indices left
and right
inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]
).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 |1 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= left <= right < nums.length
104
calls will be made to sumRange
.Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
and false
otherwise.
Each letter in magazine
can only be used once in ransomNote
.
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 |1 <= ransomNote.length, magazine.length <= 105
ransomNote
and magazine
consist of lowercase English letters.You are given a string s
, which contains stars *
.
In one operation, you can:
5 | 6 |s
.Return the string after all stars have been removed.
12 | 13 |Note:
14 | 15 |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 |1 <= s.length <= 105
s
consists of lowercase English letters and stars *
.s
.Given a string s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
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 |1 <= s.length <= 104
s
consists of lowercase English letters.In MATLAB, there is a handy function called reshape
which can reshape an m x n
matrix into a new one with a different size r x c
keeping its original data.
You are given an m x n
matrix mat
and two integers r
and c
representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
7 | 8 |If the reshape
operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
11 |
Example 1:
12 |Input: mat = [[1,2],[3,4]], r = 1, c = 4 14 | Output: [[1,2,3,4]] 15 |16 | 17 |
Example 2:
18 |Input: mat = [[1,2],[3,4]], r = 2, c = 4 20 | Output: [[1,2],[3,4]] 21 |22 | 23 |
24 |
Constraints:
25 | 26 |m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
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
.
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 |-231 <= x <= 231 - 1
You are given an m x n
integer grid accounts
where accounts[i][j]
is the amount of money the ith
customer has in the jth
bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
5 | 6 |7 |
Example 1:
8 | 9 |Input: accounts = [[1,2,3],[3,2,1]] 10 | Output: 6 11 | Explanation: 12 |16 | 17 |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 |
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 |m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
There is a function signFunc(x)
that returns:
1
if x
is positive.-1
if x
is negative.0
if x
is equal to 0
.You are given an integer array nums
. Let product
be the product of all values in the array nums
.
Return signFunc(product)
.
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 |1 <= nums.length <= 1000
-100 <= nums[i] <= 100
Given a positive integer millis
, write an asynchronous function that sleeps for millis
milliseconds. It can resolve any value.
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 |1 <= millis <= 1000
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
5 |
Example 1:
6 |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 |1 <= n <= 20
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
5 |
Example 1:
6 |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 |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 |m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
You are given a string s
representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A'
: Absent.'L'
: Late.'P'
: Present.The student is eligible for an attendance award if they meet both of the following criteria:
11 | 12 |'A'
) for strictly fewer than 2 days total.'L'
) for 3 or more consecutive days.Return true
if the student is eligible for an attendance award, or false
otherwise.
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 |1 <= s.length <= 1000
s[i]
is either 'A'
, 'L'
, or 'P'
.You are given the root
of a binary tree containing digits from 0
to 9
only.
Each root-to-leaf path in the tree represents a number.
5 | 6 |1 -> 2 -> 3
represents the number 123
.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 |Input: root = [1,2,3] 18 | Output: 25 19 | Explanation: 20 | The root-to-leaf path24 | 25 |1->2
represents the number12
. 21 | The root-to-leaf path1->3
represents the number13
. 22 | Therefore, sum = 12 + 13 =25
. 23 |
Example 2:
26 |Input: root = [4,9,0,5,1] 28 | Output: 1026 29 | Explanation: 30 | The root-to-leaf path35 | 36 |4->9->5
represents the number 495. 31 | The root-to-leaf path4->9->1
represents the number 491. 32 | The root-to-leaf path4->0
represents the number 40. 33 | Therefore, sum = 495 + 491 + 40 =1026
. 34 |
37 |
Constraints:
38 | 39 |[1, 1000]
.0 <= Node.val <= 9
10
.Given an array of positive integers arr
, return the sum of all possible odd-length subarrays of arr
.
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 = 5822 | 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 |1 <= arr.length <= 100
1 <= arr[i] <= 1000
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.
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 |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 |[1, 1000]
.-1000 <= Node.val <= 1000
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 |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 |[0, 100]
.0 <= Node.val <= 100
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
5 |
Example 1:
6 |Input: root = [1,2,2,3,4,4,3] 8 | Output: true 9 |10 | 11 |
Example 2:
12 |Input: root = [1,2,2,null,3,null,3] 14 | Output: false 15 |16 | 17 |
18 |
Constraints:
19 | 20 |[1, 1000]
.-100 <= Node.val <= 100
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
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
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 |1 <= nums.length <= 105
-104 <= nums[i] <= 104
k
is in the range [1, the number of unique elements in the array]
.23 |
Follow up: Your algorithm's time complexity must be better than O(n log n)
, where n is the array's size.
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
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 |2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
39 | Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?
--------------------------------------------------------------------------------
/Two Sum/two-sum.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vectorGiven two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
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 |1 <= s.length, t.length <= 5 * 104
s
and t
consist of lowercase English letters.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.
An input string is valid if:
5 | 6 |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 |1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.