From a570fd0bebf2fa64f83f9c49d6c1a94fcd87cb1d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:28:58 -0500 Subject: [PATCH 001/485] Initial commit --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..d5dc0a35 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# LeetCode solutions in JavaScript + +[https://leetcode.com/](https://leetcode.com/) + +## License + +[MIT License](https://opensource.org/licenses/MIT) + +Copyright (c) 2019 [Josh Crozier](https://joshcrozier.com) From 371c40b07410ce10bc2e662c7503a750e43c0880 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:35:19 -0500 Subject: [PATCH 002/485] Add solution #1290 --- ...nary-number-in-a-linked-list-to-integer.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 1290-convert-binary-number-in-a-linked-list-to-integer.js diff --git a/1290-convert-binary-number-in-a-linked-list-to-integer.js b/1290-convert-binary-number-in-a-linked-list-to-integer.js new file mode 100644 index 00000000..da99bb95 --- /dev/null +++ b/1290-convert-binary-number-in-a-linked-list-to-integer.js @@ -0,0 +1,32 @@ +/** + * 1290. Convert Binary Number in a Linked List to Integer + * https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ + * Difficulty: Easy + * + * Given `head` which is a reference node to a singly-linked list. + * The value of each node in the linked list is either 0 or 1. + * The linked list holds the binary representation of a number. + * Return the decimal value of the number in the linked list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number} + */ +var getDecimalValue = function(head) { + let binary = String(head.val); + + while (head.next !== null) { + head = head.next; + binary += head.val; + } + + return parseInt(binary, 2); +}; From c15f416f0995e91472f493b670643711d1a31891 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:39:34 -0500 Subject: [PATCH 003/485] Add solution #1291 --- 1291-sequential-digits.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1291-sequential-digits.js diff --git a/1291-sequential-digits.js b/1291-sequential-digits.js new file mode 100644 index 00000000..077d6a45 --- /dev/null +++ b/1291-sequential-digits.js @@ -0,0 +1,29 @@ +/** + * 1291. Sequential Digits + * https://leetcode.com/problems/sequential-digits/ + * Difficulty: Medium + * + * An integer has sequential digits if and only if each digit in the number is one more than the previous digit. + * Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. + */ + +/** + * @param {number} low + * @param {number} high + * @return {number[]} + */ +var sequentialDigits = function(low, high) { + return getSequentialNumbers().filter(n => n >= low && n <= high); +}; + +function getSequentialNumbers() { + const numbers = new Set([]); + + for (let i = 0; i < 10; i++) { + for (let j = 9; j > 0 && j > i + 1; j--) { + numbers.add(+'123456789'.slice(i, j)); + } + } + + return [...numbers].sort((a, b) => a - b); +} From d23bc2d5f2bf920cb3f55b61f8b422ef6e4b02b0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:45:57 -0500 Subject: [PATCH 004/485] Add solution #1292 --- ...ith-sum-less-than-or-equal-to-threshold.js | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js diff --git a/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js b/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js new file mode 100644 index 00000000..67723550 --- /dev/null +++ b/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js @@ -0,0 +1,37 @@ +/** + * 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold + * https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/ + * Difficulty: Medium + * + * Given a `m x n` matrix `mat` and an integer `threshold`. + * Return the maximum side-length of a square with a sum less than or equal to `threshold` or return 0 if there is no such square. + */ + +/** + * @param {number[][]} mat + * @param {number} threshold + * @return {number} + */ +var maxSideLength = function(mat, threshold) { + let max = 0; + + loop1: for (let i = 0; i < mat[0].length; i++) { + loop2: for (let j = 0; j < mat.length; j++) { + if (!mat[j + 1] || !mat[j][i + 1]) { break loop2; } + loop3: for (let s = 1; s < 1000; s++) { + if (!mat[j + s] || !mat[j][i + s] || getSquareSum(mat, i, j, s + 1) > threshold) { break loop3; } + max = Math.max(s + 1, max); + } + } + } + + return max; +}; + +function getSquareSum(mat, i, j, size) { + let sum = 0; + for (let s = 0; s < size; s++) { + mat[j + s].slice(i, i + size).forEach(v => sum += v); + } + return sum; +} From 1bf733e5cd5ed730381b522e07e1bfb057db61e8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2020 23:14:34 -0500 Subject: [PATCH 005/485] Add solution #1287 --- ...-appearing-more-than-25-in-sorted-array.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1287-element-appearing-more-than-25-in-sorted-array.js diff --git a/1287-element-appearing-more-than-25-in-sorted-array.js b/1287-element-appearing-more-than-25-in-sorted-array.js new file mode 100644 index 00000000..4d9bd3e2 --- /dev/null +++ b/1287-element-appearing-more-than-25-in-sorted-array.js @@ -0,0 +1,25 @@ +/** + * 1287. Element Appearing More Than 25% In Sorted Array + * https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/ + * Difficulty: Easy + * + * Given an integer array sorted in non-decreasing order, + * there is exactly one integer in the array that occurs more than 25% of the time. + * + * Return that integer. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var findSpecialInteger = function(arr) { + const limit = arr.length * 0.25; + const offset = limit % 1 === 0 ? limit : Math.ceil(limit) - 1; + + for (let i = 0; i < arr.length; i++) { + if (arr[i] === arr[i + offset]) { + return arr[i]; + } + } +}; \ No newline at end of file From d8ee22d87850c4f6e5d9382fd0cddaf24b29d6f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2020 00:28:35 -0500 Subject: [PATCH 006/485] Add solution #1252 --- 1252-cells-with-odd-values-in-a-matrix.js | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 1252-cells-with-odd-values-in-a-matrix.js diff --git a/1252-cells-with-odd-values-in-a-matrix.js b/1252-cells-with-odd-values-in-a-matrix.js new file mode 100644 index 00000000..cbbffc45 --- /dev/null +++ b/1252-cells-with-odd-values-in-a-matrix.js @@ -0,0 +1,34 @@ +/** + * 1252. Cells with Odd Values in a Matrix + * https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ + * Difficulty: Easy + * + * Given `n` and `m` which are the dimensions of a matrix + * initialized by zeros and given an array `indices` + * where `indices[i] = [ri, ci]`. + * For each pair of `[ri, ci]` you have to increment all + * cells in row `ri` and column `ci` by 1. + * + * Return the number of cells with odd values in the + * matrix after applying the increment to all `indices`. + */ + +/** + * @param {number} n + * @param {number} m + * @param {number[][]} indices + * @return {number} + */ +var oddCells = function(n, m, indices) { + const matrix = new Array(n).fill().map(_ => new Array(m).fill(0)); + + indices.forEach(indice => { + const [row, column] = indice; + matrix[row].forEach((value, index) => matrix[row][index] = value + 1); + matrix.forEach(row => row[column] = row[column] + 1); + }); + + return matrix.reduce((count, row) => { + return count + row.filter(value => value % 2 !== 0).length; + }, 0); +}; From f89f104f62cfd64fefb4c448247a127da6f4ebc7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2020 23:11:12 -0500 Subject: [PATCH 007/485] Add solution #58 --- 0058-length-of-last-word.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 0058-length-of-last-word.js diff --git a/0058-length-of-last-word.js b/0058-length-of-last-word.js new file mode 100644 index 00000000..db2632c8 --- /dev/null +++ b/0058-length-of-last-word.js @@ -0,0 +1,23 @@ +/** + * 58. Length of Last Word + * https://leetcode.com/problems/length-of-last-word/ + * Difficulty: Easy + * + * Given a string `s` consists of upper/lower-case alphabets + * and empty space characters ' ', return the length of last + * word (last word means the last appearing word if we loop + * from left to right) in the string. + * + * If the last word does not exist, return 0. + * + * Note: A word is defined as a maximal substring consisting + * of non-space characters only. + */ + +/** + * @param {string} s + * @return {number} + */ +var lengthOfLastWord = function(s) { + return s.trim().split(/\s+/).pop().length; +}; From 072f2983e3905b4637359c0ce6f4811b05b071e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2020 23:26:09 -0500 Subject: [PATCH 008/485] Add solution #1232 --- 1232-check-if-it-is-a-straight-line.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 1232-check-if-it-is-a-straight-line.js diff --git a/1232-check-if-it-is-a-straight-line.js b/1232-check-if-it-is-a-straight-line.js new file mode 100644 index 00000000..691780d0 --- /dev/null +++ b/1232-check-if-it-is-a-straight-line.js @@ -0,0 +1,21 @@ +/** + * 1232. Check If It Is a Straight Line + * https://leetcode.com/problems/check-if-it-is-a-straight-line/ + * Difficulty: Easy + * + * You are given an array `coordinates`, `coordinates[i] = [x, y]`, + * where `[x, y] represents the coordinate of a point. + * + * Check if these points make a straight line in the XY plane. + */ + +/** + * @param {number[][]} coordinates + * @return {boolean} + */ +var checkStraightLine = function(coords) { + const m = (coords[0][1] - coords[1][1]) / (coords[0][0] - coords[1][0]); + const b = coords[0][1] - m * coords[0][0]; + + return coords.every(coord => coord[1] === m * coord[0] + b); +}; From ab7ac000521f91f21cc3e43cfeb79a6f2e78b7c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2020 23:16:36 -0500 Subject: [PATCH 009/485] Add solution #1103 --- 1103-distribute-candies-to-people.js | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 1103-distribute-candies-to-people.js diff --git a/1103-distribute-candies-to-people.js b/1103-distribute-candies-to-people.js new file mode 100644 index 00000000..b808b80a --- /dev/null +++ b/1103-distribute-candies-to-people.js @@ -0,0 +1,38 @@ +/** + * 1103. Distribute Candies to People + * https://leetcode.com/problems/distribute-candies-to-people/ + * Difficulty: Easy + * + * We distribute some number of `candies`, to a row of `n = num_people` + * people in the following way: + * + * We then give 1 candy to the first person, 2 candies to the second + * person, and so on until we give `n` candies to the last person. + * + * Then, we go back to the start of the row, giving `n + 1` candies to + * the first person, `n + 2` candies to the second person, and so on + * until we give `2 * n` candies to the last person. + * + * This process repeats (with us giving one more candy each time, + * and moving to the start of the row after we reach the end) until + * we run out of candies. The last person will receive all of our + * remaining candies (not necessarily one more than the previous gift). + * + * Return an array (of length `num_people` and sum `candies`) that + * represents the final distribution of candies. + */ + +/** + * @param {number} candies + * @param {number} num_people + * @return {number[]} + */ +var distributeCandies = function(candies, num_people) { + const answer = new Array(num_people).fill(0); + + for (let amount = 0; candies > 0; candies -= amount) { + answer[amount % num_people] += Math.min(candies, ++amount); + } + + return answer; +}; From 83420010d77adb9a55c19100fb3607015b6136c2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2020 23:49:19 -0500 Subject: [PATCH 010/485] Add solution #1009 --- 1009-complement-of-base-10-integer.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1009-complement-of-base-10-integer.js diff --git a/1009-complement-of-base-10-integer.js b/1009-complement-of-base-10-integer.js new file mode 100644 index 00000000..8b48eef1 --- /dev/null +++ b/1009-complement-of-base-10-integer.js @@ -0,0 +1,25 @@ +/** + * 1009. Complement of Base 10 Integer + * https://leetcode.com/problems/complement-of-base-10-integer/ + * Difficulty: Easy + * + * Every non-negative integer N has a binary representation. + * For example, 5 can be represented as "101" in binary, + * 11 as "1011" in binary, and so on. Note that except for + * N = 0, there are no leading zeroes in any binary representation. + * + * The complement of a binary representation is the number in binary + * you get when changing every 1 to a 0 and 0 to a 1. For example, + * the complement of "101" in binary is "010" in binary. + * + * For a given number N in base-10, return the complement of it's + * binary representation as a base-10 integer. + */ + +/** + * @param {number} N + * @return {number} + */ +var bitwiseComplement = function(N) { + return parseInt(N.toString(2).split('').map(n => n ^ 1).join(''), 2); +}; From f9edab224a7178ae6898ad06ace0794a37efb296 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2020 22:07:03 -0500 Subject: [PATCH 011/485] Add solution #989 --- 0989-add-to-arrayform-of-integer.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 0989-add-to-arrayform-of-integer.js diff --git a/0989-add-to-arrayform-of-integer.js b/0989-add-to-arrayform-of-integer.js new file mode 100644 index 00000000..715e131e --- /dev/null +++ b/0989-add-to-arrayform-of-integer.js @@ -0,0 +1,21 @@ +/** + * 989. Add to Array-Form of Integer + * https://leetcode.com/problems/add-to-array-form-of-integer/ + * Difficulty: Easy + * + * For a non-negative integer X, the array-form of X is + * an array of its digits in left to right order. + * For example, if X = 1231, then the array form is [1,2,3,1]. + * + * Given the array-form A of a non-negative integer X, + * return the array-form of the integer X+K. + */ + +/** + * @param {number[]} A + * @param {number} K + * @return {number[]} + */ +var addToArrayForm = function(A, K) { + return String(BigInt(A.join('')) + BigInt(K)).split(''); +}; From 2ddd3d6e9b2a954af4bcac40d1af92f2f859d8fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2020 22:31:34 -0500 Subject: [PATCH 012/485] Add solution #977 --- 0977-squares-of-a-sorted-array.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 0977-squares-of-a-sorted-array.js diff --git a/0977-squares-of-a-sorted-array.js b/0977-squares-of-a-sorted-array.js new file mode 100644 index 00000000..e1a37507 --- /dev/null +++ b/0977-squares-of-a-sorted-array.js @@ -0,0 +1,17 @@ +/** + * 977. Squares of a Sorted Array + * https://leetcode.com/problems/squares-of-a-sorted-array/ + * Difficulty: Easy + * + * Given an array of integers A sorted in non-decreasing order, + * return an array of the squares of each number, + * also in sorted non-decreasing order. + */ + +/** + * @param {number[]} A + * @return {number[]} + */ +var sortedSquares = function(A) { + return A.map(n => Math.pow(n, 2)).sort((a, b) => a - b); +}; From 6baa71b5f4d8a5e30961e88471175b9d69fe2a63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2020 22:28:40 -0500 Subject: [PATCH 013/485] Add solution #976 --- 0976-largest-perimeter-triangle.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 0976-largest-perimeter-triangle.js diff --git a/0976-largest-perimeter-triangle.js b/0976-largest-perimeter-triangle.js new file mode 100644 index 00000000..ec9c72c2 --- /dev/null +++ b/0976-largest-perimeter-triangle.js @@ -0,0 +1,28 @@ +/** + * 976. Largest Perimeter Triangle + * https://leetcode.com/problems/largest-perimeter-triangle/ + * Difficulty: Easy + * + * Given an array A of positive lengths, return the largest + * perimeter of a triangle with non-zero area, formed from 3 + * of these lengths. + * + * If it is impossible to form any triangle of non-zero + * area, return 0. + */ + +/** + * @param {number[]} A + * @return {number} + */ +var largestPerimeter = function(A) { + A.sort((a, b) => a - b); + + for (let i = A.length - 1; i > 1; --i) { + if (A[i] < A[i - 1] + A[i - 2]) { + return A[i] + A[i - 1] + A[i - 2]; + } + } + + return 0; +}; From 35c876077de0fe910a4cc850c3955a37d55a2a0a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2020 22:52:46 -0500 Subject: [PATCH 014/485] Add solution #970 --- 0970-powerful-integers.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 0970-powerful-integers.js diff --git a/0970-powerful-integers.js b/0970-powerful-integers.js new file mode 100644 index 00000000..327dc660 --- /dev/null +++ b/0970-powerful-integers.js @@ -0,0 +1,37 @@ +/** + * 970. Powerful Integers + * https://leetcode.com/problems/powerful-integers/ + * Difficulty: Easy + * + * Given two positive integers x and y, an integer + * is powerful if it is equal to x^i + y^j for some + * integers i >= 0 and j >= 0. + * + * Return a list of all powerful integers that have + * value less than or equal to bound. + * + * You may return the answer in any order. In your + * answer, each value should occur at most once. + */ + +/** + * @param {number} x + * @param {number} y + * @param {number} bound + * @return {number[]} + */ +var powerfulIntegers = function(x, y, bound) { + const result = new Set(); + + for (let i = 1; i < bound; i *= x) { + for (let j = 1; i + j <= bound; j *= y) { + result.add(i + j); + + if (y === 1) { break }; + } + + if (x === 1) { break }; + } + + return Array.from(result); +}; From f2b3b8593ddf0a28d1d23c97a116052c169d40aa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2020 23:04:20 -0500 Subject: [PATCH 015/485] Add solution #985 --- 0985-sum-of-even-numbers-after-queries.js | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 0985-sum-of-even-numbers-after-queries.js diff --git a/0985-sum-of-even-numbers-after-queries.js b/0985-sum-of-even-numbers-after-queries.js new file mode 100644 index 00000000..2f75f8d8 --- /dev/null +++ b/0985-sum-of-even-numbers-after-queries.js @@ -0,0 +1,29 @@ +/** + * 985. Sum of Even Numbers After Queries + * https://leetcode.com/problems/sum-of-even-numbers-after-queries/ + * Difficulty: Easy + * + * We have an array A of integers, and an array queries of queries. + * + * For the i-th query val = queries[i][0], index = queries[i][1], + * we add val to A[index]. Then, the answer to the i-th query + * is the sum of the even values of A. + * + * (Here, the given index = queries[i][1] is a 0-based index, and + * each query permanently modifies the array A.) + * + * Return the answer to all queries. Your answer array should + * have answer[i] as the answer to the i-th query. + */ + +/** + * @param {number[]} A + * @param {number[][]} queries + * @return {number[]} + */ +var sumEvenAfterQueries = function(A, queries) { + return queries.reduce((sums, query) => { + A[query[1]] += query[0]; + return [...sums, A.reduce((sum, n) => sum + (n % 2 === 0 ? n : 0), 0)]; + }, []); +}; From 87055ab10bf564f758ef41ee58109035f9916f3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2020 23:15:40 -0500 Subject: [PATCH 016/485] Add solution #985 --- 0985-sum-of-even-numbers-after-queries.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/0985-sum-of-even-numbers-after-queries.js b/0985-sum-of-even-numbers-after-queries.js index 2f75f8d8..fcb6468a 100644 --- a/0985-sum-of-even-numbers-after-queries.js +++ b/0985-sum-of-even-numbers-after-queries.js @@ -27,3 +27,20 @@ var sumEvenAfterQueries = function(A, queries) { return [...sums, A.reduce((sum, n) => sum + (n % 2 === 0 ? n : 0), 0)]; }, []); }; + +// Significantly faster, less elegant approach: +/** + * @param {number[]} A + * @param {number[][]} queries + * @return {number[]} + */ +var sumEvenAfterQueries = function(A, queries) { + return queries.reduce((sums, query) => { + const [v, i] = query; + const prev = A[i]; + const lastSum = sums.length ? sums[sums.length - 1] : A.reduce((sum, n) => sum + (n % 2 === 0 ? n : 0), 0); + A[i] += v; + sums.push(lastSum - (prev % 2 === 0 ? prev : 0) + (A[i] % 2 === 0 ? A[i] : 0)); + return sums; + }, []); +}; From fc767976337c492154ac177926523359598f5101 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2020 23:37:23 -0500 Subject: [PATCH 017/485] Add solution #929 --- 0929-unique-email-addresses.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 0929-unique-email-addresses.js diff --git a/0929-unique-email-addresses.js b/0929-unique-email-addresses.js new file mode 100644 index 00000000..fc3a29e5 --- /dev/null +++ b/0929-unique-email-addresses.js @@ -0,0 +1,33 @@ +/** + * 929. Unique Email Addresses + * https://leetcode.com/problems/unique-email-addresses/ + * Difficulty: Easy + * + * Every email consists of a local name and a domain name, separated by the @ sign. + * + * For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. + * + * Besides lowercase letters, these emails may contain '.'s or '+'s. + * + * If you add periods ('.') between some characters in the local name part of an email address, mail + * sent there will be forwarded to the same address without dots in the local name. + * For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. + * (Note that this rule does not apply for domain names.) + * + * If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. + * This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to + * my@email.com. (Again, this rule does not apply for domain names.) + * + * It is possible to use both of these rules at the same time. + * + * Given a list of emails, we send one email to each address in the list. + * How many different addresses actually receive mails? + */ + +/** + * @param {string[]} emails + * @return {number} + */ +var numUniqueEmails = function(emails) { + return new Set(emails.map(e => e.replace(/\.(?=[\w\.+]+@)|\+[\w.+]+(?=@)/g, ''))).size; +}; From 6c9333535ce1f56f3621124cb8538beb003774c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 14:10:54 -0500 Subject: [PATCH 018/485] Add solution #387 --- 0387-first-unique-character-in-a-string.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 0387-first-unique-character-in-a-string.js diff --git a/0387-first-unique-character-in-a-string.js b/0387-first-unique-character-in-a-string.js new file mode 100644 index 00000000..4004b60b --- /dev/null +++ b/0387-first-unique-character-in-a-string.js @@ -0,0 +1,22 @@ +/** + * 387. First Unique Character in a String + * https://leetcode.com/problems/first-unique-character-in-a-string/ + * Difficulty: Easy + * + * Given a string, find the first non-repeating character in + * it and return it's index. If it doesn't exist, return -1. + */ + +/** + * @param {string} s + * @return {number} + */ +var firstUniqChar = function(s) { + for (let i = 0; i < s.length; i++) { + if (s.indexOf(s.charAt(i)) === s.lastIndexOf(s.charAt(i))) { + return i; + } + } + + return -1; +}; From 169b717afd065a6c51a8ee9971cc382e63478b4f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 19:37:08 -0500 Subject: [PATCH 019/485] Add solution #451 --- 0451-sort-characters-by-frequency.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 0451-sort-characters-by-frequency.js diff --git a/0451-sort-characters-by-frequency.js b/0451-sort-characters-by-frequency.js new file mode 100644 index 00000000..4c29eed3 --- /dev/null +++ b/0451-sort-characters-by-frequency.js @@ -0,0 +1,24 @@ +/** + * 451. Sort Characters By Frequency + * https://leetcode.com/problems/sort-characters-by-frequency/ + * Difficulty: Medium + * + * Given a string, sort it in decreasing order + * based on the frequency of characters. + */ + +/** + * @param {string} s + * @return {string} + */ +var frequencySort = function(s) { + const map = new Map(); + s.split('').forEach(char => { + map.set(char, map.has(char) ? map.get(char) + 1 : 1); + }); + + return [...map] + .sort((a, b) => b[1] - a[1]) + .map(entry => entry[0].repeat(entry[1])) + .join(''); +}; From ac8b4e56111e14bc044877b8915cb2f3ee57f0c2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 19:55:03 -0500 Subject: [PATCH 020/485] Add solution #739 --- 0739-daily-temperatures.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 0739-daily-temperatures.js diff --git a/0739-daily-temperatures.js b/0739-daily-temperatures.js new file mode 100644 index 00000000..1e73f855 --- /dev/null +++ b/0739-daily-temperatures.js @@ -0,0 +1,36 @@ +/** + * 739. Daily Temperatures + * https://leetcode.com/problems/daily-temperatures/ + * Difficulty: Medium + * + * Given a list of daily temperatures T, return a list such that, for + * each day in the input, tells you how many days you would have to + * wait until a warmer temperature. If there is no future day for + * which this is possible, put 0 instead. + * + * For example, given the list of temperatures + * T = [73, 74, 75, 71, 69, 72, 76, 73], your output + * should be [1, 1, 4, 2, 1, 1, 0, 0]. + * + * Note: The length of temperatures will be in the range [1, 30000]. + * Each temperature will be an integer in the range [30, 100]. + */ + +/** + * @param {number[]} T + * @return {number[]} + */ +var dailyTemperatures = function(T) { + const result = new Array(T.length).fill(0); + const stack = []; + + for (let i = 0; i < T.length; i++) { + while (stack.length && T[stack[stack.length - 1]] < T[i]) { + const topIndex = stack.pop(); + result[topIndex] = i - topIndex; + } + stack.push(i); + } + + return result; +}; From 39ead0bb5f5fb4b6a9a2d660c2f5259a98883201 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 21:21:34 -0500 Subject: [PATCH 021/485] Add solution #1304 --- 1304-find-n-unique-integers-sum-up-to-zero.js | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 1304-find-n-unique-integers-sum-up-to-zero.js diff --git a/1304-find-n-unique-integers-sum-up-to-zero.js b/1304-find-n-unique-integers-sum-up-to-zero.js new file mode 100644 index 00000000..f019e9ae --- /dev/null +++ b/1304-find-n-unique-integers-sum-up-to-zero.js @@ -0,0 +1,20 @@ +/** + * 1304. Find N Unique Integers Sum up to Zero + * https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ + * Difficulty: Easy + * + * Given an integer n, return any array containing + * n unique integers such that they add up to 0. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var sumZero = function(n) { + const result = n % 2 !== 0 ? [0] : []; + while (result.length < n) { + result.push(result.length + 1, (result.length + 1) * -1); + } + return result; +}; From df4dd7f18394757c6f1cc7bbc42f2bbf4cc17490 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 21:26:12 -0500 Subject: [PATCH 022/485] Add solution #989 --- ...rrayform-of-integer.js => 0989-add-to-array-form-of-integer.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 0989-add-to-arrayform-of-integer.js => 0989-add-to-array-form-of-integer.js (100%) diff --git a/0989-add-to-arrayform-of-integer.js b/0989-add-to-array-form-of-integer.js similarity index 100% rename from 0989-add-to-arrayform-of-integer.js rename to 0989-add-to-array-form-of-integer.js From 7cf07777e32d913a5f26a173fc467ab7befdfcf6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2020 19:11:52 -0500 Subject: [PATCH 023/485] Add solution #1317 --- ...eger-to-the-sum-of-two-no-zero-integers.js | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1317-convert-integer-to-the-sum-of-two-no-zero-integers.js diff --git a/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js b/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js new file mode 100644 index 00000000..dbdfd608 --- /dev/null +++ b/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js @@ -0,0 +1,29 @@ +/** + * 1317. Convert Integer to the Sum of Two No-Zero Integers + * https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ + * Difficulty: Easy + * + * Given an integer n. No-Zero integer is a positive integer which + * doesn't contain any 0 in its decimal representation. + * + * Return a list of two integers [A, B] where: + * + * - A and B are No-Zero integers. + * - A + B = n + * + * It's guarateed that there is at least one valid solution. + * If there are many valid solutions you can return any of them. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var getNoZeroIntegers = function(n) { + const hasNoZero = n => String(n).indexOf('0') === -1; + for (let i = n; i; --i) { + if (hasNoZero(i) && hasNoZero(n - i)) { + return [i, n - i]; + } + } +}; From de8f5720663fc39482b53a133e67ef54b139c15c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2020 23:05:32 -0500 Subject: [PATCH 024/485] Add solution #226 --- 0226-invert-binary-tree.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 0226-invert-binary-tree.js diff --git a/0226-invert-binary-tree.js b/0226-invert-binary-tree.js new file mode 100644 index 00000000..8ca433ef --- /dev/null +++ b/0226-invert-binary-tree.js @@ -0,0 +1,23 @@ +/** + * 226. Invert Binary Tree + * https://leetcode.com/problems/invert-binary-tree/ + * Difficulty: Easy + * + * Invert a binary tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} node + * @return {TreeNode} + */ +var invertTree = function(node) { + if (node) [node.left, node.right] = [invertTree(node.right), invertTree(node.left)]; + return node; +}; From 7fa1871deafaa2bf63d47edf700b109e71a9ecee Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2020 23:20:54 -0500 Subject: [PATCH 025/485] Add solution #1318 --- ...minimum-flips-to-make-a-or-b-equal-to-c.js | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 1318-minimum-flips-to-make-a-or-b-equal-to-c.js diff --git a/1318-minimum-flips-to-make-a-or-b-equal-to-c.js b/1318-minimum-flips-to-make-a-or-b-equal-to-c.js new file mode 100644 index 00000000..5b48e885 --- /dev/null +++ b/1318-minimum-flips-to-make-a-or-b-equal-to-c.js @@ -0,0 +1,31 @@ +/** + * 1318. Minimum Flips to Make a OR b Equal to c + * https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ + * Difficulty: Medium + * + * Given 3 positives numbers a, b and c. + * Return the minimum flips required in some bits of a and b + * to make ( a OR b == c ). (bitwise OR operation). + * + * Flip operation consists of change any single bit 1 to 0 + * or change the bit 0 to 1 in their binary representation. + */ + +/** + * @param {number} a + * @param {number} b + * @param {number} c + * @return {number} + */ +var minFlips = function(a, b, c, flips = 0) { + [a, b, c] = [a, b, c].map(x => x.toString(2).padStart(32, 0)); + + for (let i = 0; i < c.length; i++) { + if ((+a[i] | +b[i]) !== +c[i]) { + if (((+a[i] ^ 1) | +b[i]) === +c[i] || (+a[i] | (+b[i] ^ 1)) === +c[i]) flips++; + else if (((+a[i] ^ 1) | (+b[i] ^ 1)) === +c[i]) flips += 2; + } + } + + return flips; +}; From 18ebfdd38255dd52e0dfa175e68e5b7e263021d1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2020 22:41:36 -0500 Subject: [PATCH 026/485] Add solution #617 --- 0617-merge-two-binary-trees.js | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 0617-merge-two-binary-trees.js diff --git a/0617-merge-two-binary-trees.js b/0617-merge-two-binary-trees.js new file mode 100644 index 00000000..2e518f7b --- /dev/null +++ b/0617-merge-two-binary-trees.js @@ -0,0 +1,38 @@ +/** + * 617. Merge Two Binary Trees + * https://leetcode.com/problems/merge-two-binary-trees/ + * Difficulty: Easy + * + * Given two binary trees and imagine that when you put one + * of them to cover the other, some nodes of the two trees + * are overlapped while the others are not. + * + * You need to merge them into a new binary tree. + * The merge rule is that if two nodes overlap, then sum + * node values up as the new value of the merged node. + * Otherwise, the NOT null node will be used as the + * node of new tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} t1 + * @param {TreeNode} t2 + * @return {TreeNode} + */ +var mergeTrees = function(t1, t2) { + if (!t1) return t2; + if (!t2) return t1; + + t1.val += t2.val; + t1.left = mergeTrees(t1.left, t2.left); + t1.right = mergeTrees(t1.right, t2.right); + + return t1; +}; From b31597915aa2436162a6fbf3ff0e1f9ee08ab732 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2020 23:00:06 -0500 Subject: [PATCH 027/485] Add solution #1207 --- 1207-unique-number-of-occurrences.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 1207-unique-number-of-occurrences.js diff --git a/1207-unique-number-of-occurrences.js b/1207-unique-number-of-occurrences.js new file mode 100644 index 00000000..35b8cacf --- /dev/null +++ b/1207-unique-number-of-occurrences.js @@ -0,0 +1,21 @@ +/** + * 1207. Unique Number of Occurrences + * https://leetcode.com/problems/unique-number-of-occurrences/ + * Difficulty: Easy + * + * Given an array of integers arr, write a + * function that returns true if and only + * if the number of occurrences of each + * value in the array is unique. + */ + +/** + * @param {number[]} numbers + * @return {boolean} + */ +var uniqueOccurrences = function(numbers) { + const map = new Map(); + numbers.forEach(n => map.set(n, map.has(n) ? map.get(n) + 1 : 1)); + const occurrences = Array.from(map.values()); + return new Set(occurrences).size === occurrences.length +}; From b1f2bd1789348f177a3db2b9fc9f0dc6b57aa7ff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2020 23:59:22 -0500 Subject: [PATCH 028/485] Add solution #804 --- 0804-unique-morse-code-words.js | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 0804-unique-morse-code-words.js diff --git a/0804-unique-morse-code-words.js b/0804-unique-morse-code-words.js new file mode 100644 index 00000000..40a0e44d --- /dev/null +++ b/0804-unique-morse-code-words.js @@ -0,0 +1,39 @@ +/** + * 804. Unique Morse Code Words + * https://leetcode.com/problems/unique-morse-code-words/ + * Difficulty: Easy + * + * International Morse Code defines a standard encoding where + * each letter is mapped to a series of dots and dashes, as + * follows: "a" maps to ".-", "b" maps to "-...", + * "c" maps to "-.-.", and so on. + * + * For convenience, the full table for the 26 letters of the + * English alphabet is given below: + * + * [".-","-...","-.-.","-..",".","..-.","--.","....","..", + * ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.", + * "...","-","..-","...-",".--","-..-","-.--","--.."] + * + * Now, given a list of words, each word can be written as a + * concatenation of the Morse code of each letter. + * For example, "cba" can be written as "-.-..--...", + * (which is the concatenation "-.-." + "-..." + ".-"). + * We'll call such a concatenation, the transformation of a word. + * + * Return the number of different transformations + * among all words we have. + */ + +/** + * @param {string[]} words + * @return {number} + */ +var uniqueMorseRepresentations = function(words) { + const codes = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---", + "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-", + "..-","...-",".--","-..-","-.--","--.."]; + const map = new Map(codes.map((v, i) => [String.fromCharCode(97 + i), v])); + const transformed = words.map(word => word.split('').map(c => map.get(c)).join('')); + return new Set(transformed).size; +}; From 6dcc72c29ff40d9d187990448b7fddddf82cf629 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 20:53:23 -0500 Subject: [PATCH 029/485] Add solution #36 --- 0036-valid-sudoku.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 0036-valid-sudoku.js diff --git a/0036-valid-sudoku.js b/0036-valid-sudoku.js new file mode 100644 index 00000000..bb000b2e --- /dev/null +++ b/0036-valid-sudoku.js @@ -0,0 +1,38 @@ +/** + * 36. Valid Sudoku + * https://leetcode.com/problems/valid-sudoku/ + * Difficulty: Medium + * + * Determine if a 9x9 Sudoku board is valid. + * Only the filled cells need to be validated according to the following rules: + * + * - Each row must contain the digits 1-9 without repetition. + * - Each column must contain the digits 1-9 without repetition. + * - Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. + * + * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. + */ + +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function(board) { + const rows = new Array(9).fill().map(() => new Set()); + const columns = new Array(9).fill().map(() => new Set()); + const boxes = new Array(9).fill().map(() => new Set()); + + for (let i = 0; i < 9; i++) { + for (let j = 0; j < 9; j++) { + const value = board[i][j]; + const k = Math.floor(i / 3) * 3 + Math.floor(j / 3); + const options = [rows[i], columns[j], boxes[k]]; + + if (options.some(option => option.has(value))) return false; + if (value === '.') continue; + options.forEach(option => option.add(value)); + } + } + + return true; +}; From 7e45b25921bbd117b046e60c9421a418fa23dd38 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 21:37:05 -0500 Subject: [PATCH 030/485] Add solution #1309 --- ...string-from-alphabet-to-integer-mapping.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1309-decrypt-string-from-alphabet-to-integer-mapping.js diff --git a/1309-decrypt-string-from-alphabet-to-integer-mapping.js b/1309-decrypt-string-from-alphabet-to-integer-mapping.js new file mode 100644 index 00000000..153dd6ae --- /dev/null +++ b/1309-decrypt-string-from-alphabet-to-integer-mapping.js @@ -0,0 +1,25 @@ +/** + * 1309. Decrypt String from Alphabet to Integer Mapping + * https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ + * Difficulty: Easy + * + * Given a string s formed by digits ('0' - '9') and '#' . + * We want to map s to English lowercase characters as follows: + * + * - Characters ('a' to 'i') are represented by ('1' to '9') respectively. + * - Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. + * + * Return the string formed after mapping. + * + * It's guaranteed that a unique mapping will always exist. + */ + +/** + * @param {string} s + * @return {string} + */ +var freqAlphabets = function(s) { + return s.replace(/\d{2}#|\d/g, match => { + return String.fromCharCode('a'.charCodeAt() + parseInt(match, 10) - 1); + }); +}; From c621f3e7029be92e1064ceb72652aed20456ee82 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 21:48:19 -0500 Subject: [PATCH 031/485] Add solution #819 --- 0819-most-common-word.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 0819-most-common-word.js diff --git a/0819-most-common-word.js b/0819-most-common-word.js new file mode 100644 index 00000000..44d2db32 --- /dev/null +++ b/0819-most-common-word.js @@ -0,0 +1,27 @@ +/** + * 819. Most Common Word + * https://leetcode.com/problems/most-common-word/ + * Difficulty: Easy + * + * Given a paragraph and a list of banned words, return the most frequent word that + * is not in the list of banned words. It is guaranteed there is at least one word + * that isn't banned, and that the answer is unique. + * + * Words in the list of banned words are given in lowercase, and free of punctuation. + * Words in the paragraph are not case sensitive. The answer is in lowercase. + */ + +/** + * @param {string} paragraph + * @param {string[]} banned + * @return {string} + */ +var mostCommonWord = function(paragraph, banned) { + const occurrences = new Map(); + paragraph.toLowerCase().replace(/[^\w\s]/g, ' ').split(/\s+/).forEach(word => { + if (!banned.includes(word)) { + occurrences.set(word, occurrences.has(word) ? occurrences.get(word) + 1 : 1); + } + }); + return Array.from(occurrences).sort((a, b) => b[1] - a[1])[0][0]; +}; From 47a5a3f10ff143d96bfe77e6c916e6cccaab2cfd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 21:54:37 -0500 Subject: [PATCH 032/485] Add solution #151 --- 0151-reverse-words-in-a-string.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 0151-reverse-words-in-a-string.js diff --git a/0151-reverse-words-in-a-string.js b/0151-reverse-words-in-a-string.js new file mode 100644 index 00000000..0b25efa6 --- /dev/null +++ b/0151-reverse-words-in-a-string.js @@ -0,0 +1,15 @@ +/** + * 151. Reverse Words in a String + * https://leetcode.com/problems/reverse-words-in-a-string/ + * Difficulty: Medium + * + * Given an input string, reverse the string word by word. + */ + +/** + * @param {string} s + * @return {string} + */ +var reverseWords = function(s) { + return s.trim().replace(/\s+/g, ' ').split(/\s/).reverse().join(' '); +}; From 770201c1d700045ed7757361fd5d56082a0abe5b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2020 21:40:27 -0500 Subject: [PATCH 033/485] Add solution #1297 --- ...um-number-of-occurrences-of-a-substring.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 1297-maximum-number-of-occurrences-of-a-substring.js diff --git a/1297-maximum-number-of-occurrences-of-a-substring.js b/1297-maximum-number-of-occurrences-of-a-substring.js new file mode 100644 index 00000000..0d4d06fb --- /dev/null +++ b/1297-maximum-number-of-occurrences-of-a-substring.js @@ -0,0 +1,32 @@ +/** + * 1297. Maximum Number of Occurrences of a Substring + * https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/ + * Difficulty: Medium + * + * Given a string s, return the maximum number of ocurrences of + * any substring under the following rules: + * + * - The number of unique characters in the substring must be less + * than or equal to maxLetters. + * - The substring size must be between minSize and maxSize inclusive. + */ + +/** + * @param {string} s + * @param {number} maxLetters + * @param {number} minSize + * @param {number} maxSize + * @return {number} + */ +var maxFreq = function(s, maxLetters, minSize, maxSize) { + const occurrences = new Map(); + + for (let i = 0; i <= s.length - minSize; i++) { + const string = s.substr(i, minSize); + if (new Set(string.split('')).size <= maxLetters) { + occurrences.set(string, occurrences.has(string) ? occurrences.get(string) + 1 : 1); + } + } + + return (Array.from(occurrences).sort((a, b) => b[1] - a[1])[0] || [])[1] || 0; +}; From 9deeb377c0afcb4e193436989757096ecb4e644a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2020 23:23:54 -0500 Subject: [PATCH 034/485] Add solution #1189 --- 1189-maximum-number-of-balloons.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1189-maximum-number-of-balloons.js diff --git a/1189-maximum-number-of-balloons.js b/1189-maximum-number-of-balloons.js new file mode 100644 index 00000000..8aea11b4 --- /dev/null +++ b/1189-maximum-number-of-balloons.js @@ -0,0 +1,25 @@ +/** + * 1189. Maximum Number of Balloons + * https://leetcode.com/problems/maximum-number-of-balloons/ + * Difficulty: Easy + * + * Given a string text, you want to use the characters of text + * to form as many instances of the word "balloon" as possible. + * + * You can use each character in text at most once. Return the + * maximum number of instances that can be formed. + */ + +/** + * @param {string} text + * @return {number} + */ +var maxNumberOfBalloons = function(text, word = 'balloon', i = 0, count = 0) { + const map = text.split('').reduce((o, k) => ({...o, [k]: o[k] ? ++o[k] : 1}), {}); + while (true) { + const char = word[i++ % word.length]; + if (!map[char] || map[char]-- === 0) break; + if (i % word.length === 0) count++; + } + return count; +}; From 06eef3c3b82679d909d57b146d82a0667035f0bd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2020 23:39:05 -0500 Subject: [PATCH 035/485] Add solution #1108 --- 1108-defanging-an-ip-address.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 1108-defanging-an-ip-address.js diff --git a/1108-defanging-an-ip-address.js b/1108-defanging-an-ip-address.js new file mode 100644 index 00000000..5d871e53 --- /dev/null +++ b/1108-defanging-an-ip-address.js @@ -0,0 +1,27 @@ +/** + * 1108. Defanging an IP Address + * https://leetcode.com/problems/defanging-an-ip-address/ + * Difficulty: Easy + * + * Given a valid (IPv4) IP address, return a defanged version of that IP address. + * + * A defanged IP address replaces every period "." with "[.]". + */ + +/** + * @param {string} address + * @return {string} + */ +var defangIPaddr = function(address) { + return address.replace(/\./g, '[.]'); +}; + +// or... + +/** + * @param {string} address + * @return {string} + */ +var defangIPaddr = function(address) { + return address.split('.').join('[.]'); +}; From e1403cefdd31379b6998aab5821d5f911b98117f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2020 00:09:08 -0500 Subject: [PATCH 036/485] Add solution #791 --- 0791-custom-sort-string.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 0791-custom-sort-string.js diff --git a/0791-custom-sort-string.js b/0791-custom-sort-string.js new file mode 100644 index 00000000..afb64d09 --- /dev/null +++ b/0791-custom-sort-string.js @@ -0,0 +1,26 @@ +/** + * 791. Custom Sort String + * https://leetcode.com/problems/custom-sort-string/ + * Difficulty: Medium + * + * S and T are strings composed of lowercase letters. In S, + * no letter occurs more than once. + * + * S was sorted in some custom order previously. We want to + * permute the characters of T so that they match the order + * that S was sorted. More specifically, if x occurs before + * y in S, then x should occur before y in the returned string. + * + * Return any permutation of T (as a string) that satisfies + * this property. + */ + +/** + * @param {string} S + * @param {string} T + * @return {string} + */ +var customSortString = function(S, T) { + const order = S.split('').reduce((o, k, i) => ({...o, [k]: i}), {}); + return T.split('').sort((a, b) => (order[a] || 0) - (order[b] || 0)).join(''); +}; From ea8c823a966e7739101f207f865c6a6aff048712 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2020 00:46:42 -0500 Subject: [PATCH 037/485] Add solution #606 --- 0606-construct-string-from-binary-tree.js | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 0606-construct-string-from-binary-tree.js diff --git a/0606-construct-string-from-binary-tree.js b/0606-construct-string-from-binary-tree.js new file mode 100644 index 00000000..c08594ad --- /dev/null +++ b/0606-construct-string-from-binary-tree.js @@ -0,0 +1,41 @@ +/** + * 606. Construct String from Binary Tree + * https://leetcode.com/problems/construct-string-from-binary-tree/ + * Difficulty: Easy + * + * You need to construct a string consists of parenthesis and integers + * from a binary tree with the preorder traversing way. + * + * The null node needs to be represented by empty parenthesis pair "()". + * And you need to omit all the empty parenthesis pairs that don't + * affect the one-to-one mapping relationship between the string + * and the original binary tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} t + * @return {string} + */ +var tree2str = function(t) { + return !t ? '' : `${t.val}(${tree2str(t.left)})(${tree2str(t.right)})`.replace(/(\(\)){2}|\(\)(?=$|\))/g, ''); +}; + + +// alternative, longer but faster version: +/** + * @param {TreeNode} t + * @return {string} + */ +var tree2str = function(t) { + let str = t ? `${t.val}` : ''; + if (t && t.right) str += `(${tree2str(t.left)})(${tree2str(t.right)})`; + else if (t && t.left) str += `(${tree2str(t.left)})`; + return str; +}; From aaaf3ee769f57b7681e157e2a496bbcf07d0f45e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2020 23:12:06 -0500 Subject: [PATCH 038/485] Add solution #263 --- 0263-ugly-number.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 0263-ugly-number.js diff --git a/0263-ugly-number.js b/0263-ugly-number.js new file mode 100644 index 00000000..3fff6eee --- /dev/null +++ b/0263-ugly-number.js @@ -0,0 +1,21 @@ +/** + * 263. Ugly Number + * https://leetcode.com/problems/ugly-number/ + * Difficulty: Easy + * + * Write a program to check whether a given number is an ugly number. + * + * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. + */ + +/** + * @param {number} num + * @return {boolean} + */ +var isUgly = function(num) { + if (num < 1) return false; + while (num % 5 === 0) num /= 5; + while (num % 3 === 0) num /= 3; + while (num % 2 === 0) num /= 2; + return num === 1; +}; From 9ea67eaed235d18cb164f5ac96c6b638ad7b774a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2020 23:14:48 -0500 Subject: [PATCH 039/485] Add solution #1037 --- 1037-valid-boomerang.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 1037-valid-boomerang.js diff --git a/1037-valid-boomerang.js b/1037-valid-boomerang.js new file mode 100644 index 00000000..a50f5d18 --- /dev/null +++ b/1037-valid-boomerang.js @@ -0,0 +1,18 @@ +/** + * 1037. Valid Boomerang + * https://leetcode.com/problems/valid-boomerang/ + * Difficulty: Easy + * + * A boomerang is a set of 3 points that are all distinct and not in a straight line. + * + * Given a list of three points in the plane, return whether these points are a boomerang. + */ + +/** + * @param {number[][]} points + * @return {boolean} + */ +var isBoomerang = function(points) { + return (points[0][1] - points[1][1]) * (points[1][0] - points[2][0]) + !== (points[0][0] - points[1][0]) * (points[1][1] - points[2][1]); +}; From 8d27db1436743e320642fa77ac81a5d84906e622 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2020 13:00:45 -0500 Subject: [PATCH 040/485] Add solution #264 --- 0264-ugly-number-ii.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 0264-ugly-number-ii.js diff --git a/0264-ugly-number-ii.js b/0264-ugly-number-ii.js new file mode 100644 index 00000000..f9b3780d --- /dev/null +++ b/0264-ugly-number-ii.js @@ -0,0 +1,24 @@ +/** + * 264. Ugly Number II + * https://leetcode.com/problems/ugly-number-ii/ + * Difficulty: Medium + * + * Write a program to find the n-th ugly number. + * + * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. + */ + +/** + * @param {number} n + * @return {number} + */ +var nthUglyNumber = function(n, factors = [2, 3, 5], offsets = [0, 0, 0]) { + const numbers = [1]; + while (numbers.length < n) { + const candidates = factors.map((v, i) => numbers[offsets[i]] * v); + const target = Math.min(...candidates); + candidates.forEach((c, i) => target === c ? offsets[i]++ : null); + numbers.push(target) + } + return numbers[n - 1]; +}; From e90771bed09134c4ecea6eccefd1227f08823d74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2020 22:33:04 -0500 Subject: [PATCH 041/485] Add solution #890 --- 0890-find-and-replace-pattern.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 0890-find-and-replace-pattern.js diff --git a/0890-find-and-replace-pattern.js b/0890-find-and-replace-pattern.js new file mode 100644 index 00000000..cf385ebb --- /dev/null +++ b/0890-find-and-replace-pattern.js @@ -0,0 +1,27 @@ +/** + * 890. Find and Replace Pattern + * https://leetcode.com/problems/find-and-replace-pattern/ + * Difficulty: Medium + * + * You have a list of words and a pattern, and you want to know which words in words matches the pattern. + * + * A word matches the pattern if there exists a permutation of letters p so that after replacing every + * letter x in the pattern with p(x), we get the desired word. + * + * (Recall that a permutation of letters is a bijection from letters to letters: every letter maps to + * another letter, and no two letters map to the same letter.) + * + * Return a list of the words in words that match the given pattern. + * + * You may return the answer in any order. + */ + +/** + * @param {string[]} words + * @param {string} pattern + * @return {string[]} + */ +var findAndReplacePattern = function(words, pattern) { + const map = (p, o = {}, count = 0) => p.split('').map(c => o[c] = o[c] || String(count++)).join(''); + return words.filter(word => map(word) === map(pattern)); +}; From 46af9f0f0d76062da05ee958984a5e3dfd20b02f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2020 23:03:40 -0500 Subject: [PATCH 042/485] Add solution #1313 --- 1313-decompress-run-length-encoded-list.js | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 1313-decompress-run-length-encoded-list.js diff --git a/1313-decompress-run-length-encoded-list.js b/1313-decompress-run-length-encoded-list.js new file mode 100644 index 00000000..b33c219c --- /dev/null +++ b/1313-decompress-run-length-encoded-list.js @@ -0,0 +1,23 @@ +/** + * 1313. Decompress Run-Length Encoded List + * https://leetcode.com/problems/decompress-run-length-encoded-list/ + * Difficulty: Easy + * + * We are given a list nums of integers representing a list compressed with run-length encoding. + * + * Consider each adjacent pair of elements [a, b] = [nums[2*i], nums[2*i+1]] (with i >= 0). + * For each such pair, there are a elements with value b in the decompressed list. + * + * Return the decompressed list. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var decompressRLElist = function(nums, result = []) { + for (let i = 0; i < nums.length; i += 2) { + result.push(...new Array(nums[i]).fill(nums[i + 1])); + } + return result; +}; From b635d1aebab0285f64a1fe8aa24d0fd5d0ebc2d7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2020 23:14:18 -0500 Subject: [PATCH 043/485] Add solution #263 --- 0263-ugly-number.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/0263-ugly-number.js b/0263-ugly-number.js index 3fff6eee..7666c7bf 100644 --- a/0263-ugly-number.js +++ b/0263-ugly-number.js @@ -13,9 +13,8 @@ * @return {boolean} */ var isUgly = function(num) { - if (num < 1) return false; - while (num % 5 === 0) num /= 5; - while (num % 3 === 0) num /= 3; - while (num % 2 === 0) num /= 2; + for (let i of [2, 3, 5]) { + while (num && num % i === 0) num /= i; + } return num === 1; }; From 04ba0c6d15c2fc81a7846a0b6793600f5b740df0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 00:35:49 -0500 Subject: [PATCH 044/485] Add solution #916 --- 0916-word-subsets.js | 30 +++++++++++++++++++++++++++++ README.md | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 0916-word-subsets.js diff --git a/0916-word-subsets.js b/0916-word-subsets.js new file mode 100644 index 00000000..0456e435 --- /dev/null +++ b/0916-word-subsets.js @@ -0,0 +1,30 @@ +/** + * 916. Word Subsets + * https://leetcode.com/problems/word-subsets/ + * Difficulty: Medium + * + * We are given two arrays A and B of words. Each word is a string of lowercase letters. + * + * Now, say that word b is a subset of word a if every letter in b occurs in a, including + * multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world". + * + * Now say a word a from A is universal if for every b in B, b is a subset of a. + * + * Return a list of all universal words in A. You can return the words in any order. + */ + +/** + * @param {string[]} A + * @param {string[]} B + * @return {string[]} + */ +var wordSubsets = function(A, B) { + const count = (string, char) => string.split(char).length - 1; + const subset = Array.from(B.reduce((map, b) => { + b.split('').forEach(char => { + map.set(char, (map.get(char) || 0) > count(b, char) ? map.get(char) : count(b, char)); + }); + return map; + }, new Map())); + return A.filter(a => subset.every(match => count(a, match[0]) >= match[1])); +}; diff --git a/README.md b/README.md index d5dc0a35..93d8e6fd 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,51 @@ [https://leetcode.com/](https://leetcode.com/) +## Table of Contents: + +|#|Title|Difficulty| +|:---|:---|:---| +36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| +226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +263|[Ugly Number](./0263-ugly-number.js)|Easy| +264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| +606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| +617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| +804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| +819|[Most Common Word](./0819-most-common-word.js)|Easy| +890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| +916|[Word Subsets](./0916-word-subsets.js)|Medium| +929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| +970|[Powerful Integers](./0970-powerful-integers.js)|Easy| +976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| +977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| +985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| +989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| +1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| +1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| +1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| +1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| +1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| +1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| +1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| +1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| +1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| +1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| +1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| +1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| +1297|[Maximum Number of Occurrences of a Substring](./1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| +1304|[Find N Unique Integers Sum up to Zero](./1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| +1309|[Decrypt String from Alphabet to Integer Mapping](./1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| +1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| +1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| +1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| + ## License [MIT License](https://opensource.org/licenses/MIT) From 261b7e0598a51f9d2bc3f93a9b85ee87ccb8bd66 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 14:00:26 -0500 Subject: [PATCH 045/485] Add solution #966 --- 0966-vowel-spellchecker.js | 44 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0966-vowel-spellchecker.js diff --git a/0966-vowel-spellchecker.js b/0966-vowel-spellchecker.js new file mode 100644 index 00000000..0979ed60 --- /dev/null +++ b/0966-vowel-spellchecker.js @@ -0,0 +1,44 @@ +/** + * 966. Vowel Spellchecker + * https://leetcode.com/problems/vowel-spellchecker/ + * Difficulty: Medium + * + * Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. + * For a given query word, the spell checker handles two categories of spelling mistakes: + * + * - Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word + * is returned with the same case as the case in the wordlist. + * Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" + * Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" + * Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" + * - Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel + * individually, it matches a word in the wordlist (case-insensitive), then the query word is returned + * with the same case as the match in the wordlist. + * Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" + * Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) + * Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) + * + * In addition, the spell checker operates under the following precedence rules: + * - When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. + * - When the query matches a word up to capitlization, you should return the first such match in the wordlist. + * - When the query matches a word up to vowel errors, you should return the first such match in the wordlist. + * - If the query has no matches in the wordlist, you should return the empty string. + * + * Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i]. + */ + +/** + * @param {string[]} words + * @param {string[]} queries + * @return {string[]} + */ +var spellchecker = function(words, queries) { + const set = new Set(words); + const map = new Map(); + const format = s => s.toLowerCase().replace(/[aeiou]/g, '_'); + words.forEach(word => { + if (!map.has(word.toLowerCase())) map.set(word.toLowerCase(), word); + if (!map.has(format(word))) map.set(format(word), word); + }); + return queries.map(q => set.has(q) ? q : map.get(q.toLowerCase()) || map.get(format(q)) || ''); +}; diff --git a/README.md b/README.md index 93d8e6fd..f5729904 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| +966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| 976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| 977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| From 0c2d49e92e86bc673670c1f9d57604208d816df4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 14:18:14 -0500 Subject: [PATCH 046/485] Add solution #648 --- 0648-replace-words.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0648-replace-words.js diff --git a/0648-replace-words.js b/0648-replace-words.js new file mode 100644 index 00000000..14179342 --- /dev/null +++ b/0648-replace-words.js @@ -0,0 +1,30 @@ +/** + * 648. Replace Words + * https://leetcode.com/problems/replace-words/ + * Difficulty: Medium + * + * In English, we have a concept called root, which can be followed by some other words + * to form another longer word - let's call this word successor. For example, the root + * an, followed by other, which can form another word another. + * + * Now, given a dictionary consisting of many roots and a sentence. You need to replace + * all the successor in the sentence with the root forming it. If a successor has many + * roots can form it, replace it with the root with the shortest length. + * + * You need to output the sentence after the replacement. + */ + +/** + * @param {string[]} dict + * @param {string} sentence + * @return {string} + */ +var replaceWords = function(dict, sentence) { + const set = new Set(dict); + return sentence.split(/\s+/).map(word => { + for (let i = 1; i <= word.length; i++) { + if (set.has(word.slice(0, i))) return word.slice(0, i); + } + return word; + }).join(' '); +}; diff --git a/README.md b/README.md index f5729904..42f28b37 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +648|[Replace Words](./0648-replace-words.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 94f5f3e1f4ace148caa190118d9f7ec99eea55e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 14:40:44 -0500 Subject: [PATCH 047/485] Add solution #459 --- 0459-repeated-substring-pattern.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0459-repeated-substring-pattern.js diff --git a/0459-repeated-substring-pattern.js b/0459-repeated-substring-pattern.js new file mode 100644 index 00000000..07598eb0 --- /dev/null +++ b/0459-repeated-substring-pattern.js @@ -0,0 +1,18 @@ +/** + * 459. Repeated Substring Pattern + * https://leetcode.com/problems/repeated-substring-pattern/ + * Difficulty: Easy + * + * Given a non-empty string check if it can be constructed by taking a + * substring of it and appending multiple copies of the substring + * together. You may assume the given string consists of lowercase + * English letters only and its length will not exceed 10000. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var repeatedSubstringPattern = function(s) { + return (s + s).slice(1, s.length * 2 - 1).indexOf(s) !== -1; +}; diff --git a/README.md b/README.md index 42f28b37..578074f6 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| +459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| From e6178966b83847673d58841d4c4cdc17c08442cb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 15:44:12 -0500 Subject: [PATCH 048/485] Add solution #686 --- 0686-repeated-string-match.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0686-repeated-string-match.js diff --git a/0686-repeated-string-match.js b/0686-repeated-string-match.js new file mode 100644 index 00000000..927a408f --- /dev/null +++ b/0686-repeated-string-match.js @@ -0,0 +1,25 @@ +/** + * 686. Repeated String Match + * https://leetcode.com/problems/repeated-string-match/ + * Difficulty: Easy + * + * Given two strings A and B, find the minimum number of times A has to be + * repeated such that B is a substring of it. If no such solution, return -1. + * + * For example, with A = "abcd" and B = "cdabcdab". + * + * Return 3, because by repeating A three times (“abcdabcdabcd”), B is a + * substring of it; and B is not a substring of A repeated two times ("abcdabcd"). + */ + +/** + * @param {string} A + * @param {string} B + * @return {number} + */ +var repeatedStringMatch = function(A, B) { + const length = Math.ceil(B.length / A.length); + if (A.repeat(length).includes(B)) return length; + if ((A.repeat(length) + A).includes(B)) return length + 1; + return -1; +}; diff --git a/README.md b/README.md index 578074f6..01df301e 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| +686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 62fbde463f59ec9a1ab00d08cdbc7089d21711dc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 22:27:45 -0500 Subject: [PATCH 049/485] Add solution #1324 --- 1324-print-words-vertically.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1324-print-words-vertically.js diff --git a/1324-print-words-vertically.js b/1324-print-words-vertically.js new file mode 100644 index 00000000..4e29c973 --- /dev/null +++ b/1324-print-words-vertically.js @@ -0,0 +1,25 @@ +/** + * 1324. Print Words Vertically + * https://leetcode.com/problems/print-words-vertically/ + * Difficulty: Medium + * + * Given a string s. Return all the words vertically in the same + * order in which they appear in s. + * Words are returned as a list of strings, complete with spaces + * when is necessary. (Trailing spaces are not allowed). + * Each word would be put on only one column and that in one + * column there will be only one word. + */ + +/** + * @param {string} s + * @return {string[]} + */ +var printVertically = function(s) { + const result = []; + s.split(/\s+/).forEach((word, i) => word.split('').forEach((letter, j) => { + result[j] = result[j] || ''; + result[j] += letter.padStart(i - result[j].length + 1, ' '); + })); + return result; +}; diff --git a/README.md b/README.md index 01df301e..b4a2627b 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ 1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| 1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| +1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| ## License From a16f99cea0d9c9e40525d7343f6c0673960088de Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 21:46:12 -0500 Subject: [PATCH 050/485] Add solution #722 --- 0722-remove-comments.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0722-remove-comments.js diff --git a/0722-remove-comments.js b/0722-remove-comments.js new file mode 100644 index 00000000..069218e4 --- /dev/null +++ b/0722-remove-comments.js @@ -0,0 +1,26 @@ +/** + * 722. Remove Comments + * https://leetcode.com/problems/remove-comments/ + * Difficulty: Medium + * + * Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th + * line of the source code. This represents the result of splitting the original source code string by the + * newline character \n. + * In C++, there are two types of comments, line comments, and block comments. + * The string // denotes a line comment, which represents that it and rest of the characters to the right + * of it in the same line should be ignored. + * The string /* denotes a block comment, which represents that all characters until the next + * (non-overlapping) occurrence of should be ignored. + * It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block + * comment always starts a new comment. + * Finally, implicit newline characters can be deleted by block comments. + * After removing the comments from the source code, return the source code in the same format. + */ + +/** + * @param {string[]} source + * @return {string[]} + */ +var removeComments = function(source) { + return source.join('\n').replace(/\/\*.*?\*\/|\/\/[^\n]+/gs, '').split(/\n/).filter(Boolean); +}; diff --git a/README.md b/README.md index b4a2627b..ec8ca8d5 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 3167a9d9f8b2d1e99ef2187c90dfeb179a46cdfa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 22:47:36 -0500 Subject: [PATCH 051/485] Add solution #1249 --- ...inimum-remove-to-make-valid-parentheses.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 1249-minimum-remove-to-make-valid-parentheses.js diff --git a/1249-minimum-remove-to-make-valid-parentheses.js b/1249-minimum-remove-to-make-valid-parentheses.js new file mode 100644 index 00000000..b2743c4e --- /dev/null +++ b/1249-minimum-remove-to-make-valid-parentheses.js @@ -0,0 +1,40 @@ +/** + * 1249. Minimum Remove to Make Valid Parentheses + * https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ + * Difficulty: Medium + * + * Given a string s of '(' , ')' and lowercase English characters. + * + * Your task is to remove the minimum number of parentheses ( '(' or ')', + * in any positions ) so that the resulting parentheses string is valid + * and return any valid string. + * + * Formally, a parentheses string is valid if and only if: + * - It is the empty string, contains only lowercase characters, or + * - It can be written as AB (A concatenated with B), where A and B are valid strings, or + * - It can be written as (A), where A is a valid string. + */ + +/** + * @param {string} s + * @return {string} + */ +var minRemoveToMakeValid = function(s) { + const inputArray = s.split(''); + const stack = []; + + inputArray.forEach((letter, index) => { + if (letter === '(') { + stack.push(index); + } else if (letter === ')') { + if (stack.length) { + stack.pop(); + } else { + inputArray[index] = ''; + } + } + }); + + stack.forEach(index => inputArray[index] = ''); + return inputArray.join(''); +}; diff --git a/README.md b/README.md index ec8ca8d5..428808ae 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| +1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| 1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| From 9a6931d90b309756e01e7800dfce862590e64a7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 22:55:24 -0500 Subject: [PATCH 052/485] Add solution #1323 --- 1323-maximum-69-number.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 1323-maximum-69-number.js diff --git a/1323-maximum-69-number.js b/1323-maximum-69-number.js new file mode 100644 index 00000000..a472a90e --- /dev/null +++ b/1323-maximum-69-number.js @@ -0,0 +1,18 @@ +/** + * 1323. Maximum 69 Number + * https://leetcode.com/problems/maximum-69-number/submissions/ + * Difficulty: Easy + * + * Given a positive integer num consisting only of digits 6 and 9. + * + * Return the maximum number you can get by changing at most + * one digit (6 becomes 9, and 9 becomes 6). + */ + +/** + * @param {number} num + * @return {number} + */ +var maximum69Number = function(num) { + return +String(num).replace(6, 9); +}; diff --git a/README.md b/README.md index 428808ae..aac75485 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ 1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| 1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| +1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| ## License From 1aaf413f5268ab4a804d14447d66b25101501115 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 23:51:51 -0500 Subject: [PATCH 053/485] Add solution #4 --- 0004-median-of-two-sorted-arrays.js | 50 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0004-median-of-two-sorted-arrays.js diff --git a/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js new file mode 100644 index 00000000..ffc7d59d --- /dev/null +++ b/0004-median-of-two-sorted-arrays.js @@ -0,0 +1,50 @@ +/** + * 4. Median of Two Sorted Arrays + * https://leetcode.com/problems/median-of-two-sorted-arrays/ + * Difficulty: Hard + * + * There are two sorted arrays nums1 and nums2 of size m and n respectively. + * + * Find the median of the two sorted arrays. + * The overall run time complexity should be O(log (m+n)). + * + * You may assume nums1 and nums2 cannot be both empty. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + const total = nums1.length + nums2.length; + const limit = Math.floor(total / 2) + 1; + let i = 0, j = 0, prev, last + + while(i + j < limit) { + if (last !== undefined) { + prev = last; + } + if (nums1[i] < nums2[j] || j === nums2.length) { + last = nums1[i++]; + } else { + last = nums2[j++]; + } + } + + return total % 2 === 0 ? (prev + last) / 2 : last; +}; + +// shorter/readable alternative with higher time complexity: +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + const sorted = [...nums1, ...nums2].sort((a, b) => a - b); + const index = Math.floor((sorted.length - 1) / 2); + return sorted.length % 2 === 0 + ? (sorted[index] + sorted[index + 1]) / 2 + : sorted[index]; +}; diff --git a/README.md b/README.md index aac75485..5f97d71a 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ |#|Title|Difficulty| |:---|:---|:---| +4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From 559c21e630a1e65b0358fdac3bc86302660ca2ab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 23:54:30 -0500 Subject: [PATCH 054/485] Add MIT license --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..779eb431 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Josh Crozier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file From 81438282b9dac8387901a847b8b2b03ab9a907ce Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 19:58:16 -0500 Subject: [PATCH 055/485] Add solution #67 --- 0067-add-binary.js | 18 ++++++++++++++++++ README.md | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 0067-add-binary.js diff --git a/0067-add-binary.js b/0067-add-binary.js new file mode 100644 index 00000000..6e44f81c --- /dev/null +++ b/0067-add-binary.js @@ -0,0 +1,18 @@ +/** + * 67. Add Binary + * https://leetcode.com/problems/add-binary/ + * Difficulty: Easy + * + * Given two binary strings, return their sum (also a binary string). + * + * The input strings are both non-empty and contains only characters 1 or 0. + */ + +/** + * @param {string} a + * @param {string} b + * @return {string} + */ +var addBinary = function(a, b) { + return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); +}; diff --git a/README.md b/README.md index 5f97d71a..10378f71 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| @@ -60,4 +61,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2020 [Josh Crozier](https://joshcrozier.com) From d1dc9977bce6859bb9d767e4789b1423465f0feb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:21:15 -0500 Subject: [PATCH 056/485] Add solution #43 --- 0043-multiply-strings.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0043-multiply-strings.js diff --git a/0043-multiply-strings.js b/0043-multiply-strings.js new file mode 100644 index 00000000..62e3d7b7 --- /dev/null +++ b/0043-multiply-strings.js @@ -0,0 +1,40 @@ +/** + * 43. Multiply Strings + * https://leetcode.com/problems/multiply-strings/ + * Difficulty: Medium + * + * Given two non-negative integers num1 and num2 represented as strings, + * return the product of num1 and num2, also represented as a string. + * + * - The length of both num1 and num2 is < 110. + * - Both num1 and num2 contain only digits 0-9. + * - Both num1 and num2 do not contain any leading zero, except the number 0 itself. + * - You must not use any built-in BigInteger library or convert the inputs to integer directly. + */ + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = function(num1, num2) { + const result = new Array(num1.length + num2.length).fill(0); + for (let i = num1.length - 1; i >= 0; i--) { + for (let j = num2.length - 1; j >= 0; j--) { + const sum = num1[i] * num2[j] + result[i + j + 1]; + result[i + j] += Math.floor(sum / 10); + result[i + j + 1] = sum % 10; + } + } + return result.join('').replace(/^0+(?!$)/, ''); +}; + +// one-liner alternative that breaks the rules: +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = function(num1, num2) { + return ((BigInt(num1) * BigInt(num2))).toString(); +}; diff --git a/README.md b/README.md index 10378f71..77446c83 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From 607826e79696d47ecf81dd0d03cb1f985f0bf786 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:22:12 -0500 Subject: [PATCH 057/485] Add solution #4 --- 0004-median-of-two-sorted-arrays.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js index ffc7d59d..88a7613a 100644 --- a/0004-median-of-two-sorted-arrays.js +++ b/0004-median-of-two-sorted-arrays.js @@ -21,7 +21,7 @@ var findMedianSortedArrays = function(nums1, nums2) { const limit = Math.floor(total / 2) + 1; let i = 0, j = 0, prev, last - while(i + j < limit) { + while (i + j < limit) { if (last !== undefined) { prev = last; } From 34aa663cfec12b5c9941aa66f0cfc25ce8a63691 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:42:43 -0500 Subject: [PATCH 058/485] Add solution #66 --- 0066-plus-one.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0066-plus-one.js diff --git a/0066-plus-one.js b/0066-plus-one.js new file mode 100644 index 00000000..20987a33 --- /dev/null +++ b/0066-plus-one.js @@ -0,0 +1,41 @@ +/** + * 66. Plus One + * https://leetcode.com/problems/plus-one/ + * Difficulty: Easy + * + * Given a non-empty array of digits representing a non-negative integer, + * plus one to the integer. + * + * The digits are stored such that the most significant digit is at the + * head of the list, and each element in the array contain a single digit. + * + * You may assume the integer does not contain any leading zero, + * except the number 0 itself. + */ + +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + let i = digits.length - 1; + digits[i] += 1; + while (digits[i] > 9) { + digits[i--] = 0; + if (digits[i]) { + digits[i] += 1; + } else { + digits.unshift(1); + } + } + return digits; +}; + +// alternative one-liner that breaks the rules: +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + return String(BigInt(digits.join('')) + BigInt(1)).split(''); +}; diff --git a/README.md b/README.md index 77446c83..3eaafad6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From 7359e0f65a67b6b6920b791263992dcd56674a63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:51:17 -0500 Subject: [PATCH 059/485] Add solution #824 --- 0824-goat-latin.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0824-goat-latin.js diff --git a/0824-goat-latin.js b/0824-goat-latin.js new file mode 100644 index 00000000..a49073ea --- /dev/null +++ b/0824-goat-latin.js @@ -0,0 +1,34 @@ +/** + * 824. Goat Latin + * https://leetcode.com/problems/goat-latin/ + * Difficulty: Easy + * + * A sentence S is given, composed of words separated by spaces. + * Each word consists of lowercase and uppercase letters only. + * + * We would like to convert the sentence to "Goat Latin" + * (a made-up language similar to Pig Latin.) + * + * The rules of Goat Latin are as follows: + * - If a word begins with a vowel (a, e, i, o, or u), append "ma" to the + * end of the word. For example, the word 'apple' becomes 'applema'. + * - If a word begins with a consonant (i.e. not a vowel), remove the + * first letter and append it to the end, then add "ma". + * For example, the word "goat" becomes "oatgma". + * - Add one letter 'a' to the end of each word per its word index in + * the sentence, starting with 1. + * For example, the first word gets "a" added to the end, the second word gets + * "aa" added to the end and so on. + * + * Return the final sentence representing the conversion from S to Goat Latin. + */ + +/** + * @param {string} S + * @return {string} + */ +var toGoatLatin = function(S) { + return S.split(' ').map((word, index) => { + return `${word.replace(/^([^aeiou])(.*)/ig, '$2$1')}ma${'a'.repeat(index + 1)}`; + }).join(' '); +}; diff --git a/README.md b/README.md index 3eaafad6..d7047c96 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| +824|[Goat Latin](./0824-goat-latin.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From ddf325e0d1a377b60ff009b02c90f37defa6c4e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2020 00:33:38 -0500 Subject: [PATCH 060/485] Add solution #831 --- 0831-masking-personal-information.js | 57 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0831-masking-personal-information.js diff --git a/0831-masking-personal-information.js b/0831-masking-personal-information.js new file mode 100644 index 00000000..4f3ca6f4 --- /dev/null +++ b/0831-masking-personal-information.js @@ -0,0 +1,57 @@ +/** + * 831. Masking Personal Information + * https://leetcode.com/problems/masking-personal-information/ + * Difficulty: Medium + * + * We are given a personal information string S, which may represent either an email address or a phone number. + * We would like to mask this personal information according to the following rules: + * 1. Email address: + * We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z. + * An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and + * followed by a name. All email addresses are guaranteed to be valid and in the format of "name1@name2.name3". + * To mask an email, all names must be converted to lowercase and all letters between the first and last letter of + * the first name must be replaced by 5 asterisks '*'. + * + * 2. Phone number: + * A phone number is a string consisting of only the digits 0-9 or the characters from the set + * {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits. The last 10 digits make up the + * local number, while the digits before those make up the country code. Note that the country code is optional. We + * want to expose only the last 4 digits and mask all other digits. The local number should be formatted and masked + * as "***-***-1111", where 1 represents the exposed digits. To mask a phone number with country code like + * "+111 111 111 1111", we write it in the form "+***-***-***-1111". The '+' sign and the first '-' sign before the + * local number should only exist if there is a country code. For example, a 12 digit phone number mask should start + * with "+**-". Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of + * the above formatting scheme should be removed. + * + * Return the correct "mask" of the information provided. + */ + +// The one-line solution: +/** + * @param {string} S + * @return {string} + */ +var maskPII = function(S) { + return S.toLowerCase() + .replace(/^([a-z])[a-z]*([a-z])/, '$1*****$2') + .replace(/[)(\-\s+]+/g, '') + .replace(/^(\d*)(\d{3})(\d{3})(\d{4})$/, '+$1-$2-$3-$4') + .replace(/\d(?!\d{0,3}$)/g, '*') + .replace(/^\+\-/, ''); +}; + +// More readable alternative: +/** + * @param {string} S + * @return {string} + */ +var maskPII = function(S) { + if (S.includes('@')) { + return S.toLowerCase().replace(/^(\w)\w*(\w)/, '$1*****$2'); + } else { + return S.replace(/\D+/g, '') + .replace(/^(\d*)(\d{3})(\d{3})(\d{4})$/, '+$1-$2-$3-$4') + .replace(/\d(?!\d{0,3}$)/g, '*') + .replace(/^\+\-/, ''); + } +}; \ No newline at end of file diff --git a/README.md b/README.md index d7047c96..a7e42c8b 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| +831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From ac44de24fd4151e83a114ac00496c4a1e2887b07 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2020 23:29:45 -0500 Subject: [PATCH 061/485] Add solution #1233 --- ...-remove-sub-folders-from-the-filesystem.js | 32 +++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 1233-remove-sub-folders-from-the-filesystem.js diff --git a/1233-remove-sub-folders-from-the-filesystem.js b/1233-remove-sub-folders-from-the-filesystem.js new file mode 100644 index 00000000..a876bd66 --- /dev/null +++ b/1233-remove-sub-folders-from-the-filesystem.js @@ -0,0 +1,32 @@ +/** + * 1233. Remove Sub-Folders from the Filesystem + * https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ + * Difficulty: Medium + * + * Given a list of folders, remove all sub-folders in those folders + * and return in any order the folders after removing. + * + * If a folder[i] is located within another folder[j], it is called + * a sub-folder of it. The format of a path is one or more concatenated + * strings of the form: / followed by one or more lowercase English + * letters. For example, /leetcode and /leetcode/problems are valid + * paths while an empty string and / are not. + */ + +/** + * @param {string[]} folder + * @return {string[]} + */ +var removeSubfolders = function(folder) { + const set = new Set(folder); + return folder.filter(path => !getPathSegments(path).some(p => set.has(p))); +}; + +function getPathSegments(path) { + const split = path.split('/'); + const segments = [split.shift()]; + while (split.length > 1) { + segments.push(segments[segments.length - 1] + '/' + split.shift()); + } + return segments; +} diff --git a/README.md b/README.md index a7e42c8b..8f7a50bf 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| +1233|[Remove Sub-Folders from the Filesystem](./1233-remove-sub-folders-from-the-filesystem.js)|Medium| 1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| From 881a1140963b90499099ca8b1127696b1754f5ba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2020 23:53:29 -0500 Subject: [PATCH 062/485] Add solution #541 --- 0541-reverse-string-ii.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0541-reverse-string-ii.js diff --git a/0541-reverse-string-ii.js b/0541-reverse-string-ii.js new file mode 100644 index 00000000..1f98f1db --- /dev/null +++ b/0541-reverse-string-ii.js @@ -0,0 +1,24 @@ +/** + * 541. Reverse String II + * https://leetcode.com/problems/reverse-string-ii/ + * Difficulty: Easy + * + * Given a string and an integer k, you need to reverse the first k characters + * for every 2k characters counting from the start of the string. If there are + * less than k characters left, reverse all of them. If there are less than 2k + * but greater than or equal to k characters, then reverse the first k + * characters and left the other as original. + */ + +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var reverseStr = function(s, k) { + const split = s.split(''); + for (let i = 0; i < s.length; i += 2 * k) { + split.splice(i, 0, ...split.splice(i, k).reverse()); + } + return split.join(''); +}; diff --git a/README.md b/README.md index 8f7a50bf..18066092 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| From f9de6f9291415aa321e0ebd4927c6a1a1b068e52 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2020 00:15:12 -0500 Subject: [PATCH 063/485] Add solution #345 --- 0345-reverse-vowels-of-a-string.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 0345-reverse-vowels-of-a-string.js diff --git a/0345-reverse-vowels-of-a-string.js b/0345-reverse-vowels-of-a-string.js new file mode 100644 index 00000000..b21b2b54 --- /dev/null +++ b/0345-reverse-vowels-of-a-string.js @@ -0,0 +1,17 @@ +/** + * 345. Reverse Vowels of a String + * https://leetcode.com/problems/reverse-vowels-of-a-string/ + * Difficulty: Easy + * + * Write a function that takes a string as input + * and reverse only the vowels of a string. + */ + +/** + * @param {string} s + * @return {string} + */ +var reverseVowels = function(s) { + const vowels = s.match(/[aeiou]/ig); + return s.replace(/[aeiou]/ig, () => vowels.pop()); +}; diff --git a/README.md b/README.md index 18066092..4291d45e 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From cb5857a6010783c6348826cbffc85e4a5d034ded Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2020 23:33:20 -0500 Subject: [PATCH 064/485] Add solution #5320 --- ...ts-by-vegan-friendly-price-and-distance.js | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js diff --git a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js new file mode 100644 index 00000000..3b0aa472 --- /dev/null +++ b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js @@ -0,0 +1,30 @@ +/** + * 5320. Filter Restaurants by Vegan-Friendly, Price and Distance + * https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/ + * Difficulty: Medium + * + * Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. + * You have to filter the restaurants using three filters. + * + * The veganFriendly filter will be either true (meaning you should only include restaurants with + * veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you + * have the filters maxPrice and maxDistance which are the maximum value for price and distance of + * restaurants you should consider respectively. + * + * Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. + * For restaurants with the same rating, order them by id from highest to lowest. For simplicity + * veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false. + */ + +/** + * @param {number[][]} restaurants + * @param {number} veganFriendly + * @param {number} maxPrice + * @param {number} maxDistance + * @return {number[]} + */ +var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) { + return restaurants.filter(r => (!veganFriendly || r[2]) && r[3] <= maxPrice && r[4] <= maxDistance) + .sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1]) + .map(r => r[0]); +}; diff --git a/README.md b/README.md index 4291d45e..427bc372 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| +5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 59bc0c2d750226f48f59a193aa19bb12d34606e4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2020 23:36:27 -0500 Subject: [PATCH 065/485] Add solution #5319 --- 5319-remove-palindromic-subsequences.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 5319-remove-palindromic-subsequences.js diff --git a/5319-remove-palindromic-subsequences.js b/5319-remove-palindromic-subsequences.js new file mode 100644 index 00000000..2939bfd4 --- /dev/null +++ b/5319-remove-palindromic-subsequences.js @@ -0,0 +1,23 @@ +/** + * 5319. Remove Palindromic Subsequences + * https://leetcode.com/problems/remove-palindromic-subsequences/ + * Difficulty: Easy + * + * Given a string s consisting only of letters 'a' and 'b'. + * In a single step you can remove one palindromic subsequence from s. + * + * Return the minimum number of steps to make the given string empty. + * A string is a subsequence of a given string, if it is generated by + * deleting some characters of a given string without changing its order. + * + * A string is called palindrome if is one that reads the same backward + * as well as forward. + */ + +/** + * @param {string} s + * @return {number} + */ +var removePalindromeSub = function(s) { + return s.length === 0 ? 0 : (s.split('').reverse().join('') === s ? 1 : 2); +}; diff --git a/README.md b/README.md index 427bc372..e565ba42 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| +5319|[Remove Palindromic Subsequences](./5319-remove-palindromic-subsequences.js)|Easy| 5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 9885b734b26875e1725251e24558b5e7da434338 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2020 23:44:34 -0500 Subject: [PATCH 066/485] Add solution #5320 --- 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js index 3b0aa472..daac80f1 100644 --- a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js +++ b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js @@ -24,7 +24,7 @@ * @return {number[]} */ var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) { - return restaurants.filter(r => (!veganFriendly || r[2]) && r[3] <= maxPrice && r[4] <= maxDistance) + return restaurants.filter(([,, v, p, d]) => v >= veganFriendly && p <= maxPrice && d <= maxDistance) .sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1]) .map(r => r[0]); }; From ad577c19d26e4f1ca8e747fdb7ef9ad2de52357e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 21:36:56 -0500 Subject: [PATCH 067/485] Add solution #867 --- 0867-transpose-matrix.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0867-transpose-matrix.js diff --git a/0867-transpose-matrix.js b/0867-transpose-matrix.js new file mode 100644 index 00000000..4154b7d6 --- /dev/null +++ b/0867-transpose-matrix.js @@ -0,0 +1,18 @@ +/** + * 867. Transpose Matrix + * https://leetcode.com/problems/transpose-matrix/ + * Difficulty: Easy + * + * Given a matrix A, return the transpose of A. + * + * The transpose of a matrix is the matrix flipped over it's main + * diagonal, switching the row and column indices of the matrix. + */ + +/** + * @param {number[][]} A + * @return {number[][]} + */ +var transpose = function(A) { + return A[0].map((_, i) => A.map(j => j[i])); +}; diff --git a/README.md b/README.md index e565ba42..e223aa13 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ 819|[Most Common Word](./0819-most-common-word.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| +867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From a5906218d7ba97c9749044fc3f05f19a9c12999b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 22:15:42 -0500 Subject: [PATCH 068/485] Add solution #565 --- 0565-array-nesting.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0565-array-nesting.js diff --git a/0565-array-nesting.js b/0565-array-nesting.js new file mode 100644 index 00000000..1c34798e --- /dev/null +++ b/0565-array-nesting.js @@ -0,0 +1,34 @@ +/** + * 565. Array Nesting + * https://leetcode.com/problems/array-nesting/ + * Difficulty: Medium + * + * A zero-indexed array A of length N contains all integers from 0 to N-1. + * Find and return the longest length of set S, where S[i] = {A[i], + * A[A[i]], A[A[A[i]]], ... } subjected to the rule below. + * + * Suppose the first element in S starts with the selection of element + * A[i] of index = i, the next element in S should be A[A[i]], and then + * A[A[A[i]]]… By that analogy, we stop adding right before a duplicate + * element occurs in S. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var arrayNesting = function(nums) { + const history = new Set(); + let max = 0; + for (let i = 0; i < nums.length; i++) { + let count = 0; + let j = i; + while (!history.has(nums[j])) { + j = nums[j]; + history.add(j); + count++; + } + max = Math.max(max, count); + } + return max; +}; diff --git a/README.md b/README.md index e223aa13..ae269ba6 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +565|[Array Nesting](./0565-array-nesting.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| From 35606fe1e0c1921752624c31c9b1aa32f9d167dd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 22:43:13 -0500 Subject: [PATCH 069/485] Add solution #628 --- 0628-maximum-product-of-three-numbers.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0628-maximum-product-of-three-numbers.js diff --git a/0628-maximum-product-of-three-numbers.js b/0628-maximum-product-of-three-numbers.js new file mode 100644 index 00000000..fb973d59 --- /dev/null +++ b/0628-maximum-product-of-three-numbers.js @@ -0,0 +1,18 @@ +/** + * 628. Maximum Product of Three Numbers + * https://leetcode.com/problems/maximum-product-of-three-numbers/ + * Difficulty: Easy + * + * Given an integer array, find three numbers whose + * product is maximum and output the maximum product. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumProduct = function(nums) { + const n = nums.length; + nums.sort((a, b) => a - b); + return Math.max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]); +}; diff --git a/README.md b/README.md index ae269ba6..5db842a6 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From cd6f060a44fe950d2f43c860c2a70ff83c0bd83d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 23:10:40 -0500 Subject: [PATCH 070/485] Add solution #36 --- 0036-valid-sudoku.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/0036-valid-sudoku.js b/0036-valid-sudoku.js index bb000b2e..41b1560f 100644 --- a/0036-valid-sudoku.js +++ b/0036-valid-sudoku.js @@ -29,8 +29,7 @@ var isValidSudoku = function(board) { const options = [rows[i], columns[j], boxes[k]]; if (options.some(option => option.has(value))) return false; - if (value === '.') continue; - options.forEach(option => option.add(value)); + if (value !== '.') options.forEach(option => option.add(value)); } } From f87d0405fb2b5e33799a899dda4be41c9221860a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2020 21:59:12 -0500 Subject: [PATCH 071/485] Add solution #1332 --- ...c-subsequences.js => 1332-remove-palindromic-subsequences.js | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename 5319-remove-palindromic-subsequences.js => 1332-remove-palindromic-subsequences.js (94%) diff --git a/5319-remove-palindromic-subsequences.js b/1332-remove-palindromic-subsequences.js similarity index 94% rename from 5319-remove-palindromic-subsequences.js rename to 1332-remove-palindromic-subsequences.js index 2939bfd4..89eae0fb 100644 --- a/5319-remove-palindromic-subsequences.js +++ b/1332-remove-palindromic-subsequences.js @@ -1,5 +1,5 @@ /** - * 5319. Remove Palindromic Subsequences + * 1332. Remove Palindromic Subsequences * https://leetcode.com/problems/remove-palindromic-subsequences/ * Difficulty: Easy * diff --git a/README.md b/README.md index 5db842a6..455951cc 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| -5319|[Remove Palindromic Subsequences](./5319-remove-palindromic-subsequences.js)|Easy| +1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 9e22948bf15a03856c9b9619962ef4fae0c646d4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2020 22:03:06 -0500 Subject: [PATCH 072/485] Add solution #1333 --- ...3-filter-restaurants-by-vegan-friendly-price-and-distance.js | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js => 1333-filter-restaurants-by-vegan-friendly-price-and-distance.js (95%) diff --git a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js b/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js similarity index 95% rename from 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js rename to 1333-filter-restaurants-by-vegan-friendly-price-and-distance.js index daac80f1..e926910a 100644 --- a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js +++ b/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js @@ -1,5 +1,5 @@ /** - * 5320. Filter Restaurants by Vegan-Friendly, Price and Distance + * 1333. Filter Restaurants by Vegan-Friendly, Price and Distance * https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/ * Difficulty: Medium * diff --git a/README.md b/README.md index 455951cc..76b26471 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| -5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 7b95fcbe09cb2ba71bead76389c673ffaa06cc9a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2020 22:03:31 -0500 Subject: [PATCH 073/485] Add solution #152 --- 0152-maximum-product-subarray.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0152-maximum-product-subarray.js diff --git a/0152-maximum-product-subarray.js b/0152-maximum-product-subarray.js new file mode 100644 index 00000000..44084d42 --- /dev/null +++ b/0152-maximum-product-subarray.js @@ -0,0 +1,23 @@ +/** + * 152. Maximum Product Subarray + * https://leetcode.com/problems/maximum-product-subarray/ + * Difficulty: Medium + * + * Given an integer array nums, find the contiguous subarray within an array + * (containing at least one number) which has the largest product. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxProduct = function(nums) { + let result = nums[0]; + let min = 1; + let max = 1; + for (let n of nums) { + [min, max] = [Math.min(n, min * n, max * n), Math.max(n, min * n, max * n)]; + result = Math.max(result, max); + } + return result; +}; diff --git a/README.md b/README.md index 76b26471..6a807fc6 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| +152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 97055812e5a45c856e6d0ad2d5eccb8bc78a0775 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2020 21:37:35 -0500 Subject: [PATCH 074/485] Add solution #713 --- 0713-subarray-product-less-than-k.js | 30 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0713-subarray-product-less-than-k.js diff --git a/0713-subarray-product-less-than-k.js b/0713-subarray-product-less-than-k.js new file mode 100644 index 00000000..48a11c48 --- /dev/null +++ b/0713-subarray-product-less-than-k.js @@ -0,0 +1,30 @@ +/** + * 713. Subarray Product Less Than K + * https://leetcode.com/problems/subarray-product-less-than-k/ + * Difficulty: Medium + * + * Your are given an array of positive integers nums. + * + * Count and print the number of (contiguous) subarrays where the + * product of all the elements in the subarray is less than k. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var numSubarrayProductLessThanK = function(nums, k) { + let result = 0; + for (let right = 0, left = 0, product = 1; right < nums.length; right++) { + product *= nums[right]; + while (product >= k && left < nums.length) { + product /= nums[left]; + left++; + } + if (left < nums.length) { + result = result + right - left + 1; + } + } + return result; +}; diff --git a/README.md b/README.md index 6a807fc6..2a23ef16 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From c0504d418c4a7a0d7cfb07c600baa8879a7fd727 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Feb 2020 22:58:12 -0500 Subject: [PATCH 075/485] Add solution #925 --- 0925-long-pressed-name.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0925-long-pressed-name.js diff --git a/0925-long-pressed-name.js b/0925-long-pressed-name.js new file mode 100644 index 00000000..7b983317 --- /dev/null +++ b/0925-long-pressed-name.js @@ -0,0 +1,21 @@ +/** + * 925. Long Pressed Name + * https://leetcode.com/problems/long-pressed-name/ + * Difficulty: Easy + * + * Your friend is typing his name into a keyboard. Sometimes, when typing a character c, + * the key might get long pressed, and the character will be typed 1 or more times. + * + * You examine the typed characters of the keyboard. Return True if it is possible that + * it was your friends name, with some characters (possibly none) being long pressed. + */ + +/** + * @param {string} name + * @param {string} typed + * @return {boolean} + */ +var isLongPressedName = function(name, typed) { + let i = 0; + return typed.split('').filter(l => name[i] === l ? ++i : false).length === name.length; +}; diff --git a/README.md b/README.md index 2a23ef16..3491b029 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| +925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| From c9989498d9edbdeeee9675d882c6d6b1b29fee92 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Sep 2021 14:54:20 -0400 Subject: [PATCH 076/485] Add solution #31 --- 0031-next-permutation.js | 50 ++++++++++++++++++++++++++++++++++++++++ README.md | 3 ++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 0031-next-permutation.js diff --git a/0031-next-permutation.js b/0031-next-permutation.js new file mode 100644 index 00000000..cc05f03c --- /dev/null +++ b/0031-next-permutation.js @@ -0,0 +1,50 @@ +/** + * 31. Next Permutation + * https://leetcode.com/problems/next-permutation/ + * Difficulty: Medium + * + * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. + * + * If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). + * + * The replacement must be in place and use only constant extra memory. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ + var nextPermutation = function(nums) { + let i = nums.length - 2; + + while (i >= 0 && nums[i + 1] <= nums[i]) { + i--; + } + + if (i >= 0) { + let cursor = nums.length - 1; + while (nums[cursor] <= nums[i]) { + cursor--; + } + swap(nums, i, cursor); + } + + reverse(nums, i + 1); +}; + +function reverse(nums, start) { + let i = start; + let j = nums.length - 1; + + while (i < j) { + swap(nums, i, j); + i++; + j--; + } +} + +function swap(nums, i, j) { + const temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; +} \ No newline at end of file diff --git a/README.md b/README.md index 3491b029..1979ea1b 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ |#|Title|Difficulty| |:---|:---|:---| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| @@ -76,4 +77,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2020 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2021 [Josh Crozier](https://joshcrozier.com) From 396948e7659af061b6a539f097465e651c9496d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Sep 2021 15:04:18 -0400 Subject: [PATCH 077/485] Add solution #1360 --- 1360-number-of-days-between-two-dates.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 1360-number-of-days-between-two-dates.js diff --git a/1360-number-of-days-between-two-dates.js b/1360-number-of-days-between-two-dates.js new file mode 100644 index 00000000..b3a6ed22 --- /dev/null +++ b/1360-number-of-days-between-two-dates.js @@ -0,0 +1,18 @@ +/** + * 1360. Number of Days Between Two Dates + * https://leetcode.com/problems/number-of-days-between-two-dates/ + * Difficulty: Easy + * + * Write a program to count the number of days between two dates. + * + * The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. + */ + +/** + * @param {string} date1 + * @param {string} date2 + * @return {number} + */ + var daysBetweenDates = function(date1, date2) { + return Math.abs(new Date(date1) - new Date(date2)) / (24 * 60 * 60 * 1000); +}; \ No newline at end of file diff --git a/README.md b/README.md index 1979ea1b..d9cfecf7 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| ## License From c863b390a02309e923222269119f937bc5d2b74c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Sep 2021 15:45:18 -0400 Subject: [PATCH 078/485] Add solution #1 --- 0001-two-sum.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0001-two-sum.js diff --git a/0001-two-sum.js b/0001-two-sum.js new file mode 100644 index 00000000..788e9d47 --- /dev/null +++ b/0001-two-sum.js @@ -0,0 +1,30 @@ +/** + * 1. Two Sum + * https://leetcode.com/problems/two-sum/ + * Difficulty: Easy + * + * 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. + * + * You can return the answer in any order. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + const diff = target - nums[i]; + + if (map.has(diff)) { + return [map.get(diff), i]; + } + + map.set(nums[i], i); + } +}; diff --git a/README.md b/README.md index d9cfecf7..ab6b580a 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ |#|Title|Difficulty| |:---|:---|:---| +1|[Two Sum](./0001-two-sum.js)|Easy| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From 0c5117e8bef4da49a51ff844c43c92bc650b77fc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Sep 2021 23:59:49 -0400 Subject: [PATCH 079/485] Add solution #54 --- 0054-spiral-matrix.js | 43 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0054-spiral-matrix.js diff --git a/0054-spiral-matrix.js b/0054-spiral-matrix.js new file mode 100644 index 00000000..3e6616e3 --- /dev/null +++ b/0054-spiral-matrix.js @@ -0,0 +1,43 @@ +/** + * 54. Spiral Matrix + * https://leetcode.com/problems/spiral-matrix/ + * Difficulty: Medium + * + * Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order. + */ + +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function(matrix) { + const output = []; + let top = 0; + let right = matrix[0].length - 1; + let bottom = matrix.length - 1; + let left = 0; + + while (output.length < matrix.length * matrix[0].length) { + for (let i = left; i <= right; i++) { + output.push(matrix[top][i]); + } + top++; + + for (let i = top; i <= bottom; i++) { + output.push(matrix[i][right]); + } + right--; + + for (let i = right; top <= bottom && i >= left; i--) { + output.push(matrix[bottom][i]); + } + bottom--; + + for (let i = bottom; left <= right && i >= top; i--) { + output.push(matrix[i][left]); + } + left++; + } + + return output; +}; diff --git a/README.md b/README.md index ab6b580a..6d066af1 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| From 495f66b778a04ebe088ea7492881596147d7ae50 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Sep 2021 16:57:25 -0400 Subject: [PATCH 080/485] Add solution #350 --- 0350-intersection-of-two-arrays-ii.js | 30 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0350-intersection-of-two-arrays-ii.js diff --git a/0350-intersection-of-two-arrays-ii.js b/0350-intersection-of-two-arrays-ii.js new file mode 100644 index 00000000..4e837cf7 --- /dev/null +++ b/0350-intersection-of-two-arrays-ii.js @@ -0,0 +1,30 @@ +/** + * 350. Intersection of Two Arrays II + * https://leetcode.com/problems/intersection-of-two-arrays-ii/ + * Difficulty: Easy + * + * Given two integer arrays nums1 and nums2, return an array of their intersection. + * + * Each element in the result must appear as many times as it shows in both arrays + * and you may return the result in any order. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function(nums1, nums2) { + const result = []; + const map = {}; + + nums1.forEach(value => map[value] = (map[value] || 0) + 1); + nums2.forEach(value => { + if (map[value]) { + result.push(value); + map[value]--; + } + }); + + return result; +}; diff --git a/README.md b/README.md index 6d066af1..b714a8e1 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| +350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From ad60b301877f684bd4650e2ed6e72a4b208f2081 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Sep 2021 16:59:10 -0400 Subject: [PATCH 081/485] Add solution #283 --- 0283-move-zeroes.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0283-move-zeroes.js diff --git a/0283-move-zeroes.js b/0283-move-zeroes.js new file mode 100644 index 00000000..3264be77 --- /dev/null +++ b/0283-move-zeroes.js @@ -0,0 +1,29 @@ +/** + * 283. Move Zeroes + * https://leetcode.com/problems/move-zeroes/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function(nums) { + for (let i = 0, j = 0; i < nums.length; i++) { + if (nums[i] !== 0) { + swap(nums, i, j++); + } + } + + return nums; +}; + +function swap(nums, i, j) { + const temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; +} diff --git a/README.md b/README.md index b714a8e1..1f268fb1 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 6a7247bf50c0e710eea48bca7fe2ddc8ac60648a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Sep 2021 19:51:34 -0400 Subject: [PATCH 082/485] Add solution #27 --- 0027-remove-element.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0027-remove-element.js diff --git a/0027-remove-element.js b/0027-remove-element.js new file mode 100644 index 00000000..5547faec --- /dev/null +++ b/0027-remove-element.js @@ -0,0 +1,29 @@ +/** + * 27. Remove Element + * https://leetcode.com/problems/remove-element/ + * Difficulty: Easy + * + * Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. + * The relative order of the elements may be changed. + * + * Since it is impossible to change the length of the array in some languages, you must instead + * have the result be placed in the first part of the array nums. More formally, if there are + * k elements after removing the duplicates, then the first k elements of nums should hold the + * final result. It does not matter what you leave beyond the first k elements. + * + * Return k after placing the final result in the first k slots of nums. + * + * Do not allocate extra space for another array. You must do this by modifying the input + * array in-place with O(1) extra memory. + */ + +/** + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function(nums, val) { + for (let i = nums.length - 1; i > -1; i--) { + if (nums[i] === val) nums.splice(i, 1); + } +}; diff --git a/README.md b/README.md index 1f268fb1..3a285857 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| From b3b62ffc6f10b85995fc2b8cab5205934892eb49 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Sep 2021 20:39:51 -0400 Subject: [PATCH 083/485] Add solution #7 --- 0007-reverse-integer.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0007-reverse-integer.js diff --git a/0007-reverse-integer.js b/0007-reverse-integer.js new file mode 100644 index 00000000..bf9ed763 --- /dev/null +++ b/0007-reverse-integer.js @@ -0,0 +1,23 @@ +/** + * 7. Reverse Integer + * https://leetcode.com/problems/reverse-integer/ + * Difficulty: Easy + * + * 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 [-2^31, 2^31 - 1], then return 0. + */ + +/** + * @param {number} x + * @return {number} + */ +var reverse = function(x) { + const reversed = String(Math.abs(x)).split('').reverse().join(''); + + if (reversed > Math.pow(2, 31)) { + return 0; + } + + return reversed * Math.sign(x); +}; diff --git a/README.md b/README.md index 3a285857..b6d1a104 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From 9b858c65619b2e720fc82937bcc1386d97807c38 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Sep 2021 20:45:45 -0400 Subject: [PATCH 084/485] Add solution #2 --- 0002-add-two-numbers.js | 43 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0002-add-two-numbers.js diff --git a/0002-add-two-numbers.js b/0002-add-two-numbers.js new file mode 100644 index 00000000..93b52403 --- /dev/null +++ b/0002-add-two-numbers.js @@ -0,0 +1,43 @@ +/** + * 2. Add Two Numbers + * https://leetcode.com/problems/add-two-numbers/ + * Difficulty: Medium + * + * 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. + * + * You may assume the two numbers do not contain any leading zero, except the number 0 itself. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + const result = new ListNode(); + let tail = result; + let carry = 0; + + while (l1 || l2 || carry) { + const v1 = l1 ? l1.val : 0; + const v2 = l2 ? l2.val : 0; + const v = v1 + v2 + carry; + + tail.next = new ListNode(v % 10); + tail = tail.next; + carry = v >= 10 ? 1 : 0; + l1 = l1 && l1.next; + l2 = l2 && l2.next; + } + + return result.next; +}; diff --git a/README.md b/README.md index b6d1a104..eba29e71 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ |#|Title|Difficulty| |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| +2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From 02ab7d9110b762b882e591f7ea23b7c065c42573 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Sep 2021 21:18:18 -0400 Subject: [PATCH 085/485] Add solution #3 --- ...-substring-without-repeating-characters.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0003-longest-substring-without-repeating-characters.js diff --git a/0003-longest-substring-without-repeating-characters.js b/0003-longest-substring-without-repeating-characters.js new file mode 100644 index 00000000..2bdecb15 --- /dev/null +++ b/0003-longest-substring-without-repeating-characters.js @@ -0,0 +1,22 @@ +/** + * 3. Longest Substring Without Repeating Characters + * https://leetcode.com/problems/longest-substring-without-repeating-characters/ + * Difficulty: Medium + * + * Given a string `s`, find the length of the longest substring without repeating characters. + */ + +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + const map = {}; + let offset = 0; + + return s.split('').reduce((max, value, i) => { + offset = map[value] >= offset ? map[value] + 1 : offset; + map[value] = i; + return Math.max(max, i - offset + 1); + }, 0); +}; diff --git a/README.md b/README.md index eba29e71..474520b4 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| 2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| +3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From b864874beba28a028ee4bcb1c9d3cb275644f278 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 17:55:20 -0400 Subject: [PATCH 086/485] Add solution #14 --- 0014-longest-common-prefix.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0014-longest-common-prefix.js diff --git a/0014-longest-common-prefix.js b/0014-longest-common-prefix.js new file mode 100644 index 00000000..cfbe6d07 --- /dev/null +++ b/0014-longest-common-prefix.js @@ -0,0 +1,27 @@ +/** + * 14. Longest Common Prefix + * https://leetcode.com/problems/longest-common-prefix/ + * Difficulty: Easy + * + * Write a function to find the longest common prefix string amongst an array of strings. + * + * If there is no common prefix, return an empty string `""`. + */ + +/** + * @param {string[]} strs + * @return {string} + */ +var longestCommonPrefix = function(strs) { + const prefixes = strs[0].split('').map((_, i) => strs[0].slice(0, i + 1)); + + for (let i = strs.length - 1; i > -1; i--) { + for (let j = prefixes.length - 1; j > -1; j--) { + if (strs[i].substr(0, j + 1) !== prefixes[j]) { + prefixes.pop(); + } + } + } + + return prefixes.pop() || ''; +}; diff --git a/README.md b/README.md index 474520b4..6152281f 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| +14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From daa969fb39532345f522149200c751e74923754c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 17:57:29 -0400 Subject: [PATCH 087/485] Add solution #10 --- 0010-regular-expression-matching.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0010-regular-expression-matching.js diff --git a/0010-regular-expression-matching.js b/0010-regular-expression-matching.js new file mode 100644 index 00000000..9e43518d --- /dev/null +++ b/0010-regular-expression-matching.js @@ -0,0 +1,22 @@ +/** + * 10. Regular Expression Matching + * https://leetcode.com/problems/regular-expression-matching/ + * Difficulty: Hard + * + * Given an input string s and a pattern p, implement regular expression + * matching with support for '.' and '*' where: + * + * '.' Matches any single character. + * '*' Matches zero or more of the preceding element. + * + * The matching should cover the entire input string (not partial). + */ + +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function(s, p) { + return new RegExp(`^${p}$`).test(s); +}; diff --git a/README.md b/README.md index 6152281f..f438b24f 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| +10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From 395ae6cb05cdef7ace3770d116ba8a37094a7058 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 18:13:42 -0400 Subject: [PATCH 088/485] Add solution #1880 --- ...k-if-word-equals-summation-of-two-words.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 1880-check-if-word-equals-summation-of-two-words.js diff --git a/1880-check-if-word-equals-summation-of-two-words.js b/1880-check-if-word-equals-summation-of-two-words.js new file mode 100644 index 00000000..ea784f3c --- /dev/null +++ b/1880-check-if-word-equals-summation-of-two-words.js @@ -0,0 +1,34 @@ +/** + * 1880. Check if Word Equals Summation of Two Words + * https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/ + * Difficulty: Easy + * + * The letter value of a letter is its position in the alphabet starting from + * 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). + * + * The numerical value of some string of lowercase English letters s is the + * concatenation of the letter values of each letter in s, which is then + * converted into an integer. + * + * For example, if s = "acb", we concatenate each letter's letter value, + * resulting in "021". After converting it, we get 21. + * + * You are given three strings firstWord, secondWord, and targetWord, each + * consisting of lowercase English letters 'a' through 'j' inclusive. + * + * Return true if the summation of the numerical values of firstWord and + * secondWord equals the numerical value of targetWord, or false otherwise. + */ + +/** + * @param {string} firstWord + * @param {string} secondWord + * @param {string} targetWord + * @return {boolean} + */ +var isSumEqual = function(firstWord, secondWord, targetWord) { + const [a, b, c] = [firstWord, secondWord, targetWord] + .map(str => +str.split('').map(v => v.charCodeAt() - 97).join('')); + + return a + b === c; +}; diff --git a/README.md b/README.md index f438b24f..e480fbe8 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| ## License From 288507208ae2c44bb8bb2a6f8581845e6434dd3e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 18:38:46 -0400 Subject: [PATCH 089/485] Add solution #8 --- 0008-string-to-integer-atoi.js | 37 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0008-string-to-integer-atoi.js diff --git a/0008-string-to-integer-atoi.js b/0008-string-to-integer-atoi.js new file mode 100644 index 00000000..99adf77d --- /dev/null +++ b/0008-string-to-integer-atoi.js @@ -0,0 +1,37 @@ +/** + * 8. String to Integer (atoi) + * https://leetcode.com/problems/string-to-integer-atoi/ + * Difficulty: Medium + * + * Implement the myAtoi(string s) function, which converts a string to a + * 32-bit signed integer (similar to C/C++'s atoi function). + * + * The algorithm for myAtoi(string s) is as follows: + * + * - Read in and ignore any leading whitespace. + * - Check if the next character (if not already at the end of the string) + * is '-' or '+'. Read this character in if it is either. This determines + * if the final result is negative or positive respectively. + * Assume the result is positive if neither is present. + * - Read in next the characters until the next non-digit charcter or the end + * of the input is reached. The rest of the string is ignored. + * - Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). + * If no digits were read, then the integer is 0. Change the sign as + * necessary (from step 2). + * - If the integer is out of the 32-bit signed integer range [-231, 231 - 1], + * then clamp the integer so that it remains in the range. Specifically, + * integers less than -231 should be clamped to -231, and integers greater + * than 231 - 1 should be clamped to 231 - 1. + * - Return the integer as the final result. + */ + +/** + * @param {string} s + * @return {number} + */ +var myAtoi = function(s) { + const parsed = +(s.trim().match(/^[-+]?\d+/g) || [0])[0]; + const clamped = Math.min(Math.max(parsed, (-2)**31), 2**31 - 1); + + return clamped; +}; diff --git a/README.md b/README.md index e480fbe8..9996d91d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| +8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From a7d885d2f374682ea44ce1560d19e545b38e9002 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 00:48:35 -0400 Subject: [PATCH 090/485] Add solution #1598 --- 1598-crawler-log-folder.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1598-crawler-log-folder.js diff --git a/1598-crawler-log-folder.js b/1598-crawler-log-folder.js new file mode 100644 index 00000000..fc82db84 --- /dev/null +++ b/1598-crawler-log-folder.js @@ -0,0 +1,35 @@ +/** + * 1598. Crawler Log Folder + * https://leetcode.com/problems/crawler-log-folder/ + * Difficulty: Easy + * + * The Leetcode file system keeps a log each time some user performs + * a change folder operation. + * + * The operations are described below: + * + * - `"../"` : Move to the parent folder of the current folder. (If + * you are already in the main folder, remain in the same folder). + * - `"./"` : Remain in the same folder. + * - `"x/"` : Move to the child folder named x (This folder is + * guaranteed to always exist). + * + * You are given a list of strings logs where logs[i] is the operation + * performed by the user at the ith step. + * + * The file system starts in the main folder, then the operations in + * logs are performed. + * + * Return the minimum number of operations needed to go back to the + * main folder after the change folder operations. + */ + +/** + * @param {string[]} logs + * @return {number} + */ +var minOperations = function(logs) { + return logs.reduce((depth, log) => + Math.max(0, depth + (log === '../' ? -1 : log === './' ? 0 : 1)), 0 + ); +}; diff --git a/README.md b/README.md index 9996d91d..8c6377c0 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| ## License From b5c8a3fe0c5a0e75935c6873c8b8647015d3debe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 00:57:42 -0400 Subject: [PATCH 091/485] Add solution #844 --- 0844-backspace-string-compare.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0844-backspace-string-compare.js diff --git a/0844-backspace-string-compare.js b/0844-backspace-string-compare.js new file mode 100644 index 00000000..c5dab2e4 --- /dev/null +++ b/0844-backspace-string-compare.js @@ -0,0 +1,30 @@ +/** + * 844. Backspace String Compare + * https://leetcode.com/problems/backspace-string-compare/ + * Difficulty: Easy + * + * Given two strings `s` and `t`, return true if they are equal when both + * are typed into empty text editors. '#' means a backspace character. + * + * Note that after backspacing an empty text, the text will continue empty. + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var backspaceCompare = function(s, t) { + return handleBackspaces(s) === handleBackspaces(t); +}; + +function handleBackspaces(input) { + return input.split('').reduce((result, char) => { + if (char === '#') { + result.pop(); + } else { + result.push(char); + } + return result; + }, []).join(''); +} diff --git a/README.md b/README.md index 8c6377c0..df0264c4 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ 819|[Most Common Word](./0819-most-common-word.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| +844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From 52c700f923fc63e444429e7ea4220b15cfecdc9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 01:00:29 -0400 Subject: [PATCH 092/485] Add solution #1472 --- 1472-design-browser-history.js | 59 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 1472-design-browser-history.js diff --git a/1472-design-browser-history.js b/1472-design-browser-history.js new file mode 100644 index 00000000..59a77531 --- /dev/null +++ b/1472-design-browser-history.js @@ -0,0 +1,59 @@ +/** + * 1472. Design Browser History + * https://leetcode.com/problems/design-browser-history/ + * Difficulty: Medium + * + * You have a browser of one tab where you start on the homepage and you + * can visit another url, get back in the history number of steps or move + * forward in the history number of steps. + * + * Implement the BrowserHistory class: + * + * - `BrowserHistory(string homepage)` Initializes the object with the + * homepage of the browser. + * - `void visit(string url)` Visits url from the current page. It clears + * up all the forward history. + * - `string back(int steps)` Move steps back in history. If you can only + * return x steps in the history and steps > x, you will return only x + * steps. Return the current url after moving back in history at most steps. + * - `string forward(int steps)` Move steps forward in history. If you can + * only forward x steps in the history and steps > x, you will forward only + * x steps. Return the current url after forwarding in history at most steps. + */ + +/** + * @param {string} homepage + */ +var BrowserHistory = function(homepage) { + this.history = []; + this.cursor = -1; + this.visit(homepage); +}; + +/** + * @param {string} url + * @return {void} + */ +BrowserHistory.prototype.visit = function(url) { + this.history.splice(this.cursor + 1, this.history.length); + this.history.push(url); + this.cursor++; +}; + +/** + * @param {number} steps + * @return {string} + */ +BrowserHistory.prototype.back = function(steps) { + this.cursor = Math.max(0, this.cursor - steps); + return this.history[this.cursor]; +}; + +/** + * @param {number} steps + * @return {string} + */ +BrowserHistory.prototype.forward = function(steps) { + this.cursor = Math.min(this.cursor + steps, this.history.length - 1); + return this.history[this.cursor]; +}; diff --git a/README.md b/README.md index df0264c4..72effc1c 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f82030aa9b9c26cbc1e3ddd0c6f7d27139befc29 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 19:01:32 -0400 Subject: [PATCH 093/485] Add solution #349 --- 0349-intersection-of-two-arrays.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0349-intersection-of-two-arrays.js diff --git a/0349-intersection-of-two-arrays.js b/0349-intersection-of-two-arrays.js new file mode 100644 index 00000000..c80df42f --- /dev/null +++ b/0349-intersection-of-two-arrays.js @@ -0,0 +1,19 @@ +/** + * 349. Intersection of Two Arrays + * https://leetcode.com/problems/intersection-of-two-arrays/ + * Difficulty: Easy + * + * Given two integer arrays `nums1` and `nums2`, return an array of their intersection. + * + * Each element in the result must be unique and you may return the result in any order. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function(nums1, nums2) { + const set = new Set(nums1); + return nums2.filter(value => set.delete(value)); +}; diff --git a/README.md b/README.md index 72effc1c..7820c9cc 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| +349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 0b5920d3e6dd8df2c766f08bebc62f9aae51e420 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 19:18:43 -0400 Subject: [PATCH 094/485] Add solution #347 --- 0347-top-k-frequent-elements.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0347-top-k-frequent-elements.js diff --git a/0347-top-k-frequent-elements.js b/0347-top-k-frequent-elements.js new file mode 100644 index 00000000..87b6b3e5 --- /dev/null +++ b/0347-top-k-frequent-elements.js @@ -0,0 +1,24 @@ +/** + * 347. Top K Frequent Elements + * https://leetcode.com/problems/top-k-frequent-elements/ + * Difficulty: Medium + * + * Given an integer array `nums` and an integer `k`, return the `k` most + * frequent elements. You may return the answer in any order. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + const map = new Map(); + + nums.forEach(value => map.set(value, (map.get(value) || 0) + 1)); + + return [...map] + .sort((a, b) => b[1] - a[1]) + .slice(0, k) + .map(([value]) => value) +}; diff --git a/README.md b/README.md index 7820c9cc..435b5940 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| +347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From f4509a8bb285383cce397b5bdb0abd74361c11e3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:42:33 -0400 Subject: [PATCH 095/485] Add solution #448 --- ...ind-all-numbers-disappeared-in-an-array.js | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0448-find-all-numbers-disappeared-in-an-array.js diff --git a/0448-find-all-numbers-disappeared-in-an-array.js b/0448-find-all-numbers-disappeared-in-an-array.js new file mode 100644 index 00000000..fda2a892 --- /dev/null +++ b/0448-find-all-numbers-disappeared-in-an-array.js @@ -0,0 +1,33 @@ +/** + * 448. Find All Numbers Disappeared in an Array + * https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ + * Difficulty: Easy + * + * Given an array `nums` of `n` integers where `nums[i]` is in the + * range `[1, n]`, return an array of all the integers in the + * range `[1, n]` that do not appear in nums. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var findDisappearedNumbers = function(nums) { + const result = []; + + for (let i = 0; i < nums.length;) { + if (nums[nums[i] - 1] !== nums[i]) { + [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; + } else { + i++; + } + } + + nums.forEach((v, i) => { + if (v != i + 1) { + result.push(i + 1); + } + }); + + return result; +}; diff --git a/README.md b/README.md index 435b5940..4e724bce 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| From 002983c874120a04d14ca92eb44ee2000024b2f5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:45:06 -0400 Subject: [PATCH 096/485] Add solution #41 --- 0041-first-missing-positive.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0041-first-missing-positive.js diff --git a/0041-first-missing-positive.js b/0041-first-missing-positive.js new file mode 100644 index 00000000..45d5107b --- /dev/null +++ b/0041-first-missing-positive.js @@ -0,0 +1,33 @@ +/** + * 41. First Missing Positive + * https://leetcode.com/problems/first-missing-positive/ + * Difficulty: Hard + * + * Given an unsorted integer array nums, return the smallest missing positive integer. + * + * You must implement an algorithm that runs in O(n) time and uses constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var firstMissingPositive = function(nums) { + let i = 0; + + while (i < nums.length) { + if (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] !== nums[i]) { + [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; + } else { + i++; + } + } + + for (i = 0; i < nums.length; i++) { + if (nums[i] !== i + 1) { + return i + 1; + } + } + + return i + 1; +}; diff --git a/README.md b/README.md index 4e724bce..93a0573f 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| From f9493227c3eb31cd787ff9e4b7a1e0fc4ef0fa9f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:46:38 -0400 Subject: [PATCH 097/485] Add solution #268 --- 0268-missing-number.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0268-missing-number.js diff --git a/0268-missing-number.js b/0268-missing-number.js new file mode 100644 index 00000000..f8624b64 --- /dev/null +++ b/0268-missing-number.js @@ -0,0 +1,25 @@ +/** + * 268. Missing Number + * https://leetcode.com/problems/missing-number/ + * Difficulty: Easy + * + * Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, + * return the only number in the range that is missing from the array. + * + * Follow up: Could you implement a solution using only `O(1)` extra space + * complexity and `O(n)` runtime complexity? + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function(nums) { + let result = 0; + + for (let i = 0; i < nums.length; i++) { + result += i + 1 - nums[i]; + } + + return result; +}; diff --git a/README.md b/README.md index 93a0573f..12993a07 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +268|[Missing Number](./0268-missing-number.js)|Easy| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| From 073003a23f30569abfb7395dafc6d5f66b4dd58d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:48:14 -0400 Subject: [PATCH 098/485] Add solution #17 --- 0017-letter-combinations-of-a-phone-number.js | 47 +++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0017-letter-combinations-of-a-phone-number.js diff --git a/0017-letter-combinations-of-a-phone-number.js b/0017-letter-combinations-of-a-phone-number.js new file mode 100644 index 00000000..fd215917 --- /dev/null +++ b/0017-letter-combinations-of-a-phone-number.js @@ -0,0 +1,47 @@ +/** + * 17. Letter Combinations of a Phone Number + * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ + * Difficulty: Medium + * + * Given a string containing digits from 2-9 inclusive, return all possible + * letter combinations that the number could represent. Return the answer + * in any order. + * + * A mapping of digit to letters (just like on the telephone buttons) is + * given below. Note that 1 does not map to any letters. + */ + +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function(digits) { + if (!digits || !digits.length) return []; + + const map = { + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'pqrs', + 8: 'tuv', + 9: 'wxyz' + }; + + if (digits.length === 1) { + return map[digits].split(''); + } + + const result = []; + const group1 = letterCombinations(digits.substr(0, 1)); + const group2 = letterCombinations(digits.substr(1)); + + for (let i = 0; i < group1.length; i++) { + for (let j = 0; j < group2.length; j++) { + result.push(group1[i] + group2[j]); + } + } + + return result; +}; diff --git a/README.md b/README.md index 12993a07..a0d9d909 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| +17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From 49a1fd12a57246f3c28c475363d9580f3365e4cf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:55:43 -0400 Subject: [PATCH 099/485] Add solution #2000 --- 2000-reverse-prefix-of-word.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2000-reverse-prefix-of-word.js diff --git a/2000-reverse-prefix-of-word.js b/2000-reverse-prefix-of-word.js new file mode 100644 index 00000000..531eabeb --- /dev/null +++ b/2000-reverse-prefix-of-word.js @@ -0,0 +1,22 @@ +/** + * 2000. Reverse Prefix of Word + * https://leetcode.com/problems/reverse-prefix-of-word/ + * Difficulty: Easy + * + * Given a 0-indexed string word and a character ch, reverse the segment of word that + * starts at index 0 and ends at the index of the first occurrence of ch (inclusive). + * If the character ch does not exist in word, do nothing. + * + * For example, if word = "abcdefd" and ch = "d", then you should reverse the segment + * that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". + */ + +/** + * @param {string} word + * @param {character} ch + * @return {string} + */ +var reversePrefix = function(word, ch) { + const index = word.indexOf(ch) + 1; + return word.slice(0, index).split('').reverse().join('') + word.slice(index); +}; diff --git a/README.md b/README.md index a0d9d909..d71081f8 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| ## License From 78dee2bba0f9d142773259eb1809e3ee0dfe4393 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:57:01 -0400 Subject: [PATCH 100/485] Add solution #884 --- 0884-uncommon-words-from-two-sentences.js | 26 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0884-uncommon-words-from-two-sentences.js diff --git a/0884-uncommon-words-from-two-sentences.js b/0884-uncommon-words-from-two-sentences.js new file mode 100644 index 00000000..6ee36541 --- /dev/null +++ b/0884-uncommon-words-from-two-sentences.js @@ -0,0 +1,26 @@ +/** + * 884. Uncommon Words from Two Sentences + * https://leetcode.com/problems/uncommon-words-from-two-sentences/submissions/ + * Difficulty: Easy + * + * A sentence is a string of single-space separated words where each word consists + * only of lowercase letters. + * + * A word is uncommon if it appears exactly once in one of the sentences, and does + * not appear in the other sentence. + * + * Given two sentences s1 and s2, return a list of all the uncommon words. You may + * return the answer in any order. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {string[]} + */ +var uncommonFromSentences = function(s1, s2) { + const map = new Map(); + + (s1 + ' ' + s2).split(/\s+/).forEach(s => map.set(s, (map.get(s) || 0) + 1)); + return [...map].reduce((a, [k, c]) => c === 1 ? [...a, k] : a, []); +}; diff --git a/README.md b/README.md index d71081f8..a02f578e 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| From ba78a6b073e63aff3d78b80ae10b407ff1ac7c32 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:58:19 -0400 Subject: [PATCH 101/485] Add solution #50 --- 0050-powx-n.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0050-powx-n.js diff --git a/0050-powx-n.js b/0050-powx-n.js new file mode 100644 index 00000000..e0fafc09 --- /dev/null +++ b/0050-powx-n.js @@ -0,0 +1,21 @@ +/** + * 50. Pow(x, n) + * https://leetcode.com/problems/powx-n/ + * Difficulty: Medium + * + * Implement `pow(x, n)`, which calculates `x` raised to the power `n` (i.e., `x^n`). + */ + +/** + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = function(x, n) { + if (n === 0) return 1; + if (n === 1) return x; + if (n < 0) return 1 / myPow(x, -n); + if (n % 2 === 0) return myPow(x * x, n / 2); + + return x * myPow(x * x, (n - 1) / 2); +}; diff --git a/README.md b/README.md index a02f578e..c0332676 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +50|[Pow(x, n)](./0050-powx-n.js)|Medium| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| From 196bf5d1fae7aac00f5b9c973108979285952710 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:59:52 -0400 Subject: [PATCH 102/485] Add solution #49 --- 0049-group-anagrams.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0049-group-anagrams.js diff --git a/0049-group-anagrams.js b/0049-group-anagrams.js new file mode 100644 index 00000000..3f48828b --- /dev/null +++ b/0049-group-anagrams.js @@ -0,0 +1,26 @@ +/** + * 49. Group Anagrams + * https://leetcode.com/problems/group-anagrams/ + * Difficulty: Medium + * + * Given an array of strings `strs`, group the anagrams together. You can return the + * answer in any order. + * + * 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. + */ + +/** + * @param {string[]} strs + * @return {string[][]} + */ +var groupAnagrams = function(strs) { + const map = {}; + + strs.forEach(str => { + const key = [...str].sort(); + map[key] = map[key] ? [...map[key], str] : [str]; + }); + + return Object.values(map); +}; diff --git a/README.md b/README.md index c0332676..f0848190 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| From 1a90f7beb7eaf0692a60704139201bf0864521e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 13:03:34 -0400 Subject: [PATCH 103/485] Add solution #12 --- 0012-integer-to-roman.js | 44 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0012-integer-to-roman.js diff --git a/0012-integer-to-roman.js b/0012-integer-to-roman.js new file mode 100644 index 00000000..b4e941f6 --- /dev/null +++ b/0012-integer-to-roman.js @@ -0,0 +1,44 @@ +/** + * 12. Integer to Roman + * https://leetcode.com/problems/integer-to-roman/ + * Difficulty: Medium + * + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written + * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * + * Roman numerals are usually written largest to smallest from left to right. However, the numeral for + * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five + * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. + * There are six instances where subtraction is used: + * + * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. + * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. + * - `C` can be placed before `D (500)` and `M (1000)` to make 400 and 900. + * + * Given an integer, convert it to a roman numeral. + */ + +/** + * @param {number} num + * @return {string} + */ +var intToRoman = function(num) { + const map = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }; + + return Object.entries(map).reduce((result, [letter, n]) => { + result += letter.repeat(Math.floor(num / n)); + num %= n; + return result; + }, ''); +}; diff --git a/README.md b/README.md index f0848190..9aa3c8d8 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| +12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| From f0ca466b646f4637175218ec6abf066731971172 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 13:05:05 -0400 Subject: [PATCH 104/485] Add solution #13 --- 0013-roman-to-integer.js | 45 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0013-roman-to-integer.js diff --git a/0013-roman-to-integer.js b/0013-roman-to-integer.js new file mode 100644 index 00000000..14593317 --- /dev/null +++ b/0013-roman-to-integer.js @@ -0,0 +1,45 @@ +/** + * 13. Roman to Integer + * https://leetcode.com/problems/roman-to-integer/ + * Difficulty: Easy + * + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written + * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * + * Roman numerals are usually written largest to smallest from left to right. However, the numeral for + * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five + * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. + * There are six instances where subtraction is used: + * + * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. + * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. + * - `C` can be placed before `D (500)` and `M (1000)` to make 400 and 900. + * + * Given a roman numeral, convert it to an integer. + */ + +/** + * @param {string} s + * @return {number} + */ +var romanToInt = function(s) { + const map = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 }; + + return s.split('').reduce((result, v, i) => { + result += map[v] >= map[s[i + 1]] || s.length === i + 1 + ? map[v] + : -1 * map[v]; + return result; + }, 0); +}; diff --git a/README.md b/README.md index 9aa3c8d8..fd3a1acc 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| +13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| From 3a62368d01f0cb2f038ef99e8260dbe9ae7561a3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 14:02:43 -0400 Subject: [PATCH 105/485] Add solution #1929 --- 1929-concatenation-of-array.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1929-concatenation-of-array.js diff --git a/1929-concatenation-of-array.js b/1929-concatenation-of-array.js new file mode 100644 index 00000000..084d4b59 --- /dev/null +++ b/1929-concatenation-of-array.js @@ -0,0 +1,21 @@ +/** + * 1929. Concatenation of Array + * https://leetcode.com/problems/concatenation-of-array/ + * Difficulty: Easy + * + * Given an integer array `nums` of length `n`, you want to create an + * array `ans` of length `2n` where `ans[i] == nums[i`] and + * `ans[i + n] == nums[i]` for `0 <= i < n` (0-indexed). + * + * Specifically, `ans` is the concatenation of two `nums` arrays. + * + * Return the array `ans`. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var getConcatenation = function(nums) { + return [...nums, ...nums]; +}; diff --git a/README.md b/README.md index fd3a1acc..8a472980 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| ## License From 50f42ec0774702c6e03f0409dad725673c8b7bdc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 16:26:57 -0400 Subject: [PATCH 106/485] Add solution #217 --- 0217-contains-duplicate.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0217-contains-duplicate.js diff --git a/0217-contains-duplicate.js b/0217-contains-duplicate.js new file mode 100644 index 00000000..951c214f --- /dev/null +++ b/0217-contains-duplicate.js @@ -0,0 +1,16 @@ +/** + * 217. Contains Duplicate + * https://leetcode.com/problems/contains-duplicate/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + return new Set(nums).size !== nums.length; +}; diff --git a/README.md b/README.md index 8a472980..19924cb8 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 4213dca7f438ace5707687ad50cf3fec6f48eaa1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 16:28:38 -0400 Subject: [PATCH 107/485] Add solution #219 --- 0219-contains-duplicate-ii.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0219-contains-duplicate-ii.js diff --git a/0219-contains-duplicate-ii.js b/0219-contains-duplicate-ii.js new file mode 100644 index 00000000..1b02742c --- /dev/null +++ b/0219-contains-duplicate-ii.js @@ -0,0 +1,27 @@ +/** + * 219. Contains Duplicate II + * https://leetcode.com/problems/contains-duplicate-ii/ + * Difficulty: Easy + * + * Given an integer array `nums` and an integer `k`, return `true` if there are + * two distinct indices `i` and `j` in the array such that `nums[i] == nums[j]` + * and `abs(i - j) <= k`. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var containsNearbyDuplicate = function(nums, k) { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + if (Math.abs(i - map.get(nums[i])) <= k) { + return true; + } + map.set(nums[i], i); + } + + return false; +}; diff --git a/README.md b/README.md index 19924cb8..dbb01348 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| +219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 9dde91bebe2328b6e6af0a277d9a439c9f0f2790 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:48:45 -0400 Subject: [PATCH 108/485] Add solution #88 --- 0088-merge-sorted-array.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0088-merge-sorted-array.js diff --git a/0088-merge-sorted-array.js b/0088-merge-sorted-array.js new file mode 100644 index 00000000..c94a4117 --- /dev/null +++ b/0088-merge-sorted-array.js @@ -0,0 +1,34 @@ +/** + * 88. Merge Sorted Array + * https://leetcode.com/problems/merge-sorted-array/ + * Difficulty: Easy + * + * You are given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, + * and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` + * respectively. + * + * Merge `nums1` and `nums2` into a single array sorted in non-decreasing order. + * + * The final sorted array should not be returned by the function, but instead be + * stored inside the array `nums1`. To accommodate this, `nums1` has a length of `m + n`, + * where the first `m` elements denote the elements that should be merged, and the + * last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. + */ + +/** + * @param {number[]} nums1 + * @param {number} m + * @param {number[]} nums2 + * @param {number} n + * @return {void} Do not return anything, modify nums1 in-place instead. + */ +var merge = function(nums1, m, nums2, n) { + let i = m + n - 1; + + m--; + n--; + + while (n >= 0) { + nums1[i--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; + } +}; diff --git a/README.md b/README.md index dbb01348..1254fb10 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 43744db7fcd2e97d7bc1e1cc8a995fcea95c28c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:49:35 -0400 Subject: [PATCH 109/485] Add solution #53 --- 0053-maximum-subarray.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0053-maximum-subarray.js diff --git a/0053-maximum-subarray.js b/0053-maximum-subarray.js new file mode 100644 index 00000000..55634cfc --- /dev/null +++ b/0053-maximum-subarray.js @@ -0,0 +1,24 @@ +/** + * 53. Maximum Subarray + * https://leetcode.com/problems/maximum-subarray/ + * Difficulty: Easy + * + * Given an integer array `nums`, find the contiguous subarray (containing at + * least one number) which has the largest sum and return its sum. + * + * A subarray is a contiguous part of an array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function(nums) { + for (let i = 1; i < nums.length; i++) { + if (nums[i - 1] > 0) { + nums[i] += nums[i - 1]; + } + } + + return Math.max(...nums); +}; diff --git a/README.md b/README.md index 1254fb10..551ab0e3 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| +53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| From 61bf2632c75528f9fce58dba895f9fedb000d7fd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:52:11 -0400 Subject: [PATCH 110/485] Add solution #6 --- 0006-zigzag-conversion.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0006-zigzag-conversion.js diff --git a/0006-zigzag-conversion.js b/0006-zigzag-conversion.js new file mode 100644 index 00000000..37d5c314 --- /dev/null +++ b/0006-zigzag-conversion.js @@ -0,0 +1,30 @@ +/** + * 6. ZigZag Conversion + * https://leetcode.com/problems/zigzag-conversion/ + * Difficulty: Medium + * + * The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given + * number of rows like this: (you may want to display this pattern in a + * fixed font for better legibility) + * + * > P A H N + * > A P L S I I G + * > Y I R + * + * And then read line by line: `"PAHNAPLSIIGYIR"` + */ + +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function(s, numRows) { + const order = [...new Array(numRows).keys()]; + order.push(...order.slice(1, -1).reverse()); + + const rows = new Array(numRows).fill(''); + [...s].forEach((c, i) => (rows[order[i % order.length]] += c)); + + return rows.join(''); +}; diff --git a/README.md b/README.md index 551ab0e3..8a98e944 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ 2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +6|[ZigZag Conversion](./0006-zigzag-conversion.js)|Medium| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| From b105795f4716099a5f30d1c4eadb812ab9c5544c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:58:43 -0400 Subject: [PATCH 111/485] Add solution #9 --- 0009-palindrome-number.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0009-palindrome-number.js diff --git a/0009-palindrome-number.js b/0009-palindrome-number.js new file mode 100644 index 00000000..e696c444 --- /dev/null +++ b/0009-palindrome-number.js @@ -0,0 +1,19 @@ +/** + * 9. Palindrome Number + * https://leetcode.com/problems/palindrome-number/ + * Difficulty: Easy + * + * Given an integer `x`, return `true` if `x` is palindrome integer. + +An integer is a palindrome when it reads the same backward as forward. +For example, `121` is palindrome while `123` is not. + */ + +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function(x) { + if (x < 0) return false; + return +String(x).split('').reverse().join('') === x; +}; diff --git a/README.md b/README.md index 8a98e944..09f0fa32 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 6|[ZigZag Conversion](./0006-zigzag-conversion.js)|Medium| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| +9|[Palindrome Number](./0009-palindrome-number.js)|Easy| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| From 25ada88c5f5b480230b79a602a7bf4a7a5d39cbf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 18:07:26 -0400 Subject: [PATCH 112/485] Add solution #234 --- 0234-palindrome-linked-list.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0234-palindrome-linked-list.js diff --git a/0234-palindrome-linked-list.js b/0234-palindrome-linked-list.js new file mode 100644 index 00000000..37b4a5e6 --- /dev/null +++ b/0234-palindrome-linked-list.js @@ -0,0 +1,30 @@ +/** + * 234. Palindrome Linked List + * https://leetcode.com/problems/palindrome-linked-list/ + * Difficulty: Easy + * + * Given the `head` of a singly linked list, return `true` if it is a palindrome. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {boolean} + */ +var isPalindrome = function(head) { + let a = '', b = ''; + + while (head) { + a = a + head.val; + b = head.val + b; + head = head.next; + } + + return a === b; +}; diff --git a/README.md b/README.md index 09f0fa32..550b2a12 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| From 4012c416abdbd11f65e99c2066a3f01a8b8ea1f8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:21:38 -0400 Subject: [PATCH 113/485] Add solution #42 --- 0042-trapping-rain-water.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0042-trapping-rain-water.js diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js new file mode 100644 index 00000000..4a7af38b --- /dev/null +++ b/0042-trapping-rain-water.js @@ -0,0 +1,35 @@ +/** + * 42. Trapping Rain Water + * https://leetcode.com/problems/trapping-rain-water/ + * Difficulty: Hard + * + * Given `n` non-negative integers representing an elevation map where the width + * of each bar is `1`, compute how much water it can trap after raining. + */ + +/** + * @param {number[]} height + * @return {number} + */ +var trap = function(height) { + const leftMax = []; + const rightMax = []; + let result = 0; + + leftMax[0] = height[0]; + rightMax[height.length - 1] = height[height.length - 1]; + + for (let i = 1; i < height.length; i++) { + leftMax[i] = Math.max(height[i], leftMax[i - 1]); + } + + for (let i = height.length - 2; i > -1; i--){ + rightMax[i] = Math.max(height[i], rightMax[i + 1]); + } + + for (let i = 0; i < height.length; i++) { + result += Math.min(leftMax[i], rightMax[i]) - height[i]; + } + + return result; +}; diff --git a/README.md b/README.md index 550b2a12..2455adf3 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| +42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| From 3aac099f730f2550a94d127306f1c6639ed67ab6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:23:53 -0400 Subject: [PATCH 114/485] Add solution #11 --- 0011-container-with-most-water.js | 35 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0011-container-with-most-water.js diff --git a/0011-container-with-most-water.js b/0011-container-with-most-water.js new file mode 100644 index 00000000..51818c6e --- /dev/null +++ b/0011-container-with-most-water.js @@ -0,0 +1,35 @@ +/** + * 11. Container With Most Water + * https://leetcode.com/problems/container-with-most-water/ + * Difficulty: Medium + * + * Given n non-negative integers `a1, a2, ..., an ,` where each represents a point at + * coordinate `(i, ai)`. `n` vertical lines are drawn such that the two endpoints of + * the line `i` is at `(i, ai)` and `(i, 0)`. Find two lines, which, together with the + * x-axis forms a container, such that the container contains the most water. + * + * Notice that you may not slant the container. + */ + +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function(height) { + let maxArea = 0; + + for (let left = 0, right = height.length - 1; left < right;) { + maxArea = Math.max( + maxArea, + Math.min(height[left], height[right]) * (right - left) + ); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return maxArea; +}; diff --git a/README.md b/README.md index 2455adf3..f976e203 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 9|[Palindrome Number](./0009-palindrome-number.js)|Easy| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| +11|[Container With Most Water](./0011-container-with-most-water.js)|Medium| 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| From 007bf8d379f43dde0154307ed70f659d1170573f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:25:23 -0400 Subject: [PATCH 115/485] Add solution #42 --- 0042-trapping-rain-water.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js index 4a7af38b..871e37a7 100644 --- a/0042-trapping-rain-water.js +++ b/0042-trapping-rain-water.js @@ -23,7 +23,7 @@ var trap = function(height) { leftMax[i] = Math.max(height[i], leftMax[i - 1]); } - for (let i = height.length - 2; i > -1; i--){ + for (let i = height.length - 2; i > -1; i--) { rightMax[i] = Math.max(height[i], rightMax[i + 1]); } From 1cf52caea84a52de65893634e7a2126df84aaec6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:28:08 -0400 Subject: [PATCH 116/485] Add solution #73 --- 0073-set-matrix-zeroes.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0073-set-matrix-zeroes.js diff --git a/0073-set-matrix-zeroes.js b/0073-set-matrix-zeroes.js new file mode 100644 index 00000000..fbce9692 --- /dev/null +++ b/0073-set-matrix-zeroes.js @@ -0,0 +1,33 @@ +/** + * 73. Set Matrix Zeroes + * https://leetcode.com/problems/set-matrix-zeroes/ + * Difficulty: Medium + * + * Given an `m x n` integer `matrix` matrix, if an element is `0`, set its entire + * row and column to `0`'s, and return the matrix. + * + * You must do it in place. + */ + +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var setZeroes = function(matrix) { + const columns = new Set(); + const rows = new Set(); + + matrix.forEach((row, i) => { + row.forEach((value, j) => { + if (value === 0) { + columns.add(i); + rows.add(j); + } + }); + }); + + [...columns].forEach(i => matrix[i].forEach((_, j) => matrix[i][j] = 0)); + matrix.forEach((_, i) => [...rows].forEach(j => matrix[i][j] = 0)); + + return matrix; +}; diff --git a/README.md b/README.md index f976e203..7ecba5bb 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From 03e751ef3210568872b70d4dfe2bc168bdf4a517 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:53:22 -0400 Subject: [PATCH 117/485] Add solution #273 --- 0273-integer-to-english-words.js | 33 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0273-integer-to-english-words.js diff --git a/0273-integer-to-english-words.js b/0273-integer-to-english-words.js new file mode 100644 index 00000000..b664e25c --- /dev/null +++ b/0273-integer-to-english-words.js @@ -0,0 +1,33 @@ +/** + * 273. Integer to English Words + * https://leetcode.com/problems/integer-to-english-words/ + * Difficulty: Hard + * + * Convert a non-negative integer `num` to its English words representation. + */ + +/** + * @param {number} num + * @return {string} + */ +var numberToWords = function(num) { + if (num === 0) { + return 'Zero'; + } + + return convert(num).replace(/\s+/g, ' ').trim(); +}; + +const belowTen = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']; +const belowTwenty = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']; +const belowHundred = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']; + +function convert(num) { + if (num < 10) return belowTen[num]; + else if (num < 20) return belowTwenty[num - 10]; + else if (num < 100) return belowHundred[Math.floor(num / 10)] + ' ' + convert(num % 10); + else if (num < 1000) return convert(Math.floor(num / 100)) + ' Hundred ' + convert(num % 100); + else if (num < 1000000) return convert(Math.floor(num / 1000)) + ' Thousand ' + convert(num % 1000); + else if (num < 1000000000) return convert(Math.floor(num / 1000000)) + ' Million ' + convert(num % 1000000); + else return convert(Math.floor(num / 1000000000)) + ' Billion ' + convert(num % 1000000000); +} diff --git a/README.md b/README.md index 7ecba5bb..6ea7a55b 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| +273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| From d9224345e6c2bb7eae8febff3428056c15cbf655 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 02:05:52 -0400 Subject: [PATCH 118/485] Add solution #121 --- 0121-best-time-to-buy-and-sell-stock.js | 29 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0121-best-time-to-buy-and-sell-stock.js diff --git a/0121-best-time-to-buy-and-sell-stock.js b/0121-best-time-to-buy-and-sell-stock.js new file mode 100644 index 00000000..20d2557f --- /dev/null +++ b/0121-best-time-to-buy-and-sell-stock.js @@ -0,0 +1,29 @@ +/** + * 121. Best Time to Buy and Sell Stock + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ + * Difficulty: Easy + * + * You 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. + * + * Return the maximum profit you can achieve from this transaction. If you + * cannot achieve any profit, return 0. + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let max = 0; + + for (let i = 0, min = prices[0]; i < prices.length; i++) { + min = Math.min(min, prices[i]); + max = Math.max(max, prices[i] - min); + } + + return max; +}; diff --git a/README.md b/README.md index 6ea7a55b..00885999 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 391c8ff32cf043ee6b1150aade4ade6e747cf23b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 16:07:10 -0400 Subject: [PATCH 119/485] Add solution #5 --- 0005-longest-palindromic-substring.js | 37 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0005-longest-palindromic-substring.js diff --git a/0005-longest-palindromic-substring.js b/0005-longest-palindromic-substring.js new file mode 100644 index 00000000..d15b8499 --- /dev/null +++ b/0005-longest-palindromic-substring.js @@ -0,0 +1,37 @@ +/** + * 5. Longest Palindromic Substring + * https://leetcode.com/problems/longest-palindromic-substring/ + * Difficulty: Medium + * + * Given a string `s`, return the longest palindromic substring in `s`. + */ + +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function(s) { + let result = ''; + + for (let i = 0; i < s.length; i++) { + let palindrome1 = getExtendedPalindrome(s, i, i); + let palindrome2 = getExtendedPalindrome(s, i, i + 1); + let longerPalindrome = palindrome1.length > palindrome2.length + ? palindrome1 : palindrome2; + + if (longerPalindrome.length > result.length) { + result = longerPalindrome; + } + } + + return result; +}; + +function getExtendedPalindrome(s, start, end) { + while (start >= 0 && end < s.length && s[start] === s[end]) { + start--; + end++; + } + + return s.slice(start + 1, end); +} diff --git a/README.md b/README.md index 00885999..df1f81d6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ 2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +5|[Longest Palindromic Substring](./0005-longest-palindromic-substring.js)|Medium| 6|[ZigZag Conversion](./0006-zigzag-conversion.js)|Medium| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| From 7d50d6ff603571a60eaa04c7dc2a39f62ad65ba2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:32:38 -0400 Subject: [PATCH 120/485] Add solution #383 --- 0383-ransom-note.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0383-ransom-note.js diff --git a/0383-ransom-note.js b/0383-ransom-note.js new file mode 100644 index 00000000..5bda58f1 --- /dev/null +++ b/0383-ransom-note.js @@ -0,0 +1,32 @@ +/** + * 383. Ransom Note + * https://leetcode.com/problems/ransom-note/ + * Difficulty: Easy + * + * Given two stings ransomNote and magazine, return true if ransomNote + * can be constructed from magazine and false otherwise. + * + * Each letter in magazine can only be used once in ransomNote. + */ + +/** + * @param {string} ransomNote + * @param {string} magazine + * @return {boolean} + */ +var canConstruct = function(ransomNote, magazine) { + const map = new Map(); + + for (let i = magazine.length - 1; i > -1; i--) { + map.set(magazine[i], (map.get(magazine[i]) || 0) + 1); + } + + for (let i = ransomNote.length - 1; i > -1; i--) { + if ((map.get(ransomNote[i]) || 0) < 1) { + return false; + } + map.set(ransomNote[i], map.get(ransomNote[i]) - 1); + } + + return true; +}; diff --git a/README.md b/README.md index df1f81d6..82dff531 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 68fe9ef269af16b2d35f68030497bcac12a4993b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:33:54 -0400 Subject: [PATCH 121/485] Add solution #442 --- 0442-find-all-duplicates-in-an-array.js | 31 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0442-find-all-duplicates-in-an-array.js diff --git a/0442-find-all-duplicates-in-an-array.js b/0442-find-all-duplicates-in-an-array.js new file mode 100644 index 00000000..551c3a8e --- /dev/null +++ b/0442-find-all-duplicates-in-an-array.js @@ -0,0 +1,31 @@ +/** + * 442. Find All Duplicates in an Array + * https://leetcode.com/problems/find-all-duplicates-in-an-array/ + * Difficulty: Medium + * + * Given an integer array nums of length n where all the integers of nums + * are in the range [1, n] and each integer appears once or twice, return + * an array of all the integers that appears twice. + * + * You must write an algorithm that runs in O(n) time and uses only constant + * extra space. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var findDuplicates = function(nums) { + const result = []; + + nums.forEach((num, i) => { + const key = Math.abs(num) - 1; + if (nums[key] < 0) { + result.push(Math.abs(num)); + } else { + nums[key] *= -1; + } + }); + + return result; +}; diff --git a/README.md b/README.md index 82dff531..8e79c4d5 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From 2c6618efb6c88d1c23d10ba82b180700a18b77c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:35:53 -0400 Subject: [PATCH 122/485] Add solution #2016 --- ...-difference-between-increasing-elements.js | 26 +++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2016-maximum-difference-between-increasing-elements.js diff --git a/2016-maximum-difference-between-increasing-elements.js b/2016-maximum-difference-between-increasing-elements.js new file mode 100644 index 00000000..18c1a4f4 --- /dev/null +++ b/2016-maximum-difference-between-increasing-elements.js @@ -0,0 +1,26 @@ +/** + * 2016. Maximum Difference Between Increasing Elements + * https://leetcode.com/problems/maximum-difference-between-increasing-elements/ + * Difficulty: Easy + * + * Given a 0-indexed integer array nums of size n, find the maximum difference + * between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that + * 0 <= i < j < n and nums[i] < nums[j]. + * + * Return the maximum difference. If no such i and j exists, return -1. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumDifference = function(nums) { + let max = 0; + + for (let i = 0, min = nums[0]; i < nums.length; i++) { + min = Math.min(min, nums[i]); + max = Math.max(max, nums[i] - min); + } + + return max === 0 ? -1 : max; +}; diff --git a/README.md b/README.md index 8e79c4d5..c2a273fe 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| +2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| ## License From bea154f744355c9f4364b9088c4e84a11aeba1eb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:36:46 -0400 Subject: [PATCH 123/485] Add solution #118 --- 0118-pascals-triangle.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0118-pascals-triangle.js diff --git a/0118-pascals-triangle.js b/0118-pascals-triangle.js new file mode 100644 index 00000000..f2f31523 --- /dev/null +++ b/0118-pascals-triangle.js @@ -0,0 +1,27 @@ +/** + * 118. Pascal's Triangle + * https://leetcode.com/problems/pascals-triangle/ + * Difficulty: Easy + * + * Given an integer numRows, return the first numRows of Pascal's triangle. + * + * In Pascal's triangle, each number is the sum of the two numbers directly + * above it as shown: + */ + +/** + * @param {number} numRows + * @return {number[][]} + */ +var generate = function(numRows) { + const result = [[1]]; + + for (let i = 1; i < numRows; i++) { + result[i] = [1]; + result[i - 1].forEach((value, j, prev) => { + result[i][j + 1] = (prev[j + 1] + value) || 1; + }); + } + + return result; +}; diff --git a/README.md b/README.md index c2a273fe..7e975d07 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From f1af596bb2e57c4f3d1cdbeffa54d2ebad5210f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:37:28 -0400 Subject: [PATCH 124/485] Add solution #119 --- 0119-pascals-triangle-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0119-pascals-triangle-ii.js diff --git a/0119-pascals-triangle-ii.js b/0119-pascals-triangle-ii.js new file mode 100644 index 00000000..94c61352 --- /dev/null +++ b/0119-pascals-triangle-ii.js @@ -0,0 +1,32 @@ +/** + * 119. Pascal's Triangle II + * https://leetcode.com/problems/pascals-triangle-ii/ + * Difficulty: Easy + * + * Given an integer rowIndex, return the rowIndexth (0-indexed) row of + * the Pascal's triangle. + * + * In Pascal's triangle, each number is the sum of the two numbers + * directly above it as shown: + */ + +/** + * @param {number} rowIndex + * @return {number[]} + */ +var getRow = function(rowIndex) { + return generateTriangle(rowIndex + 1)[rowIndex]; +}; + +function generateTriangle(numRows) { + const result = [[1]]; + + for (let i = 1; i < numRows; i++) { + result[i] = [1]; + result[i - 1].forEach((value, j, prev) => { + result[i][j + 1] = (prev[j + 1] + value) || 1; + }); + } + + return result; +}; diff --git a/README.md b/README.md index 7e975d07..7dafb1fc 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| +119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From 035be28a8c2905a27cdd6cc2ff950dd7da9335e2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:38:30 -0400 Subject: [PATCH 125/485] Add solution #566 --- 0566-reshape-the-matrix.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0566-reshape-the-matrix.js diff --git a/0566-reshape-the-matrix.js b/0566-reshape-the-matrix.js new file mode 100644 index 00000000..35660d2f --- /dev/null +++ b/0566-reshape-the-matrix.js @@ -0,0 +1,38 @@ +/** + * 566. Reshape the Matrix + * https://leetcode.com/problems/reshape-the-matrix/ + * Difficulty: Easy + * + * In MATLAB, there is a handy function called reshape which can reshape an m x n + * matrix into a new one with a different size r x c keeping its original data. + * + * You are given an m x n matrix mat and two integers r and c representing the + * number of rows and the number of columns of the wanted reshaped matrix. + * + * The reshaped matrix should be filled with all the elements of the original + * matrix in the same row-traversing order as they were. + * + * If the reshape operation with given parameters is possible and legal, output + * the new reshaped matrix; Otherwise, output the original matrix. + */ + +/** + * @param {number[][]} mat + * @param {number} r + * @param {number} c + * @return {number[][]} + */ +var matrixReshape = function(mat, r, c) { + const flat = mat.flat(); + const result = []; + + if (flat.length !== r * c) { + return mat; + } + + while (flat.length) { + result.push(flat.splice(0, c)); + } + + return result; +}; diff --git a/README.md b/README.md index 7dafb1fc..aa1e8fae 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| +566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 3cbf944276d5c161b9eb20a1654e2e0474ba9426 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:39:15 -0400 Subject: [PATCH 126/485] Add solution #136 --- 0136-single-number.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0136-single-number.js diff --git a/0136-single-number.js b/0136-single-number.js new file mode 100644 index 00000000..eed32355 --- /dev/null +++ b/0136-single-number.js @@ -0,0 +1,19 @@ +/** + * 136. Single Number + * https://leetcode.com/problems/single-number/ + * Difficulty: Easy + * + * Given a non-empty array of integers nums, every element appears twice + * except for one. Find that single one. + * + * You must implement a solution with a linear runtime complexity and + * use only constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function(nums) { + return nums.reduce((result, num) => result ^= num, 0); +}; diff --git a/README.md b/README.md index aa1e8fae..06fb0efc 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +136|[Single Number](./0136-single-number.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 844525680da52dcc34b775fb58a2842b755f1c07 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 00:35:15 -0400 Subject: [PATCH 127/485] Add solution #83 --- 0083-remove-duplicates-from-sorted-list.js | 38 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0083-remove-duplicates-from-sorted-list.js diff --git a/0083-remove-duplicates-from-sorted-list.js b/0083-remove-duplicates-from-sorted-list.js new file mode 100644 index 00000000..1bd5a0ad --- /dev/null +++ b/0083-remove-duplicates-from-sorted-list.js @@ -0,0 +1,38 @@ +/** + * 83. Remove Duplicates from Sorted List + * https://leetcode.com/problems/remove-duplicates-from-sorted-list/ + * Difficulty: Easy + * + * Given the head of a sorted linked list, delete all duplicates such that each + * element appears only once. Return the linked list sorted as well. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + const result = new ListNode(); + const set = new Set(); + let tail = result; + + while (head) { + if (!set.has(head.val)) { + tail.next = new ListNode(head.val); + tail = tail.next; + } + + set.add(head.val); + + head = head.next; + } + + return result.next; +}; diff --git a/README.md b/README.md index 06fb0efc..be04336b 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| +83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From 97dcf402cc67f2f461377703e8431ab7cd77801c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 00:36:10 -0400 Subject: [PATCH 128/485] Add solution #74 --- 0074-search-a-2d-matrix.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0074-search-a-2d-matrix.js diff --git a/0074-search-a-2d-matrix.js b/0074-search-a-2d-matrix.js new file mode 100644 index 00000000..8cb17adb --- /dev/null +++ b/0074-search-a-2d-matrix.js @@ -0,0 +1,22 @@ +/** + * 74. Search a 2D Matrix + * https://leetcode.com/problems/search-a-2d-matrix/ + * Difficulty: Medium + * + * Write an efficient algorithm that searches for a value in an m x n matrix. + * This matrix has the following properties: + * + * Integers in each row are sorted from left to right. + * The first integer of each row is greater than the last integer of the previous row. + */ + +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + return matrix + .filter(row => row[0] <= target && row[row.length - 1] >= target) + .find(row => row.includes(target)) !== undefined; +}; diff --git a/README.md b/README.md index be04336b..36792e15 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| +74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| From f2aff574d79e9b1bd243fcbcfd7a54796cbcb641 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 00:36:56 -0400 Subject: [PATCH 129/485] Add solution #242 --- 0242-valid-anagram.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 0242-valid-anagram.js diff --git a/0242-valid-anagram.js b/0242-valid-anagram.js new file mode 100644 index 00000000..e922f3d0 --- /dev/null +++ b/0242-valid-anagram.js @@ -0,0 +1,17 @@ +/** + * 242. Valid Anagram + * https://leetcode.com/problems/valid-anagram/ + * Difficulty: Easy + * + * Given two strings s and t, return true if t is an anagram of s, and false otherwise. + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function(s, t) { + const sort = str => str.split('').sort().join(''); + return sort(s) === sort(t); +}; diff --git a/README.md b/README.md index 36792e15..668ac2b8 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| +242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| From 2781cb6169f2de7910641cbff46d1beb340f201d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 01:11:58 -0400 Subject: [PATCH 130/485] Add solution #141 --- 0141-linked-list-cycle.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0141-linked-list-cycle.js diff --git a/0141-linked-list-cycle.js b/0141-linked-list-cycle.js new file mode 100644 index 00000000..8d522ee2 --- /dev/null +++ b/0141-linked-list-cycle.js @@ -0,0 +1,38 @@ +/** + * 141. Linked List Cycle + * https://leetcode.com/problems/linked-list-cycle/ + * Difficulty: Easy + * + * Given head, the head of a linked list, determine if the linked list has a cycle in it. + * + * There is a cycle in a linked list if there is some node in the list that can be reached + * again by continuously following the next pointer. Internally, pos is used to denote the + * index of the node that tail's next pointer is connected to. Note that pos is not passed + * as a parameter. + * + * Return true if there is a cycle in the linked list. Otherwise, return false. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + while (head) { + if (head.visited) { + return true; + } + head.visited = 1; + head = head.next; + } + + return false; +}; diff --git a/README.md b/README.md index 668ac2b8..675acbe5 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 136|[Single Number](./0136-single-number.js)|Easy| +141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 93af056b3cb84801596fdc1195192a8e35d7f106 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 01:12:43 -0400 Subject: [PATCH 131/485] Add solution #21 --- 0021-merge-two-sorted-lists.js | 35 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0021-merge-two-sorted-lists.js diff --git a/0021-merge-two-sorted-lists.js b/0021-merge-two-sorted-lists.js new file mode 100644 index 00000000..f5c16393 --- /dev/null +++ b/0021-merge-two-sorted-lists.js @@ -0,0 +1,35 @@ +/** + * 21. Merge Two Sorted Lists + * https://leetcode.com/problems/merge-two-sorted-lists/ + * Difficulty: Easy + * + * Merge two sorted linked lists and return it as a sorted list. + * The list should be made by splicing together the nodes of the + * first two lists. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + if (!l1 || !l2) { + return l1 || l2; + } + + if (l1.val > l2.val) { + [l2, l1] = [l1, l2]; + } + + l1.next = mergeTwoLists(l1.next, l2); + + return l1; +}; diff --git a/README.md b/README.md index 675acbe5..b11412d5 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From da51e8b93085de8bd578343bf338ed43fd99d109 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Sep 2021 23:45:57 -0400 Subject: [PATCH 132/485] Add solution #203 --- 0203-remove-linked-list-elements.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0203-remove-linked-list-elements.js diff --git a/0203-remove-linked-list-elements.js b/0203-remove-linked-list-elements.js new file mode 100644 index 00000000..e305011f --- /dev/null +++ b/0203-remove-linked-list-elements.js @@ -0,0 +1,27 @@ +/** + * 203. Remove Linked List Elements + * https://leetcode.com/problems/remove-linked-list-elements/ + * Difficulty: Easy + * + * Given the head of a linked list and an integer val, remove all the + * nodes of the linked list that has Node.val == val, and return the + * new head. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} val + * @return {ListNode} + */ +var removeElements = function(head, val) { + if (!head) return null; + head.next = removeElements(head.next, val); + return head.val === val ? head.next : head; +}; diff --git a/README.md b/README.md index b11412d5..3b025879 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From df880399a51ca734607e3c2dcc567d4ef9d96548 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Sep 2021 20:32:57 -0400 Subject: [PATCH 133/485] Add solution #206 --- 0206-reverse-linked-list.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0206-reverse-linked-list.js diff --git a/0206-reverse-linked-list.js b/0206-reverse-linked-list.js new file mode 100644 index 00000000..c1b3e19a --- /dev/null +++ b/0206-reverse-linked-list.js @@ -0,0 +1,32 @@ +/** + * 206. Reverse Linked List + * https://leetcode.com/problems/reverse-linked-list/ + * Difficulty: Easy + * + * Given the head of a singly linked list, reverse the list, and return the reversed list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function(head) { + let prev = null; + let tail = head; + + while (tail) { + const next = tail.next; + tail.next = prev; + prev = tail; + tail = next; + } + + return prev; +}; diff --git a/README.md b/README.md index 3b025879..8e8a0e31 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| +206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From add48a1d89499da93f191a48f2e406689ba936ab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Sep 2021 20:34:19 -0400 Subject: [PATCH 134/485] Add solution #237 --- 0237-delete-node-in-a-linked-list.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0237-delete-node-in-a-linked-list.js diff --git a/0237-delete-node-in-a-linked-list.js b/0237-delete-node-in-a-linked-list.js new file mode 100644 index 00000000..d3d89b9b --- /dev/null +++ b/0237-delete-node-in-a-linked-list.js @@ -0,0 +1,27 @@ +/** + * 237. Delete Node in a Linked List + * https://leetcode.com/problems/delete-node-in-a-linked-list/ + * Difficulty: Easy + * + * Write a function to delete a node in a singly-linked list. You will not be + * given access to the head of the list, instead you will be given access to + * the node to be deleted directly. + * + * It is guaranteed that the node to be deleted is not a tail node in the list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} node + * @return {void} Do not return anything, modify node in-place instead. + */ +var deleteNode = function(node) { + node.val = node.next.val; + node.next = node.next.next; +}; diff --git a/README.md b/README.md index 8e8a0e31..468b19ea 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| +237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 853d7b2410cb0c63fcdfb83a535119453e120d7d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Sep 2021 20:35:20 -0400 Subject: [PATCH 135/485] Add solution #20 --- 0020-valid-parentheses.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0020-valid-parentheses.js diff --git a/0020-valid-parentheses.js b/0020-valid-parentheses.js new file mode 100644 index 00000000..bc7a1752 --- /dev/null +++ b/0020-valid-parentheses.js @@ -0,0 +1,37 @@ +/** + * 20. Valid Parentheses + * https://leetcode.com/problems/valid-parentheses/ + * Difficulty: Easy + * + * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', + * determine if the input string is valid. + * + * An input string is valid if: + * - Open brackets must be closed by the same type of brackets. + * - Open brackets must be closed in the correct order. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function(s) { + const map = { + '(': ')', + '[': ']', + '{': '}' + } + const stack = []; + + for (let i = 0; i < s.length; i++) { + if (map[s[i]]) { + stack.push(map[s[i]]); + } else { + if (stack.pop() !== s[i]) { + return false; + } + } + } + + return stack.length === 0; +}; diff --git a/README.md b/README.md index 468b19ea..427da6bd 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From 175cb74f0f7e6a89d4d894e960edb7f620af2846 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:40:39 -0400 Subject: [PATCH 136/485] Add solution #144 --- 0144-binary-tree-preorder-traversal.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0144-binary-tree-preorder-traversal.js diff --git a/0144-binary-tree-preorder-traversal.js b/0144-binary-tree-preorder-traversal.js new file mode 100644 index 00000000..882ba125 --- /dev/null +++ b/0144-binary-tree-preorder-traversal.js @@ -0,0 +1,25 @@ +/** + * 144. Binary Tree Preorder Traversal + * https://leetcode.com/problems/binary-tree-preorder-traversal/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the preorder traversal of its nodes' values. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var preorderTraversal = function(root) { + return root + ? [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)] + : []; +}; diff --git a/README.md b/README.md index 427da6bd..095c99a1 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| +144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| From d9dad63e610818d8b1486cc5795a56264cdcd67a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:41:32 -0400 Subject: [PATCH 137/485] Add solution #94 --- 0094-binary-tree-inorder-traversal.js | 37 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0094-binary-tree-inorder-traversal.js diff --git a/0094-binary-tree-inorder-traversal.js b/0094-binary-tree-inorder-traversal.js new file mode 100644 index 00000000..aa0510c1 --- /dev/null +++ b/0094-binary-tree-inorder-traversal.js @@ -0,0 +1,37 @@ +/** + * 94. Binary Tree Inorder Traversal + * https://leetcode.com/problems/binary-tree-inorder-traversal/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the inorder traversal of its nodes' values. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function(root) { + const result = []; + const stack = []; + + while (root || stack.length) { + if (root) { + stack.push(root); + root = root.left; + } else { + const { val, right } = stack.pop(); + result.push(val); + root = right; + } + } + + return result; +}; diff --git a/README.md b/README.md index 095c99a1..6c4439bc 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From 6a7410fffdda37b5803e2638e773ccf49f177c33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:46:39 -0400 Subject: [PATCH 138/485] Add solution #1356 --- 1356-sort-integers-by-the-number-of-1-bits.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1356-sort-integers-by-the-number-of-1-bits.js diff --git a/1356-sort-integers-by-the-number-of-1-bits.js b/1356-sort-integers-by-the-number-of-1-bits.js new file mode 100644 index 00000000..6565d125 --- /dev/null +++ b/1356-sort-integers-by-the-number-of-1-bits.js @@ -0,0 +1,22 @@ +/** + * 1356. Sort Integers by The Number of 1 Bits + * https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ + * Difficulty: Easy + * + * Given an integer array arr. You have to sort the integers in the array in + * ascending order by the number of 1's in their binary representation and + * in case of two or more integers have the same number of 1's you have to + * sort them in ascending order. + * + * Return the sorted array. + */ + +/** + * @param {number[]} arr + * @return {number[]} + */ +var sortByBits = function(arr) { + const getCount = n => n.toString(2).replace(/0/g, '').length; + + return arr.sort((a, b) => getCount(a) - getCount(b) || a - b); +}; diff --git a/README.md b/README.md index 6c4439bc..4761388f 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From 4930965594180d059ae8c055f700b603d1e33746 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:50:48 -0400 Subject: [PATCH 139/485] Add solution #1351 --- ...unt-negative-numbers-in-a-sorted-matrix.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1351-count-negative-numbers-in-a-sorted-matrix.js diff --git a/1351-count-negative-numbers-in-a-sorted-matrix.js b/1351-count-negative-numbers-in-a-sorted-matrix.js new file mode 100644 index 00000000..d232bb99 --- /dev/null +++ b/1351-count-negative-numbers-in-a-sorted-matrix.js @@ -0,0 +1,21 @@ +/** + * 1351. Count Negative Numbers in a Sorted Matrix + * https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ + * Difficulty: Easy + * + * Given a m x n matrix grid which is sorted in non-increasing order both + * row-wise and column-wise, return the number of negative numbers in grid. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var countNegatives = function(grid) { + return grid.reduce((count, row) => { + while (row.pop() < 0) { + count++; + } + return count; + }, 0); +}; diff --git a/README.md b/README.md index 4761388f..46dab742 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| From aaa8743b148f01b7c385641806a30b8f8d4210c2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:53:08 -0400 Subject: [PATCH 140/485] Add solution #1295 --- 1295-find-numbers-with-even-number-of-digits.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 1295-find-numbers-with-even-number-of-digits.js diff --git a/1295-find-numbers-with-even-number-of-digits.js b/1295-find-numbers-with-even-number-of-digits.js new file mode 100644 index 00000000..2683787d --- /dev/null +++ b/1295-find-numbers-with-even-number-of-digits.js @@ -0,0 +1,16 @@ +/** + * 1295. Find Numbers with Even Number of Digits + * https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ + * Difficulty: Easy + * + * Given an array nums of integers, return how many of them contain an even + * number of digits. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findNumbers = function(nums) { + return nums.filter(num => String(num).length % 2 === 0).length; +}; diff --git a/README.md b/README.md index 46dab742..ec24f6a0 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ 1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| 1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| 1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| +1295|[Find Numbers with Even Number of Digits](./1295-find-numbers-with-even-number-of-digits.js)|Easy| 1297|[Maximum Number of Occurrences of a Substring](./1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| 1304|[Find N Unique Integers Sum up to Zero](./1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| 1309|[Decrypt String from Alphabet to Integer Mapping](./1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| From 3e935d89d9d48e2a8f918da10454210121f60ec3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:55:10 -0400 Subject: [PATCH 141/485] Add solution #1296 --- ...-array-in-sets-of-k-consecutive-numbers.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 1296-divide-array-in-sets-of-k-consecutive-numbers.js diff --git a/1296-divide-array-in-sets-of-k-consecutive-numbers.js b/1296-divide-array-in-sets-of-k-consecutive-numbers.js new file mode 100644 index 00000000..45719c06 --- /dev/null +++ b/1296-divide-array-in-sets-of-k-consecutive-numbers.js @@ -0,0 +1,40 @@ +/** + * 1296. Divide Array in Sets of K Consecutive Numbers + * https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ + * Difficulty: Medium + * + * Given an array of integers nums and a positive integer k, find whether it is + * possible to divide this array into sets of k consecutive numbers. + * + * Return true if it is possible. Otherwise, return false. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var isPossibleDivide = function(nums, k) { + if (nums.length % k) { + return false; + } + + const map = {}; + const set = new Set(nums); + nums.forEach(x => map[x] ? map[x]++ : map[x] = 1); + + let count = nums.length / k; + while (count--) { + let min = Math.min(...set); + for (let i = min; i < min + k; i++) { + if (!map[i]) { + return false; + } + if (!--map[i]) { + set.delete(i); + } + } + } + + return true; +}; diff --git a/README.md b/README.md index ec24f6a0..7da5cb51 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ 1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| 1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| 1295|[Find Numbers with Even Number of Digits](./1295-find-numbers-with-even-number-of-digits.js)|Easy| +1296|[Divide Array in Sets of K Consecutive Numbers](./1296-divide-array-in-sets-of-k-consecutive-numbers.js)|Medium| 1297|[Maximum Number of Occurrences of a Substring](./1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| 1304|[Find N Unique Integers Sum up to Zero](./1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| 1309|[Decrypt String from Alphabet to Integer Mapping](./1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| From 8ed36d4513040c2a67e4f89f3c3848a054f9e711 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:56:32 -0400 Subject: [PATCH 142/485] Add solution #846 --- 0846-hand-of-straights.js | 43 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0846-hand-of-straights.js diff --git a/0846-hand-of-straights.js b/0846-hand-of-straights.js new file mode 100644 index 00000000..4a2bf2b1 --- /dev/null +++ b/0846-hand-of-straights.js @@ -0,0 +1,43 @@ +/** + * 846. Hand of Straights + * https://leetcode.com/problems/hand-of-straights/ + * Difficulty: Medium + * + * Alice has some number of cards and she wants to rearrange + * the cards into groups so that each group is of size groupSize, + * and consists of groupSize consecutive cards. + * + * Given an integer array hand where hand[i] is the value written + * on the ith card and an integer groupSize, return true if she + * can rearrange the cards, or false otherwise. + */ + +/** + * @param {number[]} hand + * @param {number} groupSize + * @return {boolean} + */ +var isNStraightHand = function(hand, groupSize) { + if (hand.length % groupSize) { + return false; + } + + const map = {}; + const set = new Set(hand); + hand.forEach(x => map[x] ? map[x]++ : map[x] = 1); + + let count = hand.length / groupSize; + while (count--) { + let min = Math.min(...set); + for (let i = min; i < min + groupSize; i++) { + if (!map[i]) { + return false; + } + if (!--map[i]) { + set.delete(i); + } + } + } + + return true; +}; diff --git a/README.md b/README.md index 7da5cb51..833fe508 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| +846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| From d135e7644948bb0108071ac0b474bb5079ba64b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 2 Oct 2021 19:01:59 -0400 Subject: [PATCH 143/485] Add solution #225 --- 0225-implement-stack-using-queues.js | 59 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0225-implement-stack-using-queues.js diff --git a/0225-implement-stack-using-queues.js b/0225-implement-stack-using-queues.js new file mode 100644 index 00000000..71bb7bd8 --- /dev/null +++ b/0225-implement-stack-using-queues.js @@ -0,0 +1,59 @@ +/** + * 225. Implement Stack using Queues + * https://leetcode.com/problems/implement-stack-using-queues/ + * Difficulty: Easy + * + * Implement a last-in-first-out (LIFO) stack using only two queues. + * The implemented stack should support all the functions of a normal + * stack (push, top, pop, and empty). + * + * Implement the MyStack class: + * + * - void push(int x) Pushes element x to the top of the stack. + * - int pop() Removes the element on the top of the stack and returns it. + * - int top() Returns the element on the top of the stack. + * - boolean empty() Returns true if the stack is empty, false otherwise. + */ + + +var MyStack = function() { + this.data = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyStack.prototype.push = function(x) { + this.data.push(x); +}; + +/** + * @return {number} + */ +MyStack.prototype.pop = function() { + return this.data.pop(); +}; + +/** + * @return {number} + */ +MyStack.prototype.top = function() { + return this.data[this.data.length - 1]; +}; + +/** + * @return {boolean} + */ +MyStack.prototype.empty = function() { + return !this.data.length; +}; + +/** + * Your MyStack object will be instantiated and called as such: + * var obj = new MyStack() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.empty() + */ diff --git a/README.md b/README.md index 833fe508..6cf3ac92 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| +225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| From 553a14439a3d19fa8e479587a4d70e4824d2a91b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 2 Oct 2021 19:03:04 -0400 Subject: [PATCH 144/485] Add solution #232 --- 0232-implement-queue-using-stacks.js | 58 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 0232-implement-queue-using-stacks.js diff --git a/0232-implement-queue-using-stacks.js b/0232-implement-queue-using-stacks.js new file mode 100644 index 00000000..7a152a5a --- /dev/null +++ b/0232-implement-queue-using-stacks.js @@ -0,0 +1,58 @@ +/** + * 232. Implement Queue using Stacks + * https://leetcode.com/problems/implement-queue-using-stacks/ + * Difficulty: Easy + * + * Implement a first in first out (FIFO) queue using only two stacks. + * The implemented queue should support all the functions of a normal + * queue (push, peek, pop, and empty). + * + * Implement the MyQueue class: + * - void push(int x) Pushes element x to the back of the queue. + * - int pop() Removes the element from the front of the queue and returns it. + * - int peek() Returns the element at the front of the queue. + * - boolean empty() Returns true if the queue is empty, false otherwise. + */ + + +var MyQueue = function() { + this.data = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function(x) { + this.data.push(x); +}; + +/** + * @return {number} + */ +MyQueue.prototype.pop = function() { + return this.data.shift(); +}; + +/** + * @return {number} + */ +MyQueue.prototype.peek = function() { + return this.data[0]; +}; + +/** + * @return {boolean} + */ +MyQueue.prototype.empty = function() { + return !this.data.length; +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * var obj = new MyQueue() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.peek() + * var param_4 = obj.empty() + */ diff --git a/README.md b/README.md index 6cf3ac92..71fcdbf8 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| From 2b81e0939b40702f3e2573beee8cb0bf7f01020f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 2 Oct 2021 21:23:05 -0400 Subject: [PATCH 145/485] Add solution #145 --- 0145-binary-tree-postorder-traversal.js | 32 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0145-binary-tree-postorder-traversal.js diff --git a/0145-binary-tree-postorder-traversal.js b/0145-binary-tree-postorder-traversal.js new file mode 100644 index 00000000..06c23f9c --- /dev/null +++ b/0145-binary-tree-postorder-traversal.js @@ -0,0 +1,32 @@ +/** + * 145. Binary Tree Postorder Traversal + * https://leetcode.com/problems/binary-tree-postorder-traversal/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the postorder traversal + * of its nodes' values. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var postorderTraversal = function(root) { + if (!root) { + return []; + } + + return [ + ...postorderTraversal(root.left), + ...postorderTraversal(root.right), + root.val + ]; +}; diff --git a/README.md b/README.md index 71fcdbf8..0950a05b 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| +145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| From cdfc6e64bd973769660b5e2602edd1fc56f0eac8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 3 Oct 2021 14:27:29 -0400 Subject: [PATCH 146/485] Add solution #102 --- 0102-binary-tree-level-order-traversal.js | 40 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0102-binary-tree-level-order-traversal.js diff --git a/0102-binary-tree-level-order-traversal.js b/0102-binary-tree-level-order-traversal.js new file mode 100644 index 00000000..eb34e09b --- /dev/null +++ b/0102-binary-tree-level-order-traversal.js @@ -0,0 +1,40 @@ +/** + * 102. Binary Tree Level Order Traversal + * https://leetcode.com/problems/binary-tree-level-order-traversal/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the level order traversal of its + * nodes' values. (i.e., from left to right, level by level). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function(root) { + const result = []; + + traverse(result, root); + + return result; +}; + +function traverse(result, node, level = 0) { + if (!node) { + return []; + } + + result[level] = result[level] || []; + result[level].push(node.val); + + traverse(result, node.left, level + 1); + traverse(result, node.right, level + 1); +} diff --git a/README.md b/README.md index 0950a05b..c6e67cc1 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From b53f63caa6e11da9100365fe081a1e1ff654e02d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 3 Oct 2021 14:28:31 -0400 Subject: [PATCH 147/485] Add solution #111 --- 0111-minimum-depth-of-binary-tree.js | 32 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0111-minimum-depth-of-binary-tree.js diff --git a/0111-minimum-depth-of-binary-tree.js b/0111-minimum-depth-of-binary-tree.js new file mode 100644 index 00000000..c0abee2b --- /dev/null +++ b/0111-minimum-depth-of-binary-tree.js @@ -0,0 +1,32 @@ +/** + * 111. Minimum Depth of Binary Tree + * https://leetcode.com/problems/minimum-depth-of-binary-tree/ + * Difficulty: Easy + * + * Given a binary tree, find its minimum depth. + * + * The minimum depth is the number of nodes along the shortest path from the + * root node down to the nearest leaf node. + * + * Note: A leaf is a node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function(root) { + if (!root) { + return 0; + } + const [left, right] = [root.left, root.right].map(minDepth); + return 1 + (Math.min(left, right) || Math.max(left, right)); +}; diff --git a/README.md b/README.md index c6e67cc1..6ac28654 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| +111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From a3f9471ba71d10840bc9f1eaca3b2562043d20d7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 3 Oct 2021 14:29:19 -0400 Subject: [PATCH 148/485] Add solution #104 --- 0104-maximum-depth-of-binary-tree.js | 30 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0104-maximum-depth-of-binary-tree.js diff --git a/0104-maximum-depth-of-binary-tree.js b/0104-maximum-depth-of-binary-tree.js new file mode 100644 index 00000000..8b7858e0 --- /dev/null +++ b/0104-maximum-depth-of-binary-tree.js @@ -0,0 +1,30 @@ +/** + * 104. Maximum Depth of Binary Tree + * https://leetcode.com/problems/maximum-depth-of-binary-tree/ + * Difficulty: Easy + * + * 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. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function(root) { + if (!root) { + return 0; + } + const [left, right] = [root.left, root.right].map(maxDepth); + return 1 + Math.max(left, right); +}; diff --git a/README.md b/README.md index 6ac28654..1b7c1d30 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| +104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From 4473e367af4ff4f5e9facf8f3c7a88f09a298907 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 4 Oct 2021 20:55:10 -0400 Subject: [PATCH 149/485] Add solution #112 --- 0112-path-sum.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0112-path-sum.js diff --git a/0112-path-sum.js b/0112-path-sum.js new file mode 100644 index 00000000..c4f37a2f --- /dev/null +++ b/0112-path-sum.js @@ -0,0 +1,44 @@ +/** + * 112. Path Sum + * https://leetcode.com/problems/path-sum/ + * Difficulty: Easy + * + * Given the root of a binary tree and an integer targetSum, return true if the + * tree has a root-to-leaf path such that adding up all the values along the + * path equals targetSum. + * + * A leaf is a node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} targetSum + * @return {boolean} + */ +var hasPathSum = function(root, targetSum) { + if (!root) { + return false; + } + const result = []; + + traverse(result, root); + + return result.includes(targetSum); +}; + +function traverse(result, node, sum = 0) { + if (!node.left && !node.right) { + result.push(sum + node.val); + } + + if (node.left) traverse(result, node.left, sum + node.val); + if (node.right) traverse(result, node.right, sum + node.val); +} diff --git a/README.md b/README.md index 1b7c1d30..86d9bd64 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| +112|[Path Sum](./0112-path-sum.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From ca0e5a068e54079466e72f359a2cbf7ea72e2f85 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 4 Oct 2021 20:56:21 -0400 Subject: [PATCH 150/485] Add solution #653 --- 0653-two-sum-iv---input-is-a-bst.js | 36 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0653-two-sum-iv---input-is-a-bst.js diff --git a/0653-two-sum-iv---input-is-a-bst.js b/0653-two-sum-iv---input-is-a-bst.js new file mode 100644 index 00000000..6f3b4256 --- /dev/null +++ b/0653-two-sum-iv---input-is-a-bst.js @@ -0,0 +1,36 @@ +/** + * 653. Two Sum IV - Input is a BST + * https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ + * Difficulty: Easy + * + * Given the root of a Binary Search Tree and a target number k, return + * true if there exist two elements in the BST such that their sum is + * equal to the given target. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {boolean} + */ +var findTarget = function(root, k) { + const set = new Set(); + return dfs(set, root, k); +}; + +function dfs(set, node, k) { + if (!node) return false; + if (set.has(k - node.val)) return true; + + set.add(node.val); + + return dfs(set, node.left, k) || dfs(set, node.right, k); +} diff --git a/README.md b/README.md index 86d9bd64..4a210bd2 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| +653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 9ab2580add8c77468c2c732e6b94d492a4e1d6a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 4 Oct 2021 20:59:39 -0400 Subject: [PATCH 151/485] Add solution #101 --- 0101-symmetric-tree.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0101-symmetric-tree.js diff --git a/0101-symmetric-tree.js b/0101-symmetric-tree.js new file mode 100644 index 00000000..548cfb75 --- /dev/null +++ b/0101-symmetric-tree.js @@ -0,0 +1,34 @@ +/** + * 101. Symmetric Tree + * https://leetcode.com/problems/symmetric-tree/ + * Difficulty: Easy + * + * Given the root of a binary tree, check whether it is a mirror + * of itself (i.e., symmetric around its center). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isSymmetric = function(root) { + return isBalanced(root.left, root.right); +}; + +function isBalanced(a, b) { + if (!a && !b) { + return true; + } + if (!a || !b) { + return false; + } + return a.val === b.val && isBalanced(a.left, b.right) && isBalanced(a.right, b.left); +} diff --git a/README.md b/README.md index 4a210bd2..7a7d7410 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| From 65a96ba0be4c0c7c241f891661dcf255fa38323c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 5 Oct 2021 21:09:34 -0400 Subject: [PATCH 152/485] Add solution #701 --- 0701-insert-into-a-binary-search-tree.js | 41 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0701-insert-into-a-binary-search-tree.js diff --git a/0701-insert-into-a-binary-search-tree.js b/0701-insert-into-a-binary-search-tree.js new file mode 100644 index 00000000..ceb4a474 --- /dev/null +++ b/0701-insert-into-a-binary-search-tree.js @@ -0,0 +1,41 @@ +/** + * 701. Insert into a Binary Search Tree + * https://leetcode.com/problems/insert-into-a-binary-search-tree/ + * Difficulty: Medium + * + * You are given the root node of a binary search tree (BST) and a value + * to insert into the tree. Return the root node of the BST after the + * insertion. It is guaranteed that the new value does not exist in the + * original BST. + * + * Notice that there may exist multiple valid ways for the insertion, + * as long as the tree remains a BST after insertion. You can return + * any of them. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @return {TreeNode} + */ +var insertIntoBST = function(root, val) { + if (!root) { + return new TreeNode(val); + } + + if (val > root.val) { + root.right = insertIntoBST(root.right, val); + } else { + root.left = insertIntoBST(root.left, val); + } + + return root; +}; diff --git a/README.md b/README.md index 7a7d7410..6c30c54c 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From a9f7bf8a703b7d1c42d1b9b0488db3cb1631f39f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 5 Oct 2021 21:10:13 -0400 Subject: [PATCH 153/485] Add solution #700 --- 0700-search-in-a-binary-search-tree.js | 34 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0700-search-in-a-binary-search-tree.js diff --git a/0700-search-in-a-binary-search-tree.js b/0700-search-in-a-binary-search-tree.js new file mode 100644 index 00000000..3de1c309 --- /dev/null +++ b/0700-search-in-a-binary-search-tree.js @@ -0,0 +1,34 @@ +/** + * 700. Search in a Binary Search Tree + * https://leetcode.com/problems/search-in-a-binary-search-tree/ + * Difficulty: Easy + * + * You are given the root of a binary search tree (BST) and an integer val. + * + * Find the node in the BST that the node's value equals val and return the + * subtree rooted with that node. If such a node does not exist, return null. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @return {TreeNode} + */ +var searchBST = function(root, val) { + while (root) { + if (root.val === val) { + return root; + } + root = root.val > val ? root.left : root.right; + } + + return null; +}; diff --git a/README.md b/README.md index 6c30c54c..66486efa 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 2fac8adbf13529633549d993c335d1cc9cef3f0d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 6 Oct 2021 22:50:13 -0400 Subject: [PATCH 154/485] Add solution #653 --- 0653-two-sum-iv-input-is-a-bst.js | 36 +++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 0653-two-sum-iv-input-is-a-bst.js diff --git a/0653-two-sum-iv-input-is-a-bst.js b/0653-two-sum-iv-input-is-a-bst.js new file mode 100644 index 00000000..75b351e9 --- /dev/null +++ b/0653-two-sum-iv-input-is-a-bst.js @@ -0,0 +1,36 @@ +/** + * 653. Two Sum IV - Input is a BST + * https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ + * Difficulty: Easy + * + * Given the root of a Binary Search Tree and a target number k, return true + * if there exist two elements in the BST such that their sum is equal to the + * given target. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {boolean} + */ +var findTarget = function(root, k) { + const set = new Set(); + return dfs(set, root, k); +}; + +function dfs(set, node, k) { + if (!node) return false; + if (set.has(k - node.val)) return true; + + set.add(node.val); + + return dfs(set, node.left, k) || dfs(set, node.right, k); +} diff --git a/README.md b/README.md index 66486efa..6fa92232 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| -653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| +653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| From f1988a2776e73201da93f11ed4ff7fe8e8299765 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 6 Oct 2021 23:25:00 -0400 Subject: [PATCH 155/485] Add solution #1380 --- 1380-lucky-numbers-in-a-matrix.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1380-lucky-numbers-in-a-matrix.js diff --git a/1380-lucky-numbers-in-a-matrix.js b/1380-lucky-numbers-in-a-matrix.js new file mode 100644 index 00000000..6c0bb84e --- /dev/null +++ b/1380-lucky-numbers-in-a-matrix.js @@ -0,0 +1,22 @@ +/** + * 1380. Lucky Numbers in a Matrix + * https://leetcode.com/problems/lucky-numbers-in-a-matrix/ + * Difficulty: Easy + * + * Given an m x n matrix of distinct numbers, return all lucky numbers + * in the matrix in any order. + * + * A lucky number is an element of the matrix such that it is the minimum + * element in its row and maximum in its column. + */ + +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var luckyNumbers = function(matrix) { + const min = matrix.map(row => Math.min(...row)); + const max = matrix[0].map((_, i) => Math.max(...matrix.map(row => row[i]))); + + return min.filter(value => max.includes(value)); +}; diff --git a/README.md b/README.md index 6fa92232..84253036 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 4cf346fc89eafa61e215d83a3eb759ecc54f8b3c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 6 Oct 2021 23:25:43 -0400 Subject: [PATCH 156/485] Add solution #1365 --- ...ers-are-smaller-than-the-current-number.js | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 1365-how-many-numbers-are-smaller-than-the-current-number.js diff --git a/1365-how-many-numbers-are-smaller-than-the-current-number.js b/1365-how-many-numbers-are-smaller-than-the-current-number.js new file mode 100644 index 00000000..6446f40f --- /dev/null +++ b/1365-how-many-numbers-are-smaller-than-the-current-number.js @@ -0,0 +1,20 @@ +/** + * 1365. How Many Numbers Are Smaller Than the Current Number + * https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ + * Difficulty: Easy + * + * Given the array nums, for each nums[i] find out how many numbers in the array are smaller + * than it. That is, for each nums[i] you have to count the number of valid j's such that + * j != i and nums[j] < nums[i]. + * + * Return the answer in an array. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var smallerNumbersThanCurrent = function(nums) { + const sorted = nums.slice().sort((a, b) => a - b); + return nums.map(num => sorted.indexOf(num)); +}; diff --git a/README.md b/README.md index 84253036..dc0eb017 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From 71bdcab61d5d2811ca7bce84d5f25e44983d8808 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 7 Oct 2021 00:58:15 -0400 Subject: [PATCH 157/485] Add solution #235 --- ...common-ancestor-of-a-binary-search-tree.js | 36 +++++++++++++++++++ 0653-two-sum-iv---input-is-a-bst.js | 36 ------------------- README.md | 1 + 3 files changed, 37 insertions(+), 36 deletions(-) create mode 100644 0235-lowest-common-ancestor-of-a-binary-search-tree.js delete mode 100644 0653-two-sum-iv---input-is-a-bst.js diff --git a/0235-lowest-common-ancestor-of-a-binary-search-tree.js b/0235-lowest-common-ancestor-of-a-binary-search-tree.js new file mode 100644 index 00000000..41b9360a --- /dev/null +++ b/0235-lowest-common-ancestor-of-a-binary-search-tree.js @@ -0,0 +1,36 @@ +/** + * 235. Lowest Common Ancestor of a Binary Search Tree + * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + * Difficulty: Easy + * + * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two + * given nodes in the BST. + * + * According to the definition of LCA on Wikipedia: “The lowest common ancestor is + * defined between two nodes p and q as the lowest node in T that has both p and q + * as descendants (where we allow a node to be a descendant of itself).” + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ + +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function(root, p, q) { + if (p.val > root.val && q.val > root.val) { + return lowestCommonAncestor(root.right, p, q); + } + if (p.val < root.val && q.val < root.val) { + return lowestCommonAncestor(root.left, p , q); + } + return root; +}; diff --git a/0653-two-sum-iv---input-is-a-bst.js b/0653-two-sum-iv---input-is-a-bst.js deleted file mode 100644 index 6f3b4256..00000000 --- a/0653-two-sum-iv---input-is-a-bst.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 653. Two Sum IV - Input is a BST - * https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ - * Difficulty: Easy - * - * Given the root of a Binary Search Tree and a target number k, return - * true if there exist two elements in the BST such that their sum is - * equal to the given target. - */ - -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {number} k - * @return {boolean} - */ -var findTarget = function(root, k) { - const set = new Set(); - return dfs(set, root, k); -}; - -function dfs(set, node, k) { - if (!node) return false; - if (set.has(k - node.val)) return true; - - set.add(node.val); - - return dfs(set, node.left, k) || dfs(set, node.right, k); -} diff --git a/README.md b/README.md index dc0eb017..6e7c6d89 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| +235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| From 7cc8b7b1ea30d97efc8741ff8fa044c64a801662 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 7 Oct 2021 21:01:29 -0500 Subject: [PATCH 158/485] Add solution #1374 --- ...ng-with-characters-that-have-odd-counts.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1374-generate-a-string-with-characters-that-have-odd-counts.js diff --git a/1374-generate-a-string-with-characters-that-have-odd-counts.js b/1374-generate-a-string-with-characters-that-have-odd-counts.js new file mode 100644 index 00000000..cd7dd6d9 --- /dev/null +++ b/1374-generate-a-string-with-characters-that-have-odd-counts.js @@ -0,0 +1,19 @@ +/** + * 1374. Generate a String With Characters That Have Odd Counts + * https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/ + * Difficulty: Easy + * + * Given an integer n, return a string with n characters such that each character in such + * string occurs an odd number of times. + * + * The returned string must contain only lowercase English letters. If there are multiples + * valid strings, return any of them. + */ + +/** + * @param {number} n + * @return {string} + */ +var generateTheString = function(n) { + return 'a'.repeat(n % 2 ? n : n - 1) + (n % 2 ? '' : 'z'); +}; diff --git a/README.md b/README.md index 6e7c6d89..69c08c47 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| +1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From 45749b8d3979b179469fd289bec97528db695dd6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 15 Oct 2021 15:19:36 -0400 Subject: [PATCH 159/485] Add solution #1389 --- ...-create-target-array-in-the-given-order.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1389-create-target-array-in-the-given-order.js diff --git a/1389-create-target-array-in-the-given-order.js b/1389-create-target-array-in-the-given-order.js new file mode 100644 index 00000000..1c31f8dc --- /dev/null +++ b/1389-create-target-array-in-the-given-order.js @@ -0,0 +1,27 @@ +/** + * 1389. Create Target Array in the Given Order + * https://leetcode.com/problems/create-target-array-in-the-given-order/ + * Difficulty: Easy + * + * Given two arrays of integers nums and index. Your task is to create target array + * under the following rules: + * + * - Initially target array is empty. + * - From left to right read nums[i] and index[i], insert at index index[i] the value + * nums[i] in target array. + * - Repeat the previous step until there are no elements to read in nums and index. + * - Return the target array. + * + * It is guaranteed that the insertion operations will be valid. + */ + +/** + * @param {number[]} nums + * @param {number[]} index + * @return {number[]} + */ +var createTargetArray = function(nums, index) { + const result = []; + index.forEach((i, j) => result.splice(i, 0, nums[j])); + return result; +}; diff --git a/README.md b/README.md index 69c08c47..af826080 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| +1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 7ebb2adf36d9121fcd2d4b6983686701334712fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 15 Oct 2021 15:43:49 -0400 Subject: [PATCH 160/485] Add solution #1408 --- 1408-string-matching-in-an-array.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1408-string-matching-in-an-array.js diff --git a/1408-string-matching-in-an-array.js b/1408-string-matching-in-an-array.js new file mode 100644 index 00000000..81eb09a1 --- /dev/null +++ b/1408-string-matching-in-an-array.js @@ -0,0 +1,19 @@ +/** + * 1408. String Matching in an Array + * https://leetcode.com/problems/string-matching-in-an-array/ + * Difficulty: Easy + * + * Given an array of string words. Return all strings in words which is + * substring of another word in any order. + * + * String words[i] is substring of words[j], if can be obtained removing + * some characters to left and/or right side of words[j]. + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var stringMatching = function(words) { + return words.filter(s => words.some(word => word !== s && word.includes(s))); +}; diff --git a/README.md b/README.md index af826080..7425f143 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| +1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 266456b4947e592a6ee31c603dcf10f42ab7c01b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 28 Oct 2021 23:08:23 -0500 Subject: [PATCH 161/485] Add solution #1436 --- 1436-destination-city.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1436-destination-city.js diff --git a/1436-destination-city.js b/1436-destination-city.js new file mode 100644 index 00000000..05f7fb78 --- /dev/null +++ b/1436-destination-city.js @@ -0,0 +1,21 @@ +/** + * 1436. Destination City + * https://leetcode.com/problems/destination-city/ + * Difficulty: Easy + * + * You are given the array paths, where paths[i] = [cityAi, cityBi] means there + * exists a direct path going from cityAi to cityBi. Return the destination city, + * that is, the city without any path outgoing to another city. + * + * It is guaranteed that the graph of paths forms a line without any loop, therefore, + * there will be exactly one destination city. + */ + +/** + * @param {string[][]} paths + * @return {string} + */ +var destCity = function(paths) { + const set = new Set(paths.map(([a]) => a)); + return paths.find(([_, b]) => !set.has(b))[1]; +}; diff --git a/README.md b/README.md index 7425f143..8fe642eb 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| +1436|[Destination City](./1436-destination-city.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 1acb7af030a4e7719862044fd024f689f251ca44 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 29 Oct 2021 15:01:08 -0500 Subject: [PATCH 162/485] Add solution #1437 --- ...ll-1s-are-at-least-length-k-places-away.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1437-check-if-all-1s-are-at-least-length-k-places-away.js diff --git a/1437-check-if-all-1s-are-at-least-length-k-places-away.js b/1437-check-if-all-1s-are-at-least-length-k-places-away.js new file mode 100644 index 00000000..26495fcf --- /dev/null +++ b/1437-check-if-all-1s-are-at-least-length-k-places-away.js @@ -0,0 +1,23 @@ +/** + * 1437. Check If All 1's Are at Least Length K Places Away + * https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ + * Difficulty: Easy + * + * Given an array nums of 0s and 1s and an integer k, return True if all 1's are at + * least k places away from each other, otherwise return False. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var kLengthApart = function(nums, k) { + let offset = k; + for (const num of nums) { + if (num === 0) { offset++; continue; } + if (offset < k) return false; + offset = 0; + } + return true; +}; diff --git a/README.md b/README.md index 8fe642eb..8285a1f6 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| +1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 95ceeef5a95194ddc8ca8a39833c49d67707b31e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 29 Oct 2021 16:28:25 -0500 Subject: [PATCH 163/485] Add solution #1446 --- 1446-consecutive-characters.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1446-consecutive-characters.js diff --git a/1446-consecutive-characters.js b/1446-consecutive-characters.js new file mode 100644 index 00000000..796f6319 --- /dev/null +++ b/1446-consecutive-characters.js @@ -0,0 +1,24 @@ +/** + * 1446. Consecutive Characters + * https://leetcode.com/problems/consecutive-characters/ + * Difficulty: Easy + * + * The power of the string is the maximum length of a non-empty substring + * that contains only one unique character. + * + * Given a string s, return the power of s. + */ + +/** + * @param {string} s + * @return {number} + */ +var maxPower = function(s) { + let max = 1, count = 0; + for (let i = 0; i < s.length; i++) { + const prev = s[i - 1]; + count = prev === s[i] ? count + 1 : 0; + max = Math.max(max, count + 1); + } + return max; +}; diff --git a/README.md b/README.md index 8285a1f6..e1d59409 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,7 @@ 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| +1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From cafc9c90f4948642c41af5339ac92535d4a5f6e4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 30 Oct 2021 20:02:44 -0500 Subject: [PATCH 164/485] Add solution #1447 --- 1447-simplified-fractions.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1447-simplified-fractions.js diff --git a/1447-simplified-fractions.js b/1447-simplified-fractions.js new file mode 100644 index 00000000..f3e60a15 --- /dev/null +++ b/1447-simplified-fractions.js @@ -0,0 +1,28 @@ +/** + * 1447. Simplified Fractions + * https://leetcode.com/problems/simplified-fractions/ + * Difficulty: Medium + * + * Given an integer n, return a list of all simplified fractions between 0 and 1 + * (exclusive) such that the denominator is less-than-or-equal-to n. The + * fractions can be in any order. + */ + +/** + * @param {number} n + * @return {string[]} + */ +var simplifiedFractions = function(n) { + const gcd = (a, b) => !b ? a : gcd(b, a % b); + const result = []; + + for (let i = 2; i <= n; i++) { + for (let j = 1; j < i; j++) { + if (gcd(i, j) === 1) { + result.push(`${j}/${i}`); + } + } + } + + return result; +}; diff --git a/README.md b/README.md index e1d59409..f000caf8 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| +1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From dc8c800bbeaeaa9e6228a4590a8773c77bedb0ac Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 12:35:10 -0600 Subject: [PATCH 165/485] Add solution #1450 --- ...students-doing-homework-at-a-given-time.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1450-number-of-students-doing-homework-at-a-given-time.js diff --git a/1450-number-of-students-doing-homework-at-a-given-time.js b/1450-number-of-students-doing-homework-at-a-given-time.js new file mode 100644 index 00000000..82384420 --- /dev/null +++ b/1450-number-of-students-doing-homework-at-a-given-time.js @@ -0,0 +1,24 @@ +/** + * 1450. Number of Students Doing Homework at a Given Time + * https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/ + * Difficulty: Easy + * + * Given two integer arrays startTime and endTime and given an integer queryTime. + * + * The ith student started doing their homework at the time startTime[i] and finished it + * at time endTime[i]. + * + * Return the number of students doing their homework at time queryTime. More formally, + * return the number of students where queryTime lays in the interval [startTime[i], + * endTime[i]] inclusive. + */ + +/** + * @param {number[]} startTime + * @param {number[]} endTime + * @param {number} queryTime + * @return {number} + */ +var busyStudent = function(startTime, endTime, queryTime) { + return startTime.filter((s, i) => queryTime >= s && queryTime <= endTime[i]).length; +}; diff --git a/README.md b/README.md index f000caf8..6b0ea5ad 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| +1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 04998960c5623a2b24be17e1177da0695064394b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 12:42:42 -0600 Subject: [PATCH 166/485] Add solution #1410 --- 1410-html-entity-parser.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1410-html-entity-parser.js diff --git a/1410-html-entity-parser.js b/1410-html-entity-parser.js new file mode 100644 index 00000000..3d4c6f59 --- /dev/null +++ b/1410-html-entity-parser.js @@ -0,0 +1,37 @@ +/** + * 1410. HTML Entity Parser + * https://leetcode.com/problems/html-entity-parser/ + * Difficulty: Medium + * + * HTML entity parser is the parser that takes HTML code as input and replace all the + * entities of the special characters by the characters itself. + * + * The special characters and their entities for HTML are: + * - Quotation Mark: the entity is " and symbol character is ". + * - Single Quote Mark: the entity is ' and symbol character is '. + * - Ampersand: the entity is & and symbol character is &. + * - Greater Than Sign: the entity is > and symbol character is >. + * - Less Than Sign: the entity is < and symbol character is <. + * - Slash: the entity is ⁄ and symbol character is /. + * + * Given the input text string to the HTML parser, you have to implement the entity parser. + * + * Return the text after replacing the entities by the special characters. + */ + +/** + * @param {string} text + * @return {string} + */ +var entityParser = function(text) { + const map = { + '"': '"', + ''': '\'', + '&': '&', + '>': '>', + '<': '<', + '⁄': '/' + }; + + return text.replace(new RegExp(Object.keys(map).join('|'), 'g'), m => map[m]); +}; diff --git a/README.md b/README.md index 6b0ea5ad..e37acc5f 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| +1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| From 4a247a7b9aec7d47b0339e25c9a121574723a59c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 12:57:52 -0600 Subject: [PATCH 167/485] Add solution #551 --- 0551-student-attendance-record-i.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0551-student-attendance-record-i.js diff --git a/0551-student-attendance-record-i.js b/0551-student-attendance-record-i.js new file mode 100644 index 00000000..53317a4e --- /dev/null +++ b/0551-student-attendance-record-i.js @@ -0,0 +1,26 @@ +/** + * 551. Student Attendance Record I + * https://leetcode.com/problems/student-attendance-record-i/ + * Difficulty: Easy + * + * You are given a string s representing an attendance record for a student + * where each character signifies whether the student was absent, late, or + * present on that day. The record only contains the following three characters: + * - 'A': Absent. + * - 'L': Late. + * - 'P': Present. + * + * The student is eligible for an attendance award if they meet both of the following criteria: + * - The student was absent ('A') for strictly fewer than 2 days total. + * - The student was never late ('L') for 3 or more consecutive days. + * + * Return true if the student is eligible for an attendance award, or false otherwise. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var checkRecord = function(s) { + return !s.includes('LLL') && (s.indexOf('A') === s.lastIndexOf('A')); +}; diff --git a/README.md b/README.md index e37acc5f..6caa91be 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From 722a46cb9a6f1fe2171d6d53edc1c69f9d6fdeae Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 17:51:41 -0600 Subject: [PATCH 168/485] Add solution #1451 --- 1451-rearrange-words-in-a-sentence.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1451-rearrange-words-in-a-sentence.js diff --git a/1451-rearrange-words-in-a-sentence.js b/1451-rearrange-words-in-a-sentence.js new file mode 100644 index 00000000..27d54cc8 --- /dev/null +++ b/1451-rearrange-words-in-a-sentence.js @@ -0,0 +1,27 @@ +/** + * 1451. Rearrange Words in a Sentence + * https://leetcode.com/problems/rearrange-words-in-a-sentence/ + * Difficulty: Medium + * + * Given a sentence text (A sentence is a string of space-separated words) in the following format: + * - First letter is in upper case. + * - Each word in text are separated by a single space. + * + * Your task is to rearrange the words in text such that all words are rearranged in an increasing + * order of their lengths. If two words have the same length, arrange them in their original order. + * + * Return the new text following the format shown above. + */ + +/** + * @param {string} text + * @return {string} + */ +var arrangeWords = function(text) { + return text + .split(/\s+/) + .sort((a, b) => a.length - b.length) + .join(' ') + .toLowerCase() + .replace(/^./, m => m.toUpperCase()); +}; diff --git a/README.md b/README.md index 6caa91be..79ab0fcb 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| +1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From cb426b96ef214416cdb52df96f26dd7208d9048d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 18:14:10 -0600 Subject: [PATCH 169/485] Add solution #1455 --- ...s-as-a-prefix-of-any-word-in-a-sentence.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js diff --git a/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js b/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js new file mode 100644 index 00000000..78f9d522 --- /dev/null +++ b/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js @@ -0,0 +1,23 @@ +/** + * 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence + * https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ + * Difficulty: Easy + * + * Given a sentence that consists of some words separated by a single space, and a searchWord, + * check if searchWord is a prefix of any word in sentence. + * + * Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. + * If searchWord is a prefix of more than one word, return the index of the first word (minimum index). + * If there is no such word return -1. + * + * A prefix of a string s is any leading contiguous substring of s. + */ + +/** + * @param {string} sentence + * @param {string} searchWord + * @return {number} + */ +var isPrefixOfWord = function(sentence, searchWord) { + return sentence.split(/\s+/).findIndex(s => s.startsWith(searchWord)) + 1 || -1; +}; diff --git a/README.md b/README.md index 79ab0fcb..ddc047eb 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| +1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From e85225a4673d8cd13b96cb925e4303319634301f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 15:44:11 -0600 Subject: [PATCH 170/485] Add solution #1456 --- ...f-vowels-in-a-substring-of-given-length.js | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 1456-maximum-number-of-vowels-in-a-substring-of-given-length.js diff --git a/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js b/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js new file mode 100644 index 00000000..5eb327c9 --- /dev/null +++ b/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js @@ -0,0 +1,33 @@ +/** + * 1456. Maximum Number of Vowels in a Substring of Given Length + * https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/ + * Difficulty: Medium + * + * Given a string s and an integer k. + * + * Return the maximum number of vowel letters in any substring of s with length k. + * + * Vowel letters in English are (a, e, i, o, u). + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var maxVowels = function(s, k) { + const vowels = 'aeiou'; + let result = 0; + + for (let i = 0, count = 0; i < s.length; i++) { + if (vowels.includes(s[i])) { + count++; + } + if (i >= k && vowels.includes(s[i - k])) { + count--; + } + result = Math.max(result, count); + } + + return result; +}; diff --git a/README.md b/README.md index ddc047eb..c50e2797 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| +1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f9f13cc8986fc7dbfec39f4784c561740d6ad4d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 16:26:49 -0600 Subject: [PATCH 171/485] Add solution #821 --- 0821-shortest-distance-to-a-character.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0821-shortest-distance-to-a-character.js diff --git a/0821-shortest-distance-to-a-character.js b/0821-shortest-distance-to-a-character.js new file mode 100644 index 00000000..0d0e93e1 --- /dev/null +++ b/0821-shortest-distance-to-a-character.js @@ -0,0 +1,40 @@ +/** + * 821. Shortest Distance to a Character + * https://leetcode.com/problems/shortest-distance-to-a-character/ + * Difficulty: Easy + * + * Given a string s and a character c that occurs in s, return an array of + * integers answer where answer.length == s.length and answer[i] is the + * distance from index i to the closest occurrence of character c in s. + * + * The distance between two indices i and j is abs(i - j), where abs is the + * absolute value function. + */ + +/** + * @param {string} s + * @param {character} c + * @return {number[]} + */ +var shortestToChar = function(s, c) { + const result = []; + const pointers = []; + + for (let i = 0; i < s.length; i++) { + if (s[i] === c) pointers.push(i); + } + + for (let i = 0, j = 0; i < s.length; i++) { + if (i > pointers[j + 1] && pointers.length - 2 > j) { + j++; + } + + const offset = pointers.length > 1 + ? Math.min(Math.abs(pointers[j] - i), Math.abs(pointers[j + 1] - i)) + : Math.abs(pointers[j] - i); + + result.push(offset); + } + + return result; +}; diff --git a/README.md b/README.md index c50e2797..6895b2b5 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| +821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| From 6604d5e2f8e99579f210a679bed7452bd35e1d9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 16:40:02 -0600 Subject: [PATCH 172/485] Add solution #179 --- 0179-largest-number.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0179-largest-number.js diff --git a/0179-largest-number.js b/0179-largest-number.js new file mode 100644 index 00000000..df659a9f --- /dev/null +++ b/0179-largest-number.js @@ -0,0 +1,22 @@ +/** + * 179. Largest Number + * https://leetcode.com/problems/largest-number/ + * Difficulty: Medium + * + * Given a list of non-negative integers nums, arrange them such that they + * form the largest number. + * + * Note: The result may be very large, so you need to return a string + * instead of an integer. + */ + +/** + * @param {number[]} nums + * @return {string} + */ +var largestNumber = function(nums) { + return nums + .sort((a, b) => `${b}${a}` - `${a}${b}`) + .join('') + .replace(/^0+/, 0); +}; diff --git a/README.md b/README.md index 6895b2b5..7662df66 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +179|[Largest Number](./0179-largest-number.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From ac3c1151b69bab26ceadcad0423dec00a7ff507f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 16:46:45 -0600 Subject: [PATCH 173/485] Add solution #1460 --- ...wo-arrays-equal-by-reversing-sub-arrays.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1460-make-two-arrays-equal-by-reversing-sub-arrays.js diff --git a/1460-make-two-arrays-equal-by-reversing-sub-arrays.js b/1460-make-two-arrays-equal-by-reversing-sub-arrays.js new file mode 100644 index 00000000..3040cf91 --- /dev/null +++ b/1460-make-two-arrays-equal-by-reversing-sub-arrays.js @@ -0,0 +1,21 @@ +/** + * 1460. Make Two Arrays Equal by Reversing Sub-arrays + * https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ + * Difficulty: Easy + * + * Given two integer arrays of equal length target and arr. + * + * In one step, you can select any non-empty sub-array of arr and reverse it. + * You are allowed to make any number of steps. + * + * Return True if you can make arr equal to target, or False otherwise. + */ + +/** + * @param {number[]} target + * @param {number[]} arr + * @return {boolean} + */ +var canBeEqual = function(target, arr) { + return target.sort().join('') === arr.sort().join(''); +}; diff --git a/README.md b/README.md index 7662df66..3e5c3175 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| +1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f8f247544afff153e95bf8d5a91b57e5b1fa81af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Dec 2021 17:49:30 -0600 Subject: [PATCH 174/485] Add solution #1464 --- ...ximum-product-of-two-elements-in-an-array.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 1464-maximum-product-of-two-elements-in-an-array.js diff --git a/1464-maximum-product-of-two-elements-in-an-array.js b/1464-maximum-product-of-two-elements-in-an-array.js new file mode 100644 index 00000000..2b1fb2cf --- /dev/null +++ b/1464-maximum-product-of-two-elements-in-an-array.js @@ -0,0 +1,17 @@ +/** + * 1464. Maximum Product of Two Elements in an Array + * https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ + * Difficulty: Easy + * + * Given the array of integers nums, you will choose two different indices i and j + * of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxProduct = function(nums) { + const [a, b] = nums.sort((a, b) => b - a); + return (a - 1) * (b - 1); +}; diff --git a/README.md b/README.md index 3e5c3175..67020ab4 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| +1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From e2715edeacb8c2aff562eb022416de84b23765f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Dec 2021 18:30:22 -0600 Subject: [PATCH 175/485] Add solution #1470 --- 1470-shuffle-the-array.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1470-shuffle-the-array.js diff --git a/1470-shuffle-the-array.js b/1470-shuffle-the-array.js new file mode 100644 index 00000000..a8ac4990 --- /dev/null +++ b/1470-shuffle-the-array.js @@ -0,0 +1,22 @@ +/** + * 1470. Shuffle the Array + * https://leetcode.com/problems/shuffle-the-array/ + * Difficulty: Easy + * + * Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. + * + * Return the array in the form [x1,y1,x2,y2,...,xn,yn]. + */ + +/** + * @param {number[]} nums + * @param {number} n + * @return {number[]} + */ +var shuffle = function(nums, n) { + const shuffled = []; + for (let i = 0; i < nums.length / 2; i++) { + shuffled.push(nums[i], nums[i + nums.length / 2]); + } + return shuffled; +}; diff --git a/README.md b/README.md index 67020ab4..ef883599 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,7 @@ 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| +1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 71da54d2c00f5c34700660859cca0fa98c4398e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Dec 2021 18:56:41 -0600 Subject: [PATCH 176/485] Add solution #1475 --- ...rices-with-a-special-discount-in-a-shop.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1475-final-prices-with-a-special-discount-in-a-shop.js diff --git a/1475-final-prices-with-a-special-discount-in-a-shop.js b/1475-final-prices-with-a-special-discount-in-a-shop.js new file mode 100644 index 00000000..02d9aed0 --- /dev/null +++ b/1475-final-prices-with-a-special-discount-in-a-shop.js @@ -0,0 +1,22 @@ +/** + * 1475. Final Prices With a Special Discount in a Shop + * https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ + * Difficulty: Easy + * + * Given the array prices where prices[i] is the price of the ith item in a shop. + * There is a special discount for items in the shop, if you buy the ith item, + * then you will receive a discount equivalent to prices[j] where j is the minimum + * index such that j > i and prices[j] <= prices[i], otherwise, you will not receive + * any discount at all. + * + * Return an array where the ith element is the final price you will pay for the ith + * item of the shop considering the special discount. + */ + +/** + * @param {number[]} prices + * @return {number[]} + */ +var finalPrices = function(prices) { + return prices.map((n, i) => n - (prices.slice(i + 1).find(v => v <= n) || 0)); +}; diff --git a/README.md b/README.md index ef883599..a7184811 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| +1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From b20ea69de7345a93c4aa4bd0fafae94fa651d146 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:16:29 -0600 Subject: [PATCH 177/485] Add solution #1486 --- 1486-xor-operation-in-an-array.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1486-xor-operation-in-an-array.js diff --git a/1486-xor-operation-in-an-array.js b/1486-xor-operation-in-an-array.js new file mode 100644 index 00000000..1a897091 --- /dev/null +++ b/1486-xor-operation-in-an-array.js @@ -0,0 +1,23 @@ +/** + * 1486. XOR Operation in an Array + * https://leetcode.com/problems/xor-operation-in-an-array/ + * Difficulty: Easy + * + * Given an integer n and an integer start. + * + * Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. + * + * Return the bitwise XOR of all elements of nums. + */ + +/** + * @param {number} n + * @param {number} start + * @return {number} + */ +var xorOperation = function(n, start) { + return new Array(n) + .fill(0) + .map((_, i) => start + 2 * i) + .reduce((result, n) => result ^ n, 0); +}; diff --git a/README.md b/README.md index a7184811..c503f72d 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| +1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From 21cba5b4da2a696b928b0996210e0ef30c1c90d9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:17:35 -0600 Subject: [PATCH 178/485] Add solution #231 --- 0231-power-of-two.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0231-power-of-two.js diff --git a/0231-power-of-two.js b/0231-power-of-two.js new file mode 100644 index 00000000..b8ad43dc --- /dev/null +++ b/0231-power-of-two.js @@ -0,0 +1,22 @@ +/** + * 231. Power of Two + * https://leetcode.com/problems/power-of-two/ + * Difficulty: Easy + * + * Given an integer n, return true if it is a power of two. Otherwise, return false. + * + * An integer n is a power of two, if there exists an integer x such that n == 2x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function(n) { + if (n > 1) { + while (n % 2 === 0) { + n /= 2 + } + } + return n === 1; +}; diff --git a/README.md b/README.md index c503f72d..9fb07093 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| From 2a41126afb912b5adf5335719893f3935321e379 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:18:14 -0600 Subject: [PATCH 179/485] Add solution #326 --- 0326-power-of-three.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0326-power-of-three.js diff --git a/0326-power-of-three.js b/0326-power-of-three.js new file mode 100644 index 00000000..514cee88 --- /dev/null +++ b/0326-power-of-three.js @@ -0,0 +1,22 @@ +/** + * 326. Power of Three + * https://leetcode.com/problems/power-of-three/ + * Difficulty: Easy + * + * Given an integer n, return true if it is a power of three. Otherwise, return false. + * + * An integer n is a power of three, if there exists an integer x such that n == 3x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfThree = function(n) { + if (n > 1) { + while (n % 3 === 0) { + n /= 3 + } + } + return n === 1; +}; diff --git a/README.md b/README.md index 9fb07093..71a62e87 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +326|[Power of Three](./0326-power-of-three.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| From 22b3708190d873c1e1d70eee2e15948ed3a6c713 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:18:50 -0600 Subject: [PATCH 180/485] Add solution #342 --- 0342-power-of-four.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0342-power-of-four.js diff --git a/0342-power-of-four.js b/0342-power-of-four.js new file mode 100644 index 00000000..1f49fe02 --- /dev/null +++ b/0342-power-of-four.js @@ -0,0 +1,22 @@ +/** + * 342. Power of Four + * https://leetcode.com/problems/power-of-four/ + * Difficulty: Easy + * + * Given an integer n, return true if it is a power of four. Otherwise, return false. + * + * An integer n is a power of four, if there exists an integer x such that n == 4x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function(n) { + if (n > 1) { + while (n % 4 === 0) { + n /= 4 + } + } + return n === 1; +}; diff --git a/README.md b/README.md index 71a62e87..b16e6297 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| +342|[Power of Four](./0342-power-of-four.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| From cb1010b19127228bc1fc79bb679f073b8c22ada7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:19:42 -0600 Subject: [PATCH 181/485] Add solution #191 --- 0191-number-of-1-bits.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0191-number-of-1-bits.js diff --git a/0191-number-of-1-bits.js b/0191-number-of-1-bits.js new file mode 100644 index 00000000..dc765426 --- /dev/null +++ b/0191-number-of-1-bits.js @@ -0,0 +1,16 @@ +/** + * 191. Number of 1 Bits + * https://leetcode.com/problems/number-of-1-bits/ + * Difficulty: Easy + * + * Write a function that takes an unsigned integer and returns the number of + * '1' bits it has (also known as the Hamming weight). + */ + +/** + * @param {number} n - a positive integer + * @return {number} + */ +var hammingWeight = function(n) { + return n.toString(2).match(/1/g)?.length || 0; +}; diff --git a/README.md b/README.md index b16e6297..27e0f198 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 179|[Largest Number](./0179-largest-number.js)|Medium| +191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 433e90ce5df37c2b0fbae99e7708dbe80be1f568 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:22:12 -0600 Subject: [PATCH 182/485] Add solution #1780 --- ...k-if-number-is-a-sum-of-powers-of-three.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1780-check-if-number-is-a-sum-of-powers-of-three.js diff --git a/1780-check-if-number-is-a-sum-of-powers-of-three.js b/1780-check-if-number-is-a-sum-of-powers-of-three.js new file mode 100644 index 00000000..7739fda7 --- /dev/null +++ b/1780-check-if-number-is-a-sum-of-powers-of-three.js @@ -0,0 +1,24 @@ +/** + * 1780. Check if Number is a Sum of Powers of Three + * https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/ + * Difficulty: Medium + * + * Given an integer n, return true if it is possible to represent n as the sum + * of distinct powers of three. Otherwise, return false. + * + * An integer y is a power of three if there exists an integer x such that y == 3x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var checkPowersOfThree = function(n) { + while (n) { + if (n % 3 === 2) { + return 0; + } + n = n / 3 >> 0; + } + return 1; +}; diff --git a/README.md b/README.md index 27e0f198..7901b798 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| +1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| From 00d3daec9e471564d78a0eeeb08007a9288f84bf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:50:11 -0600 Subject: [PATCH 183/485] Add solution #1480 --- 1480-running-sum-of-1d-array.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1480-running-sum-of-1d-array.js diff --git a/1480-running-sum-of-1d-array.js b/1480-running-sum-of-1d-array.js new file mode 100644 index 00000000..03c29dec --- /dev/null +++ b/1480-running-sum-of-1d-array.js @@ -0,0 +1,21 @@ +/** + * 1480. Running Sum of 1d Array + * https://leetcode.com/problems/running-sum-of-1d-array/ + * Difficulty: Easy + * + * Given an array nums. We define a running sum of an array as + * runningSum[i] = sum(nums[0]…nums[i]). + * + * Return the running sum of nums. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var runningSum = function(nums) { + for (let i = 1; i < nums.length; i++) { + nums[i] = nums[i - 1] + nums[i]; + } + return nums; +}; diff --git a/README.md b/README.md index 7901b798..cb03cf74 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| +1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 71e037c97e70d5fd88bd599fd716b820c823a900 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 23:37:56 -0600 Subject: [PATCH 184/485] Add solution #1496 --- 1496-path-crossing.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1496-path-crossing.js diff --git a/1496-path-crossing.js b/1496-path-crossing.js new file mode 100644 index 00000000..13f3e814 --- /dev/null +++ b/1496-path-crossing.js @@ -0,0 +1,37 @@ +/** + * 1496. Path Crossing + * https://leetcode.com/problems/path-crossing/ + * Difficulty: Easy + * + * Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing + * moving one unit north, south, east, or west, respectively. You start at the + * origin (0, 0) on a 2D plane and walk on the path specified by path. + * + * Return true if the path crosses itself at any point, that is, if at any time + * you are on a location you have previously visited. Return false otherwise. + */ + +/** + * @param {string} path + * @return {boolean} + */ +var isPathCrossing = function(path) { + let x = 0, y = 0; + const toKey = (a, b) => `${a},${b}`; + const history = new Set([toKey(x, y)]); + + for (let direction of path) { + switch (direction) { + case 'N': x++; break; + case 'W': y--; break; + case 'S': x--; break; + case 'E': y++; break; + } + if (history.has(toKey(x, y))) { + return true; + } + history.add(toKey(x, y)); + } + + return false; +}; diff --git a/README.md b/README.md index cb03cf74..99ab14bf 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| +1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 859595f45ffc4bbf20ff1173d90a4358fc304968 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 23:38:46 -0600 Subject: [PATCH 185/485] Add solution #1492 --- 1492-the-kth-factor-of-n.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1492-the-kth-factor-of-n.js diff --git a/1492-the-kth-factor-of-n.js b/1492-the-kth-factor-of-n.js new file mode 100644 index 00000000..0de7ad94 --- /dev/null +++ b/1492-the-kth-factor-of-n.js @@ -0,0 +1,27 @@ +/** + * 1492. The kth Factor of n + * https://leetcode.com/problems/the-kth-factor-of-n/ + * Difficulty: Medium + * + * Given two positive integers n and k. + * + * A factor of an integer n is defined as an integer i where n % i == 0. + * + * Consider a list of all factors of n sorted in ascending order, return + * the kth factor in this list or return -1 if n has less than k factors. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var kthFactor = function(n, k) { + for (let i = 1; i <= n; i++) { + if (n % i === 0) { + k--; + } + if (!k) return i; + } + return -1; +}; diff --git a/README.md b/README.md index 99ab14bf..1405af92 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| +1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 340948e27a71ffbca0bbe87df2ea3ccb6866e29a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 23:39:54 -0600 Subject: [PATCH 186/485] Add solution #1481 --- ...ber-of-unique-integers-after-k-removals.js | 26 +++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1481-least-number-of-unique-integers-after-k-removals.js diff --git a/1481-least-number-of-unique-integers-after-k-removals.js b/1481-least-number-of-unique-integers-after-k-removals.js new file mode 100644 index 00000000..a786eaf4 --- /dev/null +++ b/1481-least-number-of-unique-integers-after-k-removals.js @@ -0,0 +1,26 @@ +/** + * 1481. Least Number of Unique Integers after K Removals + * https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/ + * Difficulty: Medium + * + * Given an array of integers arr and an integer k. Find the least number of + * unique integers after removing exactly k elements. + */ + +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var findLeastNumOfUniqueInts = function(arr, k) { + const map = new Map(); + arr.forEach(n => map.set(n, map.has(n) ? map.get(n) + 1 : 1)); + + const sorted = [...map.values()].sort((a, b) => a - b); + while (k && sorted.length && sorted[0] <= k) { + k -= sorted[0]; + sorted.shift(); + } + + return sorted.length; +}; diff --git a/README.md b/README.md index 1405af92..d89a0c01 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| +1481|[Least Number of Unique Integers after K Removals](./1481-least-number-of-unique-integers-after-k-removals.js)|Medium| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| From ee7c1540c39a5070e5e230fa96352c29ea7f3600 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Dec 2021 00:10:33 -0600 Subject: [PATCH 187/485] Add solution #1502 --- ...ke-arithmetic-progression-from-sequence.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1502-can-make-arithmetic-progression-from-sequence.js diff --git a/1502-can-make-arithmetic-progression-from-sequence.js b/1502-can-make-arithmetic-progression-from-sequence.js new file mode 100644 index 00000000..d313fd83 --- /dev/null +++ b/1502-can-make-arithmetic-progression-from-sequence.js @@ -0,0 +1,27 @@ +/** + * 1502. Can Make Arithmetic Progression From Sequence + * https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ + * Difficulty: Easy + * + * A sequence of numbers is called an arithmetic progression if the difference + * between any two consecutive elements is the same. + * + * Given an array of numbers arr, return true if the array can be rearranged to + * form an arithmetic progression. Otherwise, return false. + */ + +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function(arr) { + arr.sort((a, b) => a - b); + + for (let i = 2, diff = arr[1] - arr[0]; i < arr.length; i++) { + if (arr[i] - arr[i - 1] !== diff) { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index d89a0c01..acb4f065 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| +1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From c779ef209efe88277a4cbb788416f34656d80732 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Dec 2021 00:11:24 -0600 Subject: [PATCH 188/485] Add solution #1491 --- ...xcluding-the-minimum-and-maximum-salary.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1491-average-salary-excluding-the-minimum-and-maximum-salary.js diff --git a/1491-average-salary-excluding-the-minimum-and-maximum-salary.js b/1491-average-salary-excluding-the-minimum-and-maximum-salary.js new file mode 100644 index 00000000..a4a4845b --- /dev/null +++ b/1491-average-salary-excluding-the-minimum-and-maximum-salary.js @@ -0,0 +1,21 @@ +/** + * 1491. Average Salary Excluding the Minimum and Maximum Salary + * https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/ + * Difficulty: Easy + * + * Given an array of unique integers salary where salary[i] is the salary of the employee i. + * + * Return the average salary of employees excluding the minimum and maximum salary. + */ + +/** + * @param {number[]} salary + * @return {number} + */ +var average = function(salary) { + salary.sort((a, b) => a - b); + salary.shift(); + salary.pop(); + + return salary.reduce((total, n) => total + n, 0) / salary.length; +}; diff --git a/README.md b/README.md index acb4f065..b8d53d71 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1481|[Least Number of Unique Integers after K Removals](./1481-least-number-of-unique-integers-after-k-removals.js)|Medium| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| +1491|[Average Salary Excluding the Minimum and Maximum Salary](./1491-average-salary-excluding-the-minimum-and-maximum-salary.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| From 6099ae2c79ca3670704f65b4427e59038cf245f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Dec 2021 00:12:11 -0600 Subject: [PATCH 189/485] Add solution #1493 --- ...barray-of-1s-after-deleting-one-element.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1493-longest-subarray-of-1s-after-deleting-one-element.js diff --git a/1493-longest-subarray-of-1s-after-deleting-one-element.js b/1493-longest-subarray-of-1s-after-deleting-one-element.js new file mode 100644 index 00000000..c1a11255 --- /dev/null +++ b/1493-longest-subarray-of-1s-after-deleting-one-element.js @@ -0,0 +1,29 @@ +/** + * 1493. Longest Subarray of 1's After Deleting One Element + * https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/ + * Difficulty: Medium + * + * Given a binary array nums, you should delete one element from it. + * + * Return the size of the longest non-empty subarray containing only 1's in the + * resulting array. Return 0 if there is no such subarray. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var longestSubarray = function(nums) { + const grouped = nums.join('').split('0').map(s => s.length); + let max = 0; + + for (let i = 0; i < grouped.length; i++) { + max = Math.max( + max, + (grouped[i - 1] ?? 0) + grouped[i], + grouped[i] + (grouped[i + 1] ?? 0) + ); + } + + return max - (nums.includes(0) ? 0 : 1); +}; diff --git a/README.md b/README.md index b8d53d71..cb3c2dc6 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1491|[Average Salary Excluding the Minimum and Maximum Salary](./1491-average-salary-excluding-the-minimum-and-maximum-salary.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| +1493|[Longest Subarray of 1's After Deleting One Element](./1493-longest-subarray-of-1s-after-deleting-one-element.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From bc42c36a05a9bcd057c1889988853fcb9c170cab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Dec 2021 03:09:47 -0600 Subject: [PATCH 190/485] Add solution #1507 --- 1507-reformat-date.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1507-reformat-date.js diff --git a/1507-reformat-date.js b/1507-reformat-date.js new file mode 100644 index 00000000..179493d6 --- /dev/null +++ b/1507-reformat-date.js @@ -0,0 +1,24 @@ +/** + * 1507. Reformat Date + * https://leetcode.com/problems/reformat-date/ + * Difficulty: Easy + * + * Given a date string in the form Day Month Year, where: + * - Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. + * - Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}. + * - Year is in the range [1900, 2100]. + * + * Convert the date string to the format YYYY-MM-DD, where: + * - YYYY denotes the 4 digit year. + * - MM denotes the 2 digit month. + * - DD denotes the 2 digit day. + */ + +/** + * @param {string} date + * @return {string} + */ +var reformatDate = function(date) { + const [_, day, month, year] = date.match(/(\d+)\w+\s+(\w+)\s+(\d+)/); + return new Date(`${day} ${month} ${year}`).toISOString().split('T')[0]; +}; diff --git a/README.md b/README.md index cb3c2dc6..bd0d627a 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ 1493|[Longest Subarray of 1's After Deleting One Element](./1493-longest-subarray-of-1s-after-deleting-one-element.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| +1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 2e058b2d8e387b15b0d61f585b2c4cbaeeec1641 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Dec 2021 13:55:06 -0600 Subject: [PATCH 191/485] Add solution #1550 --- 1550-three-consecutive-odds.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 1550-three-consecutive-odds.js diff --git a/1550-three-consecutive-odds.js b/1550-three-consecutive-odds.js new file mode 100644 index 00000000..3b5a9eb2 --- /dev/null +++ b/1550-three-consecutive-odds.js @@ -0,0 +1,20 @@ +/** + * 1550. Three Consecutive Odds + * https://leetcode.com/problems/three-consecutive-odds/ + * Difficulty: Easy + * + * Given an integer array arr, return true if there are three consecutive odd + * numbers in the array. Otherwise, return false. + */ + +/** + * @param {number[]} arr + * @return {boolean} + */ +var threeConsecutiveOdds = function(arr) { + for (let i = 0, count = 0; i < arr.length; i++) { + count = arr[i] % 2 !== 0 ? count + 1 : 0; + if (count === 3) return true; + } + return false; +}; diff --git a/README.md b/README.md index bd0d627a..c0023bc0 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| +1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From e464e607d091e994a1114433726fc676d34d2ae4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Dec 2021 13:59:44 -0600 Subject: [PATCH 192/485] Add solution #1551 --- ...-minimum-operations-to-make-array-equal.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1551-minimum-operations-to-make-array-equal.js diff --git a/1551-minimum-operations-to-make-array-equal.js b/1551-minimum-operations-to-make-array-equal.js new file mode 100644 index 00000000..4dd409e0 --- /dev/null +++ b/1551-minimum-operations-to-make-array-equal.js @@ -0,0 +1,24 @@ +/** + * 1551. Minimum Operations to Make Array Equal + * https://leetcode.com/problems/minimum-operations-to-make-array-equal/ + * Difficulty: Medium + * + * You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values + * of i (i.e., 0 <= i < n). + * + * In one operation, you can select two indices x and y where 0 <= x, y < n and subtract + * 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal + * is to make all the elements of the array equal. It is guaranteed that all the elements + * of the array can be made equal using some operations. + * + * Given an integer n, the length of the array, return the minimum number of operations + * needed to make all the elements of arr equal. + */ + +/** + * @param {number} n + * @return {number} + */ +var minOperations = function(n) { + return n * n / 4; +}; diff --git a/README.md b/README.md index c0023bc0..e7dce5fe 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| +1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f16e05058876ef67eae42e81874e79968d1cbe9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Dec 2021 14:20:21 -0600 Subject: [PATCH 193/485] Add solution #1402 --- 1402-reducing-dishes.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 1402-reducing-dishes.js diff --git a/1402-reducing-dishes.js b/1402-reducing-dishes.js new file mode 100644 index 00000000..76efb338 --- /dev/null +++ b/1402-reducing-dishes.js @@ -0,0 +1,38 @@ +/** + * 1402. Reducing Dishes + * https://leetcode.com/problems/reducing-dishes/ + * Difficulty: Hard + * + * A chef has collected data on the satisfaction level of his n dishes. + * Chef can cook any dish in 1 unit of time. + * + * Like-time coefficient of a dish is defined as the time taken to cook + * that dish including previous dishes multiplied by its satisfaction + * level i.e. time[i] * satisfaction[i]. + * + * Return the maximum sum of like-time coefficient that the chef can + * obtain after dishes preparation. + * + * Dishes can be prepared in any order and the chef can discard some + * dishes to get this maximum value. + */ + +/** + * @param {number[]} satisfaction + * @return {number} + */ +var maxSatisfaction = function(satisfaction) { + let max = 0; + + satisfaction.sort((a, b) => a - b); + + while (satisfaction.length) { + max = Math.max( + max, + satisfaction.reduce((total, n, i) => total + n * (i + 1), 0) + ); + satisfaction.shift(); + } + + return max; +}; diff --git a/README.md b/README.md index e7dce5fe..8ab8de3e 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| +1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| 1436|[Destination City](./1436-destination-city.js)|Easy| From 6d05e88c183fc6ee660bf2082d97ba3b60ea00a7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 14:18:28 -0500 Subject: [PATCH 194/485] Add solution #9 --- 0009-palindrome-number.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/0009-palindrome-number.js b/0009-palindrome-number.js index e696c444..a4691dc2 100644 --- a/0009-palindrome-number.js +++ b/0009-palindrome-number.js @@ -4,9 +4,9 @@ * Difficulty: Easy * * Given an integer `x`, return `true` if `x` is palindrome integer. - -An integer is a palindrome when it reads the same backward as forward. -For example, `121` is palindrome while `123` is not. + * + * An integer is a palindrome when it reads the same backward as forward. + * - For example, `121` is palindrome while `123` is not. */ /** From c1385f61869e6a70f9d305d3e5f5e6d7c00edb5a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 15:18:24 -0500 Subject: [PATCH 195/485] Add solution #133 --- 0133-clone-graph.js | 48 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0133-clone-graph.js diff --git a/0133-clone-graph.js b/0133-clone-graph.js new file mode 100644 index 00000000..3aa5c44c --- /dev/null +++ b/0133-clone-graph.js @@ -0,0 +1,48 @@ +/** + * 133. Clone Graph + * https://leetcode.com/problems/clone-graph/ + * Difficulty: Medium + * + * Given a reference of a node in a connected undirected graph. + * Return a deep copy (clone) of the graph. + * Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. + * + * Test case format: + * - For simplicity, each node's value is the same as the node's index (1-indexed). + * For example, the first node with val == 1, the second node with val == 2, and so on. + * The graph is represented in the test case using an adjacency list. + * + * - An adjacency list is a collection of unordered lists used to represent a finite graph. + * Each list describes the set of neighbors of a node in the graph. + * + * - The given node will always be the first node with val = 1. You must return the copy of + * the given node as a reference to the cloned graph. + */ + +/** + * // Definition for a Node. + * function Node(val, neighbors) { + * this.val = val === undefined ? 0 : val; + * this.neighbors = neighbors === undefined ? [] : neighbors; + * }; + */ + +/** + * @param {Node} node + * @return {Node} + */ +var cloneGraph = function(node) { + const map = new Map(); + return node && cloneNode(node, map); +}; + +function cloneNode(node, map) { + const cloned = new Node(node.val, node.neighbors); + map.set(node.val, cloned); + + cloned.neighbors = node.neighbors && node.neighbors.map(n => { + return map.get(n.val) || cloneNode(n, map); + }); + + return cloned; +} diff --git a/README.md b/README.md index 8ab8de3e..fe4651fb 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +133|[Clone Graph](./0133-clone-graph.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| From c9cb8599101f89e40bfd43d146fc758a63f1fd33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 16:53:22 -0500 Subject: [PATCH 196/485] Add solution #28 --- 0028-implement-strstr.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0028-implement-strstr.js diff --git a/0028-implement-strstr.js b/0028-implement-strstr.js new file mode 100644 index 00000000..f7cc484e --- /dev/null +++ b/0028-implement-strstr.js @@ -0,0 +1,26 @@ +/** + * 28. Implement strStr() + * https://leetcode.com/problems/implement-strstr/ + * Difficulty: Easy + * + * Return the index of the first occurrence of needle in haystack, or -1 if needle + * is not part of haystack. + * + * Clarification: + * - What should we return when needle is an empty string? This is a great question + * to ask during an interview. + * + * - For the purpose of this problem, we will return 0 when needle is an empty string. + * This is consistent to C's strstr() and Java's indexOf(). + */ + +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function(haystack, needle) { + if (!needle) return 0; + const split = haystack.split(needle); + return split.length > 1 ? split[0].length : -1; +}; diff --git a/README.md b/README.md index fe4651fb..49db8d65 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| +28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| From 3e934d313fce646ce9496dce84da43f3d8b0200a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:09:50 -0500 Subject: [PATCH 197/485] Add solution #214 --- 0214-shortest-palindrome.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0214-shortest-palindrome.js diff --git a/0214-shortest-palindrome.js b/0214-shortest-palindrome.js new file mode 100644 index 00000000..955ae2d8 --- /dev/null +++ b/0214-shortest-palindrome.js @@ -0,0 +1,24 @@ +/** + * 214. Shortest Palindrome + * https://leetcode.com/problems/shortest-palindrome/ + * Difficulty: Hard + * + * You are given a string s. You can convert s to a palindrome by adding characters + * in front of it. + * + * Return the shortest palindrome you can find by performing this transformation. + */ + +/** + * @param {string} s + * @return {string} + */ +var shortestPalindrome = function(s) { + const reversed = s.split('').reverse().join(''); + for (let i = s.length; i > 0; i--) { + if (s.slice(0, i) === reversed.slice(s.length - i)) { + return reversed.slice(0, reversed.length - i) + s; + } + } + return ''; +}; diff --git a/README.md b/README.md index 49db8d65..1e4dfba4 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| +214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| From ee0545a716a4fd92a46d05bc3195544e1bbae3d2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:20:14 -0500 Subject: [PATCH 198/485] Add solution #796 --- 0796-rotate-string.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0796-rotate-string.js diff --git a/0796-rotate-string.js b/0796-rotate-string.js new file mode 100644 index 00000000..a9d77ee8 --- /dev/null +++ b/0796-rotate-string.js @@ -0,0 +1,25 @@ +/** + * 796. Rotate String + * https://leetcode.com/problems/rotate-string/ + * Difficulty: Easy + * + * Given two strings s and goal, return true if and only if s can become goal + * after some number of shifts on s. + * + * A shift on s consists of moving the leftmost character of s to the rightmost + * position. + * + * For example, if s = "abcde", then it will be "bcdea" after one shift. + */ + +/** + * @param {string} s + * @param {string} goal + * @return {boolean} + */ +var rotateString = function(s, goal) { + for (let i = 0; i < s.length; i++) { + if (s.slice(i) + s.slice(0, i) === goal) return true; + } + return false; +}; diff --git a/README.md b/README.md index 1e4dfba4..2d436b01 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| +796|[Rotate String](./0796-rotate-string.js)|Easy| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| From 2e263486d00c0a508966826f125b6c670cb60440 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:32:52 -0500 Subject: [PATCH 199/485] Add solution #500 --- 0500-keyboard-row.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0500-keyboard-row.js diff --git a/0500-keyboard-row.js b/0500-keyboard-row.js new file mode 100644 index 00000000..f6868ab7 --- /dev/null +++ b/0500-keyboard-row.js @@ -0,0 +1,22 @@ +/** + * 500. Keyboard Row + * https://leetcode.com/problems/keyboard-row/ + * Difficulty: Easy + * + * Given an array of strings words, return the words that can be typed using letters + * of the alphabet on only one row of American keyboard like the image below. + * + * In the American keyboard: + * - the first row consists of the characters "qwertyuiop", + * - the second row consists of the characters "asdfghjkl", and + * - the third row consists of the characters "zxcvbnm". + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var findWords = function(words) { + const rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']; + return words.filter(word => rows.some(row => word.toLowerCase().split('').every(s => row.includes(s)))); +}; diff --git a/README.md b/README.md index 2d436b01..2ad3918c 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From 3e05e3f79f53b17968e131539e42d9416c688b43 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:40:04 -0500 Subject: [PATCH 200/485] Add solution #1935 --- 1935-maximum-number-of-words-you-can-type.js | 25 ++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1935-maximum-number-of-words-you-can-type.js diff --git a/1935-maximum-number-of-words-you-can-type.js b/1935-maximum-number-of-words-you-can-type.js new file mode 100644 index 00000000..5f530a5b --- /dev/null +++ b/1935-maximum-number-of-words-you-can-type.js @@ -0,0 +1,25 @@ +/** + * 1935. Maximum Number of Words You Can Type + * https://leetcode.com/problems/maximum-number-of-words-you-can-type/ + * Difficulty: Easy + * + * There is a malfunctioning keyboard where some letter keys do not work. + * All other keys on the keyboard work properly. + * + * Given a string text of words separated by a single space (no leading or + * trailing spaces) and a string brokenLetters of all distinct letter keys + * that are broken, return the number of words in text you can fully type + * using this keyboard. + */ + +/** + * @param {string} text + * @param {string} brokenLetters + * @return {number} + */ +var canBeTypedWords = function(text, brokenLetters) { + return text + .split(/\s+/) + .filter(word => !brokenLetters.split('').some(s => word.includes(s))) + .length; +}; diff --git a/README.md b/README.md index 2ad3918c..270c1013 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,7 @@ 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| +1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| From fe362a8a04af7eccf961319f5e7ceeeaf654bc54 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 15:44:08 -0500 Subject: [PATCH 201/485] Add solution #1668 --- 1668-maximum-repeating-substring.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1668-maximum-repeating-substring.js diff --git a/1668-maximum-repeating-substring.js b/1668-maximum-repeating-substring.js new file mode 100644 index 00000000..d08ce8bf --- /dev/null +++ b/1668-maximum-repeating-substring.js @@ -0,0 +1,24 @@ +/** + * 1668. Maximum Repeating Substring + * https://leetcode.com/problems/maximum-repeating-substring/ + * Difficulty: Easy + * + * For a string sequence, a string word is k-repeating if word concatenated k times is a substring + * of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating + * in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. + * + * Given strings sequence and word, return the maximum k-repeating value of word in sequence. + */ + +/** + * @param {string} sequence + * @param {string} word + * @return {number} + */ +var maxRepeating = function(sequence, word) { + let count = Math.floor(sequence.length / word.length) + 1; + while (--count) { + if (sequence.includes(word.repeat(count))) return count; + } + return count; +}; diff --git a/README.md b/README.md index 270c1013..01e94833 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| +1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From a67b067d1135d47614964f6549c167376a9ee60d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 16:06:32 -0500 Subject: [PATCH 202/485] Add solution #1566 --- ...rn-of-length-m-repeated-k-or-more-times.js | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1566-detect-pattern-of-length-m-repeated-k-or-more-times.js diff --git a/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js b/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js new file mode 100644 index 00000000..cd92cd8d --- /dev/null +++ b/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js @@ -0,0 +1,28 @@ +/** + * 1566. Detect Pattern of Length M Repeated K or More Times + * https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/ + * Difficulty: Easy + * + * Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. + * + * A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple + * times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. + * + * Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. + */ + +/** + * @param {number[]} arr + * @param {number} m + * @param {number} k + * @return {boolean} + */ +var containsPattern = function(arr, m, k) { + for (let i = 0; i < arr.length - m + 1; i++) { + const pattern = new Array(k).fill(arr.slice(i, i + m).join()).join(); + if (arr.join().includes(pattern)) { + return true; + } + } + return false; +}; diff --git a/README.md b/README.md index 01e94833..05569919 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,7 @@ 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| +1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 56bb1d77d1ab7e54f4bf4e8e807336cd25195519 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 17:56:57 -0500 Subject: [PATCH 203/485] Add solution #476 --- 0476-number-complement.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0476-number-complement.js diff --git a/0476-number-complement.js b/0476-number-complement.js new file mode 100644 index 00000000..2cb0135c --- /dev/null +++ b/0476-number-complement.js @@ -0,0 +1,21 @@ +/** + * 476. Number Complement + * https://leetcode.com/problems/number-complement/ + * Difficulty: Easy + * + * The complement of an integer is the integer you get when you flip all the 0's to 1's + * and all the 1's to 0's in its binary representation. + * + * For example, The integer 5 is "101" in binary and its complement is "010" which is + * the integer 2. + * + * Given an integer num, return its complement. + */ + +/** + * @param {number} num + * @return {number} + */ +var findComplement = function(num) { + return parseInt(num.toString(2).split('').map(n => 1 - n).join(''), 2); +}; diff --git a/README.md b/README.md index 05569919..19361219 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| From 052ad7502597617c9c98802e9cb55d2d5ef41b74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 19:49:16 -0500 Subject: [PATCH 204/485] Add solution #19 --- 0019-remove-nth-node-from-end-of-list.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0019-remove-nth-node-from-end-of-list.js diff --git a/0019-remove-nth-node-from-end-of-list.js b/0019-remove-nth-node-from-end-of-list.js new file mode 100644 index 00000000..1e133150 --- /dev/null +++ b/0019-remove-nth-node-from-end-of-list.js @@ -0,0 +1,40 @@ +/** + * 19. Remove Nth Node From End of List + * https://leetcode.com/problems/remove-nth-node-from-end-of-list/ + * Difficulty: Medium + * + * Given the head of a linked list, remove the nth node from the end of the list + * and return its head. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function(head, n) { + const result = new ListNode(); + let slow = result; + let fast = result; + slow.next = head; + + for (let i = 0; i <= n; i++) { + fast = fast.next; + } + + while (fast) { + fast = fast.next; + slow = slow.next; + } + + slow.next = slow.next.next; + + return result.next; +}; diff --git a/README.md b/README.md index 19361219..d54219ee 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From 105fa39262d2248a1947744eda5ad366a94a13d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 20:02:53 -0500 Subject: [PATCH 205/485] Add solution #22 --- 0022-generate-parentheses.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0022-generate-parentheses.js diff --git a/0022-generate-parentheses.js b/0022-generate-parentheses.js new file mode 100644 index 00000000..d3264697 --- /dev/null +++ b/0022-generate-parentheses.js @@ -0,0 +1,28 @@ +/** + * 22. Generate Parentheses + * https://leetcode.com/problems/generate-parentheses/ + * Difficulty: Medium + * + * Given n pairs of parentheses, write a function to generate all combinations of + * well-formed parentheses. + */ + +/** + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function(n) { + const result = []; + backtrack(result, '', 0, 0, n); + return result; +}; + +function backtrack(result, str, open, close, max) { + if (str.length == max * 2){ + result.push(str); + return; + } + + if (open < max) backtrack(result, `${str}(`, open + 1, close, max); + if (close < open) backtrack(result, `${str})`, open, close + 1, max); +} diff --git a/README.md b/README.md index d54219ee..7cbc7df1 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| +22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From cc373f1be9c54fb3a3cec61815b1ed9bddec5373 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 20:16:37 -0500 Subject: [PATCH 206/485] Add solution #98 --- 0098-validate-binary-search-tree.js | 40 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0098-validate-binary-search-tree.js diff --git a/0098-validate-binary-search-tree.js b/0098-validate-binary-search-tree.js new file mode 100644 index 00000000..73c8d164 --- /dev/null +++ b/0098-validate-binary-search-tree.js @@ -0,0 +1,40 @@ +/** + * 98. Validate Binary Search Tree + * https://leetcode.com/problems/validate-binary-search-tree/ + * Difficulty: Medium + * + * Given the root of a binary tree, determine if it is a valid binary search tree (BST). + * + * A valid BST is defined as follows: + * - The left subtree of a node contains only nodes with keys less than the node's key. + * - The right subtree of a node contains only nodes with keys greater than the node's key. + * - Both the left and right subtrees must also be binary search trees. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function(root) { + return traverse(root, null, null); +}; + +function traverse(root, min, max) { + if (!root) { + return true; + } + + if ((min !== null && root.val <= min) || (max !== null && root.val >= max)) { + return false; + } + + return traverse(root.left, min, root.val) && traverse(root.right, root.val, max); +} diff --git a/README.md b/README.md index 7cbc7df1..e2f85ad4 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| From a6226c175aaebf1fe99fa5087258b9e02f6e2f9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 20:32:33 -0500 Subject: [PATCH 207/485] Add solution #24 --- 0024-swap-nodes-in-pairs.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0024-swap-nodes-in-pairs.js diff --git a/0024-swap-nodes-in-pairs.js b/0024-swap-nodes-in-pairs.js new file mode 100644 index 00000000..39a27600 --- /dev/null +++ b/0024-swap-nodes-in-pairs.js @@ -0,0 +1,31 @@ +/** + * 24. Swap Nodes in Pairs + * https://leetcode.com/problems/swap-nodes-in-pairs/ + * Difficulty: Medium + * + * 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.) + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + if (!head || !head.next) return head; + + const result = head.next; + head.next = result.next; + result.next = head; + head.next = swapPairs(head.next); + + return result; +}; diff --git a/README.md b/README.md index e2f85ad4..892d90f9 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| +24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From 7c1875662ce21ad0c9a6f568f92fa4cd9adb6e5a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Dec 2021 20:50:36 -0500 Subject: [PATCH 208/485] Add solution #128 --- 0128-longest-consecutive-sequence.js | 31 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0128-longest-consecutive-sequence.js diff --git a/0128-longest-consecutive-sequence.js b/0128-longest-consecutive-sequence.js new file mode 100644 index 00000000..b72a6fe5 --- /dev/null +++ b/0128-longest-consecutive-sequence.js @@ -0,0 +1,31 @@ +/** + * 128. Longest Consecutive Sequence + * https://leetcode.com/problems/longest-consecutive-sequence/ + * Difficulty: Medium + * + * Given an unsorted array of integers nums, return the length of the + * longest consecutive elements sequence. + * + * You must write an algorithm that runs in O(n) time. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function(nums) { + const set = new Set(nums); + let result = 0; + + for (let i = 0; i < nums.length; i++) { + if (!set.has(nums[i] - 1)) { + let streak = 1; + while (set.has(nums[i] + streak)) { + streak++; + } + result = Math.max(result, streak); + } + } + + return result; +}; diff --git a/README.md b/README.md index 892d90f9..180bb46d 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| From 390f9d78949719f6b6d4c3796afee6765c6fc60b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Dec 2021 21:28:05 -0500 Subject: [PATCH 209/485] Add solution #169 --- 0169-majority-element.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0169-majority-element.js diff --git a/0169-majority-element.js b/0169-majority-element.js new file mode 100644 index 00000000..bad659bd --- /dev/null +++ b/0169-majority-element.js @@ -0,0 +1,22 @@ +/** + * 169. Majority Element + * https://leetcode.com/problems/majority-element/ + * Difficulty: Easy + * + * Given an array nums of size n, return the majority element. + * + * The majority element is the element that appears more than ⌊n / 2⌋ times. + * You may assume that the majority element always exists in the array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var majorityElement = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + const sorted = [...map].sort(([,a], [,b]) => b - a); + return sorted[0][0]; +}; diff --git a/README.md b/README.md index 180bb46d..2923d6d0 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| From 9d8bf8a8f0a421df49792bab990e317c6da3a5e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Dec 2021 21:36:47 -0500 Subject: [PATCH 210/485] Add solution #229 --- 0229-majority-element-ii.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0229-majority-element-ii.js diff --git a/0229-majority-element-ii.js b/0229-majority-element-ii.js new file mode 100644 index 00000000..f3ce6493 --- /dev/null +++ b/0229-majority-element-ii.js @@ -0,0 +1,20 @@ +/** + * 229. Majority Element II + * https://leetcode.com/problems/majority-element-ii/ + * Difficulty: Medium + * + * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var majorityElement = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + return [...map] + .filter(([key, value]) => value > nums.length / 3) + .map(([key]) => key); +}; diff --git a/README.md b/README.md index 2923d6d0..1c6aea68 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +229|[Majority Element II](./0229-majority-element-ii.js)|Medium| 231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| From 43bc233e57eb6efb310e0361f79f6cf8ac7f2b5e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 17:28:12 -0500 Subject: [PATCH 211/485] Add solution #33 --- 0033-search-in-rotated-sorted-array.js | 44 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0033-search-in-rotated-sorted-array.js diff --git a/0033-search-in-rotated-sorted-array.js b/0033-search-in-rotated-sorted-array.js new file mode 100644 index 00000000..632b7e3c --- /dev/null +++ b/0033-search-in-rotated-sorted-array.js @@ -0,0 +1,44 @@ +/** + * 33. Search in Rotated Sorted Array + * https://leetcode.com/problems/search-in-rotated-sorted-array/ + * Difficulty: Medium + * + * There is an integer array nums sorted in ascending order (with distinct values). + * + * Prior to being passed to your function, nums is possibly rotated at an unknown pivot + * index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], + * ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] + * might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. + * + * Given the array nums after the possible rotation and an integer target, return the index + * of target if it is in nums, or -1 if it is not in nums. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + let start = 0; + let end = nums.length; + + while (start < end) { + const i = Math.floor((start + end) / 2); + const middle = nums[i] < nums[0] === target < nums[0] + ? nums[i] + : target < nums[0] ? -Infinity : Infinity; + + if (middle < target) { + start = i + 1; + } else if (middle > target) { + end = i; + } else { + return i; + } + } + + return -1; +}; diff --git a/README.md b/README.md index 1c6aea68..908369b4 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| +33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| From 1ff72319ea2ebd2e0188b9478c9f85aa3089f4e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 17:46:41 -0500 Subject: [PATCH 212/485] Add solution #35 --- 0035-search-insert-position.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0035-search-insert-position.js diff --git a/0035-search-insert-position.js b/0035-search-insert-position.js new file mode 100644 index 00000000..bb8fe77a --- /dev/null +++ b/0035-search-insert-position.js @@ -0,0 +1,32 @@ +/** + * 35. Search Insert Position + * https://leetcode.com/problems/search-insert-position/ + * Difficulty: Easy + * + * Given a sorted array of distinct integers and a target value, return the + * index if the target is found. If not, return the index where it would be + * if it were inserted in order. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var searchInsert = function(nums, target) { + let start = 0; + let end = nums.length - 1; + + while (start <= end) { + const middle = Math.floor((start + end) / 2); + if (target > nums[middle]) { + start = middle + 1; + } else { + end = middle - 1; + } + } + + return start; +}; diff --git a/README.md b/README.md index 908369b4..53606f99 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| +35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| From 8b3539560319c47af83f68bfbc77744bb1f4184b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 17:57:06 -0500 Subject: [PATCH 213/485] Add solution #34 --- ...ast-position-of-element-in-sorted-array.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0034-find-first-and-last-position-of-element-in-sorted-array.js diff --git a/0034-find-first-and-last-position-of-element-in-sorted-array.js b/0034-find-first-and-last-position-of-element-in-sorted-array.js new file mode 100644 index 00000000..11d61353 --- /dev/null +++ b/0034-find-first-and-last-position-of-element-in-sorted-array.js @@ -0,0 +1,40 @@ +/** + * 34. Find First and Last Position of Element in Sorted Array + * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ + * Difficulty: Medium + * + * Given an array of integers nums sorted in non-decreasing order, find the starting and + * ending position of a given target value. + * + * If target is not found in the array, return [-1, -1]. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var searchRange = function(nums, target) { + let start = 0; + let end = nums.length - 1; + + while (start <= end) { + const middle = Math.floor((start + end) / 2); + if (target > nums[middle]) { + start = middle + 1; + } else { + end = middle - 1; + } + } + + if (nums[start] !== target) { + return [-1, -1]; + } + + while (nums[start - 1] === target) start--; + while (nums[end + 1] === target) end++; + + return [start, end]; +}; diff --git a/README.md b/README.md index 53606f99..b092a0eb 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| +34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| From b4c51d54094d399f25173299b677ffde4db38336 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 18:11:11 -0500 Subject: [PATCH 214/485] Add solution #116 --- ...lating-next-right-pointers-in-each-node.js | 50 +++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0116-populating-next-right-pointers-in-each-node.js diff --git a/0116-populating-next-right-pointers-in-each-node.js b/0116-populating-next-right-pointers-in-each-node.js new file mode 100644 index 00000000..a6efdcbc --- /dev/null +++ b/0116-populating-next-right-pointers-in-each-node.js @@ -0,0 +1,50 @@ +/** + * 116. Populating Next Right Pointers in Each Node + * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ + * Difficulty: Medium + * + * You are given a perfect binary tree where all leaves are on the same level, and + * every parent has two children. The binary tree has the following definition: + * + * Populate each next pointer to point to its next right node. If there is no next + * right node, the next pointer should be set to NULL. + * + * Initially, all next pointers are set to NULL. + */ + +/** + * // Definition for a Node. + * function Node(val, left, right, next) { + * this.val = val === undefined ? null : val; + * this.left = left === undefined ? null : left; + * this.right = right === undefined ? null : right; + * this.next = next === undefined ? null : next; + * }; + */ + +/** + * @param {Node} root + * @return {Node} + */ +var connect = function(root) { + const order = []; + traverse(order, root); + for (let level of order) { + for (let i = 0; i < level.length - 1; i++) { + level[i].next = level[i + 1]; + } + } + return root; +}; + +function traverse(order, node, level = 0) { + if (!node) { + return []; + } + + order[level] = order[level] || []; + order[level].push(node); + + traverse(order, node.left, level + 1); + traverse(order, node.right, level + 1); +} diff --git a/README.md b/README.md index b092a0eb..edc3267b 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| +116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From b72f110b67f007c0f148cd3bc8d812c2d92cb35d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 18:37:56 -0500 Subject: [PATCH 215/485] Add solution #29 --- 0029-divide-two-integers.js | 46 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0029-divide-two-integers.js diff --git a/0029-divide-two-integers.js b/0029-divide-two-integers.js new file mode 100644 index 00000000..babc4531 --- /dev/null +++ b/0029-divide-two-integers.js @@ -0,0 +1,46 @@ +/** + * 29. Divide Two Integers + * https://leetcode.com/problems/divide-two-integers/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number} dividend + * @param {number} divisor + * @return {number} + */ +var divide = function(dividend, divisor) { + if (divisor === -1 && dividend === Math.pow(-2, 31)) { + return Math.pow(2, 31) - 1; + } + const isNegative = dividend > 0 ^ divisor > 0; + let result = 0; + + dividend = Math.abs(dividend); + subtract(Math.abs(divisor), 1); + + function subtract(n, quotient) { + if (dividend > n) { + subtract(n * 2, quotient * 2); + } + if (dividend >= n) { + dividend -= n; + result += quotient; + } + } + + return isNegative ? -result : result; +}; diff --git a/README.md b/README.md index edc3267b..0a494d43 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| +29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| From 1c0851f953725dcaaa452107650755d1fe26b926 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 19:07:11 -0500 Subject: [PATCH 216/485] Add solution #23 --- 0023-merge-k-sorted-lists.js | 43 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0023-merge-k-sorted-lists.js diff --git a/0023-merge-k-sorted-lists.js b/0023-merge-k-sorted-lists.js new file mode 100644 index 00000000..2586988c --- /dev/null +++ b/0023-merge-k-sorted-lists.js @@ -0,0 +1,43 @@ +/** + * 23. Merge k Sorted Lists + * https://leetcode.com/problems/merge-k-sorted-lists/ + * Difficulty: Hard + * + * 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. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode[]} lists + * @return {ListNode} + */ +var mergeKLists = function(lists) { + const map = new Map(); + for (let list of lists) { + while (list) { + map.set(list.val, (map.get(list.val) || 0) + 1); + list = list.next; + } + } + const sorted = [...map].sort(([a], [b]) => a - b); + const result = new ListNode(); + let tail = result; + + for (let [key, value] of sorted) { + while (value--) { + tail.next = new ListNode(key); + tail = tail.next; + } + } + + return result.next; +}; diff --git a/README.md b/README.md index 0a494d43..3bbd5678 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| +23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard| 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| From 4e202ba69daa083cddab3c9f5eba0cfaa2e9bdeb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 19:22:16 -0500 Subject: [PATCH 217/485] Add solution #26 --- 0026-remove-duplicates-from-sorted-array.js | 34 +++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0026-remove-duplicates-from-sorted-array.js diff --git a/0026-remove-duplicates-from-sorted-array.js b/0026-remove-duplicates-from-sorted-array.js new file mode 100644 index 00000000..326d46ef --- /dev/null +++ b/0026-remove-duplicates-from-sorted-array.js @@ -0,0 +1,34 @@ +/** + * 26. Remove Duplicates from Sorted Array + * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ + * Difficulty: Easy + * + * Given an integer array nums sorted in non-decreasing order, remove the + * duplicates in-place such that each unique element appears only once. + * The relative order of the elements should be kept the same. + * + * Since it is impossible to change the length of the array in some languages, + * you must instead have the result be placed in the first part of the array + * nums. More formally, if there are k elements after removing the duplicates, + * then the first k elements of nums should hold the final result. It does not + * matter what you leave beyond the first k elements. + * + * Return k after placing the final result in the first k slots of nums. + * + * Do not allocate extra space for another array. You must do this by modifying + * the input array in-place with O(1) extra memory. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function(nums) { + let i = 0; + for (let j = 0; j < nums.length; j++) { + if (nums[i] !== nums[j]) { + nums[++i] = nums[j]; + } + } + return ++i; +}; diff --git a/README.md b/README.md index 3bbd5678..f073be28 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| 23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard| 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| +26|[Remove Duplicates from Sorted Array](./0026-remove-duplicates-from-sorted-array.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| From 60af415555e671863371b6c504bc7097fcdcd1f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Dec 2021 19:03:55 -0500 Subject: [PATCH 218/485] Add solution #506 --- 0506-relative-ranks.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0506-relative-ranks.js diff --git a/0506-relative-ranks.js b/0506-relative-ranks.js new file mode 100644 index 00000000..1ee77ce5 --- /dev/null +++ b/0506-relative-ranks.js @@ -0,0 +1,38 @@ +/** + * 506. Relative Ranks + * https://leetcode.com/problems/relative-ranks/ + * Difficulty: Easy + * + * You are given an integer array score of size n, where score[i] is the score of the ith + * athlete in a competition. All the scores are guaranteed to be unique. + * + * The athletes are placed based on their scores, where the 1st place athlete has the highest + * score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each + * athlete determines their rank: + * - The 1st place athlete's rank is "Gold Medal". + * - The 2nd place athlete's rank is "Silver Medal". + * - The 3rd place athlete's rank is "Bronze Medal". + * - For the 4th place to the nth place athlete, their rank is their placement number + * (i.e., the xth place athlete's rank is "x"). + * + * Return an array answer of size n where answer[i] is the rank of the ith athlete. + */ + +/** + * @param {number[]} score + * @return {string[]} + */ +var findRelativeRanks = function(score) { + const PLACEMENTS = ['Gold Medal', 'Silver Medal', 'Bronze Medal']; + const map = new Map(); + score.forEach((rank, index) => map.set(rank, index)); + + const result = score.slice(); + const sorted = [...map].sort(([a], [b]) => b - a); + + sorted.forEach(([_, index], rank) => { + result[index] = PLACEMENTS[rank] || `${rank + 1}`; + }); + + return result; +}; diff --git a/README.md b/README.md index f073be28..6081d26c 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| +506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From 36395acb4824fb08c1cdacb0f5d66a58ec1a7d7b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 13:46:34 -0500 Subject: [PATCH 219/485] Add solution #46 --- 0046-permutations.js | 32 ++++++++++++++++++++++++++++++++ README.md | 3 ++- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 0046-permutations.js diff --git a/0046-permutations.js b/0046-permutations.js new file mode 100644 index 00000000..ca0a39a4 --- /dev/null +++ b/0046-permutations.js @@ -0,0 +1,32 @@ +/** + * 46. Permutations + * https://leetcode.com/problems/permutations/ + * Difficulty: Medium + * + * Given an array nums of distinct integers, return all the possible permutations. + * You can return the answer in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function(nums) { + const result = []; + backtrack(result, nums); + return result; +}; + +function backtrack(result, nums, order = []) { + if (!nums.length) { + result.push(order); + } else { + for (let i = 0; i < nums.length; i++) { + backtrack( + result, + [...nums.slice(0, i), ...nums.slice(i + 1)], + [...order, nums[i]] + ); + } + } +} diff --git a/README.md b/README.md index 6081d26c..1926e941 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +46|[Permutations](./0046-permutations.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| @@ -216,4 +217,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2021 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2022 [Josh Crozier](https://joshcrozier.com) From 914458b593464e15c2c976a65fd41c3c4213053e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 13:58:20 -0500 Subject: [PATCH 220/485] Add solution #2011 --- ...of-variable-after-performing-operations.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2011-final-value-of-variable-after-performing-operations.js diff --git a/2011-final-value-of-variable-after-performing-operations.js b/2011-final-value-of-variable-after-performing-operations.js new file mode 100644 index 00000000..08743e60 --- /dev/null +++ b/2011-final-value-of-variable-after-performing-operations.js @@ -0,0 +1,24 @@ +/** + * 2011. Final Value of Variable After Performing Operations + * https://leetcode.com/problems/final-value-of-variable-after-performing-operations/ + * Difficulty: Easy + * + * There is a programming language with only four operations and one variable X: + * - ++X and X++ increments the value of the variable X by 1. + * - --X and X-- decrements the value of the variable X by 1. + * + * Initially, the value of X is 0. + * + * Given an array of strings operations containing a list of operations, return the + * final value of X after performing all the operations. + */ + +/** + * @param {string[]} operations + * @return {number} + */ +var finalValueAfterOperations = function(operations) { + return operations + .map(n => n.includes('++') ? 1 : -1) + .reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 1926e941..a3c92b98 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,7 @@ 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| +2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| ## License From b5525c15d8675fba6e7677433be4315b1f6dd6ad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 14:01:41 -0500 Subject: [PATCH 221/485] Add solution #1672 --- 1672-richest-customer-wealth.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 1672-richest-customer-wealth.js diff --git a/1672-richest-customer-wealth.js b/1672-richest-customer-wealth.js new file mode 100644 index 00000000..c0f89318 --- /dev/null +++ b/1672-richest-customer-wealth.js @@ -0,0 +1,20 @@ +/** + * 1672. Richest Customer Wealth + * https://leetcode.com/problems/richest-customer-wealth/ + * Difficulty: Easy + * + * You are given an m x n integer grid accounts where accounts[i][j] is the + * amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth + * that the richest customer has. + * + * A customer's wealth is the amount of money they have in all their bank + * accounts. The richest customer is the customer that has the maximum wealth. + */ + +/** + * @param {number[][]} accounts + * @return {number} + */ +var maximumWealth = function(accounts) { + return Math.max(...accounts.map(account => account.reduce((sum, n) => sum + n), 0)); +}; diff --git a/README.md b/README.md index a3c92b98..38f7ccc2 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,7 @@ 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| +1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From 09f82eb1a19f031705821aef400a0901197e02f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 14:21:34 -0500 Subject: [PATCH 222/485] Add solution #1431 --- ...ids-with-the-greatest-number-of-candies.js | 25 +++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1431-kids-with-the-greatest-number-of-candies.js diff --git a/1431-kids-with-the-greatest-number-of-candies.js b/1431-kids-with-the-greatest-number-of-candies.js new file mode 100644 index 00000000..f24b577f --- /dev/null +++ b/1431-kids-with-the-greatest-number-of-candies.js @@ -0,0 +1,25 @@ +/** + * 1431. Kids With the Greatest Number of Candies + * https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ + * Difficulty: Easy + * + * There are n kids with candies. You are given an integer array candies, where each + * candies[i] represents the number of candies the ith kid has, and an integer + * extraCandies, denoting the number of extra candies that you have. + * + * Return a boolean array result of length n, where result[i] is true if, after giving + * the ith kid all the extraCandies, they will have the greatest number of candies + * among all the kids, or false otherwise. + * + * Note that multiple kids can have the greatest number of candies. + */ + +/** + * @param {number[]} candies + * @param {number} extraCandies + * @return {boolean[]} + */ +var kidsWithCandies = function(candies, extraCandies) { + const max = Math.max(...candies); + return candies.map(count => count + extraCandies >= max); +}; diff --git a/README.md b/README.md index 38f7ccc2..7a8590b9 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ 1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| +1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| From 8cc5309423d3b3f6e2a443ce1f02241a481ea099 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Jan 2022 14:08:20 -0500 Subject: [PATCH 223/485] Add solution #25 --- 0025-reverse-nodes-in-k-group.js | 49 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0025-reverse-nodes-in-k-group.js diff --git a/0025-reverse-nodes-in-k-group.js b/0025-reverse-nodes-in-k-group.js new file mode 100644 index 00000000..8ac3e662 --- /dev/null +++ b/0025-reverse-nodes-in-k-group.js @@ -0,0 +1,49 @@ +/** + * 25. Reverse Nodes in k-Group + * https://leetcode.com/problems/reverse-nodes-in-k-group/ + * Difficulty: Hard + * + * Given the head of a linked list, reverse the nodes of the list k at a time, + * and return the modified list. + * + * k is a positive integer and is less than or equal to the length of the linked + * list. If the number of nodes is not a multiple of k then left-out nodes, in + * the end, should remain as it is. + * + * You may not alter the values in the list's nodes, only nodes themselves may + * be changed. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var reverseKGroup = function(head, k) { + const result = new ListNode(null, head); + const stack = []; + let tail = result; + + while (head) { + for (let i = 0; i < k && head; i++) { + stack.push(head); + head = head.next; + } + if (stack.length === k) { + while (stack.length) { + tail.next = stack.pop(); + tail = tail.next; + } + tail.next = head; + } + } + + return result.next; +}; diff --git a/README.md b/README.md index 7a8590b9..04d357b1 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| 23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard| 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| +25|[Reverse Nodes in k-Group](./0025-reverse-nodes-in-k-group.js)|Hard| 26|[Remove Duplicates from Sorted Array](./0026-remove-duplicates-from-sorted-array.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| From a158e7b3a9f0d51d820b05dde14244c73cb6deb3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Jan 2022 18:08:10 -0500 Subject: [PATCH 224/485] Add solution #2047 --- 2047-number-of-valid-words-in-a-sentence.js | 31 +++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2047-number-of-valid-words-in-a-sentence.js diff --git a/2047-number-of-valid-words-in-a-sentence.js b/2047-number-of-valid-words-in-a-sentence.js new file mode 100644 index 00000000..f19c7734 --- /dev/null +++ b/2047-number-of-valid-words-in-a-sentence.js @@ -0,0 +1,31 @@ +/** + * 2047. Number of Valid Words in a Sentence + * https://leetcode.com/problems/number-of-valid-words-in-a-sentence/ + * Difficulty: Easy + * + * A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), + * hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. + * Each sentence can be broken down into one or more tokens separated by one or + * more spaces ' '. + * + * A token is a valid word if all three of the following are true: + * - It only contains lowercase letters, hyphens, and/or punctuation (no digits). + * - There is at most one hyphen '-'. If present, it must be surrounded by lowercase + * characters ("a-b" is valid, but "-ab" and "ab-" are not valid). + * - There is at most one punctuation mark. If present, it must be at the end of + * the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid). + * + * Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!". + * + * Given a string sentence, return the number of valid words in sentence. + */ + +/** + * @param {string} sentence + * @return {number} + */ +var countValidWords = function(sentence) { + return sentence.trim().split(/\s+/).reduce((total, str) => { + return total + (/^(?:([a-z]+\-?[a-z]+)|([a-z+]))?[!.,]?$/.test(str) ? 1 : 0); + }, 0); +}; diff --git a/README.md b/README.md index 04d357b1..40f93aa3 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| +2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| ## License From 61ec3976ca3654f83d97443134963922c6cf7d5b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Jan 2022 18:11:06 -0500 Subject: [PATCH 225/485] Add solution #1996 --- ...e-number-of-weak-characters-in-the-game.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1996-the-number-of-weak-characters-in-the-game.js diff --git a/1996-the-number-of-weak-characters-in-the-game.js b/1996-the-number-of-weak-characters-in-the-game.js new file mode 100644 index 00000000..bbf5b54d --- /dev/null +++ b/1996-the-number-of-weak-characters-in-the-game.js @@ -0,0 +1,35 @@ +/** + * 1996. The Number of Weak Characters in the Game + * https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/ + * Difficulty: Medium + * + * You are playing a game that contains multiple characters, and each of the + * characters has two main properties: attack and defense. You are given a 2D + * integer array properties where properties[i] = [attacki, defensei] represents + * the properties of the ith character in the game. + * + * A character is said to be weak if any other character has both attack and + * defense levels strictly greater than this character's attack and defense levels. + * More formally, a character i is said to be weak if there exists another character + * j where attackj > attacki and defensej > defensei. + * + * Return the number of weak characters. + */ + +/** + * @param {number[][]} properties + * @return {number} + */ +var numberOfWeakCharacters = function(properties) { + let result = 0; + let max = 0; + + properties.sort((a, b) => (b[0] === a[0]) ? a[1] - b[1] : b[0] - a[0]); + + for (let i = 0; i < properties.length; i++) { + if (properties[i][1] < max) result++; + max = Math.max(max, properties[i][1]); + } + + return result; +}; diff --git a/README.md b/README.md index 40f93aa3..668d062f 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,7 @@ 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| +1996|[The Number of Weak Characters in the Game](./1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| From a0fc36fafb29f64424b55804ebbc31cac242b541 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Jan 2022 19:02:08 -0500 Subject: [PATCH 226/485] Add solution #1010 --- ...gs-with-total-durations-divisible-by-60.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1010-pairs-of-songs-with-total-durations-divisible-by-60.js diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60.js b/1010-pairs-of-songs-with-total-durations-divisible-by-60.js new file mode 100644 index 00000000..7f4ef23d --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60.js @@ -0,0 +1,24 @@ +/** + * 1010. Pairs of Songs With Total Durations Divisible by 60 + * https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ + * Difficulty: Medium + * + * You are given a list of songs where the ith song has a duration of time[i] seconds. + * + * Return the number of pairs of songs for which their total duration in seconds is + * divisible by 60. Formally, we want the number of indices i, j such that i < j with + * (time[i] + time[j]) % 60 == 0. + */ + +/** + * @param {number[]} time + * @return {number} + */ +var numPairsDivisibleBy60 = function(time) { + const mods = new Array(60).fill(0); + return time.reduce((sum, t) => { + sum += mods[(60 - t % 60) % 60]; + mods[t % 60]++; + return sum; + }, 0); +}; diff --git a/README.md b/README.md index 668d062f..aee23be5 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,7 @@ 985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| +1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| From eb6c4e02ce60e814146b7bdc401826cee21a9e33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Jan 2022 19:03:29 -0500 Subject: [PATCH 227/485] Add solution #1920 --- 1920-build-array-from-permutation.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1920-build-array-from-permutation.js diff --git a/1920-build-array-from-permutation.js b/1920-build-array-from-permutation.js new file mode 100644 index 00000000..fff829fc --- /dev/null +++ b/1920-build-array-from-permutation.js @@ -0,0 +1,19 @@ +/** + * 1920. Build Array from Permutation + * https://leetcode.com/problems/build-array-from-permutation/ + * Difficulty: Easy + * + * Given a zero-based permutation nums (0-indexed), build an array ans of the same length + * where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. + * + * A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 + * (inclusive). + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var buildArray = function(nums) { + return nums.map(n => nums[n]); +}; diff --git a/README.md b/README.md index aee23be5..d147e737 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 1996|[The Number of Weak Characters in the Game](./1996-the-number-of-weak-characters-in-the-game.js)|Medium| From 6afb553486e7ce6eb6e4c58cfc23df876c8fe696 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Jan 2022 19:04:59 -0500 Subject: [PATCH 228/485] Add solution #997 --- 0997-find-the-town-judge.js | 36 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0997-find-the-town-judge.js diff --git a/0997-find-the-town-judge.js b/0997-find-the-town-judge.js new file mode 100644 index 00000000..c4c67847 --- /dev/null +++ b/0997-find-the-town-judge.js @@ -0,0 +1,36 @@ +/** + * 997. Find the Town Judge + * https://leetcode.com/problems/find-the-town-judge/ + * Difficulty: Easy + * + * In a town, there are n people labeled from 1 to n. There is a rumor that one of these + * people is secretly the town judge. + * + * If the town judge exists, then: + * - The town judge trusts nobody. + * - Everybody (except for the town judge) trusts the town judge. + * - There is exactly one person that satisfies properties 1 and 2. + * + * You are given an array trust where trust[i] = [ai, bi] representing that the person labeled + * ai trusts the person labeled bi. + * + * Return the label of the town judge if the town judge exists and can be identified, or return + * -1 otherwise. + */ + +/** + * @param {number} n + * @param {number[][]} trust + * @return {number} + */ +var findJudge = function(n, trust) { + if (!trust.length) { + return n === 1 ? n : -1; + } + + const map = new Map(); + trust.forEach(([_, value]) => map.set(value, (map.get(value) || 0 ) + 1)); + + const [judge, count] = [...map].sort(([,a], [,b]) => b - a)[0]; + return count === n - 1 && !trust.find(([key]) => key === judge) ? judge : -1; +}; diff --git a/README.md b/README.md index d147e737..0ae3c587 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| 985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| +997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| From 30925dbdfe31bcd97aa301efb275ade93b8b63b2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Jan 2022 21:08:51 -0500 Subject: [PATCH 229/485] Add solution #15 --- 0015-3sum.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0015-3sum.js diff --git a/0015-3sum.js b/0015-3sum.js new file mode 100644 index 00000000..a34d0eff --- /dev/null +++ b/0015-3sum.js @@ -0,0 +1,38 @@ +/** + * 15. 3Sum + * https://leetcode.com/problems/3sum/ + * Difficulty: Medium + * + * Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, + * i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. + * + * Notice that the solution set must not contain duplicate triplets. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function(nums) { + const result = new Set(); + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 2; i++) { + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + const sum = nums[i] + nums[j] + nums[k]; + if (!sum) { + result.add(JSON.stringify([nums[i], nums[j++], nums[k--]])); + } else if (sum > 0) { + k--; + } else { + j++; + } + } + } + + return [...result].map(JSON.parse); +}; diff --git a/README.md b/README.md index 0ae3c587..89d64579 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| +15|[3Sum](./0015-3sum.js)|Medium| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| From 8a9a4fa9dcf8d02c0f8ca5efed0226a74945b45d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Jan 2022 21:10:41 -0500 Subject: [PATCH 230/485] Add solution #16 --- 0016-3sum-closest.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0016-3sum-closest.js diff --git a/0016-3sum-closest.js b/0016-3sum-closest.js new file mode 100644 index 00000000..a4fd4941 --- /dev/null +++ b/0016-3sum-closest.js @@ -0,0 +1,40 @@ +/** + * 16. 3Sum Closest + * https://leetcode.com/problems/3sum-closest/ + * Difficulty: Medium + * + * Given an integer array nums of length n and an integer target, find three integers + * in nums such that the sum is closest to target. + * + * Return the sum of the three integers. + * + * You may assume that each input would have exactly one solution. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function(nums, target) { + const sums = new Set(); + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 2; i++) { + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + const sum = nums[i] + nums[j] + nums[k]; + sums.add(sum); + if (sum > target) { + k--; + } else { + j++; + } + } + } + + return [...sums].reduce((p, c) => Math.abs(c - target) < Math.abs(p - target) ? c : p); +}; diff --git a/README.md b/README.md index 89d64579..41adf850 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 15|[3Sum](./0015-3sum.js)|Medium| +16|[3Sum Closest](./0016-3sum-closest.js)|Medium| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| From 8ef01d770037c5fa15dbc479ae85b16c2495694c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Jan 2022 21:12:10 -0500 Subject: [PATCH 231/485] Add solution #167 --- 0167-two-sum-ii-input-array-is-sorted.js | 34 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0167-two-sum-ii-input-array-is-sorted.js diff --git a/0167-two-sum-ii-input-array-is-sorted.js b/0167-two-sum-ii-input-array-is-sorted.js new file mode 100644 index 00000000..848bacf7 --- /dev/null +++ b/0167-two-sum-ii-input-array-is-sorted.js @@ -0,0 +1,34 @@ +/** + * 167. Two Sum II - Input Array Is Sorted + * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ + * Difficulty: Easy + * + * Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, + * find two numbers such that they add up to a specific target number. Let these two numbers + * be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. + * + * Return the indices of the two numbers, index1 and index2, added by one as an integer array + * [index1, index2] of length 2. + * + * The tests are generated such that there is exactly one solution. You may not use the same + * element twice. + */ + +/** + * @param {number[]} numbers + * @param {number} target + * @return {number[]} + */ +var twoSum = function(numbers, target) { + const map = new Map(); + + for (let i = 0; i < numbers.length; i++) { + const diff = target - numbers[i]; + + if (map.has(diff)) { + return [map.get(diff) + 1, i + 1]; + } + + map.set(numbers[i], i); + } +}; diff --git a/README.md b/README.md index 41adf850..b9f6ef31 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| From 763b9b9f9624ba259c063681e6c45622a1703bb1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Jan 2022 21:51:57 -0500 Subject: [PATCH 232/485] Add solution #48 --- 0048-rotate-image.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0048-rotate-image.js diff --git a/0048-rotate-image.js b/0048-rotate-image.js new file mode 100644 index 00000000..f4312bd7 --- /dev/null +++ b/0048-rotate-image.js @@ -0,0 +1,27 @@ +/** + * 48. Rotate Image + * https://leetcode.com/problems/rotate-image/ + * Difficulty: Medium + * + * You are given an n x n 2D matrix representing an image, rotate the image by + * 90 degrees (clockwise). + * + * You have to rotate the image in-place, which means you have to modify the input + * 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + */ + +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var rotate = function(matrix) { + matrix = matrix.reverse(); + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < i; j++) { + [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; + } + } + + return matrix; +}; diff --git a/README.md b/README.md index b9f6ef31..edfe3b7d 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| +48|[Rotate Image](./0048-rotate-image.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| From b4e392e75a78178db93000d834cff7d773b1a9a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Jan 2022 21:53:12 -0500 Subject: [PATCH 233/485] Add solution #1886 --- ...ther-matrix-can-be-obtained-by-rotation.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1886-determine-whether-matrix-can-be-obtained-by-rotation.js diff --git a/1886-determine-whether-matrix-can-be-obtained-by-rotation.js b/1886-determine-whether-matrix-can-be-obtained-by-rotation.js new file mode 100644 index 00000000..2cfb38f0 --- /dev/null +++ b/1886-determine-whether-matrix-can-be-obtained-by-rotation.js @@ -0,0 +1,35 @@ +/** + * 1886. Determine Whether Matrix Can Be Obtained By Rotation + * https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/ + * Difficulty: Easy + * + * Given two n x n binary matrices mat and target, return true if it is possible to make mat + * equal to target by rotating mat in 90-degree increments, or false otherwise. + */ + +/** + * @param {number[][]} mat + * @param {number[][]} target + * @return {boolean} + */ +var findRotation = function(mat, target) { + const goal = JSON.stringify(target); + for (let i = 0; i < 4; i++) { + if (JSON.stringify(rotate(mat)) === goal) { + return true; + } + } + return false; +}; + +function rotate(matrix) { + matrix = matrix.reverse(); + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < i; j++) { + [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; + } + } + + return matrix; +} diff --git a/README.md b/README.md index edfe3b7d..a99d5113 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| From 0681b182e1979fe18db6098781a3db3a1b20979d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Jan 2022 21:53:53 -0500 Subject: [PATCH 234/485] Add solution #557 --- 0557-reverse-words-in-a-string-iii.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0557-reverse-words-in-a-string-iii.js diff --git a/0557-reverse-words-in-a-string-iii.js b/0557-reverse-words-in-a-string-iii.js new file mode 100644 index 00000000..60879f01 --- /dev/null +++ b/0557-reverse-words-in-a-string-iii.js @@ -0,0 +1,16 @@ +/** + * 557. Reverse Words in a String III + * https://leetcode.com/problems/reverse-words-in-a-string-iii/ + * Difficulty: Easy + * + * Given a string s, reverse the order of characters in each word within a sentence while + * still preserving whitespace and initial word order. + */ + +/** + * @param {string} str + * @return {string} + */ +var reverseWords = function(str) { + return str.split(/\s/).map(s => s.split('').reverse().join('')).join(' '); +}; diff --git a/README.md b/README.md index a99d5113..3a476b14 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| +557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From e729699df0068a471bd446215e5e365b739900e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Jan 2022 23:53:43 -0500 Subject: [PATCH 235/485] Add solution #2114 --- ...imum-number-of-words-found-in-sentences.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 2114-maximum-number-of-words-found-in-sentences.js diff --git a/2114-maximum-number-of-words-found-in-sentences.js b/2114-maximum-number-of-words-found-in-sentences.js new file mode 100644 index 00000000..b70c9f41 --- /dev/null +++ b/2114-maximum-number-of-words-found-in-sentences.js @@ -0,0 +1,19 @@ +/** + * 2114. Maximum Number of Words Found in Sentences + * https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/ + * Difficulty: Easy + * + * A sentence is a list of words that are separated by a single space with no leading or trailing spaces. + * + * You are given an array of strings sentences, where each sentences[i] represents a single sentence. + * + * Return the maximum number of words that appear in a single sentence. + */ + +/** + * @param {string[]} sentences + * @return {number} + */ +var mostWordsFound = function(sentences) { + return sentences.reduce((max, str) => Math.max(max, str.split(/\s+/).length), 0); +}; diff --git a/README.md b/README.md index 3a476b14..fe3496bd 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| +2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| ## License From ee08d2d63896762a42b684cc2179ad2926261e79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Jan 2022 23:54:43 -0500 Subject: [PATCH 236/485] Add solution #704 --- 0704-binary-search.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0704-binary-search.js diff --git a/0704-binary-search.js b/0704-binary-search.js new file mode 100644 index 00000000..a8cf2011 --- /dev/null +++ b/0704-binary-search.js @@ -0,0 +1,30 @@ +/** + * 704. Binary Search + * https://leetcode.com/problems/binary-search/ + * Difficulty: Easy + * + * Given an array of integers nums which is sorted in ascending order, and an + * integer target, write a function to search target in nums. If target exists, + * then return its index. Otherwise, return -1. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + let left = 0; + let right = nums.length - 1; + + while (left <= right) { + const pivot = Math.floor((right + left) / 2); + if (nums[pivot] === target) return pivot; + if (target < nums[pivot]) right = pivot - 1; + else left = pivot + 1; + } + + return -1; +}; diff --git a/README.md b/README.md index fe3496bd..76543635 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| +704|[Binary Search](./0704-binary-search.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 54feb207a0f6b42b013eb3184fd3091f77aafeb6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Jan 2022 23:57:01 -0500 Subject: [PATCH 237/485] Add solution #278 --- 0278-first-bad-version.js | 43 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0278-first-bad-version.js diff --git a/0278-first-bad-version.js b/0278-first-bad-version.js new file mode 100644 index 00000000..ca7b4599 --- /dev/null +++ b/0278-first-bad-version.js @@ -0,0 +1,43 @@ +/** + * 278. First Bad Version + * https://leetcode.com/problems/first-bad-version/ + * Difficulty: Medium + * + * You are a product manager and currently leading a team to develop a new product. + * Unfortunately, the latest version of your product fails the quality check. Since + * each version is developed based on the previous version, all the versions after + * a bad version are also bad. + * + * Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad + * one, which causes all the following ones to be bad. + * + * You are given an API bool isBadVersion(version) which returns whether version is + * bad. Implement a function to find the first bad version. You should minimize the + * number of calls to the API. + */ + +/** + * @param {function} isBadVersion() + * @return {function} + */ +var solution = function(isBadVersion) { + /** + * @param {integer} n Total versions + * @return {integer} The first bad version + */ + return n => { + let left = 1; + let right = n; + + while (left <= right) { + const pivot = Math.floor((right + left) / 2); + if (isBadVersion(pivot)) { + right = pivot - 1; + } else { + left = pivot + 1; + } + } + + return left; + }; +}; diff --git a/README.md b/README.md index 76543635..1534aa3e 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| +278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| From 7f39db36ae64bbc48c87a3e97109f84d8ad79d8b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Jan 2022 18:05:59 -0500 Subject: [PATCH 238/485] Add solution #567 --- 0567-permutation-in-string.js | 38 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0567-permutation-in-string.js diff --git a/0567-permutation-in-string.js b/0567-permutation-in-string.js new file mode 100644 index 00000000..20c61c88 --- /dev/null +++ b/0567-permutation-in-string.js @@ -0,0 +1,38 @@ +/** + * 567. Permutation in String + * https://leetcode.com/problems/permutation-in-string/ + * Difficulty: Medium + * + * Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. + * + * In other words, return true if one of s1's permutations is the substring of s2. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var checkInclusion = function(s1, s2) { + const getCharCode = c => c.charCodeAt() - 'a'.charCodeAt(); + const isMatch = (a1, a2) => a1.every((n, i) => a2[i] === n); + + if (s1.length > s2.length) { + return false; + } + + const map1 = new Array(26).fill(0); + const map2 = new Array(26).fill(0); + for (let i = 0; i < s1.length; i++) { + map1[getCharCode(s1[i])]++; + map2[getCharCode(s2[i])]++; + } + + for (let i = 0; i < s2.length - s1.length; i++) { + if (isMatch(map1, map2)) return true; + map2[getCharCode(s2[i + s1.length])]++; + map2[getCharCode(s2[i])]--; + } + + return isMatch(map1, map2); +}; diff --git a/README.md b/README.md index 1534aa3e..028e983e 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| +567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 1a7929dc6da80d29f5b63103346a31319f3fa540 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Jan 2022 18:07:40 -0500 Subject: [PATCH 239/485] Add solution #733 --- 0733-flood-fill.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0733-flood-fill.js diff --git a/0733-flood-fill.js b/0733-flood-fill.js new file mode 100644 index 00000000..58e04eb0 --- /dev/null +++ b/0733-flood-fill.js @@ -0,0 +1,38 @@ +/** + * 733. Flood Fill + * https://leetcode.com/problems/flood-fill/ + * Difficulty: Easy + * + * An image is represented by an m x n integer grid image where image[i][j] represents + * the pixel value of the image. + * + * You are also given three integers sr, sc, and newColor. You should perform a flood + * fill on the image starting from the pixel image[sr][sc]. + * + * To perform a flood fill, consider the starting pixel, plus any pixels connected + * 4-directionally to the starting pixel of the same color as the starting pixel, + * plus any pixels connected 4-directionally to those pixels (also with the same color), + * and so on. Replace the color of all of the aforementioned pixels with newColor. + * + * Return the modified image after performing the flood fill. + */ + +/** + * @param {number[][]} image + * @param {number} sr + * @param {number} sc + * @param {number} newColor + * @return {number[][]} + */ +var floodFill = function(image, sr, sc, newColor) { + fill(image, sr, sc, image[sr][sc], newColor); + return image; +}; + +function fill(image, x, y, initialColor, newColor) { + if (image[x] && image[x][y] === initialColor && initialColor !== newColor) { + image[x][y] = newColor; + [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] + .forEach(([x, y]) => fill(image, x, y, initialColor, newColor)); + } +} diff --git a/README.md b/README.md index 028e983e..83b40dea 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,7 @@ 704|[Binary Search](./0704-binary-search.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| +733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| From dbcadaf80143a34a788e424d61d77eb13cb69c2b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Jan 2022 18:08:32 -0500 Subject: [PATCH 240/485] Add solution #695 --- 0695-max-area-of-island.js | 41 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0695-max-area-of-island.js diff --git a/0695-max-area-of-island.js b/0695-max-area-of-island.js new file mode 100644 index 00000000..c8957edf --- /dev/null +++ b/0695-max-area-of-island.js @@ -0,0 +1,41 @@ +/** + * 695. Max Area of Island + * https://leetcode.com/problems/max-area-of-island/ + * Difficulty: Medium + * + * You are given an m x n binary matrix grid. An island is a group of 1's (representing land) + * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the + * grid are surrounded by water. + * + * The area of an island is the number of cells with a value 1 in the island. + * + * Return the maximum area of an island in grid. If there is no island, return 0. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var maxAreaOfIsland = function(grid) { + const cache = new Set(); + let max = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + max = Math.max(max, traverse(grid, cache, i, j)); + } + } + + return max; +}; + +function traverse(grid, cache, x, y) { + let count = 0; + if (grid[x] && grid[x][y] === 1 && !cache.has(`${x},${y}`)) { + cache.add(`${x},${y}`); + count += [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] + .map(([x, y]) => traverse(grid, cache, x, y)) + .reduce((sum, count) => sum + count, 0) + 1; + } + return count; +} diff --git a/README.md b/README.md index 83b40dea..a948962a 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| From d7df6faf03162e131cc403b7850bd42ca365ec0c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Jan 2022 16:53:28 -0500 Subject: [PATCH 241/485] Add solution #189 --- 0189-rotate-array.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0189-rotate-array.js diff --git a/0189-rotate-array.js b/0189-rotate-array.js new file mode 100644 index 00000000..b6bcc49a --- /dev/null +++ b/0189-rotate-array.js @@ -0,0 +1,16 @@ +/** + * 189. Rotate Array + * https://leetcode.com/problems/rotate-array/ + * Difficulty: Medium + * + * Given an array, rotate the array to the right by k steps, where k is non-negative. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {void} Do not return anything, modify nums in-place instead. + */ +var rotate = function(nums, k) { + nums.unshift(...nums.splice((k % nums.length) * -1)); +}; diff --git a/README.md b/README.md index a948962a..9849b1e8 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| +189|[Rotate Array](./0189-rotate-array.js)|Medium| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| From 2945e6482582d398b3c67cecf3e3653acd23efd2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Jan 2022 16:54:51 -0500 Subject: [PATCH 242/485] Add solution #374 --- 0374-guess-number-higher-or-lower.js | 46 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0374-guess-number-higher-or-lower.js diff --git a/0374-guess-number-higher-or-lower.js b/0374-guess-number-higher-or-lower.js new file mode 100644 index 00000000..6ebde407 --- /dev/null +++ b/0374-guess-number-higher-or-lower.js @@ -0,0 +1,46 @@ +/** + * 374. Guess Number Higher or Lower + * https://leetcode.com/problems/guess-number-higher-or-lower/ + * Difficulty: Medium + * + * We are playing the Guess Game. The game is as follows: + * + * I pick a number from 1 to n. You have to guess which number I picked. + * + * Every time you guess wrong, I will tell you whether the number I picked is higher + * or lower than your guess. + * + * You call a pre-defined API int guess(int num), which returns 3 possible results: + * - -1: The number I picked is lower than your guess (i.e. pick < num). + * - 1: The number I picked is higher than your guess (i.e. pick > num). + * - 0: The number I picked is equal to your guess (i.e. pick == num). + * + * Return the number that I picked. + */ + +/** + * Forward declaration of guess API. + * @param {number} num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * var guess = function(num) {} + */ + +/** + * @param {number} n + * @return {number} + */ +var guessNumber = function(n) { + let left = 1; + let right = n; + + while (left <= right) { + const pivot = Math.floor((right + left) / 2); + switch (guess(pivot)) { + case -1: right = pivot - 1; break; + case 1: left = pivot + 1; break; + case 0: return pivot; + } + } +}; diff --git a/README.md b/README.md index 9849b1e8..1530905c 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From dc4f85e1337f2531bcba20239e946582fede8919 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Jan 2022 16:55:20 -0500 Subject: [PATCH 243/485] Add solution #344 --- 0344-reverse-string.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0344-reverse-string.js diff --git a/0344-reverse-string.js b/0344-reverse-string.js new file mode 100644 index 00000000..e459e954 --- /dev/null +++ b/0344-reverse-string.js @@ -0,0 +1,20 @@ +/** + * 344. Reverse String + * https://leetcode.com/problems/reverse-string/ + * Difficulty: Easy + * + * Write a function that reverses a string. The input string is given as an array + * of characters s. + * + * You must do this by modifying the input array in-place with O(1) extra memory. + */ + +/** + * @param {character[]} s + * @return {void} Do not return anything, modify s in-place instead. + */ +var reverseString = function(s) { + for (let i = 0; i < Math.floor(s.length / 2); i++) { + [s[s.length - 1 - i], s[i]] = [s[i], s[s.length - 1 - i]]; + } +}; diff --git a/README.md b/README.md index 1530905c..cd7fe430 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| +344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| From fc58fc83de93702a22fb1dfe114800651de4aa7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Jan 2022 21:41:17 -0600 Subject: [PATCH 244/485] Add solution #1748 --- 1748-sum-of-unique-elements.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1748-sum-of-unique-elements.js diff --git a/1748-sum-of-unique-elements.js b/1748-sum-of-unique-elements.js new file mode 100644 index 00000000..2329b9a4 --- /dev/null +++ b/1748-sum-of-unique-elements.js @@ -0,0 +1,23 @@ +/** + * 1748. Sum of Unique Elements + * https://leetcode.com/problems/sum-of-unique-elements/ + * Difficulty: Easy + * + * You are given an integer array nums. The unique elements of an array are the + * elements that appear exactly once in the array. + * + * Return the sum of all the unique elements of nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var sumOfUnique = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + return [...map].reduce((sum, [key, value]) => { + return sum + (value === 1 ? key : 0); + }, 0); +}; diff --git a/README.md b/README.md index cd7fe430..30fe1aa0 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| +1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From b3d127b09cd3cb564e775934ed2628353b0dba65 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Jan 2022 21:42:20 -0600 Subject: [PATCH 245/485] Add solution #876 --- 0876-middle-of-the-linked-list.js | 32 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0876-middle-of-the-linked-list.js diff --git a/0876-middle-of-the-linked-list.js b/0876-middle-of-the-linked-list.js new file mode 100644 index 00000000..f027270c --- /dev/null +++ b/0876-middle-of-the-linked-list.js @@ -0,0 +1,32 @@ +/** + * 876. Middle of the Linked List + * https://leetcode.com/problems/middle-of-the-linked-list/ + * Difficulty: Easy + * + * Given the head of a singly linked list, return the middle node of the linked list. + * + * If there are two middle nodes, return the second middle node. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var middleNode = function(head) { + let slow = head; + let fast = head; + + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + return slow; +}; diff --git a/README.md b/README.md index 30fe1aa0..fc072e02 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From f39cf945fac02f71f533b45b55d015fde9e4a852 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Jan 2022 21:43:26 -0600 Subject: [PATCH 246/485] Add solution #2095 --- ...delete-the-middle-node-of-a-linked-list.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 2095-delete-the-middle-node-of-a-linked-list.js diff --git a/2095-delete-the-middle-node-of-a-linked-list.js b/2095-delete-the-middle-node-of-a-linked-list.js new file mode 100644 index 00000000..92ff7870 --- /dev/null +++ b/2095-delete-the-middle-node-of-a-linked-list.js @@ -0,0 +1,42 @@ +/** + * 2095. Delete the Middle Node of a Linked List + * https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/ + * Difficulty: Medium + * + * You are given the head of a linked list. Delete the middle node, and return the head + * of the modified linked list. + * + * The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using + * 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x. + * + * For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteMiddle = function(head) { + let slow = new ListNode(0, head); + let fast = head; + + if (!head.next) { + return null; + } + + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + slow.next = slow.next.next; + + return head; +}; diff --git a/README.md b/README.md index fc072e02..f38371ae 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| +2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| ## License From 24f4e22106f5376205d91af7fcc932bd7beb8ba6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Jan 2022 19:32:10 -0600 Subject: [PATCH 247/485] Add solution #542 --- 0542-01-matrix.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0542-01-matrix.js diff --git a/0542-01-matrix.js b/0542-01-matrix.js new file mode 100644 index 00000000..57045094 --- /dev/null +++ b/0542-01-matrix.js @@ -0,0 +1,45 @@ +/** + * 542. 01 Matrix + * https://leetcode.com/problems/01-matrix/ + * Difficulty: Medium + * + * Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + * + * The distance between two adjacent cells is 1. + */ + +/** + * @param {number[][]} matrix + * @return {number[][]} + */ +var updateMatrix = function(matrix) { + const queue = []; + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] === 0) { + queue.push([i, j, 0]); + } else { + matrix[i][j] = Infinity; + } + } + } + + + while (queue.length) { + const [i, j, k] = queue.shift(); + if (matrix[i][j] > k) { + matrix[i][j] = k; + } + [[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => { + const [x, y, z] = [i + p[0], j + p[1], k + 1]; + if (x > -1 && x < matrix.length && y > -1 && y < matrix[0].length) { + if (matrix[x][y] === Infinity) { + queue.push([x, y, z]); + } + } + }); + } + + return matrix; +}; diff --git a/README.md b/README.md index f38371ae..f986cca8 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +542|[01 Matrix](./0542-01-matrix.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From c90114620f9c1ab6237a2ff7a1e237c2faf19727 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Jan 2022 19:33:04 -0600 Subject: [PATCH 248/485] Add solution #599 --- 0599-minimum-index-sum-of-two-lists.js | 28 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0599-minimum-index-sum-of-two-lists.js diff --git a/0599-minimum-index-sum-of-two-lists.js b/0599-minimum-index-sum-of-two-lists.js new file mode 100644 index 00000000..0723e369 --- /dev/null +++ b/0599-minimum-index-sum-of-two-lists.js @@ -0,0 +1,28 @@ +/** + * 599. Minimum Index Sum of Two Lists + * https://leetcode.com/problems/minimum-index-sum-of-two-lists/ + * Difficulty: Easy + * + * Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list + * of favorite restaurants represented by strings. + * + * You need to help them find out their common interest with the least list index sum. + * If there is a choice tie between answers, output all of them with no order requirement. + * You could assume there always exists an answer. + */ + +/** + * @param {string[]} list1 + * @param {string[]} list2 + * @return {string[]} + */ +var findRestaurant = function(list1, list2) { + const map = new Map(list1.map((str, index) => [str, index])); + + return list2 + .map((str, index) => map.has(str) ? [map.get(str) + index, str] : null) + .filter(Boolean) + .sort(([a], [b]) => a - b) + .filter(([sum], index, [[lowest]]) => sum === lowest) + .map(([, str]) => str); +}; diff --git a/README.md b/README.md index f986cca8..d1aac1d7 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| +599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 0effdb2ebcec6d0e03021903b938631dc794687c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Jan 2022 19:33:54 -0600 Subject: [PATCH 249/485] Add solution #905 --- 0905-sort-array-by-parity.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0905-sort-array-by-parity.js diff --git a/0905-sort-array-by-parity.js b/0905-sort-array-by-parity.js new file mode 100644 index 00000000..a2d65e8c --- /dev/null +++ b/0905-sort-array-by-parity.js @@ -0,0 +1,18 @@ +/** + * 905. Sort Array By Parity + * https://leetcode.com/problems/sort-array-by-parity/ + * Difficulty: Easy + * + * Given an integer array nums, move all the even integers at the beginning of + * the array followed by all the odd integers. + * + * Return any array that satisfies this condition. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArrayByParity = function(nums) { + return nums.sort((a, b) => a % 2 === 0 ? -1 : 1); +}; diff --git a/README.md b/README.md index d1aac1d7..5cfd1da0 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| +905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From c7791c41cc3b71e20155b78a3a076ef948e50dd3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Jan 2022 20:02:15 -0600 Subject: [PATCH 250/485] Add solution #1041 --- 1041-robot-bounded-in-circle.js | 34 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 1041-robot-bounded-in-circle.js diff --git a/1041-robot-bounded-in-circle.js b/1041-robot-bounded-in-circle.js new file mode 100644 index 00000000..96c15d3e --- /dev/null +++ b/1041-robot-bounded-in-circle.js @@ -0,0 +1,34 @@ +/** + * 1041. Robot Bounded In Circle + * https://leetcode.com/problems/robot-bounded-in-circle/ + * Difficulty: Medium + * + * On an infinite plane, a robot initially stands at (0, 0) and faces north. + * The robot can receive one of three instructions: + * - "G": go straight 1 unit; + * - "L": turn 90 degrees to the left; + * - "R": turn 90 degrees to the right. + * + * The robot performs the instructions given in order, and repeats them forever. + * Return true if and only if there exists a circle in the plane such that the + * robot never leaves the circle. + */ + +/** + * @param {string} instructions + * @return {boolean} + */ +var isRobotBounded = function(instructions) { + let x = 0, y = 0; + let dx = 0, dy = 1; + + for (const direction of instructions) { + switch (direction) { + case 'R': [dx, dy] = [dy, -dx]; break; + case 'L': [dy, dx] = [dx, -dy]; break; + case 'G': [x, y] = [x + dx, y + dy]; break; + } + } + + return (x === 0 && y === 0) || dy !== 1; +} diff --git a/README.md b/README.md index 5cfd1da0..5e294db9 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| +1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| From 8fa8f28ba1a82ed609c07279c12c7f23bcf4fc51 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Jan 2022 20:02:59 -0600 Subject: [PATCH 251/485] Add solution #922 --- 0922-sort-array-by-parity-ii.js | 36 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0922-sort-array-by-parity-ii.js diff --git a/0922-sort-array-by-parity-ii.js b/0922-sort-array-by-parity-ii.js new file mode 100644 index 00000000..ce626ff7 --- /dev/null +++ b/0922-sort-array-by-parity-ii.js @@ -0,0 +1,36 @@ +/** + * 922. Sort Array By Parity II + * https://leetcode.com/problems/sort-array-by-parity-ii/ + * Difficulty: Easy + * + * Given an array of integers nums, half of the integers in nums are odd, + * and the other half are even. + * + * Sort the array so that whenever nums[i] is odd, i is odd, and whenever + * nums[i] is even, i is even. + * + * Return any answer array that satisfies this condition. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArrayByParityII = function(nums) { + let i = 0; + let j = 1; + + while (i < nums.length && j < nums.length) { + if (nums[i] % 2 === 0) { + i += 2; + } else if (nums[j] % 2 === 1) { + j += 2; + } else { + [nums[i], nums[j]] = [nums[j], nums[i]]; + i += 2; + j += 2; + } + } + + return nums; +}; diff --git a/README.md b/README.md index 5e294db9..c171c480 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| 916|[Word Subsets](./0916-word-subsets.js)|Medium| +922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| From a82fa4226c7fb9b86d18414deaf18c9037144e7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Jan 2022 20:04:53 -0600 Subject: [PATCH 252/485] Add solution #706 --- 0706-design-hashmap.js | 54 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0706-design-hashmap.js diff --git a/0706-design-hashmap.js b/0706-design-hashmap.js new file mode 100644 index 00000000..1c2ee037 --- /dev/null +++ b/0706-design-hashmap.js @@ -0,0 +1,54 @@ +/** + * 706. Design HashMap + * https://leetcode.com/problems/design-hashmap/ + * Difficulty: Easy + * + * Design a HashMap without using any built-in hash table libraries. + * Implement the MyHashMap class: + * - MyHashMap() initializes the object with an empty map. + * - void put(int key, int value) inserts a (key, value) pair into the HashMap. + * If the key already exists in the map, update the corresponding value. + * - int get(int key) returns the value to which the specified key is mapped, + * or -1 if this map contains no mapping for the key. + * - void remove(key) removes the key and its corresponding value if the map + * contains the mapping for the key. + */ + + +var MyHashMap = function() { + this._keys = []; + this._values = []; +}; + +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +MyHashMap.prototype.put = function(key, value) { + if (this._keys[key] === undefined) { + this._values.push(value); + this._keys[key] = this._values.length - 1; + } else { + this._values[this._keys[key]] = value; + } +}; + +/** + * @param {number} key + * @return {number} + */ +MyHashMap.prototype.get = function(key) { + const offset = this._keys[key]; + return offset === undefined ? -1 : this._values[offset]; +} +/** + * @param {number} key + * @return {void} + */ +MyHashMap.prototype.remove = function(key) { + if (this._keys[key] !== undefined) { + this._values[this._keys[key]] = undefined; + this._keys[key] = undefined; + } +}; diff --git a/README.md b/README.md index c171c480..69869db7 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| +706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| From daae2cdff5e3973c6198a26b3c2f80a18ade5024 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Jan 2022 18:33:11 -0600 Subject: [PATCH 253/485] Add solution #705 --- 0705-design-hashset.js | 42 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0705-design-hashset.js diff --git a/0705-design-hashset.js b/0705-design-hashset.js new file mode 100644 index 00000000..23d1ea0a --- /dev/null +++ b/0705-design-hashset.js @@ -0,0 +1,42 @@ +/** + * 705. Design HashSet + * https://leetcode.com/problems/design-hashset/ + * Difficulty: Easy + * + * Design a HashSet without using any built-in hash table libraries. + * + * Implement MyHashSet class: + * - void add(key) Inserts the value key into the HashSet. + * - bool contains(key) Returns whether the value key exists in the + * HashSet or not. + * - void remove(key) Removes the value key in the HashSet. If key + * does not exist in the HashSet, do nothing. + */ + +var MyHashSet = function() { + this._keys = []; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashSet.prototype.add = function(key) { + this._keys[key] = 1; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashSet.prototype.remove = function(key) { + this._keys[key] = undefined; +}; + +/** + * @param {number} key + * @return {boolean} + */ +MyHashSet.prototype.contains = function(key) { + return this._keys[key] !== undefined; +}; diff --git a/README.md b/README.md index 69869db7..79e880c0 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| +705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 95b1a9a527eb2253fd773e7b3a94860f48a35123 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Jan 2022 18:33:58 -0600 Subject: [PATCH 254/485] Add solution #2053 --- 2053-kth-distinct-string-in-an-array.js | 29 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 2053-kth-distinct-string-in-an-array.js diff --git a/2053-kth-distinct-string-in-an-array.js b/2053-kth-distinct-string-in-an-array.js new file mode 100644 index 00000000..237b26d3 --- /dev/null +++ b/2053-kth-distinct-string-in-an-array.js @@ -0,0 +1,29 @@ +/** + * 2053. Kth Distinct String in an Array + * https://leetcode.com/problems/kth-distinct-string-in-an-array/ + * Difficulty: Medium + * + * A distinct string is a string that is present only once in an array. + * + * Given an array of strings arr, and an integer k, return the kth distinct + * string present in arr. If there are fewer than k distinct strings, return + * an empty string "". + * + * Note that the strings are considered in the order in which they appear in + * the array. + */ + +/** + * @param {string[]} arr + * @param {number} k + * @return {string} + */ +var kthDistinct = function(arr, k) { + const map = new Map(); + arr.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + const sorted = [...map].sort(([,a], [,b]) => a - b); + const [kth, count] = sorted[k - 1] || []; + + return count === 1 ? kth : ''; +}; diff --git a/README.md b/README.md index 79e880c0..078a97b9 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| +2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| From 3430070e38cc26c4c7036319728ce31ca9f56bff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Jan 2022 18:34:34 -0600 Subject: [PATCH 255/485] Add solution #2085 --- ...-count-common-words-with-one-occurrence.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2085-count-common-words-with-one-occurrence.js diff --git a/2085-count-common-words-with-one-occurrence.js b/2085-count-common-words-with-one-occurrence.js new file mode 100644 index 00000000..416258f7 --- /dev/null +++ b/2085-count-common-words-with-one-occurrence.js @@ -0,0 +1,22 @@ +/** + * 2085. Count Common Words With One Occurrence + * https://leetcode.com/problems/count-common-words-with-one-occurrence/ + * Difficulty: Easy + * + * Given two string arrays words1 and words2, return the number of strings + * that appear exactly once in each of the two arrays. + */ + +/** + * @param {string[]} words1 + * @param {string[]} words2 + * @return {number} + */ +var countWords = function(words1, words2) { + const map = new Map(); + words1.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + [...map].forEach(([key, count]) => count !== 1 ? map.delete(key) : null); + words2.forEach(n => map.has(n) ? map.set(n, (map.get(n) || 0) + 1) : null); + + return [...map].filter(([, count]) => count === 2).length; +}; diff --git a/README.md b/README.md index 078a97b9..dc5f6498 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,7 @@ 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| +2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| From 280df67942fa12cfba2e4e6377c7adc76fddeb2d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Jan 2022 21:04:44 -0600 Subject: [PATCH 256/485] Add solution #994 --- 0994-rotting-oranges.js | 50 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0994-rotting-oranges.js diff --git a/0994-rotting-oranges.js b/0994-rotting-oranges.js new file mode 100644 index 00000000..0f866273 --- /dev/null +++ b/0994-rotting-oranges.js @@ -0,0 +1,50 @@ +/** + * 994. Rotting Oranges + * https://leetcode.com/problems/rotting-oranges/ + * Difficulty: Medium + * + * You are given an m x n grid where each cell can have one of three values: + * - 0 representing an empty cell, + * - 1 representing a fresh orange, or + * - 2 representing a rotten orange. + * + * Every minute, any fresh orange that is 4-directionally adjacent to a rotten + * orange becomes rotten. + * + * Return the minimum number of minutes that must elapse until no cell has a + * fresh orange. If this is impossible, return -1. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var orangesRotting = function(grid) { + const queue = []; + let count = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 2) { + queue.push([i, j, 0]); + } + } + } + + while (queue.length) { + const [i, j, k] = queue.shift(); + [[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => { + const [x, y, z] = [i + p[0], j + p[1], k + 1]; + if (x > -1 && x < grid.length && y > -1 && y < grid[0].length) { + if (grid[x][y] === 1) { + grid[x][y] = 2; + count = Math.max(count, z); + queue.push([x, y, z]); + } + } + }); + } + + const isIncomplete = grid.some(row => row.some(n => n === 1)); + return isIncomplete ? -1 : count; +}; diff --git a/README.md b/README.md index dc5f6498..6eeb2790 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| 985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| +994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium| 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| From e3a291eb401f141833e2ee05806198b3bbcb3b0b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Jan 2022 21:06:21 -0600 Subject: [PATCH 257/485] Add solution #463 --- 0463-island-perimeter.js | 36 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0463-island-perimeter.js diff --git a/0463-island-perimeter.js b/0463-island-perimeter.js new file mode 100644 index 00000000..9860ffc2 --- /dev/null +++ b/0463-island-perimeter.js @@ -0,0 +1,36 @@ +/** + * 463. Island Perimeter + * https://leetcode.com/problems/island-perimeter/ + * Difficulty: Medium + * + * You are given row x col grid representing a map where grid[i][j] = 1 represents land and + * grid[i][j] = 0 represents water. + * + * Grid cells are connected horizontally/vertically (not diagonally). The grid is completely + * surrounded by water, and there is exactly one island (i.e., one or more connected land cells). + * + * The island doesn't have "lakes", meaning the water inside isn't connected to the water around + * the island. One cell is a square with side length 1. The grid is rectangular, width and height + * don't exceed 100. Determine the perimeter of the island. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var islandPerimeter = function(grid) { + let island = 0; + let adjacent = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1) { + island++; + if (i + 1 < grid.length && grid[i + 1][j] === 1) adjacent++; + if (j + 1 < grid[0].length && grid[i][j + 1] === 1) adjacent++; + } + } + } + + return island * 4 - adjacent * 2; +}; diff --git a/README.md b/README.md index 6eeb2790..1628e60e 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| From 6ae10697e535273404bbad8630e16eb006cd2cfa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Jan 2022 21:07:07 -0600 Subject: [PATCH 258/485] Add solution #77 --- 0077-combinations.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0077-combinations.js diff --git a/0077-combinations.js b/0077-combinations.js new file mode 100644 index 00000000..5295f645 --- /dev/null +++ b/0077-combinations.js @@ -0,0 +1,31 @@ +/** + * 77. Combinations + * https://leetcode.com/problems/combinations/ + * Difficulty: Medium + * + * Given two integers n and k, return all possible combinations of k numbers + * out of the range [1, n]. + * + * You may return the answer in any order. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number[][]} + */ +var combine = function(n, k) { + const result = []; + backtrack(result, n, k); + return result; +}; + +function backtrack(result, n, k, combination = [], offset = 1) { + if (combination.length === k) { + result.push(combination); + } else { + while (offset <= n) { + backtrack(result, n, k, [...combination, offset], ++offset); + } + } +} diff --git a/README.md b/README.md index 1628e60e..6eea46cc 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| +77|[Combinations](./0077-combinations.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From 7e9465a82d2a639f411a3815e0faf21db4e34705 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Jan 2022 22:35:59 -0600 Subject: [PATCH 259/485] Add solution #39 --- 0039-combination-sum.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0039-combination-sum.js diff --git a/0039-combination-sum.js b/0039-combination-sum.js new file mode 100644 index 00000000..967d7dd1 --- /dev/null +++ b/0039-combination-sum.js @@ -0,0 +1,39 @@ +/** + * 39. Combination Sum + * https://leetcode.com/problems/combination-sum/ + * Difficulty: Medium + * + * Given an array of distinct integers candidates and a target integer target, + * return a list of all unique combinations of candidates where the chosen + * numbers sum to target. You may return the combinations in any order. + * + * The same number may be chosen from candidates an unlimited number of times. + * Two combinations are unique if the frequency of at least one of the chosen + * numbers is different. + * + * It is guaranteed that the number of unique combinations that sum up to target + * is less than 150 combinations for the given input. + */ + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function(candidates, target) { + const result = []; + backtrack(result, candidates, target); + return result; +}; + +function backtrack(result, candidates, target, combination = [], offset = 0) { + if (target < 0) { + return; + } else if (target === 0) { + result.push(combination); + } else { + for (let i = offset; i < candidates.length; i++) { + backtrack(result, candidates, target - candidates[i], [...combination, candidates[i]], i); + } + } +} diff --git a/README.md b/README.md index 6eea46cc..b89eed22 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +39|[Combination Sum](./0039-combination-sum.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| From d0a3aa34371e9efa1b022a8627e3fd720a3b7efc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Jan 2022 22:36:51 -0600 Subject: [PATCH 260/485] Add solution #40 --- 0040-combination-sum-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0040-combination-sum-ii.js diff --git a/0040-combination-sum-ii.js b/0040-combination-sum-ii.js new file mode 100644 index 00000000..f38ed62e --- /dev/null +++ b/0040-combination-sum-ii.js @@ -0,0 +1,37 @@ +/** + * 40. Combination Sum II + * https://leetcode.com/problems/combination-sum-ii/ + * Difficulty: Medium + * + * Given a collection of candidate numbers (candidates) and a target number (target), + * find all unique combinations in candidates where the candidate numbers sum to target. + * + * Each number in candidates may only be used once in the combination. + * + * Note: The solution set must not contain duplicate combinations. + */ + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function(candidates, target) { + const result = []; + candidates.sort((a, b) => a - b); + backtrack(result, candidates, target); + return result; +}; + +function backtrack(result, candidates, target, combination = [], offset = 0) { + if (target < 0) { + return; + } else if (target === 0) { + result.push(combination); + } else { + for (let i = offset; i < candidates.length; i++) { + if (i > offset && candidates[i] === candidates[i - 1]) continue; + backtrack(result, candidates, target - candidates[i], [...combination, candidates[i]], i + 1); + } + } +} diff --git a/README.md b/README.md index b89eed22..2ff10fce 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 39|[Combination Sum](./0039-combination-sum.js)|Medium| +40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| From dc0b75b148890c530723c6341b67ab58a85b8c72 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Jan 2022 22:38:22 -0600 Subject: [PATCH 261/485] Add solution #1832 --- 1832-check-if-the-sentence-is-pangram.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1832-check-if-the-sentence-is-pangram.js diff --git a/1832-check-if-the-sentence-is-pangram.js b/1832-check-if-the-sentence-is-pangram.js new file mode 100644 index 00000000..2a50c935 --- /dev/null +++ b/1832-check-if-the-sentence-is-pangram.js @@ -0,0 +1,19 @@ +/** + * 1832. Check if the Sentence Is Pangram + * https://leetcode.com/problems/check-if-the-sentence-is-pangram/ + * Difficulty: Easy + * + * A pangram is a sentence where every letter of the English alphabet appears + * at least once. + * + * Given a string sentence containing only lowercase English letters, return + * true if sentence is a pangram, or false otherwise. + */ + +/** + * @param {string} sentence + * @return {boolean} + */ +var checkIfPangram = function(sentence) { + return new Set([...sentence]).size === 26; +}; diff --git a/README.md b/README.md index 2ff10fce..abd9609b 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| From ede1d129f344fa506e6f97bfd2bf0801f9873d37 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Jan 2022 17:33:32 -0600 Subject: [PATCH 262/485] Add solution #784 --- 0784-letter-case-permutation.js | 35 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0784-letter-case-permutation.js diff --git a/0784-letter-case-permutation.js b/0784-letter-case-permutation.js new file mode 100644 index 00000000..67b389cd --- /dev/null +++ b/0784-letter-case-permutation.js @@ -0,0 +1,35 @@ +/** + * 784. Letter Case Permutation + * https://leetcode.com/problems/letter-case-permutation/ + * Difficulty: Medium + * + * Given a string s, you can transform every letter individually to be lowercase or uppercase + * to create another string. + * + * Return a list of all possible strings we could create. Return the output in any order. + */ + +/** + * @param {string} str + * @return {string[]} + */ +var letterCasePermutation = function(str) { + const result = []; + backtrack(result, str); + return result; +}; + +function backtrack(result, input, permutation = '', offset = 0) { + if (input.length === permutation.length) { + result.push(permutation); + } else { + const target = input[offset]; + if (isNaN(target)) { + [target.toLowerCase(), target.toUpperCase()].forEach(s => { + backtrack(result, input, permutation + s, offset + 1); + }); + } else { + backtrack(result, input, permutation + target, offset + 1); + } + } +} diff --git a/README.md b/README.md index abd9609b..2badda89 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 8594f3814274f16b2c845dbf7fd5931968dd4c2d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Jan 2022 17:34:39 -0600 Subject: [PATCH 263/485] Add solution #100 --- 0100-same-tree.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0100-same-tree.js diff --git a/0100-same-tree.js b/0100-same-tree.js new file mode 100644 index 00000000..e1ef3e3a --- /dev/null +++ b/0100-same-tree.js @@ -0,0 +1,30 @@ +/** + * 100. Same Tree + * https://leetcode.com/problems/same-tree/ + * Difficulty: Easy + * + * Given the roots of two binary trees p and q, write a function to check if they are + * the same or not. + * + * Two binary trees are considered the same if they are structurally identical, and + * the nodes have the same value. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function(p, q) { + const hasSameValue = p !== null && q !== null && p.val === q.val; + const hasSameTree = hasSameValue && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + return (p === null && q === null) || hasSameTree; +}; diff --git a/README.md b/README.md index 2badda89..5886d8cc 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| +100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| From 2b9bfb2bed0d98e596fd987cc296302605ba91c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Jan 2022 17:35:43 -0600 Subject: [PATCH 264/485] Add solution #1022 --- 1022-sum-of-root-to-leaf-binary-numbers.js | 41 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 1022-sum-of-root-to-leaf-binary-numbers.js diff --git a/1022-sum-of-root-to-leaf-binary-numbers.js b/1022-sum-of-root-to-leaf-binary-numbers.js new file mode 100644 index 00000000..bfa8f868 --- /dev/null +++ b/1022-sum-of-root-to-leaf-binary-numbers.js @@ -0,0 +1,41 @@ +/** + * 1022. Sum of Root To Leaf Binary Numbers + * https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ + * Difficulty: Easy + * + * You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf + * path represents a binary number starting with the most significant bit. + * + * For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, + * which is 13. + * + * For all leaves in the tree, consider the numbers represented by the path from the root to that + * leaf. Return the sum of these numbers. + * + * The test cases are generated so that the answer fits in a 32-bits integer. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var sumRootToLeaf = function(root) { + return dfs(root); +}; + +function dfs(node, str = '') { + if (!node) return 0; + str += node.val; + if (!node.left && !node.right) { + return parseInt(str, 2) + } + return dfs(node.left, str) + dfs(node.right, str); +} diff --git a/README.md b/README.md index 5886d8cc..4ca0887f 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| +1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| From 65d7f3853ddea892ea5283f68c32d78016c41c00 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Jan 2022 22:35:34 -0600 Subject: [PATCH 265/485] Add solution #1669 --- 1669-merge-in-between-linked-lists.js | 44 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 1669-merge-in-between-linked-lists.js diff --git a/1669-merge-in-between-linked-lists.js b/1669-merge-in-between-linked-lists.js new file mode 100644 index 00000000..6a637b0a --- /dev/null +++ b/1669-merge-in-between-linked-lists.js @@ -0,0 +1,44 @@ +/** + * 1669. Merge In Between Linked Lists + * https://leetcode.com/problems/merge-in-between-linked-lists/ + * Difficulty: Medium + * + * You are given two linked lists: list1 and list2 of sizes n and m respectively. + * + * Remove list1's nodes from the ath node to the bth node, and put list2 in their place. + * + * The blue edges and nodes in the following figure indicate the result: + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {number} a + * @param {number} b + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeInBetween = function(list1, a, b, list2) { + const result = new ListNode(0, list1); + + for (let i = 1; i < a; i++) { + list1 = list1.next; + } + let tail = list1.next; + list1.next = list2; + for (let i = a; i < b; i++) { + tail = tail.next; + } + while (list1 && list1.next) { + list1 = list1.next; + } + list1.next = tail.next; + + return result.next; +}; diff --git a/README.md b/README.md index 4ca0887f..9ff1bd57 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,7 @@ 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| +1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 09dd2fe9668970e72bb8cb4b40655d0df78fb290 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Jan 2022 22:36:10 -0600 Subject: [PATCH 266/485] Add solution #1512 --- 1512-number-of-good-pairs.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 1512-number-of-good-pairs.js diff --git a/1512-number-of-good-pairs.js b/1512-number-of-good-pairs.js new file mode 100644 index 00000000..eb5c60d8 --- /dev/null +++ b/1512-number-of-good-pairs.js @@ -0,0 +1,18 @@ +/** + * 1512. Number of Good Pairs + * https://leetcode.com/problems/number-of-good-pairs/ + * Difficulty: Easy + * + * Given an array of integers nums, return the number of good pairs. + * + * A pair (i, j) is called good if nums[i] == nums[j] and i < j. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var numIdenticalPairs = function(nums) { + const map = new Array(101).fill(0); + return nums.reduce((sum, n) => sum += map[n]++, 0); +}; diff --git a/README.md b/README.md index 9ff1bd57..cc692657 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,7 @@ 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| +1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| From 24f6ea69cc4de9fd33e47d7367712e599c36bc1e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Jan 2022 22:39:47 -0600 Subject: [PATCH 267/485] Add solution #645 --- 0645-set-mismatch.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0645-set-mismatch.js diff --git a/0645-set-mismatch.js b/0645-set-mismatch.js new file mode 100644 index 00000000..8e60aa14 --- /dev/null +++ b/0645-set-mismatch.js @@ -0,0 +1,40 @@ +/** + * 645. Set Mismatch + * https://leetcode.com/problems/set-mismatch/ + * Difficulty: Medium + * + * You have a set of integers s, which originally contains all the numbers from 1 to n. + * Unfortunately, due to some error, one of the numbers in s got duplicated to another + * number in the set, which results in repetition of one number and loss of another number. + * + * You are given an integer array nums representing the data status of this set after + * the error. + * + * Find the number that occurs twice and the number that is missing and return them in + * the form of an array. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var findErrorNums = function(nums) { + const set = new Set(); + const result = []; + + for (const n of nums) { + if (set.has(n)) { + result.push(n); + } + set.add(n); + } + + for (let i = nums.length; i > 0; i--) { + if (!set.has(i)) { + result.push(i); + break; + } + } + + return result; +}; diff --git a/README.md b/README.md index cc692657..9c1592d7 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,7 @@ 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| +645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 479bd6008f8767b6984feb276751f5d9c884aca0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Jan 2022 22:42:18 -0600 Subject: [PATCH 268/485] Add solution #190 --- 0190-reverse-bits.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 0190-reverse-bits.js diff --git a/0190-reverse-bits.js b/0190-reverse-bits.js new file mode 100644 index 00000000..fef88995 --- /dev/null +++ b/0190-reverse-bits.js @@ -0,0 +1,15 @@ +/** + * 190. Reverse Bits + * https://leetcode.com/problems/reverse-bits/ + * Difficulty: Easy + * + * Reverse bits of a given 32 bits unsigned integer. + */ + +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function(n) { + return parseInt([...n.toString(2)].reverse().join('').padEnd(32, '0'), 2); +}; diff --git a/README.md b/README.md index 9c1592d7..52feaf1c 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| +190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| From a22177360b19cf812931bfb146ab24eb045c42aa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Jan 2022 22:43:37 -0600 Subject: [PATCH 269/485] Add solution #1002 --- 1002-find-common-characters.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1002-find-common-characters.js diff --git a/1002-find-common-characters.js b/1002-find-common-characters.js new file mode 100644 index 00000000..89cfa794 --- /dev/null +++ b/1002-find-common-characters.js @@ -0,0 +1,24 @@ +/** + * 1002. Find Common Characters + * https://leetcode.com/problems/find-common-characters/ + * Difficulty: Easy + * + * Given a string array words, return an array of all characters that show up in all strings within + * the words (including duplicates). You may return the answer in any order. + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var commonChars = function(words) { + return words + .map(word => [...word]) + .reduce((common, word) => common.filter(s => { + const index = word.indexOf(s); + if (index !== -1) { + word.splice(index, 1); + } + return index !== -1; + }), [...words[0]]); +}; diff --git a/README.md b/README.md index 52feaf1c..8afa3b55 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| 994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium| 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| +1002|[Find Common Characters](./1002-find-common-characters.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| From 55a25672c454e1bdc885088df9953422dd69d66f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Jan 2022 22:46:43 -0600 Subject: [PATCH 270/485] Add solution #70 --- 0070-climbing-stairs.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0070-climbing-stairs.js diff --git a/0070-climbing-stairs.js b/0070-climbing-stairs.js new file mode 100644 index 00000000..1eff99b0 --- /dev/null +++ b/0070-climbing-stairs.js @@ -0,0 +1,26 @@ +/** + * 70. Climbing Stairs + * https://leetcode.com/problems/climbing-stairs/ + * Difficulty: Easy + * + * You are climbing a staircase. It takes n steps to reach the top. + * + * Each time you can either climb 1 or 2 steps. In how many distinct + * ways can you climb to the top? + */ + +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function(n) { + const cache = new Map(); + const memo = n => { + if (n < 4) return n; + if (!cache.has(n)) { + cache.set(n, memo(n - 2) + memo(n - 1)); + } + return cache.get(n); + }; + return memo(n); +}; diff --git a/README.md b/README.md index 8afa3b55..504d0ed9 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| From 3d07962263609222c9529ba23da17d2b8e100717 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Jan 2022 23:27:19 -0600 Subject: [PATCH 271/485] Add solution #142 --- 0142-linked-list-cycle-ii.js | 39 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0142-linked-list-cycle-ii.js diff --git a/0142-linked-list-cycle-ii.js b/0142-linked-list-cycle-ii.js new file mode 100644 index 00000000..90af7780 --- /dev/null +++ b/0142-linked-list-cycle-ii.js @@ -0,0 +1,39 @@ +/** + * 142. Linked List Cycle II + * https://leetcode.com/problems/linked-list-cycle-ii/ + * Difficulty: Medium + * + * Given the head of a linked list, return the node where the cycle begins. + * If there is no cycle, return null. + * + * There is a cycle in a linked list if there is some node in the list that + * can be reached again by continuously following the next pointer. Internally, + * pos is used to denote the index of the node that tail's next pointer is + * connected to (0-indexed). It is -1 if there is no cycle. Note that pos is + * not passed as a parameter. + * + * Do not modify the linked list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {ListNode} + */ +var detectCycle = function(head) { + while (head) { + if (head.visited) { + return head; + } + head.visited = 1; + head = head.next; + } + return head; +}; diff --git a/README.md b/README.md index 504d0ed9..19a1364c 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ 133|[Clone Graph](./0133-clone-graph.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| +142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From e98e2ba5b8607f3da891e6628926978f21f0f020 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Jan 2022 23:29:43 -0600 Subject: [PATCH 272/485] Add solution #198 --- 0198-house-robber.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0198-house-robber.js diff --git a/0198-house-robber.js b/0198-house-robber.js new file mode 100644 index 00000000..ab37ccec --- /dev/null +++ b/0198-house-robber.js @@ -0,0 +1,30 @@ +/** + * 198. House Robber + * https://leetcode.com/problems/house-robber/ + * Difficulty: Medium + * + * You are a professional robber planning to rob houses along a street. Each house has a certain + * amount of money stashed, the only constraint stopping you from robbing each of them is that + * adjacent houses have security systems connected and it will automatically contact the police + * if two adjacent houses were broken into on the same night. + * + * Given an integer array nums representing the amount of money of each house, return the maximum + * amount of money you can rob tonight without alerting the police. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + let previous = 0; + let current = 0; + + for (const n of nums) { + const temp = previous; + previous = current; + current = Math.max(temp + n, previous); + } + + return Math.max(current, previous); +}; diff --git a/README.md b/README.md index 19a1364c..032ca2a7 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ 189|[Rotate Array](./0189-rotate-array.js)|Medium| 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| +198|[House Robber](./0198-house-robber.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| From eeb074eaefc5f4f04b81a62416c20fd1373be8b0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Jan 2022 23:56:04 -0600 Subject: [PATCH 273/485] Add solution #213 --- 0213-house-robber-ii.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0213-house-robber-ii.js diff --git a/0213-house-robber-ii.js b/0213-house-robber-ii.js new file mode 100644 index 00000000..9bed09ac --- /dev/null +++ b/0213-house-robber-ii.js @@ -0,0 +1,41 @@ +/** + * 213. House Robber II + * https://leetcode.com/problems/house-robber-ii/ + * Difficulty: Medium + * + * You are a professional robber planning to rob houses along a street. Each house has a certain + * amount of money stashed. All houses at this place are arranged in a circle. That means the + * first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system + * connected, and it will automatically contact the police if two adjacent houses were broken into + * on the same night. + * + * Given an integer array nums representing the amount of money of each house, return the maximum + * amount of money you can rob tonight without alerting the police. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + if (nums.length === 1) { + return nums[0]; + } + + return Math.max( + handlePermutation(nums, 0, nums.length - 1), + handlePermutation(nums, 1, nums.length) + ); +}; + +function handlePermutation(nums, start, end) { + let previous = 0, current = 0; + + for (let i = start; i < end; i++) { + const temp = previous; + previous = current; + current = Math.max(temp + nums[i], previous); + } + + return Math.max(current, previous); +} diff --git a/README.md b/README.md index 032ca2a7..8b48b911 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 198|[House Robber](./0198-house-robber.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| +213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| From 985271d295c55cbb826aa58b67fcb551e4f791b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Jan 2022 23:54:13 -0600 Subject: [PATCH 274/485] Add solution #120 --- 0120-triangle.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0120-triangle.js diff --git a/0120-triangle.js b/0120-triangle.js new file mode 100644 index 00000000..6c2c41f9 --- /dev/null +++ b/0120-triangle.js @@ -0,0 +1,25 @@ +/** + * 120. Triangle + * https://leetcode.com/problems/triangle/ + * Difficulty: Medium + * + * Given a triangle array, return the minimum path sum from top to bottom. + * + * For each step, you may move to an adjacent number of the row below. More + * formally, if you are on index i on the current row, you may move to either + * index i or index i + 1 on the next row. + */ + +/** + * @param {number[][]} triangle + * @return {number} + */ +var minimumTotal = function(triangle) { + for (let i = triangle.length - 2; i > -1; i--) { + for (let j = 0; j < triangle[i].length; j++) { + triangle[i][j] += Math.min( triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + + return triangle[0][0]; +}; diff --git a/README.md b/README.md index 8b48b911..4882ee78 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| +120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| From a6b0ee83063ff5b1eb4c00ea8cca89c4ede2586a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 00:21:17 -0600 Subject: [PATCH 275/485] Add solution #1528 --- 1528-shuffle-string.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1528-shuffle-string.js diff --git a/1528-shuffle-string.js b/1528-shuffle-string.js new file mode 100644 index 00000000..ab185f8c --- /dev/null +++ b/1528-shuffle-string.js @@ -0,0 +1,23 @@ +/** + * 1528. Shuffle String + * https://leetcode.com/problems/shuffle-string/ + * Difficulty: Easy + * + * You are given a string s and an integer array indices of the same length. + * The string s will be shuffled such that the character at the ith position + * moves to indices[i] in the shuffled string. + * + * Return the shuffled string. + */ + +/** + * @param {string} s + * @param {number[]} indices + * @return {string} + */ +var restoreString = function(s, indices) { + return indices.reduce((result, index, offset) => { + result[index] = s[offset]; + return result; + }, new Array(indices.length)).join(''); +}; diff --git a/README.md b/README.md index 4882ee78..2bca2492 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,7 @@ 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| +1528|[Shuffle String](./1528-shuffle-string.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| From ee118b0bf2159f8adc56534d4cf821ef19186d2d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 00:47:10 -0600 Subject: [PATCH 276/485] Add solution #1576 --- ...-avoid-consecutive-repeating-characters.js | 39 +++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 1576-replace-all-s-to-avoid-consecutive-repeating-characters.js diff --git a/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js b/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js new file mode 100644 index 00000000..cc502651 --- /dev/null +++ b/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js @@ -0,0 +1,39 @@ +/** + * 1576. Replace All ?'s to Avoid Consecutive Repeating Characters + * https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/ + * Difficulty: Medium + * + * Given a string s containing only lowercase English letters and the '?' character, convert all + * the '?' characters into lowercase letters such that the final string does not contain any + * consecutive repeating characters. You cannot modify the non '?' characters. + * + * It is guaranteed that there are no consecutive repeating characters in the given string except + * for '?'. + * + * Return the final string after all the conversions (possibly zero) have been made. If there is + * more than one solution, return any of them. It can be shown that an answer is always possible + * with the given constraints. + */ + +/** + * @param {string} s + * @return {string} + */ +var modifyString = function(s) { + const substitute = takenCharacteres => { + for (let charCode = 97; ; charCode++) { + const attempt = String.fromCharCode(charCode); + + if (!takenCharacteres.includes(attempt)) { + return attempt; + } + } + }; + + const result = [...s]; + for (let index = 0; index < s.length; index++) { + const takenCharacteres = [result[index - 1], result[index + 1]]; + result[index] = s[index] === '?' ? substitute(takenCharacteres) : s[index]; + } + return result.join(''); +}; diff --git a/README.md b/README.md index 2bca2492..1ad97805 100644 --- a/README.md +++ b/README.md @@ -247,6 +247,7 @@ 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| +1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| From fc51da9f06f832016c416e17b507ccf59e594631 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 23:53:08 -0600 Subject: [PATCH 277/485] Add solution #143 --- 0143-reorder-list.js | 57 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0143-reorder-list.js diff --git a/0143-reorder-list.js b/0143-reorder-list.js new file mode 100644 index 00000000..e1739ce2 --- /dev/null +++ b/0143-reorder-list.js @@ -0,0 +1,57 @@ +/** + * 143. Reorder List + * https://leetcode.com/problems/reorder-list/ + * Difficulty: Medium + * + * You are given the head of a singly linked-list. The list can be represented as: + * + * L0 → L1 → … → Ln - 1 → Ln + * Reorder the list to be on the following form: + * + * L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … + * You may not modify the values in the list's nodes. Only nodes themselves may be changed. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {void} Do not return anything, modify head in-place instead. + */ +var reorderList = function(head) { + if (!head || !head.next || !head.next.next) { + return head; + } + + let list1 = head; + let list2 = head; + + while (list2.next && list2.next.next) { + list1 = list1.next; + list2 = list2.next.next; + } + + let center1 = list1; + let center2 = list1.next; + while (center2.next) { + const temp = center2.next; + center2.next = temp.next; + temp.next = center1.next; + center1.next = temp; + } + + list1 = head; + list2 = center1.next; + while (list1 != center1) { + center1.next = list2.next; + list2.next = list1.next; + list1.next = list2; + list1 = list2.next; + list2 = center1.next; + } +}; diff --git a/README.md b/README.md index 1ad97805..727be0b7 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| +143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From 7a6694e488b0e6c7b00eae54ed4ab2409485fa7c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 23:54:02 -0600 Subject: [PATCH 278/485] Add solution #1342 --- ...ber-of-steps-to-reduce-a-number-to-zero.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1342-number-of-steps-to-reduce-a-number-to-zero.js diff --git a/1342-number-of-steps-to-reduce-a-number-to-zero.js b/1342-number-of-steps-to-reduce-a-number-to-zero.js new file mode 100644 index 00000000..1b46d186 --- /dev/null +++ b/1342-number-of-steps-to-reduce-a-number-to-zero.js @@ -0,0 +1,22 @@ +/** + * 1342. Number of Steps to Reduce a Number to Zero + * https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ + * Difficulty: Easy + * + * Given an integer num, return the number of steps to reduce it to zero. + * + * In one step, if the current number is even, you have to divide it by 2, + * otherwise, you have to subtract 1 from it. + */ + +/** + * @param {number} num + * @return {number} + */ +var numberOfSteps = function(num) { + let steps = 0; + while (num > 0 && ++steps) { + num = num % 2 === 0 ? num / 2 : num -1; + } + return steps; +}; diff --git a/README.md b/README.md index 727be0b7..e9c31fd7 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1342|[Number of Steps to Reduce a Number to Zero](./1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy| 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| From 3f91703206e47a8d5fcd93d6b68bd262b13e93be Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Jan 2022 00:00:12 -0600 Subject: [PATCH 279/485] Add solution #1716 --- 1716-calculate-money-in-leetcode-bank.js | 26 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1716-calculate-money-in-leetcode-bank.js diff --git a/1716-calculate-money-in-leetcode-bank.js b/1716-calculate-money-in-leetcode-bank.js new file mode 100644 index 00000000..fc184df4 --- /dev/null +++ b/1716-calculate-money-in-leetcode-bank.js @@ -0,0 +1,26 @@ +/** + * 1716. Calculate Money in Leetcode Bank + * https://leetcode.com/problems/calculate-money-in-leetcode-bank/ + * Difficulty: Easy + * + * Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. + * + * He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will + * put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the + * previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at + * the end of the nth day. + */ + +/** + * @param {number} n + * @return {number} + */ +var totalMoney = function(n) { + let mondayCount = Math.floor(n / 7); + let aggregate = (mondayCount ** 2 + 7 * mondayCount) / 2; + let result = aggregate * 7; + for (let i = 0; i < n - mondayCount * 7; i++) { + result += mondayCount + i + 1; + } + return result; +}; diff --git a/README.md b/README.md index e9c31fd7..3fc65544 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,7 @@ 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| +1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| From 9c3ed0b313bba3669628984f86149a054dd98a34 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Jan 2022 22:13:40 -0600 Subject: [PATCH 280/485] Add solution #22 --- 0022-generate-parentheses.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/0022-generate-parentheses.js b/0022-generate-parentheses.js index d3264697..6c666c1e 100644 --- a/0022-generate-parentheses.js +++ b/0022-generate-parentheses.js @@ -18,7 +18,7 @@ var generateParenthesis = function(n) { }; function backtrack(result, str, open, close, max) { - if (str.length == max * 2){ + if (str.length === max * 2) { result.push(str); return; } From 8f0710f87eb6ea41afed36c5391380fe3b39eeb1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Jan 2022 23:53:32 -0600 Subject: [PATCH 281/485] Add solution #1791 --- 1791-find-center-of-star-graph.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1791-find-center-of-star-graph.js diff --git a/1791-find-center-of-star-graph.js b/1791-find-center-of-star-graph.js new file mode 100644 index 00000000..04fb502a --- /dev/null +++ b/1791-find-center-of-star-graph.js @@ -0,0 +1,28 @@ +/** + * 1791. Find Center of Star Graph + * https://leetcode.com/problems/find-center-of-star-graph/ + * Difficulty: Easy + * + * There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a + * graph where there is one center node and exactly n - 1 edges that connect the center node with + * every other node. + * + * You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an + * edge between the nodes ui and vi. Return the center of the given star graph. + */ + +/** + * @param {number[][]} edges + * @return {number} + */ +var findCenter = function(edges) { + const set = new Set(); + for (const edge of edges) { + for (const node of edge) { + if (set.has(node)) { + return node; + } + set.add(node); + } + } +}; diff --git a/README.md b/README.md index 3fc65544..28a7d8d7 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From 8c2f9ec25c58742d4bee46af6e722cd692faf1d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Jan 2022 23:57:52 -0600 Subject: [PATCH 282/485] Add solution #2099 --- ...quence-of-length-k-with-the-largest-sum.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 2099-find-subsequence-of-length-k-with-the-largest-sum.js diff --git a/2099-find-subsequence-of-length-k-with-the-largest-sum.js b/2099-find-subsequence-of-length-k-with-the-largest-sum.js new file mode 100644 index 00000000..bb989697 --- /dev/null +++ b/2099-find-subsequence-of-length-k-with-the-largest-sum.js @@ -0,0 +1,36 @@ +/** + * 2099. Find Subsequence of Length K With the Largest Sum + * https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer k. You want to find a subsequence + * of nums of length k that has the largest sum. + * + * Return any such subsequence as an integer array of length k. + * + * A subsequence is an array that can be derived from another array by deleting some or + * no elements without changing the order of the remaining elements. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSubsequence = function(nums, k) { + const map = new Map(); + nums.slice() + .sort((a, b) => a - b) + .slice(-k) + .forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + return nums.filter(n => { + const isInSubsequence = map.get(n); + + if (isInSubsequence) { + map.set(n, map.get(n) - 1); + } + + return isInSubsequence; + }); +}; diff --git a/README.md b/README.md index 28a7d8d7..aef3e643 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,7 @@ 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| +2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| ## License From 563927fb2df880ea9fdf8a32015b14a519fa3c4a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 00:01:53 -0600 Subject: [PATCH 283/485] Add solution #215 --- 0215-kth-largest-element-in-an-array.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0215-kth-largest-element-in-an-array.js diff --git a/0215-kth-largest-element-in-an-array.js b/0215-kth-largest-element-in-an-array.js new file mode 100644 index 00000000..a41a489b --- /dev/null +++ b/0215-kth-largest-element-in-an-array.js @@ -0,0 +1,18 @@ +/** + * 215. Kth Largest Element in an Array + * https://leetcode.com/problems/kth-largest-element-in-an-array/ + * Difficulty: Medium + * + * Given an integer array nums and an integer k, return the kth largest element in the array. + * + * Note that it is the kth largest element in the sorted order, not the kth distinct element. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findKthLargest = function(nums, k) { + return nums.sort((a, b) => a - b)[nums.length - k]; +}; diff --git a/README.md b/README.md index aef3e643..36b9687d 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| +215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| From 4d63108dac14e439336c7f4fe7a0a32195b9ec1a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 00:09:23 -0600 Subject: [PATCH 284/485] Add solution #414 --- 0414-third-maximum-number.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0414-third-maximum-number.js diff --git a/0414-third-maximum-number.js b/0414-third-maximum-number.js new file mode 100644 index 00000000..816c3336 --- /dev/null +++ b/0414-third-maximum-number.js @@ -0,0 +1,21 @@ +/** + * 414. Third Maximum Number + * https://leetcode.com/problems/third-maximum-number/ + * Difficulty: Easy + * + * Given an integer array nums, return the third distinct maximum number in this array. + * If the third maximum does not exist, return the maximum number. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var thirdMax = function(nums) { + const sortedSet = [...new Set(nums)].sort((a, b) => a - b); + const thirdMax = sortedSet[sortedSet.length - 3]; + + return thirdMax !== undefined + ? thirdMax + : sortedSet[sortedSet.length - 1]; +}; diff --git a/README.md b/README.md index 36b9687d..fe2505b6 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 0394fb2047c302645917ad6338a539658ff46617 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 23:09:27 -0600 Subject: [PATCH 285/485] Add solution #204 --- 0204-count-primes.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0204-count-primes.js diff --git a/0204-count-primes.js b/0204-count-primes.js new file mode 100644 index 00000000..681460c1 --- /dev/null +++ b/0204-count-primes.js @@ -0,0 +1,25 @@ +/** + * 204. Count Primes + * https://leetcode.com/problems/count-primes/ + * Difficulty: Medium + * + * Given an integer n, return the number of prime numbers that are strictly less than n. + */ + +/** + * @param {number} n + * @return {number} + */ +var countPrimes = function(n) { + const nonPrimes = []; + let result = 0; + for (let i = 2; i < n; i++) { + if (!nonPrimes[i]) { + result++; + for (let j = 2; i * j < n; j++) { + nonPrimes[i * j] = 1; + } + } + } + return result; +}; diff --git a/README.md b/README.md index fe2505b6..69cffdad 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 198|[House Robber](./0198-house-robber.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| +204|[Count Primes](./0204-count-primes.js)|Medium| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| From 942b6730e1799cb755568bbbe3b68629438eeea5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 23:14:08 -0600 Subject: [PATCH 286/485] Add solution #520 --- 0520-detect-capital.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0520-detect-capital.js diff --git a/0520-detect-capital.js b/0520-detect-capital.js new file mode 100644 index 00000000..639780b8 --- /dev/null +++ b/0520-detect-capital.js @@ -0,0 +1,21 @@ +/** + * 520. Detect Capital + * https://leetcode.com/problems/detect-capital/ + * Difficulty: Easy + * + * We define the usage of capitals in a word to be right when one of the following + * cases holds: + * - All letters in this word are capitals, like "USA". + * - All letters in this word are not capitals, like "leetcode". + * - Only the first letter in this word is capital, like "Google". + * + * Given a string word, return true if the usage of capitals in it is right. + */ + +/** + * @param {string} word + * @return {boolean} + */ +var detectCapitalUse = function(word) { + return /^[A-Z]?[a-z]+$|^[A-Z]+$/.test(word); +}; diff --git a/README.md b/README.md index 69cffdad..36325adf 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| +520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| From 83440f4a982d5730de051b5e81455696b928e2d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Jan 2022 23:48:10 -0600 Subject: [PATCH 287/485] Add solution #18 --- 0018-4sum.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0018-4sum.js diff --git a/0018-4sum.js b/0018-4sum.js new file mode 100644 index 00000000..ab1a8592 --- /dev/null +++ b/0018-4sum.js @@ -0,0 +1,59 @@ +/** + * 18. 4Sum + * https://leetcode.com/problems/4sum/ + * Difficulty: Medium + * + * Given an array nums of n integers, return an array of all the unique + * quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: + * - 0 <= a, b, c, d < n + * - a, b, c, and d are distinct. + * - nums[a] + nums[b] + nums[c] + nums[d] == target + * + * You may return the answer in any order. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function(nums, target) { + const result = []; + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 3; i++) { + for (let j = i + 1; j < nums.length - 2; j++) { + let high = nums.length - 1; + let low = j + 1; + + while (low < high) { + const sum = nums[i] + nums[j] + nums[low] + nums[high]; + + if (sum === target) { + result.push([nums[i], nums[j], nums[low], nums[high]]); + while (nums[low] === nums[low + 1]) { + low++; + } + while (nums[high] === nums[high - 1]) { + high--; + } + low++; + high--; + } else if (sum < target) { + low++; + } else { + high--; + } + } + while (nums[j] === nums[j + 1]) { + j++; + } + } + while (nums[i] === nums[i + 1]) { + i++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 36325adf..d29098d2 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ 15|[3Sum](./0015-3sum.js)|Medium| 16|[3Sum Closest](./0016-3sum-closest.js)|Medium| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +18|[4Sum](./0018-4sum.js)|Medium| 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| From 47908370043c163b88715a2045c2b6859e7528de Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Jan 2022 23:56:12 -0600 Subject: [PATCH 288/485] Add solution #2129 --- 2129-capitalize-the-title.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2129-capitalize-the-title.js diff --git a/2129-capitalize-the-title.js b/2129-capitalize-the-title.js new file mode 100644 index 00000000..8a9760f4 --- /dev/null +++ b/2129-capitalize-the-title.js @@ -0,0 +1,22 @@ +/** + * 2129. Capitalize the Title + * https://leetcode.com/problems/capitalize-the-title/ + * Difficulty: Easy + * + * You are given a string title consisting of one or more words separated by a single space, + * where each word consists of English letters. Capitalize the string by changing the + * capitalization of each word such that: + * - If the length of the word is 1 or 2 letters, change all letters to lowercase. + * - Otherwise, change the first letter to uppercase and the remaining letters to lowercase. + * Return the capitalized title. + */ + +/** + * @param {string} title + * @return {string} + */ +var capitalizeTitle = function(title) { + return title.split(/\s+/).map(word => { + return word.toLowerCase().replace(/^\w/, l => word.length > 2 ? l.toUpperCase() : l); + }).join(' '); +}; diff --git a/README.md b/README.md index d29098d2..41f01a05 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,7 @@ 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| +2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| ## License From 15e6f2a73e6d3ad858c3caaab967b8a28c5af69e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 1 Jan 2023 17:06:40 -0600 Subject: [PATCH 289/485] Add solution #290 --- 0290-word-pattern.js | 29 +++++++++++++++++++++++++++++ README.md | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 0290-word-pattern.js diff --git a/0290-word-pattern.js b/0290-word-pattern.js new file mode 100644 index 00000000..293062d4 --- /dev/null +++ b/0290-word-pattern.js @@ -0,0 +1,29 @@ +/** + * 290. Word Pattern + * https://leetcode.com/problems/word-pattern/ + * Difficulty: Easy + * + * Given a pattern and a string s, find if s follows the same pattern. + * + * Here follow means a full match, such that there is a bijection between + * a letter in pattern and a non-empty word in s. + */ + +/** + * @param {string} pattern + * @param {string} s + * @return {boolean} + */ +var wordPattern = function(pattern, s) { + const words = s.split(/\s+/); + const map = new Map(); + + return words.every((word, index) => { + const offset = pattern.length === words.length ? index + 1 : words.length / pattern.length; + const sequence = pattern.slice(index, offset); + if (!map.has(sequence) && !Array.from(map.values()).includes(word)) { + map.set(sequence, word); + } + return map.get(sequence) === word && pattern.length <= words.length; + }); +}; diff --git a/README.md b/README.md index 41f01a05..94f18d5b 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +290|[Word Pattern](./0290-word-pattern.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| @@ -285,4 +286,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2022 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2023 [Josh Crozier](https://joshcrozier.com) From a488d646528307cb2e3290f1ed5ba2f048436623 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 1 Jan 2023 17:14:52 -0600 Subject: [PATCH 290/485] Add solution #2427 --- 2427-number-of-common-factors.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2427-number-of-common-factors.js diff --git a/2427-number-of-common-factors.js b/2427-number-of-common-factors.js new file mode 100644 index 00000000..03ba1993 --- /dev/null +++ b/2427-number-of-common-factors.js @@ -0,0 +1,22 @@ +/** + * 2427. Number of Common Factors + * https://leetcode.com/problems/number-of-common-factors/ + * Difficulty: Easy + * + * Given two positive integers a and b, return the number of common factors of a and b. + * + * An integer x is a common factor of a and b if x divides both a and b. + */ + +/** + * @param {number} a + * @param {number} b + * @return {number} + */ +var commonFactors = function(a, b) { + let count = 0; + for (let i = Math.min(a, b); i > 0; i--) { + if (a % i === 0 && b % i === 0) count++; + } + return count; +}; diff --git a/README.md b/README.md index 94f18d5b..07aea69e 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| ## License From b39c80d7e03b5689677ee5f0d2dc4bead39b9e7b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 1 Jan 2023 17:36:55 -0600 Subject: [PATCH 291/485] Add solution #1812 --- ...-determine-color-of-a-chessboard-square.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1812-determine-color-of-a-chessboard-square.js diff --git a/1812-determine-color-of-a-chessboard-square.js b/1812-determine-color-of-a-chessboard-square.js new file mode 100644 index 00000000..ca7bb3dd --- /dev/null +++ b/1812-determine-color-of-a-chessboard-square.js @@ -0,0 +1,22 @@ +/** + * 1812. Determine Color of a Chessboard Square + * https://leetcode.com/problems/determine-color-of-a-chessboard-square/ + * Difficulty: Easy + * + * You are given coordinates, a string that represents the coordinates of a square of + * the chessboard. Below is a chessboard for your reference. + * + * Return true if the square is white, and false if the square is black. + * + * The coordinate will always represent a valid chessboard square. The coordinate will + * always have the letter first, and the number second. + */ + +/** + * @param {string} coordinates + * @return {boolean} + */ +var squareIsWhite = function(coordinates) { + const [x, y] = coordinates; + return (x.charCodeAt() + +y) % 2 !== 0; +}; diff --git a/README.md b/README.md index 07aea69e..ab1585b3 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,7 @@ 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| +1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From 3b2f1f734ce413cf1dd2de1a3979e2285c92f552 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 2 Jan 2023 17:15:49 -0600 Subject: [PATCH 292/485] Add solution #316 --- 0316-remove-duplicate-letters.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0316-remove-duplicate-letters.js diff --git a/0316-remove-duplicate-letters.js b/0316-remove-duplicate-letters.js new file mode 100644 index 00000000..f33d96e6 --- /dev/null +++ b/0316-remove-duplicate-letters.js @@ -0,0 +1,29 @@ +/** + * 316. Remove Duplicate Letters + * https://leetcode.com/problems/remove-duplicate-letters/ + * Difficulty: Medium + * + * Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is + * the smallest in lexicographical order among all possible results. + */ + +/** + * @param {string} s + * @return {string} + */ +var removeDuplicateLetters = function(s) { + const stack = []; + + for (let i = 0; i < s.length; i++) { + const letter = s[i]; + if (stack.indexOf(letter) > -1) { + continue; + } + while (stack.length > 0 && stack[stack.length - 1] > letter && s.indexOf(stack[stack.length - 1], i) > i) { + stack.pop(); + } + stack.push(letter); + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index ab1585b3..b581bf0d 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| +316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| From 30d77fb185ab60d8d3814ab630294c49866be72f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 2 Jan 2023 17:17:27 -0600 Subject: [PATCH 293/485] Add solution #1081 --- ...lest-subsequence-of-distinct-characters.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1081-smallest-subsequence-of-distinct-characters.js diff --git a/1081-smallest-subsequence-of-distinct-characters.js b/1081-smallest-subsequence-of-distinct-characters.js new file mode 100644 index 00000000..9ecfe62d --- /dev/null +++ b/1081-smallest-subsequence-of-distinct-characters.js @@ -0,0 +1,29 @@ +/** + * 1081. Smallest Subsequence of Distinct Characters + * https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ + * Difficulty: Medium + * + * Given a string s, return the lexicographically smallest subsequence + * of s that contains all the distinct characters of s exactly once. + */ + +/** + * @param {string} s + * @return {string} + */ +var smallestSubsequence = function(s) { + const stack = []; + + for (let i = 0; i < s.length; i++) { + const letter = s[i]; + if (stack.indexOf(letter) > -1) { + continue; + } + while (stack.length > 0 && stack[stack.length - 1] > letter && s.indexOf(stack[stack.length - 1], i) > i) { + stack.pop(); + } + stack.push(letter); + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index b581bf0d..a642140e 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,7 @@ 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| +1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| From 4d67380ace68de3586e3535970f3791bd0397439 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 2 Jan 2023 17:25:24 -0600 Subject: [PATCH 294/485] Add solution #2027 --- 2027-minimum-moves-to-convert-string.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2027-minimum-moves-to-convert-string.js diff --git a/2027-minimum-moves-to-convert-string.js b/2027-minimum-moves-to-convert-string.js new file mode 100644 index 00000000..cde8e1b1 --- /dev/null +++ b/2027-minimum-moves-to-convert-string.js @@ -0,0 +1,21 @@ +/** + * 2027. Minimum Moves to Convert String + * https://leetcode.com/problems/minimum-moves-to-convert-string/ + * Difficulty: Easy + * + * You are given a string s consisting of n characters which are either 'X' or 'O'. + * + * A move is defined as selecting three consecutive characters of s and converting them + * to 'O'. Note that if a move is applied to the character 'O', it will stay the same. + * + * Return the minimum number of moves required so that all the characters of s are + * converted ]to 'O'. + */ + +/** + * @param {string} s + * @return {number} + */ +var minimumMoves = function(s) { + return s.match(/X.{0,2}/g)?.length ?? 0; +}; diff --git a/README.md b/README.md index a642140e..a2f0fb80 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,7 @@ 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| +2027|[Minimum Moves to Convert String](./2027-minimum-moves-to-convert-string.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| From 672f4100ba6e4463e0faa08215c1f78715674fc2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 3 Jan 2023 19:18:40 -0600 Subject: [PATCH 295/485] Add solution #2244 --- 2244-minimum-rounds-to-complete-all-tasks.js | 31 ++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2244-minimum-rounds-to-complete-all-tasks.js diff --git a/2244-minimum-rounds-to-complete-all-tasks.js b/2244-minimum-rounds-to-complete-all-tasks.js new file mode 100644 index 00000000..9aa85e1f --- /dev/null +++ b/2244-minimum-rounds-to-complete-all-tasks.js @@ -0,0 +1,31 @@ +/** + * 2244. Minimum Rounds to Complete All Tasks + * https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level + * of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. + * + * Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to + * complete all the tasks. + */ + +/** + * @param {number[]} tasks + * @return {number} + */ +var minimumRounds = function(tasks) { + const map = new Map(); + let result = 0; + + tasks.forEach(task => map.set(task, map.has(task) ? map.get(task) + 1 : 1)); + + for (const count of map.values()) { + if (count < 2) { + return -1; + } + result += Math.floor(count / 3) + (count % 3 === 0 ? 0 : 1); + } + + return result; +}; diff --git a/README.md b/README.md index a2f0fb80..eb72c08f 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| ## License From 86c1964141711ea46ebf7d10072e277ab668398e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 3 Jan 2023 19:25:37 -0600 Subject: [PATCH 296/485] Add solution #762 --- ...er-of-set-bits-in-binary-representation.js | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0762-prime-number-of-set-bits-in-binary-representation.js diff --git a/0762-prime-number-of-set-bits-in-binary-representation.js b/0762-prime-number-of-set-bits-in-binary-representation.js new file mode 100644 index 00000000..7b929382 --- /dev/null +++ b/0762-prime-number-of-set-bits-in-binary-representation.js @@ -0,0 +1,30 @@ +/** + * 762. Prime Number of Set Bits in Binary Representation + * https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/ + * Difficulty: Easy + * + * Given two integers left and right, return the count of numbers in the inclusive range [left, right] having + * a prime number of set bits in their binary representation. + * + * Recall that the number of set bits an integer has is the number of 1's present when written in binary. + * + * For example, 21 written in binary is 10101, which has 3 set bits. + */ + +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +var countPrimeSetBits = function(left, right) { + const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]); + let result = 0; + + for (let i = left; i <= right; i++) { + if (primes.has(i.toString(2).replace(/0+/g, '').length)) { + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index eb72c08f..9df21fc5 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| From 922bd2a5841b222f29acc57937acf980e0b520ca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 3 Jan 2023 19:44:44 -0600 Subject: [PATCH 297/485] Add solution #746 --- 0746-min-cost-climbing-stairs.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0746-min-cost-climbing-stairs.js diff --git a/0746-min-cost-climbing-stairs.js b/0746-min-cost-climbing-stairs.js new file mode 100644 index 00000000..65b22d5d --- /dev/null +++ b/0746-min-cost-climbing-stairs.js @@ -0,0 +1,28 @@ +/** + * 746. Min Cost Climbing Stairs + * https://leetcode.com/problems/min-cost-climbing-stairs/ + * Difficulty: Easy + * + * You are given an integer array cost where cost[i] is the cost of ith step on a staircase. + * Once you pay the cost, you can either climb one or two steps. + * + * You can either start from the step with index 0, or the step with index 1. + * + * Return the minimum cost to reach the top of the floor. + */ + +/** + * @param {number[]} cost + * @return {number} + */ +var minCostClimbingStairs = function(cost) { + let [first, second] = cost; + + for (let index = 2; index < cost.length; index++) { + const cursor = cost[index] + Math.min(first, second); + first = second; + second = cursor; + } + + return Math.min(first, second); +}; diff --git a/README.md b/README.md index 9df21fc5..a8369120 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From dc44d7e2087a4afb39fc0e399fe31715ce512549 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 4 Jan 2023 17:34:51 -0600 Subject: [PATCH 298/485] Add solution #747 --- ...largest-number-at-least-twice-of-others.js | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0747-largest-number-at-least-twice-of-others.js diff --git a/0747-largest-number-at-least-twice-of-others.js b/0747-largest-number-at-least-twice-of-others.js new file mode 100644 index 00000000..9a0f6feb --- /dev/null +++ b/0747-largest-number-at-least-twice-of-others.js @@ -0,0 +1,20 @@ +/** + * 747. Largest Number At Least Twice of Others + * https://leetcode.com/problems/largest-number-at-least-twice-of-others/ + * Difficulty: Easy + * + * You are given an integer array nums where the largest integer is unique. + * + * Determine whether the largest element in the array is at least twice as much + * as every other number in the array. If it is, return the index of the largest + * element, or return -1 otherwise. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var dominantIndex = function(nums) { + const max = Math.max(...nums); + return nums.find(n => n !== max && n > max / 2) ? -1 : nums.indexOf(max); +}; diff --git a/README.md b/README.md index a8369120..7d1afeac 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| +747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From be50f60cba89f94a51bca8831827bfd7fc33e7c1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 4 Jan 2023 18:07:09 -0600 Subject: [PATCH 299/485] Add solution #38 --- 0038-count-and-say.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0038-count-and-say.js diff --git a/0038-count-and-say.js b/0038-count-and-say.js new file mode 100644 index 00000000..cca4fe01 --- /dev/null +++ b/0038-count-and-say.js @@ -0,0 +1,35 @@ +/** + * 38. Count and Say + * https://leetcode.com/problems/count-and-say/ + * Difficulty: Medium + * + * The count-and-say sequence is a sequence of digit strings defined by the recursive formula: + * - countAndSay(1) = "1" + * - countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is + * then converted into a different digit string. + * + * To determine how you "say" a digit string, split it into the minimal number of substrings such + * that each substring contains exactly one unique digit. Then for each substring, say the number + * of digits, then say the digit. Finally, concatenate every said digit. + * + * For example, the saying and conversion for digit string "3322251": + * Given a positive integer n, return the nth term of the count-and-say sequence. + */ + +/** + * @param {number} n + * @return {string} + */ +var countAndSay = function(n) { + let result = '1'; + + for (let i = 1; i < n; i++) { + result = result.replace(/((\d)\2*)/g, '$1—') + .split('—') + .map(s => s ? `${s.length}${s[0]}` : '') + .join(''); + } + + return result; +}; + diff --git a/README.md b/README.md index 7d1afeac..23ebcb9c 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +38|[Count and Say](./0038-count-and-say.js)|Medium| 39|[Combination Sum](./0039-combination-sum.js)|Medium| 40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| From ca9359080c8f9a86e4194f4ef5d376ca23366e26 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 4 Jan 2023 18:16:46 -0600 Subject: [PATCH 300/485] Add solution #2154 --- 2154-keep-multiplying-found-values-by-two.js | 25 ++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 2154-keep-multiplying-found-values-by-two.js diff --git a/2154-keep-multiplying-found-values-by-two.js b/2154-keep-multiplying-found-values-by-two.js new file mode 100644 index 00000000..bdf79461 --- /dev/null +++ b/2154-keep-multiplying-found-values-by-two.js @@ -0,0 +1,25 @@ +/** + * 2154. Keep Multiplying Found Values by Two + * https://leetcode.com/problems/keep-multiplying-found-values-by-two/ + * Difficulty: Easy + * + * You are given an array of integers nums. You are also given an integer original which + * is the first number that needs to be searched for in nums. + * + * You then do the following steps: + * If original is found in nums, multiply it by two (i.e., set original = 2 * original). + * Otherwise, stop the process. + * Repeat this process with the new number as long as you keep finding the number. + * Return the final value of original. + */ + +/** + * @param {number[]} nums + * @param {number} original + * @return {number} + */ +var findFinalValue = function(nums, original) { + return nums + .sort((a, b) => a - b) + .reduce((result, n) => result *= n === result ? 2 : 1, original); +}; diff --git a/README.md b/README.md index 23ebcb9c..69ea77a9 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| From 78e9815d4164f1e1498f037f3344e076c6d0d616 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 5 Jan 2023 17:47:23 -0600 Subject: [PATCH 301/485] Add solution #78 --- 0078-subsets.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0078-subsets.js diff --git a/0078-subsets.js b/0078-subsets.js new file mode 100644 index 00000000..d1e23dd7 --- /dev/null +++ b/0078-subsets.js @@ -0,0 +1,27 @@ +/** + * 78. Subsets + * https://leetcode.com/problems/subsets/ + * Difficulty: Medium + * + * Given an integer array nums of unique elements, return all possible subsets (the power set). + * + * The solution set must not contain duplicate subsets. Return the solution in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var subsets = function(nums) { + const result = []; + dfs([], 0); + + function dfs(subset, start) { + result.push(subset); + for (let index = start; index < nums.length; index++) { + dfs([...subset, nums[index]], index + 1); + } + } + + return result; +}; diff --git a/README.md b/README.md index 69ea77a9..d566f272 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| +78|[Subsets](./0078-subsets.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From 374d4ee473da399072db13dde0a9c0cef8862a0b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 5 Jan 2023 17:50:54 -0600 Subject: [PATCH 302/485] Add solution #452 --- ...imum-number-of-arrows-to-burst-balloons.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0452-minimum-number-of-arrows-to-burst-balloons.js diff --git a/0452-minimum-number-of-arrows-to-burst-balloons.js b/0452-minimum-number-of-arrows-to-burst-balloons.js new file mode 100644 index 00000000..ab5f6dfe --- /dev/null +++ b/0452-minimum-number-of-arrows-to-burst-balloons.js @@ -0,0 +1,42 @@ +/** + * 452. Minimum Number of Arrows to Burst Balloons + * https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ + * Difficulty: Medium + * + * There are some spherical balloons taped onto a flat wall that represents the XY-plane. + * The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] + * denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not + * know the exact y-coordinates of the balloons. + * + * Arrows can be shot up directly vertically (in the positive y-direction) from different points + * along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if + * x(start) <= x <= x(end). There is no limit to the number of arrows that can be shot. A shot + * arrow keeps traveling up infinitely, bursting any balloons in its path. + * + * Given the array points, return the minimum number of arrows that must be shot to burst all + * balloons. + */ + +/** + * @param {number[][]} points + * @return {number} + */ +var findMinArrowShots = function(points) { + let result = 0; + let i = 0; + + points.sort(([a], [b]) => a - b); + + while (i < points.length) { + let [left, right] = points[i]; + i++; + while (i < points.length && points[i][0] <= right && points[i][1] >= left) { + left = Math.max(left, points[i][0]); + right = Math.min(right, points[i][1]); + i++; + } + result++; + } + + return result; +}; diff --git a/README.md b/README.md index d566f272..d8a1952c 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| +452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| From f5362f35720efd47263ea0eb3e96b0755f7689e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 5 Jan 2023 17:52:50 -0600 Subject: [PATCH 303/485] Add solution #69 --- 0069-sqrtx.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0069-sqrtx.js diff --git a/0069-sqrtx.js b/0069-sqrtx.js new file mode 100644 index 00000000..cfd60912 --- /dev/null +++ b/0069-sqrtx.js @@ -0,0 +1,24 @@ +/** + * 69. Sqrt(x) + * https://leetcode.com/problems/sqrtx/ + * Difficulty: Medium + * + * Given a non-negative integer x, return the square root of x rounded down to the nearest + * integer. The returned integer should be non-negative as well. + * + * You must not use any built-in exponent function or operator. + */ + +/** + * @param {number} x + * @return {number} + */ +var mySqrt = function(x) { + let result = 1; + + while (result * result <= x) { + result++; + } + + return result - 1; +}; diff --git a/README.md b/README.md index d8a1952c..c1c10d46 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| From 984c931c00c87e6c76fcf20f9bfb36fcbbd9687f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 6 Jan 2023 20:16:54 -0600 Subject: [PATCH 304/485] Add solution #134 --- 0134-gas-station.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0134-gas-station.js diff --git a/0134-gas-station.js b/0134-gas-station.js new file mode 100644 index 00000000..de7b5b6d --- /dev/null +++ b/0134-gas-station.js @@ -0,0 +1,34 @@ +/** + * 134. Gas Station + * https://leetcode.com/problems/gas-station/ + * Difficulty: Medium + * + * There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. + * + * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to + * its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. + * + * Given two integer arrays gas and cost, return the starting gas station's index if you can travel around + * the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is + * guaranteed to be unique + */ + +/** + * @param {number[]} gas + * @param {number[]} cost + * @return {number} + */ +var canCompleteCircuit = function(gas, cost) { + let total = 0, tank = 0, index = 0; + + for (let i = 0; i < gas.length; i++) { + tank += gas[i] - cost[i]; + total += gas[i] - cost[i]; + if (tank < 0) { + tank = 0; + index = i + 1; + } + } + + return total >= 0 ? index : -1; +}; diff --git a/README.md b/README.md index c1c10d46..71c6c2f6 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| +134|[Gas Station](./0134-gas-station.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| From 18a6904c2032772a32a1e48258909ee507430c02 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 6 Jan 2023 20:18:10 -0600 Subject: [PATCH 305/485] Add solution #90 --- 0090-subsets-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0090-subsets-ii.js diff --git a/0090-subsets-ii.js b/0090-subsets-ii.js new file mode 100644 index 00000000..45e2dec0 --- /dev/null +++ b/0090-subsets-ii.js @@ -0,0 +1,32 @@ +/** + * 90. Subsets II + * https://leetcode.com/problems/subsets-ii/ + * Difficulty: Medium + * + * Given an integer array nums that may contain duplicates, return all possible subsets (the power set). + * + * The solution set must not contain duplicate subsets. Return the solution in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var subsetsWithDup = function(nums) { + const seen = new Set(); + const result = []; + dfs([], 0); + + function dfs(subset, start) { + const key = subset.sort((a, b) => a - b).join(''); + if (!seen.has(key)) { + result.push(subset); + seen.add(key); + } + for (let index = start; index < nums.length; index++) { + dfs([...subset, nums[index]], index + 1); + } + } + + return result; +}; diff --git a/README.md b/README.md index 71c6c2f6..41c7cd10 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 78|[Subsets](./0078-subsets.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +90|[Subsets II](./0090-subsets-ii.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| From c4bda1b83efbe5fe257b1aa82b114bf657cc65a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 6 Jan 2023 20:25:22 -0600 Subject: [PATCH 306/485] Add solution #367 --- 0367-valid-perfect-square.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0367-valid-perfect-square.js diff --git a/0367-valid-perfect-square.js b/0367-valid-perfect-square.js new file mode 100644 index 00000000..22e6f2a2 --- /dev/null +++ b/0367-valid-perfect-square.js @@ -0,0 +1,30 @@ +/** + * 367. Valid Perfect Square + * https://leetcode.com/problems/valid-perfect-square/ + * Difficulty: Easy + * + * Given a positive integer num, return true if num is a perfect square or false otherwise. + * + * A perfect square is an integer that is the square of an integer. In other words, it is the + * product of some integer with itself. + * + * You must not use any built-in library function, such as sqrt. + */ + +/** + * @param {number} num + * @return {boolean} + */ +var isPerfectSquare = function(num) { + let i = 1; + + while (num > 0) { + num -= i; + i += 2; + if (num === 0) { + return true; + } + } + + return false; +}; diff --git a/README.md b/README.md index 41c7cd10..0f27309c 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 6d748c2f39cbc4d62befc4eb1d2288e27d3c09ac Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 7 Jan 2023 17:06:50 -0600 Subject: [PATCH 307/485] Add solution #135 --- 0135-candy.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0135-candy.js diff --git a/0135-candy.js b/0135-candy.js new file mode 100644 index 00000000..d9e373c0 --- /dev/null +++ b/0135-candy.js @@ -0,0 +1,37 @@ +/** + * 135. Candy + * https://leetcode.com/problems/candy/ + * Difficulty: Hard + * + * There are n children standing in a line. Each child is assigned a rating value given + * in the integer array ratings. + * + * You are giving candies to these children subjected to the following requirements: + * - Each child must have at least one candy. + * - Children with a higher rating get more candies than their neighbors. + * + * Return the minimum number of candies you need to have to distribute the candies to + * the children. + */ + +/** + * @param {number[]} ratings + * @return {number} + */ +var candy = function(ratings) { + const data = new Array(ratings.length).fill(1); + + for (let i = 1; i < ratings.length; i++) { + if (ratings[i - 1] < ratings[i]) { + data[i] = data[i - 1] + 1; + } + } + + for (let i = ratings.length - 1; i > 0; i--) { + if (ratings[i - 1] > ratings[i]) { + data[i - 1] = data[i - 1] > data[i] + 1 ? data[i - 1] : data[i] + 1; + } + } + + return data.reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 0f27309c..502adf81 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| +135|[Candy](./0135-candy.js)|Hard| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| From b2f838a6ead47852e6552b31f063638fd911566d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 7 Jan 2023 17:09:06 -0600 Subject: [PATCH 308/485] Add solution #2469 --- 2469-convert-the-temperature.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2469-convert-the-temperature.js diff --git a/2469-convert-the-temperature.js b/2469-convert-the-temperature.js new file mode 100644 index 00000000..8e0c2f47 --- /dev/null +++ b/2469-convert-the-temperature.js @@ -0,0 +1,21 @@ +/** + * 2469. Convert the Temperature + * https://leetcode.com/problems/convert-the-temperature/ + * Difficulty: Easy + * + * You are given a non-negative floating point number rounded to two decimal places celsius, + * that denotes the temperature in Celsius. + * + * You should convert Celsius into Kelvin and Fahrenheit and return it as an array + * ans = [kelvin, fahrenheit]. + * + * Return the array ans. Answers within 10-5 of the actual answer will be accepted. + */ + +/** + * @param {number} celsius + * @return {number[]} + */ +var convertTemperature = function(celsius) { + return [celsius + 273.15, celsius * 1.80 + 32]; +}; diff --git a/README.md b/README.md index 502adf81..1972c5a3 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| +2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| ## License From 19fa98ebd4ca7db1606399788883e0b94a41f5f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 7 Jan 2023 17:10:33 -0600 Subject: [PATCH 309/485] Add solution #137 --- 0137-single-number-ii.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0137-single-number-ii.js diff --git a/0137-single-number-ii.js b/0137-single-number-ii.js new file mode 100644 index 00000000..4031d398 --- /dev/null +++ b/0137-single-number-ii.js @@ -0,0 +1,26 @@ +/** + * 137. Single Number II + * https://leetcode.com/problems/single-number-ii/ + * Difficulty: Medium + * + * Given an integer array nums where every element appears three times except for one, which appears + * exactly once. Find the single element and return it. + * + * You must implement a solution with a linear runtime complexity and use only constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function(nums) { + let a = 0, b = 0; + + nums.forEach(c => { + const offset = (~a & b & c) | (a & ~b & ~c); + b = (~a & ~b & c) | (~a & b & ~c); + a = offset; + }); + + return a | b; +}; diff --git a/README.md b/README.md index 1972c5a3..559b88e1 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ 134|[Gas Station](./0134-gas-station.js)|Medium| 135|[Candy](./0135-candy.js)|Hard| 136|[Single Number](./0136-single-number.js)|Easy| +137|[Single Number II](./0137-single-number-ii.js)|Medium| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From e6678862b46f52fa5829f0abce86f730eb0c9983 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 8 Jan 2023 15:14:45 -0600 Subject: [PATCH 310/485] Add solution #2235 --- 2235-add-two-integers.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 2235-add-two-integers.js diff --git a/2235-add-two-integers.js b/2235-add-two-integers.js new file mode 100644 index 00000000..ab31d2c9 --- /dev/null +++ b/2235-add-two-integers.js @@ -0,0 +1,16 @@ +/** + * 2235. Add Two Integers + * https://leetcode.com/problems/add-two-integers/ + * Difficulty: Easy + * + * Given two integers num1 and num2, return the sum of the two integers. + */ + +/** + * @param {number} num1 + * @param {number} num2 + * @return {number} + */ +var sum = function(num1, num2) { + return num1 + num2; +}; diff --git a/README.md b/README.md index 559b88e1..034234ce 100644 --- a/README.md +++ b/README.md @@ -298,6 +298,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| From c70d72225d780bfb53cd293d9788c6a2413034c6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 8 Jan 2023 15:16:22 -0600 Subject: [PATCH 311/485] Add solution #149 --- 0149-max-points-on-a-line.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0149-max-points-on-a-line.js diff --git a/0149-max-points-on-a-line.js b/0149-max-points-on-a-line.js new file mode 100644 index 00000000..003f8bb8 --- /dev/null +++ b/0149-max-points-on-a-line.js @@ -0,0 +1,29 @@ +/** + * 149. Max Points on a Line + * https://leetcode.com/problems/max-points-on-a-line/ + * Difficulty: Hard + * + * Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, + * return the maximum number of points that lie on the same straight line. + */ + +/** + * @param {number[][]} points + * @return {number} + */ +var maxPoints = function(points) { + let max = 0; + + points.forEach(x => { + const slopes = new Map(); + + points.forEach(y => { + if (x === y) return; + const slope = y[0] - x[0] !== 0 ? (y[1] - x[1]) / (y[0] - x[0]) : Infinity; + slopes.set(slope, (slopes.get(slope) || 0) + 1); + max = Math.max(max, slopes.get(slope)); + }); + }); + + return max + 1; +}; diff --git a/README.md b/README.md index 034234ce..32d3e1d5 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ 143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| +149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| From efc9a1b79212f50e5a599516e0c465635c99cb72 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 8 Jan 2023 15:17:40 -0600 Subject: [PATCH 312/485] Add solution #509 --- 0509-fibonacci-number.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0509-fibonacci-number.js diff --git a/0509-fibonacci-number.js b/0509-fibonacci-number.js new file mode 100644 index 00000000..2c4db308 --- /dev/null +++ b/0509-fibonacci-number.js @@ -0,0 +1,25 @@ +/** + * 509. Fibonacci Number + * https://leetcode.com/problems/fibonacci-number/ + * Difficulty: Easy + * + * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, + * such that each number is the sum of the two preceding ones, starting from 0 and 1. That is: + * - F(0) = 0, F(1) = 1 + * - F(n) = F(n - 1) + F(n - 2), for n > 1. + * Given n, calculate F(n). + */ + +/** + * @param {number} n + * @return {number} + */ +var fib = function(n) { + const nums = [0, 1]; + + for (let i = 2; i <= n; i++) { + nums.push(nums[i - 2] + nums[i - 1]); + } + + return nums[n]; +}; diff --git a/README.md b/README.md index 32d3e1d5..8b24869d 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| +509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From 9e9c133a8981873da98d99b4697171138b390cc2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 9 Jan 2023 22:26:37 -0600 Subject: [PATCH 313/485] Add solution #1331 --- 1331-rank-transform-of-an-array.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1331-rank-transform-of-an-array.js diff --git a/1331-rank-transform-of-an-array.js b/1331-rank-transform-of-an-array.js new file mode 100644 index 00000000..40bb5243 --- /dev/null +++ b/1331-rank-transform-of-an-array.js @@ -0,0 +1,25 @@ +/** + * 1331. Rank Transform of an Array + * https://leetcode.com/problems/rank-transform-of-an-array/ + * Difficulty: Easy + * + * Given an array of integers arr, replace each element with its rank. + * + * The rank represents how large the element is. The rank has the following rules: + * - Rank is an integer starting from 1. + * - The larger the element, the larger the rank. If two elements are equal, their + * rank must be the same. + * - Rank should be as small as possible. + */ + +/** + * @param {number[]} arr + * @return {number[]} + */ +var arrayRankTransform = function(arr) { + const ranks = [...new Set(arr)] + .sort((a, b) => a - b) + .reduce((map, value, index) => map.set(value, index + 1), new Map()); + + return arr.map(rank => ranks.get(rank)); +}; diff --git a/README.md b/README.md index 8b24869d..10f0d3d0 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| +1331|[Rank Transform of an Array](./1331-rank-transform-of-an-array.js)|Easy| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1342|[Number of Steps to Reduce a Number to Zero](./1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy| From 6ac75eb58555642226c71c066ea3a980cc56ea9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 9 Jan 2023 22:28:03 -0600 Subject: [PATCH 314/485] Add solution #1817 --- 1817-finding-the-users-active-minutes.js | 39 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 1817-finding-the-users-active-minutes.js diff --git a/1817-finding-the-users-active-minutes.js b/1817-finding-the-users-active-minutes.js new file mode 100644 index 00000000..2988b8af --- /dev/null +++ b/1817-finding-the-users-active-minutes.js @@ -0,0 +1,39 @@ +/** + * 1817. Finding the Users Active Minutes + * https://leetcode.com/problems/finding-the-users-active-minutes/ + * Difficulty: Medium + * + * You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented + * by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi + * performed an action at the minute timei. + * + * Multiple users can perform actions simultaneously, and a single user can perform multiple actions + * in the same minute. + * + * The user active minutes (UAM) for a given user is defined as the number of unique minutes in which + * the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions + * occur during it. + * + * You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] + * is the number of users whose UAM equals j. + * + * Return the array answer as described above. + */ + +/** + * @param {number[][]} logs + * @param {number} k + * @return {number[]} + */ +var findingUsersActiveMinutes = function(logs, k) { + const map = new Map(); + logs.forEach(([id, time]) => { + map.set(id, map.get(id) || new Set()); + map.get(id).add(time); + }); + + const result = new Array(k).fill(0); + [...map.values()].forEach(({ size }) => result[size - 1]++); + + return result; +}; diff --git a/README.md b/README.md index 10f0d3d0..9e76a33f 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,7 @@ 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| +1817|[Finding the Users Active Minutes](./1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From 965432a9c8b7255af2f0f4172a84b7daf9f7a1ee Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 9 Jan 2023 22:29:21 -0600 Subject: [PATCH 315/485] Add solution #2482 --- ...etween-ones-and-zeros-in-row-and-column.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 2482-difference-between-ones-and-zeros-in-row-and-column.js diff --git a/2482-difference-between-ones-and-zeros-in-row-and-column.js b/2482-difference-between-ones-and-zeros-in-row-and-column.js new file mode 100644 index 00000000..67116974 --- /dev/null +++ b/2482-difference-between-ones-and-zeros-in-row-and-column.js @@ -0,0 +1,36 @@ +/** + * 2482. Difference Between Ones and Zeros in Row and Column + * https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/ + * Difficulty: Medium + * + * You are given a 0-indexed m x n binary matrix grid. + * + * A 0-indexed m x n difference matrix diff is created with the following procedure: + * - Let the number of ones in the ith row be onesRowi. + * - Let the number of ones in the jth column be onesColj. + * - Let the number of zeros in the ith row be zerosRowi. + * - Let the number of zeros in the jth column be zerosColj. + * - diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj + * + * Return the difference matrix diff. + */ + +/** + * @param {number[][]} grid + * @return {number[][]} + */ +var onesMinusZeros = function(grid) { + const rows = new Array(grid.length).fill(0); + const columns = new Array(grid[0].length).fill(0); + + grid.forEach((row, r) => row.forEach((value, c) => { + rows[r] += value; + columns[c] += value; + })); + + grid.forEach((row, r) => row.forEach((value, c) => { + grid[r][c] = 2 * rows[r] - grid.length + 2 * columns[c] - row.length; + })); + + return grid; +}; diff --git a/README.md b/README.md index 9e76a33f..88403308 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,7 @@ 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| +2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| ## License From 7eadee93e7f39c04cf20342d8166fee344770248 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 10 Jan 2023 18:28:31 -0600 Subject: [PATCH 316/485] Add solution #80 --- ...-remove-duplicates-from-sorted-array-ii.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0080-remove-duplicates-from-sorted-array-ii.js diff --git a/0080-remove-duplicates-from-sorted-array-ii.js b/0080-remove-duplicates-from-sorted-array-ii.js new file mode 100644 index 00000000..361d4910 --- /dev/null +++ b/0080-remove-duplicates-from-sorted-array-ii.js @@ -0,0 +1,36 @@ +/** + * 80. Remove Duplicates from Sorted Array II + * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ + * Difficulty: Medium + * + * Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such + * that each unique element appears at most twice. The relative order of the elements should be kept + * the same. + * + * Since it is impossible to change the length of the array in some languages, you must instead have + * the result be placed in the first part of the array nums. More formally, if there are k elements + * after removing the duplicates, then the first k elements of nums should hold the final result. + * It does not matter what you leave beyond the first k elements. + * + * Return k after placing the final result in the first k slots of nums. + * + * Do not allocate extra space for another array. You must do this by modifying the input array + * in-place with O(1) extra memory. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function(nums) { + let offset = 2; + + for (let i = 2; i < nums.length; i++) { + if (nums[i] !== nums[offset - 2]) { + nums[offset] = nums[i]; + offset++; + } + } + + return offset; +}; diff --git a/README.md b/README.md index 88403308..2db72f65 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| +80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 90|[Subsets II](./0090-subsets-ii.js)|Medium| From 442871f1eefdc501c361647b08d671b1ce1eb44d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 10 Jan 2023 18:29:39 -0600 Subject: [PATCH 317/485] Add solution #1443 --- ...um-time-to-collect-all-apples-in-a-tree.js | 43 +++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 1443-minimum-time-to-collect-all-apples-in-a-tree.js diff --git a/1443-minimum-time-to-collect-all-apples-in-a-tree.js b/1443-minimum-time-to-collect-all-apples-in-a-tree.js new file mode 100644 index 00000000..9ceb713c --- /dev/null +++ b/1443-minimum-time-to-collect-all-apples-in-a-tree.js @@ -0,0 +1,43 @@ +/** + * 1443. Minimum Time to Collect All Apples in a Tree + * https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ + * Difficulty: Medium + * + * Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples + * in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time + * in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming + * back to this vertex. + * + * The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means + * that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array + * hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not + * have any apple. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {boolean[]} hasApple + * @return {number} + */ +var minTime = function(n, edges, hasApple) { + const map = new Map(); + const seen = new Set(); + let time = 0; + + edges.forEach(([value, key]) => map.set(key, value)); + for (let i = n - 1; i >= 0; i--) { + if (hasApple[i]) { + dfs(i); + } + } + + function dfs(key) { + if (key === 0 || seen.has(key)) return; + seen.add(key); + time += 2; + dfs(map.get(key)); + } + + return time; +}; diff --git a/README.md b/README.md index 2db72f65..5cc13328 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,7 @@ 1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| +1443|[Minimum Time to Collect All Apples in a Tree](./1443-minimum-time-to-collect-all-apples-in-a-tree.js)|Medium| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| From e1d6259835d1a13a0d3a091b9b15513285eacc5c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 10 Jan 2023 18:32:14 -0600 Subject: [PATCH 318/485] Add solution #2490 --- 2490-circular-sentence.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2490-circular-sentence.js diff --git a/2490-circular-sentence.js b/2490-circular-sentence.js new file mode 100644 index 00000000..fefe5145 --- /dev/null +++ b/2490-circular-sentence.js @@ -0,0 +1,32 @@ +/** + * 2490. Circular Sentence + * https://leetcode.com/problems/circular-sentence/ + * Difficulty: Easy + * + * A sentence is a list of words that are separated by a single space with no leading or trailing spaces. + * + * For example, "Hello World", "HELLO", "hello world hello world" are all sentences. + * Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters + * are considered different. + * + * A sentence is circular if: + * - The last character of a word is equal to the first character of the next word. + * - The last character of the last word is equal to the first character of the first word. + * + * For example, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul" are all circular + * sentences. However, "Leetcode is cool", "happy Leetcode", "Leetcode" and "I like Leetcode" are not + * circular sentences. + * + * Given a string sentence, return true if it is circular. Otherwise, return false. + */ + +/** + * @param {string} sentence + * @return {boolean} + */ +var isCircularSentence = function(sentence) { + const match = sentence.match(/^\w$|^(\w).*\1$/) !== null; + const count = sentence.match(/(\w)(?=\s\1)/g)?.length || 0; + + return match && count === sentence.split(/\s/).length - 1; +}; diff --git a/README.md b/README.md index 5cc13328..76cb0048 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| +2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| ## License From e6238b24eafa001d7b8fa7b6207b50dee9c3dc8f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 11 Jan 2023 22:50:06 -0600 Subject: [PATCH 319/485] Add solution #419 --- 0419-battleships-in-a-board.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0419-battleships-in-a-board.js diff --git a/0419-battleships-in-a-board.js b/0419-battleships-in-a-board.js new file mode 100644 index 00000000..59585443 --- /dev/null +++ b/0419-battleships-in-a-board.js @@ -0,0 +1,31 @@ +/** + * 419. Battleships in a Board + * https://leetcode.com/problems/battleships-in-a-board/ + * Difficulty: Medium + * + * Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the + * number of the battleships on board. + * + * Battleships can only be placed horizontally or vertically on board. In other words, they + * can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where + * k can be of any size. At least one horizontal or vertical cell separates between two + * battleships (i.e., there are no adjacent battleships). + */ + +/** + * @param {character[][]} boardx + * @return {number} + */ +var countBattleships = function(board) { + let count = 0; + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[i].length; j++) { + if (board[i][j] === 'X' && board[i][j - 1] !== 'X' && (!board[i - 1] || board[i - 1][j] !== 'X')) { + count++; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index 76cb0048..70895a77 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| +419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From c68c6fc9307e2c231c75d93b936dcb05d95022ff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 11 Jan 2023 22:51:25 -0600 Subject: [PATCH 320/485] Add solution #30 --- ...bstring-with-concatenation-of-all-words.js | 54 +++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0030-substring-with-concatenation-of-all-words.js diff --git a/0030-substring-with-concatenation-of-all-words.js b/0030-substring-with-concatenation-of-all-words.js new file mode 100644 index 00000000..1e121f31 --- /dev/null +++ b/0030-substring-with-concatenation-of-all-words.js @@ -0,0 +1,54 @@ +/** + * 30. Substring with Concatenation of All Words + * https://leetcode.com/problems/substring-with-concatenation-of-all-words/ + * Difficulty: Hard + * + * You are given a string s and an array of strings words. All the strings of words are of the same + * length. + * + * A concatenated substring in s is a substring that contains all the strings of any permutation of + * words concatenated. + * + * - For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", + * and "efcdab" are all concatenated strings. "acdbef" is not a concatenated substring because it is + * not the concatenation of any permutation of words. + * + * Return the starting indices of all the concatenated substrings in s. You can return the answer in + * any order. + */ + +/** + * @param {string} s + * @param {string[]} words + * @return {number[]} + */ +var findSubstring = function(s, words) { + if (!words || words.length === 0) { + return []; + } + + const result = []; + const map = {}; + const count = words[0].length; + + words.forEach(word => map[word] = ~~map[word] + 1); + + for (let i = 0; i < s.length - words.length * count + 1; i++) { + const temp = Object.assign({}, map); + + for (let j = i; j < i + words.length * count; j += count) { + const key = s.slice(j, j + count); + if (!temp[key]) { + break; + } else if (--temp[key] === 0) { + delete temp[key]; + } + } + + if (Object.keys(temp).length === 0) { + result.push(i); + } + } + + return result; +}; diff --git a/README.md b/README.md index 70895a77..f1add769 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| +30|[Substring with Concatenation of All Words](./0030-substring-with-concatenation-of-all-words.js)|Hard| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| From 25877d861de8e1147253a12166b916d4e4cc0a6d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 11 Jan 2023 22:52:14 -0600 Subject: [PATCH 321/485] Add solution #461 --- 0461-hamming-distance.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0461-hamming-distance.js diff --git a/0461-hamming-distance.js b/0461-hamming-distance.js new file mode 100644 index 00000000..f27d3cd9 --- /dev/null +++ b/0461-hamming-distance.js @@ -0,0 +1,19 @@ +/** + * 461. Hamming Distance + * https://leetcode.com/problems/hamming-distance/ + * Difficulty: Easy + * + * The Hamming distance between two integers is the number of positions at which the corresponding + * bits are different. + * + * Given two integers x and y, return the Hamming distance between them. + */ + +/** + * @param {number} x + * @param {number} y + * @return {number} + */ +var hammingDistance = function(x, y) { + return (x ^ y).toString(2).replace(/0+/g, '').length; +}; diff --git a/README.md b/README.md index f1add769..86b50fe2 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| From 5a7315857a7d0d0a25ca26912aa904370ab1665e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 12 Jan 2023 18:07:09 -0600 Subject: [PATCH 322/485] Add solution #2396 --- 2396-strictly-palindromic-number.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 2396-strictly-palindromic-number.js diff --git a/2396-strictly-palindromic-number.js b/2396-strictly-palindromic-number.js new file mode 100644 index 00000000..39833aee --- /dev/null +++ b/2396-strictly-palindromic-number.js @@ -0,0 +1,20 @@ +/** + * 2396. Strictly Palindromic Number + * https://leetcode.com/problems/strictly-palindromic-number/ + * Difficulty: Medium + * + * An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), + * the string representation of the integer n in base b is palindromic. + * + * Given an integer n, return true if n is strictly palindromic and false otherwise. + * + * A string is palindromic if it reads the same forward and backward. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isStrictlyPalindromic = function(n) { + return false; +}; diff --git a/README.md b/README.md index 86b50fe2..b1b668cf 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| From 41e21e481cf710c517d917d9ad0d5310402f55ed Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 12 Jan 2023 18:12:34 -0600 Subject: [PATCH 323/485] Add solution #2413 --- 2413-smallest-even-multiple.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 2413-smallest-even-multiple.js diff --git a/2413-smallest-even-multiple.js b/2413-smallest-even-multiple.js new file mode 100644 index 00000000..657f2de5 --- /dev/null +++ b/2413-smallest-even-multiple.js @@ -0,0 +1,15 @@ +/** + * 2413. Smallest Even Multiple + * https://leetcode.com/problems/smallest-even-multiple/ + * Difficulty: Easy + * + * Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n. + */ + +/** + * @param {number} n + * @return {number} + */ +var smallestEvenMultiple = function(n) { + return n * (n % 2 + 1); +}; diff --git a/README.md b/README.md index b1b668cf..02517e84 100644 --- a/README.md +++ b/README.md @@ -310,6 +310,7 @@ 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| +2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| From 9037a4cd68d9f08e912219e9e00a6ec8742353fc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 12 Jan 2023 18:14:27 -0600 Subject: [PATCH 324/485] Add solution #138 --- 0138-copy-list-with-random-pointer.js | 61 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 62 insertions(+) create mode 100644 0138-copy-list-with-random-pointer.js diff --git a/0138-copy-list-with-random-pointer.js b/0138-copy-list-with-random-pointer.js new file mode 100644 index 00000000..9edefa18 --- /dev/null +++ b/0138-copy-list-with-random-pointer.js @@ -0,0 +1,61 @@ +/** + * 138. Copy List with Random Pointer + * https://leetcode.com/problems/copy-list-with-random-pointer/ + * Difficulty: Medium + * + * A linked list of length n is given such that each node contains an additional random pointer, + * which could point to any node in the list, or null. + * + * Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, + * where each new node has its value set to the value of its corresponding original node. Both + * the next and random pointer of the new nodes should point to new nodes in the copied list such + * that the pointers in the original list and copied list represent the same list state. None of + * the pointers in the new list should point to nodes in the original list. + * + * For example, if there are two nodes X and Y in the original list, where X.random --> Y, then + * for the corresponding two nodes x and y in the copied list, x.random --> y. + * + * Return the head of the copied linked list. + * + * The linked list is represented in the input/output as a list of n nodes. Each node is + * represented as a pair of [val, random_index] where: + * - val: an integer representing Node.val + * - random_index: the index of the node (range from 0 to n-1) that the random pointer points + * to, or null if it does not point to any node. + * + * Your code will only be given the head of the original linked list. + */ + +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head) { + const map = new Map(); + + function copy(reference) { + if (reference === null) return null; + const instance = map.get(reference); + if (instance) { + return instance; + } + + const node = new Node(reference.val); + map.set(reference, node); + node.next = copy(reference.next); + node.random = copy(reference.random); + + return node; + } + + return copy(head); +}; diff --git a/README.md b/README.md index 02517e84..4204ff9c 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ 135|[Candy](./0135-candy.js)|Hard| 136|[Single Number](./0136-single-number.js)|Easy| 137|[Single Number II](./0137-single-number-ii.js)|Medium| +138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From aa0dcf7e9ba2352eba0937768b7ed89c52883242 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 13 Jan 2023 20:47:06 -0600 Subject: [PATCH 325/485] Add solution #125 --- 0125-valid-palindrome.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0125-valid-palindrome.js diff --git a/0125-valid-palindrome.js b/0125-valid-palindrome.js new file mode 100644 index 00000000..74ad00f1 --- /dev/null +++ b/0125-valid-palindrome.js @@ -0,0 +1,20 @@ +/** + * 125. Valid Palindrome + * https://leetcode.com/problems/valid-palindrome/ + * Difficulty: Easy + * + * A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and + * removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric + * characters include letters and numbers. + * + * Given a string s, return true if it is a palindrome, or false otherwise. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + const string = s.replace(/[^A-Z\d]+/ig, '').toLowerCase(); + return string.split('').reverse().join('') === string; +}; diff --git a/README.md b/README.md index 4204ff9c..89ef5665 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| From fe4ecbbcbd172c2062520bfb27e1906d7b06812e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 13 Jan 2023 20:48:45 -0600 Subject: [PATCH 326/485] Add solution #680 --- 0680-valid-palindrome-ii.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0680-valid-palindrome-ii.js diff --git a/0680-valid-palindrome-ii.js b/0680-valid-palindrome-ii.js new file mode 100644 index 00000000..9a827b99 --- /dev/null +++ b/0680-valid-palindrome-ii.js @@ -0,0 +1,34 @@ +/** + * 680. Valid Palindrome II + * https://leetcode.com/problems/valid-palindrome-ii/ + * Difficulty: Easy + * + * Given a string s, return true if the s can be palindrome after deleting at most one + * character from it. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var validPalindrome = function(s) { + for (let left = 0, right = s.length - 1; left < right; left++, right--) { + if (s[left] !== s[right]) { + return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); + } + } + + return true; +}; + +function isPalindrome(s, left, right) { + while (left < right) { + if (s[left] !== s[right]) { + return false; + } + right--; + left++; + } + + return true; +} diff --git a/README.md b/README.md index 89ef5665..3887c09d 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| +680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| From d430920e633ff435768a18ce029bd603761f3190 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 13 Jan 2023 20:49:17 -0600 Subject: [PATCH 327/485] Add solution #139 --- 0139-word-break.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0139-word-break.js diff --git a/0139-word-break.js b/0139-word-break.js new file mode 100644 index 00000000..1ce1830b --- /dev/null +++ b/0139-word-break.js @@ -0,0 +1,30 @@ +/** + * 139. Word Break + * https://leetcode.com/problems/word-break/ + * Difficulty: Medium + * + * Given a string s and a dictionary of strings wordDict, return true if s can be segmented into + * a space-separated sequence of one or more dictionary words. + * + * Note that the same word in the dictionary may be reused multiple times in the segmentation. + */ + +/** + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ +var wordBreak = function(s, wordDict) { + const result = [1, ...new Array(s.length + 1).fill(0)]; + + for (let i = 1; i <= s.length; i++) { + for (let j = 0; j < i; j++) { + if (result[j] && wordDict.includes(s.slice(j, i))) { + result[i] = 1; + break; + } + } + } + + return result[s.length]; +}; diff --git a/README.md b/README.md index 3887c09d..a1051836 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ 136|[Single Number](./0136-single-number.js)|Easy| 137|[Single Number II](./0137-single-number-ii.js)|Medium| 138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium| +139|[Word Break](./0139-word-break.js)|Medium| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From 8f178f608ec85bf65da2109766bf64ffed216741 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 14 Jan 2023 21:45:20 -0600 Subject: [PATCH 328/485] Add solution #202 --- 0202-happy-number.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0202-happy-number.js diff --git a/0202-happy-number.js b/0202-happy-number.js new file mode 100644 index 00000000..c6b10fa3 --- /dev/null +++ b/0202-happy-number.js @@ -0,0 +1,29 @@ +/** + * 202. Happy Number + * https://leetcode.com/problems/happy-number/ + * Difficulty: Easy + * + * Write an algorithm to determine if a number n is happy. + * + * A happy number is a number defined by the following process: + * - Starting with any positive integer, replace the number by the sum of the squares of its digits. + * - Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a + * cycle which does not include 1. + * - Those numbers for which this process ends in 1 are happy. + * + * Return true if n is a happy number, and false if not. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isHappy = function(n) { + while (n !== 1) { + n = [...String(n)].reduce((sum, digit) => sum + digit ** 2, 0); + if (n === 4) { + return false; + } + } + return true; +}; diff --git a/README.md b/README.md index a1051836..a63507b9 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 198|[House Robber](./0198-house-robber.js)|Medium| +202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| From 12f366606a3246c59fca7deb112ed64ed067c060 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 14 Jan 2023 21:46:47 -0600 Subject: [PATCH 329/485] Add solution #62 --- 0062-unique-paths.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0062-unique-paths.js diff --git a/0062-unique-paths.js b/0062-unique-paths.js new file mode 100644 index 00000000..205f9601 --- /dev/null +++ b/0062-unique-paths.js @@ -0,0 +1,34 @@ +/** + * 62. Unique Paths + * https://leetcode.com/problems/unique-paths/ + * Difficulty: Medium + * + * There is a robot on an m x n grid. The robot is initially located at the top-left + * corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner + * (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any + * point in time. + * + * Given the two integers m and n, return the number of possible unique paths that + * the robot can take to reach the bottom-right corner. + */ + +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function(m, n) { + const row = new Array(n); + + for (let i = 0; i < n; i++) { + row[i] = 1; + } + + for (let i = 1; i < m; i++) { + for (let j = 1; j < n; j++) { + row[j] += row[j - 1]; + } + } + + return row[n - 1]; +}; diff --git a/README.md b/README.md index a63507b9..92bdb536 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +62|[Unique Paths](./0062-unique-paths.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| From e173bbfcaf7bb7bf78f1e25e829b6b024fbe7d24 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 14 Jan 2023 21:47:47 -0600 Subject: [PATCH 330/485] Add solution #207 --- 0207-course-schedule.js | 49 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0207-course-schedule.js diff --git a/0207-course-schedule.js b/0207-course-schedule.js new file mode 100644 index 00000000..7a19f7d4 --- /dev/null +++ b/0207-course-schedule.js @@ -0,0 +1,49 @@ +/** + * 207. Course Schedule + * https://leetcode.com/problems/course-schedule/ + * Difficulty: Medium + * + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. + * You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you + * must take course bi first if you want to take course ai. + * + * For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. + * + * Return true if you can finish all courses. Otherwise, return false. + */ + +/** + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {boolean} + */ +var canFinish = function(numCourses, prerequisites) { + const graph = new Map(); + const seen = new Set(); + + prerequisites.forEach(([course, prerequisite]) => { + graph.set(course, graph.get(course) || []); + graph.get(course).push(prerequisite); + }); + + function dfs(course) { + if (seen.has(course)) { + return false; + } + seen.add(course); + for (const prerequisite of graph.get(course) || []) { + if (!dfs(prerequisite)) return false; + } + seen.delete(course); + graph.set(course, []); + return true; + } + + for (let i = 0; i < numCourses; i++) { + if (!dfs(i)) { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 92bdb536..117f8019 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| +207|[Course Schedule](./0207-course-schedule.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| From 401dd659c398d2d4341b30e367726638838f89ba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 15 Jan 2023 17:40:56 -0600 Subject: [PATCH 331/485] Add solution #32 --- 0032-longest-valid-parentheses.js | 36 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0032-longest-valid-parentheses.js diff --git a/0032-longest-valid-parentheses.js b/0032-longest-valid-parentheses.js new file mode 100644 index 00000000..6424b108 --- /dev/null +++ b/0032-longest-valid-parentheses.js @@ -0,0 +1,36 @@ +/** + * 32. Longest Valid Parentheses + * https://leetcode.com/problems/longest-valid-parentheses/ + * Difficulty: Hard + * + * Given a string containing just the characters '(' and ')', return the + * length of the longest valid (well-formed) parentheses substring. + */ + +/** + * @param {string} s + * @return {number} + */ +var longestValidParentheses = function(s) { + if (!s.length) { + return 0; + } + + const stack = [-1]; + let max = 0; + + for (let i = 0; i < s.length; i++) { + if (s[i] === '(') { + stack.push(i); + } else { + stack.pop(); + if (!stack.length) { + stack.push(i); + } else { + max = Math.max(max, i - stack[stack.length - 1]); + } + } + } + + return max; +}; diff --git a/README.md b/README.md index 117f8019..92bcef88 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ 29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| 30|[Substring with Concatenation of All Words](./0030-substring-with-concatenation-of-all-words.js)|Hard| 31|[Next Permutation](./0031-next-permutation.js)|Medium| +32|[Longest Valid Parentheses](./0032-longest-valid-parentheses.js)|Hard| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| From 02d7600ba57504e23cbb438d55a0d236abbf5611 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 15 Jan 2023 17:45:25 -0600 Subject: [PATCH 332/485] Add solution #140 --- 0140-word-break-ii.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0140-word-break-ii.js diff --git a/0140-word-break-ii.js b/0140-word-break-ii.js new file mode 100644 index 00000000..d8e00206 --- /dev/null +++ b/0140-word-break-ii.js @@ -0,0 +1,41 @@ +/** + * 140. Word Break II + * https://leetcode.com/problems/word-break-ii/ + * Difficulty: Hard + * + * Given a string s and a dictionary of strings wordDict, add spaces in s to + * construct a sentence where each word is a valid dictionary word. Return + * all such possible sentences in any order. + * + * Note that the same word in the dictionary may be reused multiple times in + * the segmentation. + */ + +/** + * @param {string} s + * @param {string[]} wordDict + * @return {string[]} + */ +var wordBreak = function(s, wordDict) { + const result = []; + backtrack(result, s, wordDict, ''); + return result; +}; + +function backtrack(result, s, wordDict, substr) { + if (!s.length) { + result.push(substr); + return; + } + + wordDict.forEach(word => { + if (s.length >= word.length && word === s.substring(0, word.length)) { + backtrack( + result, + s.substring(word.length), + wordDict, + substr.length ? `${substr} ${word}` : word, + ); + } + }); +} diff --git a/README.md b/README.md index 92bcef88..852215b2 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ 137|[Single Number II](./0137-single-number-ii.js)|Medium| 138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium| 139|[Word Break](./0139-word-break.js)|Medium| +140|[Word Break II](./0140-word-break-ii.js)|Hard| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From 8b8cdaf266c323fd63468a6417d26cbdd0fc3b34 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 15 Jan 2023 17:46:58 -0600 Subject: [PATCH 333/485] Add solution #160 --- 0160-intersection-of-two-linked-lists.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0160-intersection-of-two-linked-lists.js diff --git a/0160-intersection-of-two-linked-lists.js b/0160-intersection-of-two-linked-lists.js new file mode 100644 index 00000000..f005bebc --- /dev/null +++ b/0160-intersection-of-two-linked-lists.js @@ -0,0 +1,40 @@ +/** + * 160. Intersection of Two Linked Lists + * https://leetcode.com/problems/intersection-of-two-linked-lists/ + * Difficulty: Medium + * + * Given the heads of two singly linked-lists headA and headB, return the + * node at which the two lists intersect. If the two linked lists have no + * intersection at all, return null. + * + * For example, the following two linked lists begin to intersect at node c1: + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ +var getIntersectionNode = function(headA, headB) { + if (!headA || !headB) { + return null; + } + + let a = headA; + let b = headB; + + while (a !== b) { + a = a === null ? headB : a.next; + b = b === null ? headA : b.next; + } + + return a; +}; diff --git a/README.md b/README.md index 852215b2..2ed45be0 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| From e776ebeee8f35ed5db6baaeb7126d7b4e9454cec Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:41:27 -0600 Subject: [PATCH 334/485] Add solution #47 --- 0047-permutations-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0047-permutations-ii.js diff --git a/0047-permutations-ii.js b/0047-permutations-ii.js new file mode 100644 index 00000000..cb3c1e35 --- /dev/null +++ b/0047-permutations-ii.js @@ -0,0 +1,32 @@ +/** + * 47. Permutations II + * https://leetcode.com/problems/permutations-ii/ + * Difficulty: Medium + * + * Given a collection of numbers, nums, that might contain duplicates, + * return all possible unique permutations in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permuteUnique = function(nums) { + const result = new Set(); + backtrack(result, nums); + return Array.from(result).map(s => s.split(',')); +}; + +function backtrack(result, nums, order = []) { + if (!nums.length) { + result.add(order.join()); + } else { + for (let i = 0; i < nums.length; i++) { + backtrack( + result, + [...nums.slice(0, i), ...nums.slice(i + 1)], + [...order, nums[i]], + ); + } + } +} diff --git a/README.md b/README.md index 2ed45be0..1f0dd9f8 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| +47|[Permutations II](./0047-permutations-ii.js)|Medium| 48|[Rotate Image](./0048-rotate-image.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| From 058070293d4dced210180302713afe5966b4c4a3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:44:14 -0600 Subject: [PATCH 335/485] Add solution #57 --- 0057-insert-interval.js | 43 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0057-insert-interval.js diff --git a/0057-insert-interval.js b/0057-insert-interval.js new file mode 100644 index 00000000..390f51f8 --- /dev/null +++ b/0057-insert-interval.js @@ -0,0 +1,43 @@ +/** + * 57. Insert Interval + * https://leetcode.com/problems/insert-interval/ + * Difficulty: Medium + * + * You are given an array of non-overlapping intervals intervals where + * intervals[i] = [starti, endi] represent the start and the end of the + * ith interval and intervals is sorted in ascending order by starti. + * You are also given an interval newInterval = [start, end] that + * represents the start and end of another interval. + * + * Insert newInterval into intervals such that intervals is still sorted + * in ascending order by starti and intervals still does not have any + * overlapping intervals (merge overlapping intervals if necessary). + * + * Return intervals after the insertion. + */ + +/** + * @param {number[][]} intervals + * @param {number[]} newInterval + * @return {number[][]} + */ +var insert = function(intervals, newInterval) { + const result = []; + + for (let i = 0; i < intervals.length; i++) { + if (newInterval[1] < intervals[i][0]) { + result.push(newInterval); + return [...result, ...intervals.slice(i)]; + } else if (newInterval[0] > intervals[i][1]) { + result.push(intervals[i]); + } else { + newInterval = [ + Math.min(newInterval[0], intervals[i][0]), + Math.max(newInterval[1], intervals[i][1]), + ]; + } + } + + result.push(newInterval); + return result; +}; diff --git a/README.md b/README.md index 1f0dd9f8..9060eb7a 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| +57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| From ea056c65e76df486c2928a99c76448d2b2e6afd2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:49:08 -0600 Subject: [PATCH 336/485] Add solution #1 --- 0001-two-sum.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/0001-two-sum.js b/0001-two-sum.js index 788e9d47..ae737454 100644 --- a/0001-two-sum.js +++ b/0001-two-sum.js @@ -3,9 +3,11 @@ * https://leetcode.com/problems/two-sum/ * Difficulty: Easy * - * Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. + * 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. + * You may assume that each input would have exactly one solution, and you + * may not use the same element twice. * * You can return the answer in any order. */ From bf013e5e2b6fcb849705d4b99b12f75b0c1a3720 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:51:10 -0600 Subject: [PATCH 337/485] Add solution #31 --- 0031-next-permutation.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/0031-next-permutation.js b/0031-next-permutation.js index cc05f03c..f3039d8e 100644 --- a/0031-next-permutation.js +++ b/0031-next-permutation.js @@ -3,9 +3,11 @@ * https://leetcode.com/problems/next-permutation/ * Difficulty: Medium * - * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. + * Implement next permutation, which rearranges numbers into the + * lexicographically next greater permutation of numbers. * - * If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). + * If such an arrangement is not possible, it must rearrange it + * as the lowest possible order (i.e., sorted in ascending order). * * The replacement must be in place and use only constant extra memory. */ @@ -14,7 +16,7 @@ * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ - var nextPermutation = function(nums) { +var nextPermutation = function(nums) { let i = nums.length - 2; while (i >= 0 && nums[i + 1] <= nums[i]) { @@ -47,4 +49,4 @@ function swap(nums, i, j) { const temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; -} \ No newline at end of file +} From 819b6e60823ed80b1e1706f233a830b35b5d61c6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:51:38 -0600 Subject: [PATCH 338/485] Add solution #1360 --- 1360-number-of-days-between-two-dates.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/1360-number-of-days-between-two-dates.js b/1360-number-of-days-between-two-dates.js index b3a6ed22..734b0be9 100644 --- a/1360-number-of-days-between-two-dates.js +++ b/1360-number-of-days-between-two-dates.js @@ -5,7 +5,8 @@ * * Write a program to count the number of days between two dates. * - * The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. + * The two dates are given as strings, their format is `YYYY-MM-DD` + * as shown in the examples. */ /** @@ -13,6 +14,6 @@ * @param {string} date2 * @return {number} */ - var daysBetweenDates = function(date1, date2) { +var daysBetweenDates = function(date1, date2) { return Math.abs(new Date(date1) - new Date(date2)) / (24 * 60 * 60 * 1000); -}; \ No newline at end of file +}; From c8dcbd02b099563e2711f21488f6848c86b8a598 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 18:25:00 -0600 Subject: [PATCH 339/485] Add solution #1519 --- ...des-in-the-sub-tree-with-the-same-label.js | 52 +++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js diff --git a/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js new file mode 100644 index 00000000..2a370d4f --- /dev/null +++ b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js @@ -0,0 +1,52 @@ +/** + * 1519. Number of Nodes in the Sub-Tree With the Same Label + * https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/ + * Difficulty: Medium + * + * You are given a tree (i.e. a connected, undirected graph that has no cycles) + * consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The + * root of the tree is the node 0, and each node of the tree has a label which + * is a lower-case character given in the string labels (i.e. The node with the + * number i has the label labels[i]). + * + * The edges array is given on the form edges[i] = [ai, bi], which means there + * is an edge between nodes ai and bi in the tree. + * + * Return an array of size n where ans[i] is the number of nodes in the subtree + * of the ith node which have the same label as node i. + * + * A subtree of a tree T is the tree consisting of a node in T and all of its + * descendant nodes. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {string} labels + * @return {number[]} + */ +var countSubTrees = function(n, edges, labels) { + const lookup = Array.from(Array(n), () => []); + const result = new Array(n).fill(0); + + edges.forEach(([x, y]) => { + lookup[x].push(y); + lookup[y].push(x); + }); + + function bfs(index, previous, chars = new Array(26).fill(0)) { + const key = labels.charCodeAt(index) - 97; + const count = chars[key]; + chars[key]++; + lookup[index].forEach(i => { + if (i !== previous) { + bfs(i, index, chars); + } + }); + result[index] = chars[key] - count; + } + + bfs(0, -1); + + return result; +}; diff --git a/README.md b/README.md index 9060eb7a..985c4398 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,7 @@ 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| +1519|[Number of Nodes in the Sub-Tree With the Same Label](./1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium| 1528|[Shuffle String](./1528-shuffle-string.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| From 366a48a0f49bf558a1204d592b9c46d8b6ef22c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Jan 2023 19:47:43 -0600 Subject: [PATCH 340/485] Add solution #926 --- 0926-flip-string-to-monotone-increasing.js | 33 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0926-flip-string-to-monotone-increasing.js diff --git a/0926-flip-string-to-monotone-increasing.js b/0926-flip-string-to-monotone-increasing.js new file mode 100644 index 00000000..b1f3c14c --- /dev/null +++ b/0926-flip-string-to-monotone-increasing.js @@ -0,0 +1,33 @@ +/** + * 926. Flip String to Monotone Increasing + * https://leetcode.com/problems/flip-string-to-monotone-increasing/ + * Difficulty: Medium + * + * A binary string is monotone increasing if it consists of some number of 0's + * (possibly none), followed by some number of 1's (also possibly none). + * + * You are given a binary string s. You can flip s[i] changing it from 0 to 1 + * or from 1 to 0. + * + * Return the minimum number of flips to make s monotone increasing. + */ + +/** + * @param {string} s + * @return {number} + */ +var minFlipsMonoIncr = function(s) { + let result = 0; + let count = 0; + + for (const str of s) { + if (str == '1') { + count++; + } else if (str =='0' && count > 0) { + result++; + count--; + } + } + + return result; +}; diff --git a/README.md b/README.md index 985c4398..ac30a8c4 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ 916|[Word Subsets](./0916-word-subsets.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| +926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| From 337b0fc65d9a67b721f9e634f7f6d3bdae5c7a39 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Jan 2023 19:48:49 -0600 Subject: [PATCH 341/485] Add solution #45 --- 0045-jump-game-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0045-jump-game-ii.js diff --git a/0045-jump-game-ii.js b/0045-jump-game-ii.js new file mode 100644 index 00000000..69cbd1f3 --- /dev/null +++ b/0045-jump-game-ii.js @@ -0,0 +1,37 @@ +/** + * 45. Jump Game II + * https://leetcode.com/problems/jump-game-ii/ + * Difficulty: Medium + * + * You are given a 0-indexed array of integers nums of length n. + * You are initially positioned at nums[0]. + * + * Each element nums[i] represents the maximum length of a forward + * jump from index i. In other words, if you are at nums[i], you + * can jump to any nums[i + j] where: + * - 0 <= j <= nums[i] and + * - i + j < n + * + * Return the minimum number of jumps to reach nums[n - 1]. + * The test cases are generated such that you can reach nums[n - 1]. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var jump = function(nums) { + let result = 0; + let max = 0; + let previous = 0; + + for (let index = 0; index < nums.length - 1; index++) { + max = Math.max(max, index + nums[index]); + if (index === previous) { + result++; + previous = max; + } + } + + return result; +}; diff --git a/README.md b/README.md index ac30a8c4..64e6808f 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +45|[Jump Game II](./0045-jump-game-ii.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| 47|[Permutations II](./0047-permutations-ii.js)|Medium| 48|[Rotate Image](./0048-rotate-image.js)|Medium| From 72c4d48af70bb5080280e01f6954a75502affa6b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Jan 2023 19:57:04 -0600 Subject: [PATCH 342/485] Add solution #37 --- 0037-sudoku-solver.js | 56 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 0037-sudoku-solver.js diff --git a/0037-sudoku-solver.js b/0037-sudoku-solver.js new file mode 100644 index 00000000..bfbf0f8c --- /dev/null +++ b/0037-sudoku-solver.js @@ -0,0 +1,56 @@ +/** + * 37. Sudoku Solver + * https://leetcode.com/problems/sudoku-solver/ + * Difficulty: Hard + * + * Write a program to solve a Sudoku puzzle by filling the empty cells. + * + * A sudoku solution must satisfy all of the following rules: + * - Each of the digits 1-9 must occur exactly once in each row. + * - Each of the digits 1-9 must occur exactly once in each column. + * - Each of the digits 1-9 must occur exactly once in each of the + * 9 3x3 sub-boxes of the grid. + * - The '.' character indicates empty cells. + */ + +/** + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var solveSudoku = function(board) { + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board.length; j++) { + if (board[i][j] === '.') { + for (let k = 1; k < 10; k++) { + if (isValid(board, i, j, k.toString())) { + board[i][j] = k.toString(); + const solution = solveSudoku(board); + if (solution !== false) { + return solution; + } + board[i][j] = '.'; + } + } + return false; + } + } + } + + return board; +}; + +function isValid(board, i, j, k) { + for (let index = 0; index < board.length; index++) { + if (board[i][index] === k) return false; + if (board[index][j] === k) return false; + const [x, y] = [ + 3 * Math.floor(i / 3) + Math.floor(index / 3), + 3 * Math.floor(j / 3) + index % 3, + ]; + if (board[x][y] === k) { + return false; + } + } + + return true; +} diff --git a/README.md b/README.md index 64e6808f..67d9ba11 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +37|[Sudoku Solver](./0037-sudoku-solver.js)|Hard| 38|[Count and Say](./0038-count-and-say.js)|Medium| 39|[Combination Sum](./0039-combination-sum.js)|Medium| 40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium| From b90660405f74fe1e2c1c19cd4d9969bea7abe7e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 18 Jan 2023 18:10:02 -0600 Subject: [PATCH 343/485] Add solution #2529 --- ...f-positive-integer-and-negative-integer.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2529-maximum-count-of-positive-integer-and-negative-integer.js diff --git a/2529-maximum-count-of-positive-integer-and-negative-integer.js b/2529-maximum-count-of-positive-integer-and-negative-integer.js new file mode 100644 index 00000000..b771cf85 --- /dev/null +++ b/2529-maximum-count-of-positive-integer-and-negative-integer.js @@ -0,0 +1,24 @@ +/** + * 2529. Maximum Count of Positive Integer and Negative Integer + * https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/ + * Difficulty: Easy + * + * Given an array nums sorted in non-decreasing order, return the maximum + * between the number of positive integers and the number of negative integers. + * + * In other words, if the number of positive integers in nums is pos and the + * number of negative integers is neg, then return the maximum of pos and neg. + * + * Note that 0 is neither positive nor negative. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumCount = function(nums) { + const result = nums.reduce(([neg = 0, pos = 0], n) => { + return [neg + (n < 0 ? 1 : 0), pos + (n > 0 ? 1 : 0)]; + }, []); + return Math.max(...result); +}; diff --git a/README.md b/README.md index 67d9ba11..938f354a 100644 --- a/README.md +++ b/README.md @@ -331,6 +331,7 @@ 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| +2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| ## License From 7f93f48f73ca2dcf8852d57cf0fc4992f9f0be21 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 18 Jan 2023 18:11:22 -0600 Subject: [PATCH 344/485] Add solution #2535 --- ...n-element-sum-and-digit-sum-of-an-array.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 2535-difference-between-element-sum-and-digit-sum-of-an-array.js diff --git a/2535-difference-between-element-sum-and-digit-sum-of-an-array.js b/2535-difference-between-element-sum-and-digit-sum-of-an-array.js new file mode 100644 index 00000000..8f6790f3 --- /dev/null +++ b/2535-difference-between-element-sum-and-digit-sum-of-an-array.js @@ -0,0 +1,23 @@ +/** + * 2535. Difference Between Element Sum and Digit Sum of an Array + * https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array/ + * Difficulty: Easy + * + * You are given a positive integer array nums: + * - The element sum is the sum of all the elements in nums. + * - The digit sum is the sum of all the digits (not necessarily distinct) + * that appear in nums. + * + * Return the absolute difference between the element sum and digit sum of nums. + * Note that the absolute difference between two integers x and y is defined + * as |x - y|. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var differenceOfSum = function(nums) { + const sum = input => input.reduce((sum, n) => sum + +n, 0); + return Math.abs(sum(nums) - sum(nums.join('').split(''))); +}; diff --git a/README.md b/README.md index 938f354a..8025358a 100644 --- a/README.md +++ b/README.md @@ -332,6 +332,7 @@ 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| +2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| ## License From c8138867364fe092d127b831ee248a053f2a91a2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 18 Jan 2023 18:12:23 -0600 Subject: [PATCH 345/485] Add solution #59 --- 0059-spiral-matrix-ii.js | 44 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0059-spiral-matrix-ii.js diff --git a/0059-spiral-matrix-ii.js b/0059-spiral-matrix-ii.js new file mode 100644 index 00000000..302411e6 --- /dev/null +++ b/0059-spiral-matrix-ii.js @@ -0,0 +1,44 @@ +/** + * 59. Spiral Matrix II + * https://leetcode.com/problems/spiral-matrix-ii/ + * Difficulty: Medium + * + * Given a positive integer n, generate an n x n matrix filled with + * elements from 1 to n2 in spiral order. + */ + +/** + * @param {number} n + * @return {number[][]} + */ +var generateMatrix = function(n) { + const result = Array.from(new Array(n), () => new Array(n).fill(0)); + let top = 0; + let right = n - 1; + let bottom = n - 1; + let left = 0; + + for (let count = 0; count < (n * n);) { + for (let i = left; i <= right; i++) { + result[top][i] = ++count; + } + top++; + + for (let i = top; i <= bottom; i++) { + result[i][right] = ++count; + } + right--; + + for (let i = right; top <= bottom && i >= left; i--) { + result[bottom][i] = ++count; + } + bottom--; + + for (let i = bottom; left <= right && i >= top; i--) { + result[i][left] = ++count; + } + left++; + } + + return result; +}; diff --git a/README.md b/README.md index 8025358a..cc613afc 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| From 0ce894c8adf78e78d7f232ebabab3031f219af76 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:40:11 -0600 Subject: [PATCH 346/485] Add solution #491 --- 0491-non-decreasing-subsequences.js | 30 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0491-non-decreasing-subsequences.js diff --git a/0491-non-decreasing-subsequences.js b/0491-non-decreasing-subsequences.js new file mode 100644 index 00000000..ac2b0eb8 --- /dev/null +++ b/0491-non-decreasing-subsequences.js @@ -0,0 +1,30 @@ +/** + * 491. Non-decreasing Subsequences + * https://leetcode.com/problems/non-decreasing-subsequences/ + * Difficulty: Medium + * + * Given an integer array nums, return all the different possible non-decreasing + * subsequences of the given array with at least two elements. You may return + * the answer in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var findSubsequences = function(nums) { + const result = new Set(); + backtrack(result, nums, 0, []); + return Array.from(result).map(s => s.split(',')); +}; + +function backtrack(result, nums, offset, order) { + if (order.length > 1) { + result.add(order.join()); + } + for (let index = offset; index < nums.length; index++) { + if (!(order[order.length - 1] > nums[index])) { + backtrack(result, nums, index + 1, [...order, nums[index]]); + } + } +} diff --git a/README.md b/README.md index cc613afc..6e27e9d3 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| From 6558275aa661fa87f3ce1dedb26a97c255414b13 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:44:05 -0600 Subject: [PATCH 347/485] Add solution #492 --- 0492-construct-the-rectangle.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0492-construct-the-rectangle.js diff --git a/0492-construct-the-rectangle.js b/0492-construct-the-rectangle.js new file mode 100644 index 00000000..673c93d5 --- /dev/null +++ b/0492-construct-the-rectangle.js @@ -0,0 +1,30 @@ +/** + * 492. Construct the Rectangle + * https://leetcode.com/problems/construct-the-rectangle/ + * Difficulty: Easy + * + * A web developer needs to know how to design a web page's size. So, given + * a specific rectangular web page’s area, your job by now is to design a + * rectangular web page, whose length L and width W satisfy the following + * requirements: + * + * The area of the rectangular web page you designed must equal to the given + * target area. The width W should not be larger than the length L, which + * means L >= W. The difference between length L and width W should be as + * small as possible. + * + * Return an array [L, W] where L and W are the length and width of the web + * page you designed in sequence. + */ + +/** + * @param {number} area + * @return {number[]} + */ +var constructRectangle = function(area) { + let width = Math.floor(Math.sqrt(area)); + while (area % width) { + width--; + } + return [area / width, width]; +}; diff --git a/README.md b/README.md index 6e27e9d3..a26aa537 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| +492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| From 8c6db71eb8c6561ced73c371f0dcd5a89a97fffa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:49:15 -0600 Subject: [PATCH 348/485] Add solution #563 --- 0563-binary-tree-tilt.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0563-binary-tree-tilt.js diff --git a/0563-binary-tree-tilt.js b/0563-binary-tree-tilt.js new file mode 100644 index 00000000..173354ac --- /dev/null +++ b/0563-binary-tree-tilt.js @@ -0,0 +1,38 @@ +/** + * 563. Binary Tree Tilt + * https://leetcode.com/problems/binary-tree-tilt/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the sum of every tree node's tilt. + * + * The tilt of a tree node is the absolute difference between the sum of all + * left subtree node values and all right subtree node values. If a node does + * not have a left child, then the sum of the left subtree node values is + * treated as 0. The rule is similar if the node does not have a right child. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var findTilt = function(root) { + const result = { val: 0 }; + dfs(root, result); + return result.val; +}; + +function dfs(root, tilt) { + if (!root) return 0; + const left = dfs(root.left, tilt); + const right = dfs(root.right, tilt); + tilt.val += Math.abs(left - right); + return root.val + left + right; +} diff --git a/README.md b/README.md index a26aa537..b7b8fef7 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ 542|[01 Matrix](./0542-01-matrix.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| +563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| From e0b9c93ac70f4c27ecfcfeac8cef8915713c0df0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:50:12 -0600 Subject: [PATCH 349/485] Add solution #884 --- 0884-uncommon-words-from-two-sentences.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/0884-uncommon-words-from-two-sentences.js b/0884-uncommon-words-from-two-sentences.js index 6ee36541..3c228191 100644 --- a/0884-uncommon-words-from-two-sentences.js +++ b/0884-uncommon-words-from-two-sentences.js @@ -1,16 +1,16 @@ /** * 884. Uncommon Words from Two Sentences - * https://leetcode.com/problems/uncommon-words-from-two-sentences/submissions/ + * https://leetcode.com/problems/uncommon-words-from-two-sentences/ * Difficulty: Easy * - * A sentence is a string of single-space separated words where each word consists - * only of lowercase letters. + * A sentence is a string of single-space separated words where each word + * consists only of lowercase letters. * - * A word is uncommon if it appears exactly once in one of the sentences, and does - * not appear in the other sentence. + * A word is uncommon if it appears exactly once in one of the sentences, + * and does not appear in the other sentence. * - * Given two sentences s1 and s2, return a list of all the uncommon words. You may - * return the answer in any order. + * Given two sentences s1 and s2, return a list of all the uncommon words. + * You may return the answer in any order. */ /** @@ -20,7 +20,6 @@ */ var uncommonFromSentences = function(s1, s2) { const map = new Map(); - (s1 + ' ' + s2).split(/\s+/).forEach(s => map.set(s, (map.get(s) || 0) + 1)); return [...map].reduce((a, [k, c]) => c === 1 ? [...a, k] : a, []); }; From 19a4fd6b70a5438b747486963b9acff2b93005c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:51:25 -0600 Subject: [PATCH 350/485] Add solution #1323 --- 1323-maximum-69-number.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/1323-maximum-69-number.js b/1323-maximum-69-number.js index a472a90e..de1e0bb8 100644 --- a/1323-maximum-69-number.js +++ b/1323-maximum-69-number.js @@ -1,6 +1,6 @@ /** * 1323. Maximum 69 Number - * https://leetcode.com/problems/maximum-69-number/submissions/ + * https://leetcode.com/problems/maximum-69-number/ * Difficulty: Easy * * Given a positive integer num consisting only of digits 6 and 9. @@ -13,6 +13,6 @@ * @param {number} num * @return {number} */ -var maximum69Number = function(num) { +var maximum69Number = function(num) { return +String(num).replace(6, 9); }; From f11a11c91a32c98f3d103cbe958e47048e5f9962 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 19:25:03 -0600 Subject: [PATCH 351/485] Add solution #501 --- 0501-find-mode-in-binary-search-tree.js | 36 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0501-find-mode-in-binary-search-tree.js diff --git a/0501-find-mode-in-binary-search-tree.js b/0501-find-mode-in-binary-search-tree.js new file mode 100644 index 00000000..816be2bb --- /dev/null +++ b/0501-find-mode-in-binary-search-tree.js @@ -0,0 +1,36 @@ +/** + * 501. Find Mode in Binary Search Tree + * https://leetcode.com/problems/find-mode-in-binary-search-tree/ + * Difficulty: Easy + * + * Given the root of a binary search tree (BST) with duplicates, return all + * the mode(s) (i.e., the most frequently occurred element) in it. + * + * If the tree has more than one mode, return them in any order. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var findMode = function(root) { + const map = new Map(); + dfs(root); + + function dfs(root) { + if (!root) return 0; + map.set(root.val, (map.get(root.val) || 0) + 1); + [root.left, root.right].forEach(dfs); + } + + const max = Math.max(...map.values()); + return Array.from(map.keys()).filter(key => map.get(key) === max); +}; diff --git a/README.md b/README.md index b7b8fef7..578a0787 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| +501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From 8a6204d461419e3f161e0c0399e7d01adc252d51 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 19:26:39 -0600 Subject: [PATCH 352/485] Add solution #502 --- 0502-ipo.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0502-ipo.js diff --git a/0502-ipo.js b/0502-ipo.js new file mode 100644 index 00000000..03dcf73c --- /dev/null +++ b/0502-ipo.js @@ -0,0 +1,52 @@ +/** + * 502. IPO + * https://leetcode.com/problems/ipo/ + * Difficulty: Hard + * + * Suppose LeetCode will start its IPO soon. In order to sell a good price of + * its shares to Venture Capital, LeetCode would like to work on some projects + * to increase its capital before the IPO. Since it has limited resources, it + * can only finish at most k distinct projects before the IPO. Help LeetCode + * design the best way to maximize its total capital after finishing at most + * k distinct projects. + * + * You are given n projects where the ith project has a pure profit profits[i] + * and a minimum capital of capital[i] is needed to start it. + * + * Initially, you have w capital. When you finish a project, you will obtain + * its pure profit and the profit will be added to your total capital. + * + * Pick a list of at most k distinct projects from given projects to maximize + * your final capital, and return the final maximized capital. + * + * The answer is guaranteed to fit in a 32-bit signed integer. + */ + +/** + * @param {number} k + * @param {number} w + * @param {number[]} profits + * @param {number[]} capital + * @return {number} + */ +var findMaximizedCapital = function(k, w, profits, capital) { + const queue = new MinPriorityQueue(); + const descendingQueue = new MaxPriorityQueue(); + + for (let i = 0; i < capital.length; i++) { + queue.enqueue([capital[i], profits[i]], capital[i]); + } + + for (let i = 0; i < k; i++) { + while (!queue.isEmpty() && queue.front().element[0] <= w) { + const element = queue.dequeue().element; + descendingQueue.enqueue(element, element[1]); + } + if (descendingQueue.isEmpty()) { + return w; + } + w += descendingQueue.dequeue().element[1]; + } + + return w; +}; diff --git a/README.md b/README.md index 578a0787..0ed9ea7a 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| +502|[IPO](./0502-ipo.js)|Hard| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From a2cd98b16900612cfe3e32563851186291ced0f8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 19:28:29 -0600 Subject: [PATCH 353/485] Add solution #503 --- 0503-next-greater-element-ii.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0503-next-greater-element-ii.js diff --git a/0503-next-greater-element-ii.js b/0503-next-greater-element-ii.js new file mode 100644 index 00000000..1f1513d0 --- /dev/null +++ b/0503-next-greater-element-ii.js @@ -0,0 +1,33 @@ +/** + * 503. Next Greater Element II + * https://leetcode.com/problems/next-greater-element-ii/ + * Difficulty: Medium + * + * Given a circular integer array nums (i.e., the next element of + * nums[nums.length - 1] is nums[0]), return the next greater number + * for every element in nums. + * + * The next greater number of a number x is the first greater number + * to its traversing-order next in the array, which means you could + * search circularly to find its next greater number. If it doesn't + * exist, return -1 for this number. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var nextGreaterElements = function(nums) { + const total = nums.length; + const result = new Array(total).fill(-1); + const stack = []; + + for (let i = 0; i < 2 * total; i++) { + while (stack.length && nums[i % total] > nums[stack[stack.length - 1]]) { + result[stack.pop()] = nums[i % total]; + } + stack.push(i % total); + } + + return result; +}; diff --git a/README.md b/README.md index 0ed9ea7a..10258505 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| +503|[Next Greater Element II](./0503-next-greater-element-ii.js)|Medium| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From 74105b4bd874e62bc35102399af26668a74142af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 21:12:46 -0600 Subject: [PATCH 354/485] Add solution #4 --- 0004-median-of-two-sorted-arrays.js | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js index 88a7613a..fbb1aeb9 100644 --- a/0004-median-of-two-sorted-arrays.js +++ b/0004-median-of-two-sorted-arrays.js @@ -11,31 +11,6 @@ * You may assume nums1 and nums2 cannot be both empty. */ -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var findMedianSortedArrays = function(nums1, nums2) { - const total = nums1.length + nums2.length; - const limit = Math.floor(total / 2) + 1; - let i = 0, j = 0, prev, last - - while (i + j < limit) { - if (last !== undefined) { - prev = last; - } - if (nums1[i] < nums2[j] || j === nums2.length) { - last = nums1[i++]; - } else { - last = nums2[j++]; - } - } - - return total % 2 === 0 ? (prev + last) / 2 : last; -}; - -// shorter/readable alternative with higher time complexity: /** * @param {number[]} nums1 * @param {number[]} nums2 @@ -44,6 +19,7 @@ var findMedianSortedArrays = function(nums1, nums2) { var findMedianSortedArrays = function(nums1, nums2) { const sorted = [...nums1, ...nums2].sort((a, b) => a - b); const index = Math.floor((sorted.length - 1) / 2); + return sorted.length % 2 === 0 ? (sorted[index] + sorted[index + 1]) / 2 : sorted[index]; From d11e6a55b2bf34305af933b0fc729213c773d458 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 21:15:52 -0600 Subject: [PATCH 355/485] Add solution #5 --- 0005-longest-palindromic-substring.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/0005-longest-palindromic-substring.js b/0005-longest-palindromic-substring.js index d15b8499..86dee903 100644 --- a/0005-longest-palindromic-substring.js +++ b/0005-longest-palindromic-substring.js @@ -14,10 +14,11 @@ var longestPalindrome = function(s) { let result = ''; for (let i = 0; i < s.length; i++) { - let palindrome1 = getExtendedPalindrome(s, i, i); - let palindrome2 = getExtendedPalindrome(s, i, i + 1); - let longerPalindrome = palindrome1.length > palindrome2.length - ? palindrome1 : palindrome2; + const palindrome1 = getExtendedPalindrome(s, i, i); + const palindrome2 = getExtendedPalindrome(s, i, i + 1); + const longerPalindrome = palindrome1.length > palindrome2.length + ? palindrome1 + : palindrome2; if (longerPalindrome.length > result.length) { result = longerPalindrome; From 3f9955029c643be25bf998d44e59ce1aa74cd926 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 21 Jan 2023 20:34:27 -0600 Subject: [PATCH 356/485] Add solution #504 --- 0504-base-7.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 0504-base-7.js diff --git a/0504-base-7.js b/0504-base-7.js new file mode 100644 index 00000000..d29d7585 --- /dev/null +++ b/0504-base-7.js @@ -0,0 +1,15 @@ +/** + * 504. Base 7 + * https://leetcode.com/problems/base-7/ + * Difficulty: Easy + * + * Given an integer num, return a string of its base 7 representation. + */ + +/** + * @param {number} num + * @return {string} + */ +var convertToBase7 = function(num) { + return num.toString(7); +}; diff --git a/README.md b/README.md index 10258505..1bb7da8c 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| 503|[Next Greater Element II](./0503-next-greater-element-ii.js)|Medium| +504|[Base 7](./0504-base-7.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From d62f8342ebf1bb1753da084c6bf2a404b8aa5be5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 21 Jan 2023 20:38:56 -0600 Subject: [PATCH 357/485] Add solution #93 --- 0093-restore-ip-addresses.js | 42 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0093-restore-ip-addresses.js diff --git a/0093-restore-ip-addresses.js b/0093-restore-ip-addresses.js new file mode 100644 index 00000000..b3b68854 --- /dev/null +++ b/0093-restore-ip-addresses.js @@ -0,0 +1,42 @@ +/** + * 93. Restore IP Addresses + * https://leetcode.com/problems/restore-ip-addresses/ + * Difficulty: Medium + * + * A valid IP address consists of exactly four integers separated by single + * dots. Each integer is between 0 and 255 (inclusive) and cannot have + * leading zeros. + * + * For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but + * "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. + * + * Given a string s containing only digits, return all possible valid IP + * addresses that can be formed by inserting dots into s. You are not allowed + * to reorder or remove any digits in s. You may return the valid IP addresses + * in any order. + */ + +/** + * @param {string} s + * @return {string[]} + */ +var restoreIpAddresses = function(s) { + return backtrack([], s); +}; + +function backtrack(order, string, result = []) { + const isValid = s => +s <= 255 && `${+s}` === s; + + if (order.length === 3 && isValid(string)) { + result.push([...order, string].join('.')); + } else { + for (let index = 1; index < 4; index++) { + const sliced = string.slice(0, index); + if (isValid(sliced)) { + backtrack([...order, sliced], string.slice(index), result); + } + } + } + + return result; +} diff --git a/README.md b/README.md index 1bb7da8c..1a869b94 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 90|[Subsets II](./0090-subsets-ii.js)|Medium| +93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| From a52f1c92a70d411d6e145d78df7e869ed15b29e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 21 Jan 2023 20:43:58 -0600 Subject: [PATCH 358/485] Add solution #44 --- 0044-wildcard-matching.js | 50 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0044-wildcard-matching.js diff --git a/0044-wildcard-matching.js b/0044-wildcard-matching.js new file mode 100644 index 00000000..5f2f2f29 --- /dev/null +++ b/0044-wildcard-matching.js @@ -0,0 +1,50 @@ +/** + * 44. Wildcard Matching + * https://leetcode.com/problems/wildcard-matching/ + * Difficulty: Hard + * + * Given an input string (s) and a pattern (p), implement wildcard pattern + * matching with support for '?' and '*' where: + * + * - '?' Matches any single character. + * - '*' Matches any sequence of characters (including the empty sequence). + * + * The matching should cover the entire input string (not partial). + */ + +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function(s, p) { + let i = 0; + let j = 0; + let start = -1; + let offset = -1; + + while (i < s.length) { + if (j < p.length && s[i] === p[j] || p[j] === '?') { + i++; + j++; + } else if (j < p.length && p[j] === '*') { + start = j; + offset = i; + j++; + } else if (start === -1) { + return false; + } else { + j = start + 1; + i = offset + 1; + offset = i; + } + } + + for (let index = j; index < p.length; index++) { + if (p[index] !== '*') { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 1a869b94..a73fe86e 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +44|[Wildcard Matching](./0044-wildcard-matching.js)|Hard| 45|[Jump Game II](./0045-jump-game-ii.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| 47|[Permutations II](./0047-permutations-ii.js)|Medium| From d10ab86d9abf29d91670cdb5dd8a5f53ba7c32fa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:52:13 -0600 Subject: [PATCH 359/485] Add solution #131 --- 0131-palindrome-partitioning.js | 46 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0131-palindrome-partitioning.js diff --git a/0131-palindrome-partitioning.js b/0131-palindrome-partitioning.js new file mode 100644 index 00000000..fabe3875 --- /dev/null +++ b/0131-palindrome-partitioning.js @@ -0,0 +1,46 @@ +/** + * 131. Palindrome Partitioning + * https://leetcode.com/problems/palindrome-partitioning/ + * Difficulty: Medium + * + * Given a string s, partition s such that every substring of the partition + * is a palindrome. Return all possible palindrome partitioning of s. + */ + +/** + * @param {string} s + * @return {string[][]} + */ +var partition = function(s) { + return backtrack([], s); +}; + +function backtrack(order, string, result = []) { + if (!string.length) { + result.push(order); + } + + for (let index = 1; index <= string.length; index++) { + const sliced = string.slice(0, index); + if (isPalindrome(sliced)) { + backtrack([...order, sliced], string.slice(index), result); + } + } + + return result; +} + +function isPalindrome(input) { + let right = input.length - 1; + let left = 0; + + while (left < right) { + if (input[left] !== input[right]) { + return false; + } + left++; + right--; + } + + return true; +} diff --git a/README.md b/README.md index a73fe86e..ea0a9e8c 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| +131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| 135|[Candy](./0135-candy.js)|Hard| From b5cfbd27accb8cf6b8b3add06ad6964b584120fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:53:15 -0600 Subject: [PATCH 360/485] Add solution #51 --- 0051-n-queens.js | 42 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0051-n-queens.js diff --git a/0051-n-queens.js b/0051-n-queens.js new file mode 100644 index 00000000..38aa53c4 --- /dev/null +++ b/0051-n-queens.js @@ -0,0 +1,42 @@ +/** + * 51. N-Queens + * https://leetcode.com/problems/n-queens/ + * Difficulty: Hard + * + * The n-queens puzzle is the problem of placing n queens on an n x n + * chessboard such that no two queens attack each other. + * + * Given an integer n, return all distinct solutions to the n-queens + * puzzle. You may return the answer in any order. + * + * Each solution contains a distinct board configuration of the n-queens' + * placement, where 'Q' and '.' both indicate a queen and an empty space, + * respectively. + */ + +/** + * @param {number} n + * @return {string[][]} + */ +var solveNQueens = function(n) { + const result = []; + backtrack(result, n); + return result; +}; + +function backtrack(result, n, board = [], size = 0) { + if (n === size) { + result.push(board.map(s => `${'.'.repeat(s)}Q${'.'.repeat(n - s - 1)}`)); + } else { + for (let rows = 0; rows < n; rows++) { + const isValid = !board.some((i, j) => { + return i === rows || i === rows + size - j || i === rows - size + j; + }); + if (isValid) { + board.push(rows); + backtrack(result, n, board, size + 1); + board.pop(); + } + } + } +} diff --git a/README.md b/README.md index ea0a9e8c..d28f1e53 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ 48|[Rotate Image](./0048-rotate-image.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| +51|[N-Queens](./0051-n-queens.js)|Hard| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| From 1925117a74afe8c6d69a9f9208f7a51c387858b8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:54:44 -0600 Subject: [PATCH 361/485] Add solution #52 --- 0052-n-queens-ii.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0052-n-queens-ii.js diff --git a/0052-n-queens-ii.js b/0052-n-queens-ii.js new file mode 100644 index 00000000..ea1ac8b5 --- /dev/null +++ b/0052-n-queens-ii.js @@ -0,0 +1,38 @@ +/** + * 52. N-Queens II + * https://leetcode.com/problems/n-queens-ii/ + * Difficulty: Hard + * + * The n-queens puzzle is the problem of placing n queens on an n x n + * chessboard such that no two queens attack each other. + * + * Given an integer n, return the number of distinct solutions to the + * n-queens puzzle. + */ + +/** + * @param {number} n + * @return {number} + */ +var totalNQueens = function(n) { + const result = []; + backtrack(result, n); + return result.length; +}; + +function backtrack(result, n, board = [], size = 0) { + if (n === size) { + result.push(board.map(s => `${'.'.repeat(s)}Q${'.'.repeat(n - s - 1)}`)); + } else { + for (let rows = 0; rows < n; rows++) { + const isValid = !board.some((i, j) => { + return i === rows || i === rows + size - j || i === rows - size + j; + }); + if (isValid) { + board.push(rows); + backtrack(result, n, board, size + 1); + board.pop(); + } + } + } +} diff --git a/README.md b/README.md index d28f1e53..4fda511e 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 51|[N-Queens](./0051-n-queens.js)|Hard| +52|[N-Queens II](./0052-n-queens-ii.js)|Hard| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| From 98e3d24e6540ce01cbc4ff903ac224016b77f9b9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:58:19 -0600 Subject: [PATCH 362/485] Add solution #20 --- 0020-valid-parentheses.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/0020-valid-parentheses.js b/0020-valid-parentheses.js index bc7a1752..8073e964 100644 --- a/0020-valid-parentheses.js +++ b/0020-valid-parentheses.js @@ -3,8 +3,8 @@ * https://leetcode.com/problems/valid-parentheses/ * Difficulty: Easy * - * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', - * determine if the input string is valid. + * Given a string s containing just the characters '(', ')', '{', '}', + * '[' and ']', determine if the input string is valid. * * An input string is valid if: * - Open brackets must be closed by the same type of brackets. @@ -17,10 +17,10 @@ */ var isValid = function(s) { const map = { - '(': ')', - '[': ']', - '{': '}' - } + '(': ')', + '[': ']', + '{': '}', + }; const stack = []; for (let i = 0; i < s.length; i++) { From f214a4ef9908775886182a7d54fdb20744e7a90f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 17:00:31 -0600 Subject: [PATCH 363/485] Add solution #12 --- 0012-integer-to-roman.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/0012-integer-to-roman.js b/0012-integer-to-roman.js index b4e941f6..a7872336 100644 --- a/0012-integer-to-roman.js +++ b/0012-integer-to-roman.js @@ -3,7 +3,8 @@ * https://leetcode.com/problems/integer-to-roman/ * Difficulty: Medium * - * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, + * `L`, `C`, `D` and `M`. * * Symbol Value * I 1 @@ -14,13 +15,15 @@ * D 500 * M 1000 * - * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written - * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * For example, `2` is written as `II` in Roman numeral, just two one's + * added together. `12` is written as `XII`, which is simply `X + II`. + * The number `27` is written as `XXVII`, which is `XX + V + II`. * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for - * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five - * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. - * There are six instances where subtraction is used: + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not `IIII`. Instead, the number four is + * written as `IV`. Because the one is before the five we subtract it making + * four. The same principle applies to the number nine, which is written as + * `IX`. There are six instances where subtraction is used: * * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. @@ -34,7 +37,10 @@ * @return {string} */ var intToRoman = function(num) { - const map = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }; + const map = { + M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, + L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 + }; return Object.entries(map).reduce((result, [letter, n]) => { result += letter.repeat(Math.floor(num / n)); From 98903f4ecf698ee661283eea293cc66dd6e78a42 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 17:01:44 -0600 Subject: [PATCH 364/485] Add solution #13 --- 0013-roman-to-integer.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/0013-roman-to-integer.js b/0013-roman-to-integer.js index 14593317..acbb22f8 100644 --- a/0013-roman-to-integer.js +++ b/0013-roman-to-integer.js @@ -3,7 +3,8 @@ * https://leetcode.com/problems/roman-to-integer/ * Difficulty: Easy * - * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, + * `L`, `C`, `D` and `M`. * * Symbol Value * I 1 @@ -14,13 +15,15 @@ * D 500 * M 1000 * - * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written - * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * For example, `2` is written as `II` in Roman numeral, just two one's + * added together. `12` is written as `XII`, which is simply `X + II`. + * The number `27` is written as `XXVII`, which is `XX + V + II`. * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for - * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five - * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. - * There are six instances where subtraction is used: + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not `IIII`. Instead, the number four is + * written as `IV`. Because the one is before the five we subtract it making + * four. The same principle applies to the number nine, which is written as + * `IX`. There are six instances where subtraction is used: * * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. From d4d98c7fa5b37ceeebc27a31839d28299d076f0a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 23 Jan 2023 22:21:17 -0600 Subject: [PATCH 365/485] Add solution #95 --- 0095-unique-binary-search-trees-ii.js | 37 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0095-unique-binary-search-trees-ii.js diff --git a/0095-unique-binary-search-trees-ii.js b/0095-unique-binary-search-trees-ii.js new file mode 100644 index 00000000..1e4c7928 --- /dev/null +++ b/0095-unique-binary-search-trees-ii.js @@ -0,0 +1,37 @@ +/** + * 95. Unique Binary Search Trees II + * https://leetcode.com/problems/unique-binary-search-trees-ii/ + * Difficulty: Medium + * + * Given an integer n, return all the structurally unique BST's (binary search + * trees), which has exactly n nodes of unique values from 1 to n. Return the + * answer in any order. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number} n + * @return {TreeNode[]} + */ +var generateTrees = function(n) { + return backtrack(n); +}; + +function backtrack(n, j = 1, k = n, result = []) { + for (let index = j; index <= k; index++) { + for (const left of backtrack(n, j, index - 1)) { + for (const right of backtrack(n, index + 1, k)) { + result.push({ val: index, left, right }); + } + } + } + + return n ? result.length ? result : [null] : []; +} diff --git a/README.md b/README.md index 4fda511e..92d7f414 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ 90|[Subsets II](./0090-subsets-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| From 0025dc667c0e8bee2604e063818fc0d978ff7ef6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 23 Jan 2023 22:27:20 -0600 Subject: [PATCH 366/485] Add solution #96 --- 0096-unique-binary-search-trees.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0096-unique-binary-search-trees.js diff --git a/0096-unique-binary-search-trees.js b/0096-unique-binary-search-trees.js new file mode 100644 index 00000000..ff3ae0ca --- /dev/null +++ b/0096-unique-binary-search-trees.js @@ -0,0 +1,20 @@ +/** + * 96. Unique Binary Search Trees + * https://leetcode.com/problems/unique-binary-search-trees/ + * Difficulty: Medium + * + * Given an integer n, return the number of structurally unique BST's (binary + * search trees) which has exactly n nodes of unique values from 1 to n. + */ + +/** + * @param {number} n + * @return {number} + */ +var numTrees = function(n) { + return traverse(2 * n) / (traverse(n + 1) * traverse(n)); +}; + +function traverse(n) { + return n <= 0 ? 1 : n * traverse(n - 1); +} diff --git a/README.md b/README.md index 92d7f414..dc4414b8 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| +96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| From babbec94aabe452db9799c597bad44f6d9e3eeca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 23 Jan 2023 22:29:32 -0600 Subject: [PATCH 367/485] Add solution #371 --- 0371-sum-of-two-integers.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0371-sum-of-two-integers.js diff --git a/0371-sum-of-two-integers.js b/0371-sum-of-two-integers.js new file mode 100644 index 00000000..0930fd60 --- /dev/null +++ b/0371-sum-of-two-integers.js @@ -0,0 +1,24 @@ +/** + * 371. Sum of Two Integers + * https://leetcode.com/problems/sum-of-two-integers/ + * Difficulty: Medium + * + * Given two integers a and b, return the sum of the two integers + * without using the operators + and -. + */ + +/** + * @param {number} a + * @param {number} b + * @return {number} + */ +var getSum = function(a, b) { + const sum = a ^ b; + const carry = (a & b) << 1; + + if (!carry) { + return sum; + } + + return getSum(sum, carry); +}; diff --git a/README.md b/README.md index dc4414b8..54455888 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| +371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 14484f7796a3d518a19b42c1a03883da85c9ce0a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 24 Jan 2023 22:52:24 -0600 Subject: [PATCH 368/485] Add solution #372 --- 0372-super-pow.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0372-super-pow.js diff --git a/0372-super-pow.js b/0372-super-pow.js new file mode 100644 index 00000000..a2ce4af2 --- /dev/null +++ b/0372-super-pow.js @@ -0,0 +1,31 @@ +/** + * 372. Super Pow + * https://leetcode.com/problems/super-pow/ + * Difficulty: Medium + * + * Your task is to calculate ab mod 1337 where a is a positive integer and b + * is an extremely large positive integer given in the form of an array. + */ + +/** + * @param {number} a + * @param {number[]} b + * @return {number} + */ +var superPow = function(a, b) { + return helper(BigInt(a), BigInt(b.join('')), 1337n); +}; + +function helper(a, b, mod) { + let r = 1n; + + while (b > 0n) { + if (b % 2n == 1) { + r = r * a % mod; + } + b >>= 1n; + a = a * a % mod; + } + + return Number(r); +}; diff --git a/README.md b/README.md index 54455888..d7942fe0 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| +372|[Super Pow](./0372-super-pow.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From ec8550b8e2f3740d208c999971e0dd3a6e548fe6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 24 Jan 2023 22:59:01 -0600 Subject: [PATCH 369/485] Add solution #86 --- 0086-partition-list.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0086-partition-list.js diff --git a/0086-partition-list.js b/0086-partition-list.js new file mode 100644 index 00000000..b461d5b7 --- /dev/null +++ b/0086-partition-list.js @@ -0,0 +1,31 @@ +/** + * 86. Partition List + * https://leetcode.com/problems/partition-list/ + * Difficulty: Medium + * + * Given the head of a linked list and a value x, partition it such that + * all nodes less than x come before nodes greater than or equal to x. + * + * You should preserve the original relative order of the nodes in each + * of the two partitions. + */ + +/** + * @param {ListNode} head + * @param {number} x + * @return {ListNode} + */ +var partition = function(head, x) { + const result = []; + const stack = []; + + while (head) { + const target = head.val >= x ? result : stack; + target.push(head.val); + head = head.next; + } + + return [...stack, ...result].reverse().reduce((a, b) => { + return new ListNode(b, a); + }, null); +}; diff --git a/README.md b/README.md index d7942fe0..77457b62 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| +86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 90|[Subsets II](./0090-subsets-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| From 1f82cdf3a05f919d21bcb1b8ed5d513e9c90e5c0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 24 Jan 2023 23:55:17 -0600 Subject: [PATCH 370/485] Add solution #64 --- 0064-minimum-path-sum.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0064-minimum-path-sum.js diff --git a/0064-minimum-path-sum.js b/0064-minimum-path-sum.js new file mode 100644 index 00000000..9c5303a4 --- /dev/null +++ b/0064-minimum-path-sum.js @@ -0,0 +1,28 @@ +/** + * 64. Minimum Path Sum + * https://leetcode.com/problems/minimum-path-sum/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var minPathSum = function(grid) { + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (i === 0 && j === 0) grid[i][j] = grid[i][j]; + else if (i === 0 && j !== 0) grid[i][j] = grid[i][j] + grid[i][j - 1]; + else if (i !== 0 && j === 0) grid[i][j] = grid[i][j] + grid[i - 1][j]; + else grid[i][j] = grid[i][j] + Math.min(grid[i - 1][j], grid[i][j - 1]); + } + } + + return grid[grid.length - 1][grid[0].length - 1]; +}; diff --git a/README.md b/README.md index 77457b62..c470c394 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| +64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| From 36e83f9da526e7e85271abf3131a395c19bb7eba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 25 Jan 2023 21:32:24 -0600 Subject: [PATCH 371/485] Add solution #55 --- 0055-jump-game.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0055-jump-game.js diff --git a/0055-jump-game.js b/0055-jump-game.js new file mode 100644 index 00000000..7e605bec --- /dev/null +++ b/0055-jump-game.js @@ -0,0 +1,28 @@ +/** + * 55. Jump Game + * https://leetcode.com/problems/jump-game/ + * Difficulty: Medium + * + * You are given an integer array nums. You are initially positioned at the + * array's first index, and each element in the array represents your maximum + * jump length at that position. + * + * Return true if you can reach the last index, or false otherwise. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var canJump = function(nums) { + let max = nums[0]; + + for (let i = 1; i < nums.length; i++) { + if (max < i) { + return false; + } + max = Math.max(nums[i] + i, max); + } + + return true; +}; diff --git a/README.md b/README.md index c470c394..e8290f43 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ 52|[N-Queens II](./0052-n-queens-ii.js)|Hard| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| +55|[Jump Game](./0055-jump-game.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| From e4732ff7116a7a4b940ac80f218d549bf6372202 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 25 Jan 2023 21:41:35 -0600 Subject: [PATCH 372/485] Add solution #56 --- 0056-merge-intervals.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0056-merge-intervals.js diff --git a/0056-merge-intervals.js b/0056-merge-intervals.js new file mode 100644 index 00000000..74b2e02f --- /dev/null +++ b/0056-merge-intervals.js @@ -0,0 +1,29 @@ +/** + * 56. Merge Intervals + * https://leetcode.com/problems/merge-intervals/ + * Difficulty: Medium + * + * Given an array of intervals where intervals[i] = [starti, endi], merge all + * overlapping intervals, and return an array of the non-overlapping intervals + * that cover all the intervals in the input. + */ + +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var merge = function(intervals) { + intervals.sort(([a], [b]) => a - b); + + const result = [intervals.shift()]; + intervals.forEach(([first, second]) => { + const [, last] = result[result.length - 1]; + if (first <= last) { + result[result.length - 1][1] = Math.max(second, last); + } else { + result.push([first, second]); + } + }); + + return result; +}; diff --git a/README.md b/README.md index e8290f43..7e7830b9 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 55|[Jump Game](./0055-jump-game.js)|Medium| +56|[Merge Intervals](./0056-merge-intervals.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| From e0145e548875fde7be1029d41952f4105b61a50c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 25 Jan 2023 21:45:10 -0600 Subject: [PATCH 373/485] Add solution #405 --- 0405-convert-a-number-to-hexadecimal.js | 32 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0405-convert-a-number-to-hexadecimal.js diff --git a/0405-convert-a-number-to-hexadecimal.js b/0405-convert-a-number-to-hexadecimal.js new file mode 100644 index 00000000..bfa94f51 --- /dev/null +++ b/0405-convert-a-number-to-hexadecimal.js @@ -0,0 +1,32 @@ +/** + * 405. Convert a Number to Hexadecimal + * https://leetcode.com/problems/convert-a-number-to-hexadecimal/ + * Difficulty: Easy + * + * Given an integer num, return a string representing its hexadecimal + * representation. For negative integers, two’s complement method is used. + * + * All the letters in the answer string should be lowercase characters, + * and there should not be any leading zeros in the answer except for + * the zero itself. + * + * Note: You are not allowed to use any built-in library method to directly + * solve this problem. + */ + +/** + * @param {number} num + * @return {string} + */ +var toHex = function(num) { + if (num === 0) { + return num.toString(); + } + const words = '0123456789abcdef'; + let result = ''; + while (num !== 0) { + result = words[num & 0xf] + result; + num >>>= 4; + } + return result; +}; diff --git a/README.md b/README.md index 7e7830b9..546f17be 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From f44be804d85fea5ac2d64d002f79fb6ac3f9137e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Feb 2023 22:31:58 -0600 Subject: [PATCH 374/485] Add solution #412 --- 0412-fizz-buzz.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0412-fizz-buzz.js diff --git a/0412-fizz-buzz.js b/0412-fizz-buzz.js new file mode 100644 index 00000000..ed737dd8 --- /dev/null +++ b/0412-fizz-buzz.js @@ -0,0 +1,22 @@ +/** + * 412. Fizz Buzz + * https://leetcode.com/problems/fizz-buzz/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {number} n + * @return {string[]} + */ +var fizzBuzz = function(n) { + return Array.from(new Array(n), (_, i) => i + 1).map(i => + i % 3 === 0 && i % 5 === 0 + ? 'FizzBuzz' : i % 3 === 0 ? 'Fizz' : i % 5 === 0 ? 'Buzz' : String(i) + ); +}; diff --git a/README.md b/README.md index 546f17be..e4416d6d 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| +412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From 946698eb7aa2b5df6f62c6183a0486f56a4f1f07 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Feb 2023 22:47:03 -0600 Subject: [PATCH 375/485] Add solution #99 --- 0099-recover-binary-search-tree.js | 43 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0099-recover-binary-search-tree.js diff --git a/0099-recover-binary-search-tree.js b/0099-recover-binary-search-tree.js new file mode 100644 index 00000000..d226cb44 --- /dev/null +++ b/0099-recover-binary-search-tree.js @@ -0,0 +1,43 @@ +/** + * 99. Recover Binary Search Tree + * https://leetcode.com/problems/recover-binary-search-tree/ + * Difficulty: Medium + * + * You are given the root of a binary search tree (BST), where the values + * of exactly two nodes of the tree were swapped by mistake. Recover the + * tree without changing its structure. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {void} Do not return anything, modify root in-place instead. + */ +var recoverTree = function(root) { + let [previous, small, large] = [null, null, null]; + + dfs(root); + [large.val, small.val] = [small.val, large.val]; + + function dfs(root) { + if (!root) return; + dfs(root.left); + if (previous != null && previous.val > root.val) { + small = root; + if (!large) { + large = previous; + } else { + return false; + } + } + previous = root; + dfs(root.right); + } +}; diff --git a/README.md b/README.md index e4416d6d..0ed777c3 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ 95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| 96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| +99|[Recover Binary Search Tree](./0099-recover-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| From b9aa4d7d6e32e0ca1b6bce0f9d028d02bfb5acb9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Feb 2023 22:56:10 -0600 Subject: [PATCH 376/485] Add solution #168 --- 0168-excel-sheet-column-title.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0168-excel-sheet-column-title.js diff --git a/0168-excel-sheet-column-title.js b/0168-excel-sheet-column-title.js new file mode 100644 index 00000000..575c0729 --- /dev/null +++ b/0168-excel-sheet-column-title.js @@ -0,0 +1,19 @@ +/** + * 168. Excel Sheet Column Title + * https://leetcode.com/problems/excel-sheet-column-title/ + * Difficulty: Easy + * + * Given an integer columnNumber, return its corresponding column + * title as it appears in an Excel sheet. + */ + +/** + * @param {number} columnNumber + * @return {string} + */ +var convertToTitle = function(columnNumber) { + const n = columnNumber - 1; + return n >= 0 && n < 26 + ? String.fromCharCode(65 + n) + : convertToTitle(parseInt(n / 26)) + convertToTitle((n % 26) + 1); +}; diff --git a/README.md b/README.md index 0ed777c3..090a42fe 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| +168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| From ef213ed4d8bfa53cf55746c4486cf0c8b15ef485 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 18:49:02 -0600 Subject: [PATCH 377/485] Add solution #81 --- 0081-search-in-rotated-sorted-array-ii.js | 28 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0081-search-in-rotated-sorted-array-ii.js diff --git a/0081-search-in-rotated-sorted-array-ii.js b/0081-search-in-rotated-sorted-array-ii.js new file mode 100644 index 00000000..2bafa642 --- /dev/null +++ b/0081-search-in-rotated-sorted-array-ii.js @@ -0,0 +1,28 @@ +/** + * 81. Search in Rotated Sorted Array II + * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ + * Difficulty: Medium + * + * There is an integer array nums sorted in non-decreasing order (not + * necessarily with distinct values). + * + * Before being passed to your function, nums is rotated at an unknown + * pivot index k (0 <= k < nums.length) such that the resulting array + * is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] + * (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot + * index 5 and become [4,5,6,6,7,0,1,2,4,4]. + * + * Given the array nums after the rotation and an integer target, return + * true if target is in nums, or false if it is not in nums. + * + * You must decrease the overall operation steps as much as possible. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {boolean} + */ +var search = function(nums, target) { + return nums.includes(target); +}; diff --git a/README.md b/README.md index 090a42fe..1df9ea1b 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| +81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| From 55f0d8062c6e020a3f7de1d07996b2889bef9897 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 19:10:18 -0600 Subject: [PATCH 378/485] Add solution #82 --- 0082-remove-duplicates-from-sorted-list-ii.js | 37 +++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0082-remove-duplicates-from-sorted-list-ii.js diff --git a/0082-remove-duplicates-from-sorted-list-ii.js b/0082-remove-duplicates-from-sorted-list-ii.js new file mode 100644 index 00000000..8bccf70f --- /dev/null +++ b/0082-remove-duplicates-from-sorted-list-ii.js @@ -0,0 +1,37 @@ +/** + * 82. Remove Duplicates from Sorted List II + * https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ + * Difficulty: Medium + * + * Given the head of a sorted linked list, delete all nodes that have duplicate + * numbers, leaving only distinct numbers from the original list. Return the + * linked list sorted as well. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + const result = new ListNode(); + let previous = null; + let tail = result; + + while (head) { + if (head.val !== head.next?.val && head.val !== previous) { + tail.next = new ListNode(head.val); + tail = tail.next; + } + previous = head.val; + head = head.next; + } + + return result.next; +}; diff --git a/README.md b/README.md index 1df9ea1b..4ddf6a5c 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| +82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| From 2c9c4f747db970e6ae0c3329890b7d29052fb89e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 19:12:20 -0600 Subject: [PATCH 379/485] Add solution #83 --- 0083-remove-duplicates-from-sorted-list.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/0083-remove-duplicates-from-sorted-list.js b/0083-remove-duplicates-from-sorted-list.js index 1bd5a0ad..b1e7de59 100644 --- a/0083-remove-duplicates-from-sorted-list.js +++ b/0083-remove-duplicates-from-sorted-list.js @@ -20,17 +20,14 @@ */ var deleteDuplicates = function(head) { const result = new ListNode(); - const set = new Set(); let tail = result; while (head) { - if (!set.has(head.val)) { + if (head.val !== head.next?.val) { tail.next = new ListNode(head.val); tail = tail.next; } - - set.add(head.val); - + previous = head.val; head = head.next; } From c4c473137934ffa6c63ae8dab3e8bf2e3161d538 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 19:19:26 -0600 Subject: [PATCH 380/485] Add solution #89 --- 0089-gray-code.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0089-gray-code.js diff --git a/0089-gray-code.js b/0089-gray-code.js new file mode 100644 index 00000000..766f0620 --- /dev/null +++ b/0089-gray-code.js @@ -0,0 +1,27 @@ +/** + * 89. Gray Code + * https://leetcode.com/problems/gray-code/ + * Difficulty: Medium + * + * An n-bit gray code sequence is a sequence of 2n integers where: + * - Every integer is in the inclusive range [0, 2n - 1], + * - The first integer is 0, + * - An integer appears no more than once in the sequence, + * - The binary representation of every pair of adjacent integers differs + * by exactly one bit, and + * - The binary representation of the first and last integers differs by + * exactly one bit. + * Given an integer n, return any valid n-bit gray code sequence. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var grayCode = function(n) { + const result = [0]; + for (let i = 0; i < n; i++) { + result.push(...result.map((v) => v | 1 << i).reverse()); + } + return result; +}; diff --git a/README.md b/README.md index 4ddf6a5c..6760b1d0 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +89|[Gray Code](./0089-gray-code.js)|Medium| 90|[Subsets II](./0090-subsets-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From b571521c1650f8b976474386997465dc1e82f069 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Jan 2025 17:41:40 -0600 Subject: [PATCH 381/485] Add solution #3402 --- ...ons-to-make-columns-strictly-increasing.js | 32 +++++++++++++++++++ README.md | 3 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 3402-minimum-operations-to-make-columns-strictly-increasing.js diff --git a/3402-minimum-operations-to-make-columns-strictly-increasing.js b/3402-minimum-operations-to-make-columns-strictly-increasing.js new file mode 100644 index 00000000..18b4b600 --- /dev/null +++ b/3402-minimum-operations-to-make-columns-strictly-increasing.js @@ -0,0 +1,32 @@ +/** + * 3402. Minimum Operations to Make Columns Strictly Increasing + * https://leetcode.com/problems/minimum-operations-to-make-columns-strictly-increasing + * Difficulty: Easy + * + * You are given a m x n matrix grid consisting of non-negative integers. + * + * In one operation, you can increment the value of any grid[i][j] by 1. + * + * Return the minimum number of operations needed to make all columns of grid strictly increasing. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var minimumOperations = function(grid) { + let count = 0; + + for (let i = 1; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + const [previous, current] = [grid[i - 1][j], grid[i][j]]; + if (current <= previous) { + const operations = previous - current + 1; + grid[i][j] = operations + current; + count += operations; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index 6760b1d0..4a36f53f 100644 --- a/README.md +++ b/README.md @@ -361,9 +361,10 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| ## License [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2023 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2025 [Josh Crozier](https://joshcrozier.com) From 2eb3f2425da230a0d1ca1057f932b4ac1eff0a08 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Jan 2025 18:32:42 -0600 Subject: [PATCH 382/485] Add solution #3396 --- ...ions-to-make-elements-in-array-distinct.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js diff --git a/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js b/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js new file mode 100644 index 00000000..ea954b6d --- /dev/null +++ b/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js @@ -0,0 +1,29 @@ +/** + * 3396. Minimum Number of Operations to Make Elements in Array Distinct + * https://leetcode.com/problems/minimum-number-of-operations-to-make-elements-in-array-distinct/ + * Difficulty: Easy + * + * You are given an integer array nums. You need to ensure that the elements in the array are + * distinct. To achieve this, you can perform the following operation any number of times: + * - Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, + * remove all remaining elements. + * Note that an empty array is considered to have distinct elements. Return the minimum number + * of operations needed to make the elements in the array distinct. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minimumOperations = function(nums) { + const unique = new Set(); + + for (let i = nums.length - 1; i > -1; i--) { + if (unique.has(nums[i])) { + return Math.ceil((i + 1) / 3); + } + unique.add(nums[i]); + } + + return 0; +}; diff --git a/README.md b/README.md index 4a36f53f..db5a9095 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| ## License From 0189ee790f35f4216685c82305767e8811f120b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Jan 2025 22:52:08 -0600 Subject: [PATCH 383/485] Add solution #3397 --- ...r-of-distinct-elements-after-operations.js | 31 +++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 3397-maximum-number-of-distinct-elements-after-operations.js diff --git a/3397-maximum-number-of-distinct-elements-after-operations.js b/3397-maximum-number-of-distinct-elements-after-operations.js new file mode 100644 index 00000000..96665e90 --- /dev/null +++ b/3397-maximum-number-of-distinct-elements-after-operations.js @@ -0,0 +1,31 @@ +/** + * 3397. Maximum Number of Distinct Elements After Operations + * https://leetcode.com/problems/maximum-number-of-distinct-elements-after-operations/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer k. + * + * You are allowed to perform the following operation on each element of the array at most once: + * - Add an integer in the range [-k, k] to the element. + * + * Return the maximum possible number of distinct elements in nums after performing the operations. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxDistinctElements = function(nums, k) { + nums.sort((a, b) => a - b); + let last = nums[0] - k; + let count = 1; + + for (let i = 1; i < nums.length; i++) { + if (last + 1 > nums[i] + k) continue; + last = Math.max(last + 1, nums[i] - k); + count++; + } + + return count; +}; diff --git a/README.md b/README.md index db5a9095..2c70f6ef 100644 --- a/README.md +++ b/README.md @@ -362,6 +362,7 @@ 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| +3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| ## License From 64ad37e5666b5d503da780075dad73301bdfb930 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:09:48 -0600 Subject: [PATCH 384/485] Add solution #3392 --- ...arrays-of-length-three-with-a-condition.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 3392-count-subarrays-of-length-three-with-a-condition.js diff --git a/3392-count-subarrays-of-length-three-with-a-condition.js b/3392-count-subarrays-of-length-three-with-a-condition.js new file mode 100644 index 00000000..a18fa0b8 --- /dev/null +++ b/3392-count-subarrays-of-length-three-with-a-condition.js @@ -0,0 +1,22 @@ +/** + * 3392. Count Subarrays of Length Three With a Condition + * https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition/ + * Difficulty: Easy + * + * Given an integer array nums, return the number of subarrays of length 3 such that + * the sum of the first and third numbers equals exactly half of the second number. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countSubarrays = function(nums) { + let count = 0; + for (let i = 0; i < nums.length - 2; i++) { + if (nums[i] + nums[i + 2] === nums[i + 1] / 2) { + count++; + } + } + return count; +}; diff --git a/README.md b/README.md index 2c70f6ef..cdf8bd47 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| From 5017c935592ba03fa0ec68e299a4586c59034385 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:13:58 -0600 Subject: [PATCH 385/485] Add solution #2618 --- 2618-check-if-object-instance-of-class.js | 24 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2618-check-if-object-instance-of-class.js diff --git a/2618-check-if-object-instance-of-class.js b/2618-check-if-object-instance-of-class.js new file mode 100644 index 00000000..f54fe6c0 --- /dev/null +++ b/2618-check-if-object-instance-of-class.js @@ -0,0 +1,24 @@ +/** + * 2618. Check if Object Instance of Class + * https://leetcode.com/problems/check-if-object-instance-of-class/ + * Difficulty: Medium + * + * 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. + * + * 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. + */ + +/** + * @param {*} obj + * @param {*} classFunction + * @return {boolean} + */ +var checkIfInstanceOf = function(obj, classFunction) { + if (obj === null || obj === undefined || typeof classFunction !== 'function') { + return false; + } + return Object(obj) instanceof classFunction; +}; diff --git a/README.md b/README.md index cdf8bd47..298b7d1c 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 34140f11b97873e569f4c3572e6c756c50654682 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:16:29 -0600 Subject: [PATCH 386/485] Add solution #2619 --- 2619-array-prototype-last.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 2619-array-prototype-last.js diff --git a/2619-array-prototype-last.js b/2619-array-prototype-last.js new file mode 100644 index 00000000..7e99a754 --- /dev/null +++ b/2619-array-prototype-last.js @@ -0,0 +1,18 @@ +/** + * 2619. Array Prototype Last + * https://leetcode.com/problems/array-prototype-last/ + * Difficulty: Easy + * + * 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. + * + * You may assume the array is the output of JSON.parse. + */ + +/** + * @return {null|boolean|number|string|Array|Object} + */ +Array.prototype.last = function() { + return !this.length ? -1 : this[this.length - 1]; +}; diff --git a/README.md b/README.md index 298b7d1c..bfec9892 100644 --- a/README.md +++ b/README.md @@ -362,6 +362,7 @@ 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| +2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 4f33e0c3f5819e786b4233c70489f40c48c985ab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:37:57 -0600 Subject: [PATCH 387/485] Add solution #2629 --- 2629-function-composition.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 2629-function-composition.js diff --git a/2629-function-composition.js b/2629-function-composition.js new file mode 100644 index 00000000..30546886 --- /dev/null +++ b/2629-function-composition.js @@ -0,0 +1,23 @@ +/** + * 2629. Function Composition + * https://leetcode.com/problems/function-composition/ + * Difficulty: Easy + * + * Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function + * composition of the array of functions. + * + * The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))). + * + * The function composition of an empty list of functions is the identity function f(x) = x. + * + * You may assume each function in the array accepts one integer as input and returns one integer + * as output. + */ + +/** + * @param {Function[]} functions + * @return {Function} + */ +var compose = function(functions) { + return x => functions.reduceRight((result, fn) => fn(result), x); +}; diff --git a/README.md b/README.md index bfec9892..35df3dae 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| +2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 7dadfe9f56b5bb59db3a4fbeb7f356f612685dbd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:46:29 -0600 Subject: [PATCH 388/485] Add solution #2620 --- 2620-counter.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 2620-counter.js diff --git a/2620-counter.js b/2620-counter.js new file mode 100644 index 00000000..933a4630 --- /dev/null +++ b/2620-counter.js @@ -0,0 +1,18 @@ +/** + * 2620. Counter + * https://leetcode.com/problems/counter/ + * Difficulty: Easy + * + * 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). + */ + +/** + * @param {number} n + * @return {Function} counter + */ +var createCounter = function(n) { + let count = n; + return () => count++; +}; diff --git a/README.md b/README.md index 35df3dae..008eec04 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| +2620|[Counter](./2620-counter.js)|Easy| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From b1ce8ca6ad4fa6b623877620db29e725b58cbb51 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:49:48 -0600 Subject: [PATCH 389/485] Add solution #2621 --- 2621-sleep.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 2621-sleep.js diff --git a/2621-sleep.js b/2621-sleep.js new file mode 100644 index 00000000..46d3fcd4 --- /dev/null +++ b/2621-sleep.js @@ -0,0 +1,16 @@ +/** + * 2621. Sleep + * https://leetcode.com/problems/sleep/ + * Difficulty: Easy + * + * Given a positive integer `ms`, write an asynchronous function that + * sleeps for `ms` milliseconds. It can resolve any value. + */ + +/** + * @param {number} ms + * @return {Promise} + */ +async function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/README.md b/README.md index 008eec04..0105b202 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,7 @@ 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| +2621|[Sleep](./2621-sleep.js)|Easy| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 29acd611abfb273608443ef5b50d3f55b5ccc648 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 16:20:30 -0600 Subject: [PATCH 390/485] Add solution #2622 --- 2622-cache-with-time-limit.js | 54 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 2622-cache-with-time-limit.js diff --git a/2622-cache-with-time-limit.js b/2622-cache-with-time-limit.js new file mode 100644 index 00000000..3097145e --- /dev/null +++ b/2622-cache-with-time-limit.js @@ -0,0 +1,54 @@ +/** + * 2622. Cache With Time Limit + * https://leetcode.com/problems/cache-with-time-limit/ + * Difficulty: Medium + * + * Write a class that allows getting and setting key-value pairs, however a time until + * expiration is associated with each key. + * + * The class has three public methods: + * - set(key, value, duration): accepts an integer key, an integer value, and a duration + * in milliseconds. Once the duration has elapsed, the key should be inaccessible. + * The method should return true if the same un-expired key already exists and false + * otherwise. Both the value and duration should be overwritten if the key already exists. + * + * - get(key): if an un-expired key exists, it should return the associated value. + * Otherwise it should return -1. + * + * - count(): returns the count of un-expired keys. + */ + +var TimeLimitedCache = function() { + this.cache = new Map(); +}; + +/** + * @param {number} key + * @param {number} value + * @param {number} duration time until expiration in ms + * @return {boolean} if un-expired key already existed + */ +TimeLimitedCache.prototype.set = function(key, value, duration) { + const hit = this.cache.has(key) && this.cache.get(key)[1] > Date.now(); + this.cache.set(key, [value, Date.now() + duration]); + return hit; +}; + +/** + * @param {number} key + * @return {number} value associated with key + */ +TimeLimitedCache.prototype.get = function(key) { + if (!this.cache.has(key)) return -1; + const [value, expiredAt] = this.cache.get(key); + return expiredAt > Date.now() ? value : -1; +}; + +/** + * @return {number} count of non-expired keys + */ +TimeLimitedCache.prototype.count = function() { + return [...this.cache.keys()].reduce((count, key) => { + return this.cache.get(key)[1] > Date.now() ? ++count : count; + }, 0); +}; diff --git a/README.md b/README.md index 0105b202..d5292649 100644 --- a/README.md +++ b/README.md @@ -365,6 +365,7 @@ 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| 2621|[Sleep](./2621-sleep.js)|Easy| +2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 9ff5d72e38bb3509aaeb75c77cdbf517ad6d9ab8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 17:56:05 -0600 Subject: [PATCH 391/485] Add solution #60 --- 0060-permutation-sequence.js | 43 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0060-permutation-sequence.js diff --git a/0060-permutation-sequence.js b/0060-permutation-sequence.js new file mode 100644 index 00000000..0f6f1a55 --- /dev/null +++ b/0060-permutation-sequence.js @@ -0,0 +1,43 @@ +/** + * 60. Permutation Sequence + * https://leetcode.com/problems/permutation-sequence/ + * Difficulty: Hard + * + * The set [1, 2, 3, ..., n] contains a total of n! unique permutations. + * + * By listing and labeling all of the permutations in order, we get the + * following sequence for n = 3: + * - "123" + * - "132" + * - "213" + * - "231" + * - "312" + * - "321" + * + * Given n and k, return the kth permutation sequence. + */ + +/** + * @param {number} n + * @param {number} k + * @return {string} + */ +var getPermutation = function(n, k) { + const factorial = [1]; + for (let i = 1; i < n; i++) { + factorial[i] = factorial[i-1] * i; + } + + const values = new Array(n).fill(0).map((_, i) => i + 1); + let result = ''; + k--; + + for (let i = n - 1; i >= 0; i--) { + const index = Math.floor(k / factorial[i]); + k = k % factorial[i]; + result += values[index]; + values.splice(index, 1); + } + + return result; +}; diff --git a/README.md b/README.md index d5292649..561b4ec9 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| +60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| From e54a0cbb7d7e7ecf75cef9055233aeb17fad3ba4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 17:59:06 -0600 Subject: [PATCH 392/485] Add solution #148 --- 0148-sort-list.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0148-sort-list.js diff --git a/0148-sort-list.js b/0148-sort-list.js new file mode 100644 index 00000000..d70b320d --- /dev/null +++ b/0148-sort-list.js @@ -0,0 +1,49 @@ +/** + * 148. Sort List + * https://leetcode.com/problems/sort-list/ + * Difficulty: Medium + * + * Given the head of a linked list, return the list after sorting it in ascending order. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var sortList = function(head) { + if (!head || !head.next) return head; + let fast = head; + let slow = head; + while (fast.next && fast.next.next) { + fast = fast.next.next; + slow = slow.next; + } + const middle = slow.next; + slow.next = null; + return mergeList(sortList(head), sortList(middle)); +}; + +function mergeList(a, b) { + const ordered = new ListNode(-1); + let list = ordered; + + while (a && b) { + list.next = a.val < b.val ? a : b; + list = list.next; + if (a.val < b.val) { + a = a.next; + } else { + b = b.next; + } + } + + list.next = a ?? b; + return ordered.next; +} diff --git a/README.md b/README.md index 561b4ec9..0fd5dc91 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ 143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| +148|[Sort List](./0148-sort-list.js)|Medium| 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From 8141707a2bcc4cdc3423785041886222bbe447e3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:01:06 -0600 Subject: [PATCH 393/485] Add solution #2623 --- 2623-memoize.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 2623-memoize.js diff --git a/2623-memoize.js b/2623-memoize.js new file mode 100644 index 00000000..d63b830d --- /dev/null +++ b/2623-memoize.js @@ -0,0 +1,41 @@ +/** + * 2623. Memoize + * https://leetcode.com/problems/memoize/ + * Difficulty: Medium + * + * Given a function fn, return a memoized version of that function. + * + * A memoized function is a function that will never be called twice + * with the same inputs. Instead it will return a cached value. + * + * You can assume there are 3 possible input functions: sum, fib, + * and factorial. + * + * - `sum` accepts two integers a and b and returns a + b. Assume that + * if a value has already been cached for the arguments (b, a) where + * a != b, it cannot be used for the arguments (a, b). For example, + * if the arguments are (3, 2) and (2, 3), two separate calls should + * be made. + * - `fib` accepts a single integer n and returns 1 if n <= 1 or + * fib(n - 1) + fib(n - 2) otherwise. + * - `factorial` accepts a single integer n and returns 1 if n <= 1 or + * factorial(n - 1) * n otherwise. + */ + +/** + * @param {Function} fn + * @return {Function} + */ +function memoize(fn) { + const cache = new Map(); + + return (...args) => { + const key = String(args); + if (cache.has(key)) { + return cache.get(key); + } + const value = fn(...args); + cache.set(key, value); + return value; + }; +} diff --git a/README.md b/README.md index 0fd5dc91..550cbb9a 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,7 @@ 2620|[Counter](./2620-counter.js)|Easy| 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| +2623|[Memoize](./2623-memoize.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 3e7be463960e8ba83f1e543f41a3da182de9aa3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:02:02 -0600 Subject: [PATCH 394/485] Add solution #2630 --- 2630-memoize-ii.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 2630-memoize-ii.js diff --git a/2630-memoize-ii.js b/2630-memoize-ii.js new file mode 100644 index 00000000..eeab53c6 --- /dev/null +++ b/2630-memoize-ii.js @@ -0,0 +1,30 @@ +/** + * 2630. Memoize II + * https://leetcode.com/problems/memoize-ii/ + * Difficulty: Hard + * + * Given a function fn, return a memoized version of that function. + * + * A memoized function is a function that will never be called twice + * with the same inputs. Instead it will return a cached value. + * + * fn can be any function and there are no constraints on what type + * of values it accepts. Inputs are considered identical if they + * are === to each other. + */ + +/** + * @param {Function} fn + * @return {Function} + */ +function memoize(fn) { + const cache = {}; + const idLookup = new Map(); + function generateId(item) { + return idLookup.get(item) ?? idLookup.set(item, idLookup.size + 1).get(item); + } + return (...args) => { + const key = args.map(generateId).join('-'); + return !cache.hasOwnProperty(key) ? (cache[key] = fn(...args)) : cache[key]; + }; +} diff --git a/README.md b/README.md index 550cbb9a..b572c4c0 100644 --- a/README.md +++ b/README.md @@ -370,6 +370,7 @@ 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| +2630|[Memoize II](./2630-memoize-ii.js)|Hard| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 26ca6fd11df5db5b6ccdd0e38ac44365bbf7515e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:03:47 -0600 Subject: [PATCH 395/485] Add solution #2627 --- 2627-debounce.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2627-debounce.js diff --git a/2627-debounce.js b/2627-debounce.js new file mode 100644 index 00000000..2d017ae5 --- /dev/null +++ b/2627-debounce.js @@ -0,0 +1,32 @@ +/** + * 2627. Debounce + * https://leetcode.com/problems/debounce/ + * Difficulty: Medium + * + * Given a function fn and a time in milliseconds t, return a debounced version of that function. + * + * A debounced function is a function whose execution is delayed by t milliseconds and whose + * execution is cancelled if it is called again within that window of time. The debounced + * function should also receive the passed parameters. + * + * For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. + * + * The first 2 function calls would be cancelled, and the 3rd function call would be executed + * at 150ms. + * + * If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, + * and the 3rd would be executed at 135ms. + */ + +/** + * @param {Function} fn + * @param {number} t milliseconds + * @return {Function} + */ +var debounce = function(fn, t) { + let timer; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), t); + }; +}; diff --git a/README.md b/README.md index b572c4c0..bf2fc51d 100644 --- a/README.md +++ b/README.md @@ -369,6 +369,7 @@ 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| +2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 0feb722700aa106f9549f3d1b31e8fc576d9d645 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:24:33 -0600 Subject: [PATCH 396/485] Add solution #205 --- 0205-isomorphic-strings.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0205-isomorphic-strings.js diff --git a/0205-isomorphic-strings.js b/0205-isomorphic-strings.js new file mode 100644 index 00000000..5067078c --- /dev/null +++ b/0205-isomorphic-strings.js @@ -0,0 +1,27 @@ +/** + * 205. Isomorphic Strings + * https://leetcode.com/problems/isomorphic-strings/ + * Difficulty: Easy + * + * Given two strings s and t, determine if they are isomorphic. + * + * Two strings s and t are isomorphic if the characters in s can be replaced to get t. + * + * All occurrences of a character must be replaced with another character while preserving + * the order of characters. No two characters may map to the same character, but a character + * may map to itself. + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isIsomorphic = function(s, t) { + for (let i = 0; i < s.length; i++) { + if (s.indexOf(s[i], i + 1) !== t.indexOf(t[i], i + 1)) { + return false; + } + } + return true; +}; diff --git a/README.md b/README.md index bf2fc51d..1585a507 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ 202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| +205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 207|[Course Schedule](./0207-course-schedule.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| From 964f35f5aab294a7a3b985b3a98b7dc94fd83b79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 19:03:48 -0600 Subject: [PATCH 397/485] Add solution #914 --- 0914-x-of-a-kind-in-a-deck-of-cards.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0914-x-of-a-kind-in-a-deck-of-cards.js diff --git a/0914-x-of-a-kind-in-a-deck-of-cards.js b/0914-x-of-a-kind-in-a-deck-of-cards.js new file mode 100644 index 00000000..adc311f2 --- /dev/null +++ b/0914-x-of-a-kind-in-a-deck-of-cards.js @@ -0,0 +1,24 @@ +/** + * 914. X of a Kind in a Deck of Cards + * https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/ + * Difficulty: Medium + * + * You are given an integer array deck where deck[i] represents the number written on the ith card. + * + * Partition the cards into one or more groups such that: + * - Each group has exactly x cards where x > 1, and + * - All the cards in one group have the same integer written on them. + * + * Return true if such partition is possible, or false otherwise. + */ + +/** + * @param {number[]} deck + * @return {boolean} + */ +var hasGroupsSizeX = function(deck) { + const gcd = (a, b) => !b ? a : gcd(b, a % b); + const map = new Map(); + deck.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + return [...map.values()].reduce(gcd) > 1; +}; diff --git a/README.md b/README.md index 1585a507..1b86aad4 100644 --- a/README.md +++ b/README.md @@ -238,6 +238,7 @@ 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| +914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| From 7f2239ddcd8b7a4710f297e65aa9e78c6a5218ca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:03:13 -0600 Subject: [PATCH 398/485] Add solution #443 --- 0443-string-compression.js | 42 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0443-string-compression.js diff --git a/0443-string-compression.js b/0443-string-compression.js new file mode 100644 index 00000000..63dffb2a --- /dev/null +++ b/0443-string-compression.js @@ -0,0 +1,42 @@ +/** + * 443. String Compression + * https://leetcode.com/problems/string-compression/ + * Difficulty: Medium + * + * Given an array of characters chars, compress it using the following algorithm: + * + * Begin with an empty string s. For each group of consecutive repeating characters in chars: + * - If the group's length is 1, append the character to s. + * - Otherwise, append the character followed by the group's length. + * + * The compressed string s should not be returned separately, but instead, be stored in the + * input character array chars. Note that group lengths that are 10 or longer will be split + * into multiple characters in chars. + * + * After you are done modifying the input array, return the new length of the array. + * + * You must write an algorithm that uses only constant extra space. + */ + +/** + * @param {character[]} chars + * @return {number} + */ +var compress = function(chars) { + let pointer = 0; + for (let i = 0; i < chars.length; i++) { + const char = chars[i]; + let count = 0; + while (i < chars.length && chars[i] === char) { + count++; + i++; + } + chars[pointer++] = char; + if (count !== 1) { + String(count).split('').forEach(n => chars[pointer++] = n); + } + i--; + } + chars.length = pointer; + return pointer; +}; diff --git a/README.md b/README.md index 1b86aad4..4edc9a0f 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,7 @@ 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| +443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| From 43552e2272cfc4db60528665211d27db4605dbb3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:04:12 -0600 Subject: [PATCH 399/485] Add solution #334 --- 0334-increasing-triplet-subsequence.js | 31 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0334-increasing-triplet-subsequence.js diff --git a/0334-increasing-triplet-subsequence.js b/0334-increasing-triplet-subsequence.js new file mode 100644 index 00000000..734afe32 --- /dev/null +++ b/0334-increasing-triplet-subsequence.js @@ -0,0 +1,31 @@ +/** + * 334. Increasing Triplet Subsequence + * https://leetcode.com/problems/increasing-triplet-subsequence/ + * Difficulty: Medium + * + * Given an integer array nums, return true if there exists a triple of indices + * (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such + * indices exists, return false. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var increasingTriplet = function(nums) { + let first = Infinity; + let second = Infinity; + + for (const current of nums) { + if (current > second && current > first) { + return true; + } + if (current > first) { + second = current; + } else { + first = current; + } + } + + return false; +}; diff --git a/README.md b/README.md index 4edc9a0f..b251e738 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,7 @@ 290|[Word Pattern](./0290-word-pattern.js)|Easy| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| +334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| From 55c3e4b81c139a42284a1682285dd750afe7a1c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:05:23 -0600 Subject: [PATCH 400/485] Add solution #238 --- 0238-product-of-array-except-self.js | 30 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0238-product-of-array-except-self.js diff --git a/0238-product-of-array-except-self.js b/0238-product-of-array-except-self.js new file mode 100644 index 00000000..f297cd25 --- /dev/null +++ b/0238-product-of-array-except-self.js @@ -0,0 +1,30 @@ +/** + * 238. Product of Array Except Self + * https://leetcode.com/problems/product-of-array-except-self/ + * Difficulty: Medium + * + * Given an integer array nums, return an array answer such that answer[i] is equal to the product + * of all the elements of nums except nums[i]. + * + * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. + * + * You must write an algorithm that runs in O(n) time and without using the division operation. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function(nums) { + const emptyResult = new Array(nums.length).fill(0); + const zeroCount = nums.filter(n => n === 0).length; + if (zeroCount > 1) { + return emptyResult; + } + const product = nums.reduce((product, n) => product * (n === 0 ? 1 : n), 1); + if (zeroCount === 1) { + emptyResult[nums.indexOf(0)] = product; + return emptyResult; + } + return nums.map(n => product / n); +}; diff --git a/README.md b/README.md index b251e738..486a6ea5 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| +238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From a5ede838c24ff36b99e6718306159f41f70ec112 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:06:12 -0600 Subject: [PATCH 401/485] Add solution #605 --- 0605-can-place-flowers.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0605-can-place-flowers.js diff --git a/0605-can-place-flowers.js b/0605-can-place-flowers.js new file mode 100644 index 00000000..d8c4d8a0 --- /dev/null +++ b/0605-can-place-flowers.js @@ -0,0 +1,28 @@ +/** + * 605. Can Place Flowers + * https://leetcode.com/problems/can-place-flowers/ + * Difficulty: Easy + * + * You have a long flowerbed in which some of the plots are planted, and some are not. + * However, flowers cannot be planted in adjacent plots. + * + * Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 + * means not empty, and an integer n, return true if n new flowers can be planted in + * the flowerbed without violating the no-adjacent-flowers rule and false otherwise. + */ + +/** + * @param {number[]} flowerbed + * @param {number} n + * @return {boolean} + */ +var canPlaceFlowers = function(flowerbed, n) { + let count = 0; + for (let i = 0; i < flowerbed.length; i++) { + if (flowerbed[i] === 0 && flowerbed[i - 1] !== 1 && flowerbed[i + 1] !== 1) { + count++; + flowerbed[i] = 1; + } + } + return count >= n; +}; diff --git a/README.md b/README.md index 486a6ea5..05020207 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| +605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 9994c451c68618e950aea91a7ce5c5834d00e73c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:07:03 -0600 Subject: [PATCH 402/485] Add solution #1071 --- 1071-greatest-common-divisor-of-strings.js | 26 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1071-greatest-common-divisor-of-strings.js diff --git a/1071-greatest-common-divisor-of-strings.js b/1071-greatest-common-divisor-of-strings.js new file mode 100644 index 00000000..e1639737 --- /dev/null +++ b/1071-greatest-common-divisor-of-strings.js @@ -0,0 +1,26 @@ +/** + * 1071. Greatest Common Divisor of Strings + * https://leetcode.com/problems/greatest-common-divisor-of-strings/ + * Difficulty: Easy + * + * For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t + * (i.e., t is concatenated with itself one or more times). + * + * Given two strings str1 and str2, return the largest string x such that x divides both str1 + * and str2. + */ + +/** + * @param {string} str1 + * @param {string} str2 + * @return {string} + */ +var gcdOfStrings = function(str1, str2) { + if (str1 + str2 !== str2 + str1) return ''; + + for (let i = str2.length; i >= 0; i--) { + if (str1.length % i === 0 && str2.length % i === 0) { + return str1.substring(0, i); + } + } +}; diff --git a/README.md b/README.md index 05020207..773fcad9 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,7 @@ 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| +1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| From 0061ca8ed440120a792e072bd46f1b6e5193b490 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:08:08 -0600 Subject: [PATCH 403/485] Add solution #1768 --- 1768-merge-strings-alternately.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1768-merge-strings-alternately.js diff --git a/1768-merge-strings-alternately.js b/1768-merge-strings-alternately.js new file mode 100644 index 00000000..80b58b16 --- /dev/null +++ b/1768-merge-strings-alternately.js @@ -0,0 +1,25 @@ +/** + * 1768. Merge Strings Alternately + * https://leetcode.com/problems/merge-strings-alternately/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {string} + */ +var mergeAlternately = function(word1, word2) { + let result = ''; + for (let i = 0; i < Math.max(word1.length, word2.length); i++) { + if (i < word1.length) result += word1[i]; + if (i < word2.length) result += word2[i]; + } + return result; +}; diff --git a/README.md b/README.md index 773fcad9..26f444f1 100644 --- a/README.md +++ b/README.md @@ -337,6 +337,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| From bfc3b20b876be49a3579bd1b4468ee5096e4627d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:16:57 -0600 Subject: [PATCH 404/485] Add solution #392 --- 0392-is-subsequence.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0392-is-subsequence.js diff --git a/0392-is-subsequence.js b/0392-is-subsequence.js new file mode 100644 index 00000000..a041d570 --- /dev/null +++ b/0392-is-subsequence.js @@ -0,0 +1,27 @@ +/** + * 392. Is Subsequence + * https://leetcode.com/problems/is-subsequence/ + * Difficulty: Easy + * + * Given two strings s and t, return true if s is a subsequence of t, or false otherwise. + * + * A subsequence of a string is a new string that is formed from the original string by + * deleting some (can be none) of the characters without disturbing the relative positions + * of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isSubsequence = function(s, t) { + if (s.length > t.length) return false; + let count = 0; + for (let i = 0; i < t.length; i++) { + if (s[count] === t[i]) { + count++; + } + } + return count === s.length; +}; diff --git a/README.md b/README.md index 26f444f1..e0854597 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From ab0086fe651e377d11d3c5eea1c3e8d10bad0029 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:50:41 -0600 Subject: [PATCH 405/485] Add solution #1657 --- 1657-determine-if-two-strings-are-close.js | 47 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 1657-determine-if-two-strings-are-close.js diff --git a/1657-determine-if-two-strings-are-close.js b/1657-determine-if-two-strings-are-close.js new file mode 100644 index 00000000..cc000018 --- /dev/null +++ b/1657-determine-if-two-strings-are-close.js @@ -0,0 +1,47 @@ +/** + * 1657. Determine if Two Strings Are Close + * https://leetcode.com/problems/determine-if-two-strings-are-close/ + * Difficulty: Medium + * + * Two strings are considered close if you can attain one from the other using the following + * operations: + * + * - Operation 1: Swap any two existing characters. + * For example, abcde -> aecdb + * - Operation 2: Transform every occurrence of one existing character into another existing + * character, and do the same with the other character. + * For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) + * + * You can use the operations on either string as many times as necessary. + * + * Given two strings, word1 and word2, return true if word1 and word2 are close, and false + * otherwise. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {boolean} + */ +var closeStrings = function(word1, word2) { + const map1 = helper(word1); + const map2 = helper(word2); + + for (let i = 0; i < map1.length; i++) { + if ((map1[i] === 0 || map2[i] === 0) && map1[i] !== map2[i]) { + return false; + } + } + + [map1, map2].forEach(m => m.sort((a, b) => b - a)); + + return map1.join('') === map2.join(''); +}; + +function helper(input) { + const map = Array(26).fill(0); + for (let i = 0; i < input.length; i++) { + map[input.charCodeAt(i) - 'a'.charCodeAt(0)]++; + } + return map; +} diff --git a/README.md b/README.md index e0854597..6c18cd3f 100644 --- a/README.md +++ b/README.md @@ -333,6 +333,7 @@ 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| +1657|[Determine if Two Strings Are Close](./1657-determine-if-two-strings-are-close.js)|Medium| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| From 8fa227ea4e0b26f2f88738e4efb4e983709efefe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:52:16 -0600 Subject: [PATCH 406/485] Add solution #75 --- 0075-sort-colors.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0075-sort-colors.js diff --git a/0075-sort-colors.js b/0075-sort-colors.js new file mode 100644 index 00000000..9f4b5f73 --- /dev/null +++ b/0075-sort-colors.js @@ -0,0 +1,28 @@ +/** + * 75. Sort Colors + * https://leetcode.com/problems/sort-colors/ + * Difficulty: Medium + * + * Given an array nums with n objects colored red, white, or blue, sort them in-place so + * that objects of the same color are adjacent, with the colors in the order red, white, + * and blue. + * + * We will use the integers 0, 1, and 2 to represent the color red, white, and blue, + * respectively. + * + * You must solve this problem without using the library's sort function. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var sortColors = function(nums) { + const count = nums.reduce((a, n) => ++a[n] && a, [0, 0, 0]); + for (let i = 0, j = 0; i < count.length; i++) { + for (let k = 0; k < count[i]; k++) { + nums[j++] = i; + } + } + return nums; +}; diff --git a/README.md b/README.md index 6c18cd3f..bb2b018d 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| +75|[Sort Colors](./0075-sort-colors.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| From 0d9b123788fa35b414ed061c16ada20336fe15bd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:53:25 -0600 Subject: [PATCH 407/485] Add solution #2215 --- 2215-find-the-difference-of-two-arrays.js | 25 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 2215-find-the-difference-of-two-arrays.js diff --git a/2215-find-the-difference-of-two-arrays.js b/2215-find-the-difference-of-two-arrays.js new file mode 100644 index 00000000..6185f291 --- /dev/null +++ b/2215-find-the-difference-of-two-arrays.js @@ -0,0 +1,25 @@ +/** + * 2215. Find the Difference of Two Arrays + * https://leetcode.com/problems/find-the-difference-of-two-arrays/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[][]} + */ +var findDifference = function(nums1, nums2) { + const set1 = new Set(nums1); + const set2 = new Set(nums2); + return [ + [...set1].filter(n => !set2.has(n)), + [...set2].filter(n => !set1.has(n)) + ]; +}; diff --git a/README.md b/README.md index bb2b018d..dde510f5 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| From e2b79b90e92c19e216e5efcf5342b5c6ed3bca57 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:54:55 -0600 Subject: [PATCH 408/485] Add solution #3110 --- 3110-score-of-a-string.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 3110-score-of-a-string.js diff --git a/3110-score-of-a-string.js b/3110-score-of-a-string.js new file mode 100644 index 00000000..047fe4dc --- /dev/null +++ b/3110-score-of-a-string.js @@ -0,0 +1,22 @@ +/** + * 3110. Score of a String + * https://leetcode.com/problems/score-of-a-string/ + * Difficulty: Easy + * + * You are given a string s. The score of a string is defined as the sum of the absolute + * difference between the ASCII values of adjacent characters. + * + * Return the score of s. + */ + +/** + * @param {string} s + * @return {number} + */ +var scoreOfString = function(s) { + let sum = 0; + for (let i = 0; i < s.length - 1; i++) { + sum += Math.abs(s[i].charCodeAt() - s[i + 1].charCodeAt()); + } + return sum; +}; diff --git a/README.md b/README.md index dde510f5..d9806fe7 100644 --- a/README.md +++ b/README.md @@ -384,6 +384,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 0bb0be067bcebbe872f2a7376e4e213efbdc12b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:57:54 -0600 Subject: [PATCH 409/485] Add solution #65 --- 0065-valid-number.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0065-valid-number.js diff --git a/0065-valid-number.js b/0065-valid-number.js new file mode 100644 index 00000000..ddc0723a --- /dev/null +++ b/0065-valid-number.js @@ -0,0 +1,33 @@ +/** + * 65. Valid Number + * https://leetcode.com/problems/valid-number/ + * Difficulty: Hard + * + * Given a string s, return whether s is a valid number. + * + * For example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", + * "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789", while the following are not + * valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53". + * + * Formally, a valid number is defined using one of the following definitions: + * - An integer number followed by an optional exponent. + * - A decimal number followed by an optional exponent. + * + * An integer number is defined with an optional sign '-' or '+' followed by digits. + * A decimal number is defined with an optional sign '-' or '+' followed by one of the + * following definitions: + * - Digits followed by a dot '.'. + * - Digits followed by a dot '.' followed by digits. + * - A dot '.' followed by digits. + * - An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number. + * + * The digits are defined as one or more digits. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isNumber = function(s) { + return s.trim().length && !isNaN(s.trim()) && !s.includes('Infinity'); +}; diff --git a/README.md b/README.md index d9806fe7..20481b6f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ 60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| +65|[Valid Number](./0065-valid-number.js)|Hard| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| From 42319e178d9aaff20b13cff98550a934169685c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:59:23 -0600 Subject: [PATCH 410/485] Add solution #2703 --- 2703-return-length-of-arguments-passed.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 2703-return-length-of-arguments-passed.js diff --git a/2703-return-length-of-arguments-passed.js b/2703-return-length-of-arguments-passed.js new file mode 100644 index 00000000..36efef1f --- /dev/null +++ b/2703-return-length-of-arguments-passed.js @@ -0,0 +1,15 @@ +/** + * 2703. Return Length of Arguments Passed + * https://leetcode.com/problems/return-length-of-arguments-passed/ + * Difficulty: Easy + * + * Write a function argumentsLength that returns the count of arguments passed to it. + */ + +/** + * @param {...(null|boolean|number|string|Array|Object)} args + * @return {number} + */ +var argumentsLength = function(...args) { + return args.length; +}; diff --git a/README.md b/README.md index 20481b6f..a5ee1f45 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From ac079f3f095092dc5da2df403eaa8c1cb73c5d1d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 01:00:02 -0600 Subject: [PATCH 411/485] Add solution #61 --- 0061-rotate-list.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0061-rotate-list.js diff --git a/0061-rotate-list.js b/0061-rotate-list.js new file mode 100644 index 00000000..69037d40 --- /dev/null +++ b/0061-rotate-list.js @@ -0,0 +1,37 @@ +/** + * 61. Rotate List + * https://leetcode.com/problems/rotate-list/ + * Difficulty: Medium + * + * Given the head of a linked list, rotate the list to the right by k places. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var rotateRight = function(head, k) { + if (!head || !head.next || !k) return head; + let tailCopy = head; + let tail = head; + let count = 1; + while (tail.next) { + tail = tail.next; + count++; + } + tail.next = head; + for (let i = 1; i < count - k % count; i++) { + tailCopy = tailCopy.next; + } + const result = tailCopy.next; + tailCopy.next = null; + return result; +}; diff --git a/README.md b/README.md index a5ee1f45..cbb30b11 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| 60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| +61|[Rotate List](./0061-rotate-list.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 65|[Valid Number](./0065-valid-number.js)|Hard| From a391a1db28005a1af9ebd3a26aef6f4fd834f5ad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:35:04 -0600 Subject: [PATCH 412/485] Add solution #2637 --- 2637-promise-time-limit.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2637-promise-time-limit.js diff --git a/2637-promise-time-limit.js b/2637-promise-time-limit.js new file mode 100644 index 00000000..4e1c2d9e --- /dev/null +++ b/2637-promise-time-limit.js @@ -0,0 +1,28 @@ +/** + * 2637. Promise Time Limit + * https://leetcode.com/problems/promise-time-limit/ + * Difficulty: Medium + * + * Given an asynchronous function fn and a time t in milliseconds, return a new time limited + * version of the input function. fn takes arguments provided to the time limited function. + * + * The time limited function should follow these rules: + * - If the fn completes within the time limit of t milliseconds, the time limited function + * should resolve with the result. + * - If the execution of the fn exceeds the time limit, the time limited function should + * reject with the string "Time Limit Exceeded". + */ + +/** + * @param {Function} fn + * @param {number} t + * @return {Function} + */ +var timeLimit = function(fn, t) { + return async function(...args) { + return Promise.race([ + fn(...args), + new Promise((_, reject) => setTimeout(() => reject('Time Limit Exceeded'), t)), + ]); + }; +}; diff --git a/README.md b/README.md index cbb30b11..6e04ec50 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From b519ee1ba21f8d41f95dd4ea78df00ee57a3aa71 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:35:46 -0600 Subject: [PATCH 413/485] Add solution #2648 --- 2648-generate-fibonacci-sequence.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2648-generate-fibonacci-sequence.js diff --git a/2648-generate-fibonacci-sequence.js b/2648-generate-fibonacci-sequence.js new file mode 100644 index 00000000..8e03eea5 --- /dev/null +++ b/2648-generate-fibonacci-sequence.js @@ -0,0 +1,24 @@ +/** + * 2648. Generate Fibonacci Sequence + * https://leetcode.com/problems/generate-fibonacci-sequence/ + * Difficulty: Easy + * + * Write a generator function that returns a generator object which yields the fibonacci sequence. + * + * 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. + */ + +/** + * @return {Generator} + */ +var fibGenerator = function* () { + let current = 0; + let next = 1; + + while (next) { + yield current; + [current, next] = [next, current + next]; + } +}; diff --git a/README.md b/README.md index 6e04ec50..efd99ad2 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| +2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From d5f8285675bce92ed2e40e134365f05fdab7f1aa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:36:34 -0600 Subject: [PATCH 414/485] Add solution #2649 --- 2649-nested-array-generator.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 2649-nested-array-generator.js diff --git a/2649-nested-array-generator.js b/2649-nested-array-generator.js new file mode 100644 index 00000000..ff72f6e5 --- /dev/null +++ b/2649-nested-array-generator.js @@ -0,0 +1,25 @@ +/** + * 2649. Nested Array Generator + * https://leetcode.com/problems/nested-array-generator/ + * Difficulty: Medium + * + * Given a multi-dimensional array of integers, return a generator object which yields + * integers in the same order as inorder traversal. + * + * A multi-dimensional array is a recursive data structure that contains both integers + * and other multi-dimensional arrays. + * + * inorder traversal iterates over each array from left to right, yielding any integers + * it encounters or applying inorder traversal to any arrays it encounters. + */ + +/** + * @param {Array} input + * @return {Generator} + */ +var inorderTraversal = function* (input) { + for (const item of input) { + if (!Array.isArray(item)) yield item; + else yield* inorderTraversal(item); + } +}; diff --git a/README.md b/README.md index efd99ad2..c861dd8f 100644 --- a/README.md +++ b/README.md @@ -388,6 +388,7 @@ 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| +2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From ce69fdd2c181d40654827acda7cfec9781978462 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:38:18 -0600 Subject: [PATCH 415/485] Add solution #2650 --- 2650-design-cancellable-function.js | 47 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 2650-design-cancellable-function.js diff --git a/2650-design-cancellable-function.js b/2650-design-cancellable-function.js new file mode 100644 index 00000000..c6f874ac --- /dev/null +++ b/2650-design-cancellable-function.js @@ -0,0 +1,47 @@ +/** + * 2650. Design Cancellable Function + * https://leetcode.com/problems/design-cancellable-function/ + * Difficulty: Hard + * + * Sometimes you have a long running task, and you may wish to cancel it before it completes. + * To help with this goal, write a function cancellable that accepts a generator object and + * returns an array of two values: a cancel function and a promise. + * + * You may assume the generator function will only yield promises. It is your function's + * responsibility to pass the values resolved by the promise back to the generator. If the + * promise rejects, your function should throw that error back to the generator. + * + * If the cancel callback is called before the generator is done, your function should throw + * an error back to the generator. That error should be the string "Cancelled" (Not an Error + * object). If the error was caught, the returned promise should resolve with the next value + * that was yielded or returned. Otherwise, the promise should reject with the thrown error. + * No more code should be executed. + * + * When the generator is done, the promise your function returned should resolve the value + * the generator returned. If, however, the generator throws an error, the returned promise + * should reject with the error. + */ + +/** + * @param {Generator} generator + * @return {[Function, Promise]} + */ +var cancellable = function(generator) { + let cancel; + const cancelPromise = new Promise((_, reject) => { + cancel = () => reject("Cancelled"); + }); + cancelPromise.catch(() => {}); + const promise = (async () => { + let next = generator.next(); + while (!next.done) { + try { + next = generator.next(await Promise.race([next.value, cancelPromise])); + } catch (e) { + next = generator.throw(e); + } + } + return next.value; + })(); + return [cancel, promise]; +}; diff --git a/README.md b/README.md index c861dd8f..49ddc3c6 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,7 @@ 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| +2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 5c5e6a64154d561881b608b17fbe2f8f4ec5a86f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:39:03 -0600 Subject: [PATCH 416/485] Add solution #2665 --- 2665-counter-ii.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2665-counter-ii.js diff --git a/2665-counter-ii.js b/2665-counter-ii.js new file mode 100644 index 00000000..7be48904 --- /dev/null +++ b/2665-counter-ii.js @@ -0,0 +1,26 @@ +/** + * 2665. Counter II + * https://leetcode.com/problems/counter-ii/ + * Difficulty: Easy + * + * Write a function createCounter. It should accept an initial integer init. + * It should return an object with three functions. + * + * The three functions are: + * - 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. + */ + +/** + * @param {integer} init + * @return { increment: Function, decrement: Function, reset: Function } + */ +var createCounter = function(init) { + let current = init; + return { + increment: () => ++current, + decrement: () => --current, + reset: () => current = init, + }; +}; diff --git a/README.md b/README.md index 49ddc3c6..da47f074 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,7 @@ 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| +2665|[Counter II](./2665-counter-ii.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 70ee2abc5e66f144a231772deb5b32340f16a7af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:39:43 -0600 Subject: [PATCH 417/485] Add solution #2667 --- 2667-create-hello-world-function.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 2667-create-hello-world-function.js diff --git a/2667-create-hello-world-function.js b/2667-create-hello-world-function.js new file mode 100644 index 00000000..93b1e296 --- /dev/null +++ b/2667-create-hello-world-function.js @@ -0,0 +1,15 @@ +/** + * 2667. Create Hello World Function + * https://leetcode.com/problems/create-hello-world-function/ + * Difficulty: Easy + * + * Write a function createHelloWorld. It should return a new function that + * always returns "Hello World". + */ + +/** + * @return {Function} + */ +var createHelloWorld = function() { + return () => 'Hello World'; +}; diff --git a/README.md b/README.md index da47f074..0e5a0aee 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,7 @@ 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2665|[Counter II](./2665-counter-ii.js)|Easy| +2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From e9183f94d16b95635441665c6ae98151d46889d2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:40:26 -0600 Subject: [PATCH 418/485] Add solution #2666 --- 2666-allow-one-function-call.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 2666-allow-one-function-call.js diff --git a/2666-allow-one-function-call.js b/2666-allow-one-function-call.js new file mode 100644 index 00000000..93bb604d --- /dev/null +++ b/2666-allow-one-function-call.js @@ -0,0 +1,19 @@ +/** + * 2666. Allow One Function Call + * https://leetcode.com/problems/allow-one-function-call/ + * Difficulty: Easy + * + * 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. + * + * - The first time the returned function is called, it should return the same result as fn. + * - Every subsequent time it is called, it should return undefined. + */ + +/** + * @param {Function} fn + * @return {Function} + */ +var once = function(fn) { + return (...args) => fn && [fn(...args), fn = undefined][0]; +}; diff --git a/README.md b/README.md index 0e5a0aee..236742b0 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,7 @@ 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2665|[Counter II](./2665-counter-ii.js)|Easy| +2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From aba4df3feb085ee9cea9f86a12fa39f887accafe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:02:50 -0600 Subject: [PATCH 419/485] Add solution #2634 --- 2634-filter-elements-from-array.js | 34 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2634-filter-elements-from-array.js diff --git a/2634-filter-elements-from-array.js b/2634-filter-elements-from-array.js new file mode 100644 index 00000000..bf8bd0b0 --- /dev/null +++ b/2634-filter-elements-from-array.js @@ -0,0 +1,34 @@ +/** + * 2634. Filter Elements from Array + * https://leetcode.com/problems/filter-elements-from-array/ + * Difficulty: Easy + * + * Given an integer array arr and a filtering function fn, return a filtered array filteredArr. + * + * The fn function takes one or two arguments: + * arr[i] - number from the arr + * i - index of arr[i] + * + * filteredArr should only contain the elements from the arr for which the expression + * fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where + * Boolean(value) returns true. + * + * Please solve it without the built-in Array.filter method. + */ + +/** + * @param {number[]} arr + * @param {Function} fn + * @return {number[]} + */ +var filter = function(arr, fn) { + const result = []; + + for (let i = 0; i < arr.length; i++) { + if (fn(arr[i], i)) { + result.push(arr[i]); + } + } + + return result; +}; diff --git a/README.md b/README.md index 236742b0..3709358f 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| From 9458524950d8937d6eac7c3dfeab4b878437a7a9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:03:36 -0600 Subject: [PATCH 420/485] Add solution #2635 --- ...ly-transform-over-each-element-in-array.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 2635-apply-transform-over-each-element-in-array.js diff --git a/2635-apply-transform-over-each-element-in-array.js b/2635-apply-transform-over-each-element-in-array.js new file mode 100644 index 00000000..35fa788c --- /dev/null +++ b/2635-apply-transform-over-each-element-in-array.js @@ -0,0 +1,27 @@ +/** + * 2635. Apply Transform Over Each Element in Array + * https://leetcode.com/problems/apply-transform-over-each-element-in-array/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {number[]} arr + * @param {Function} fn + * @return {number[]} + */ +var map = function(arr, fn) { + const result = []; + + for (let i = 0; i < arr.length; i++) { + result.push(fn(arr[i], i)); + } + + return result; +}; diff --git a/README.md b/README.md index 3709358f..0ec4c265 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy| +2635|[Apply Transform Over Each Element in Array](./2635-apply-transform-over-each-element-in-array.js)|Easy| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| From 3f107d4b01af03c492fd62437bee0a8c28e75e3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:04:54 -0600 Subject: [PATCH 421/485] Add solution #2626 --- 2626-array-reduce-transformation.js | 33 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 2626-array-reduce-transformation.js diff --git a/2626-array-reduce-transformation.js b/2626-array-reduce-transformation.js new file mode 100644 index 00000000..a93b28fa --- /dev/null +++ b/2626-array-reduce-transformation.js @@ -0,0 +1,33 @@ +/** + * 2626. Array Reduce Transformation + * https://leetcode.com/problems/array-reduce-transformation/ + * Difficulty: Easy + * + * Given an integer array nums, a reducer function fn, and an initial value init, return the final + * result obtained by executing the fn function on each element of the array, sequentially, + * passing in the return value from the calculation on the preceding element. + * + * This result is achieved through the following operations: val = fn(init, nums[0]), + * val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been + * processed. The ultimate value of val is then returned. + * + * If the length of the array is 0, the function should return init. + * + * Please solve it without using the built-in Array.reduce method. + */ + +/** + * @param {number[]} nums + * @param {Function} fn + * @param {number} init + * @return {number} + */ +var reduce = function(nums, fn, init) { + let result = init; + + for (let i = 0; i < nums.length; i++) { + result = fn(result, nums[i]); + } + + return result; +}; diff --git a/README.md b/README.md index 0ec4c265..9a93efab 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| +2626|[Array Reduce Transformation](./2626-array-reduce-transformation.js)|Easy| 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| From ed504316e6141008400689fe05de2a6207eb6a5a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:05:53 -0600 Subject: [PATCH 422/485] Add solution #2631 --- 2631-group-by.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 2631-group-by.js diff --git a/2631-group-by.js b/2631-group-by.js new file mode 100644 index 00000000..3a1eadd8 --- /dev/null +++ b/2631-group-by.js @@ -0,0 +1,35 @@ +/** + * 2631. Group By + * https://leetcode.com/problems/group-by/ + * Difficulty: Medium + * + * Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any + * array and it will return a grouped version of the array. + * + * A grouped array is an object where each key is the output of fn(arr[i]) and each value is an + * array containing all items in the original array which generate that key. + * + * The provided callback fn will accept an item in the array and return a string key. + * + * The order of each value list should be the order the items appear in the array. Any order of + * keys is acceptable. + * + * Please solve it without lodash's _.groupBy function. + */ + +/** + * @param {Function} fn + * @return {Object} + */ +Array.prototype.groupBy = function(fn) { + return this.reduce((grouped, item) => { + const key = fn(item); + grouped[key] = grouped[key] || []; + grouped[key].push(item); + return grouped; + }, {}); +}; + +/** + * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} + */ diff --git a/README.md b/README.md index 9a93efab..992a5937 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2631|[Group By](./2631-group-by.js)|Medium| 2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy| 2635|[Apply Transform Over Each Element in Array](./2635-apply-transform-over-each-element-in-array.js)|Easy| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| From a0d77c7c56e7082325b41ae536e1ad28aef9eff4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:07:02 -0600 Subject: [PATCH 423/485] Add solution #2625 --- 2625-flatten-deeply-nested-array.js | 31 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2625-flatten-deeply-nested-array.js diff --git a/2625-flatten-deeply-nested-array.js b/2625-flatten-deeply-nested-array.js new file mode 100644 index 00000000..73ed5916 --- /dev/null +++ b/2625-flatten-deeply-nested-array.js @@ -0,0 +1,31 @@ +/** + * 2625. Flatten Deeply Nested Array + * https://leetcode.com/problems/flatten-deeply-nested-array/ + * Difficulty: Medium + * + * Given a multi-dimensional array arr and a depth n, return a flattened version of that array. + * + * A multi-dimensional array is a recursive data structure that contains integers or other + * multi-dimensional arrays. + * + * A flattened array is a version of that array with some or all of the sub-arrays removed and + * replaced with the actual elements in that sub-array. This flattening operation should only + * be done if the current depth of nesting is less than n. The depth of the elements in the + * first array are considered to be 0. + * + * Please solve it without the built-in Array.flat method. + */ + +/** + * @param {Array} arr + * @param {number} depth + * @return {Array} + */ +var flat = function(arr, n) { + if (n === 0) return arr; + const result = []; + for (let i = 0; i < arr.length; i++) { + result.push(...(Array.isArray(arr[i]) ? flat(arr[i], n - 1) : [arr[i]])); + } + return result; +}; diff --git a/README.md b/README.md index 992a5937..0769ebab 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| +2625|[Flatten Deeply Nested Array](./2625-flatten-deeply-nested-array.js)|Medium| 2626|[Array Reduce Transformation](./2626-array-reduce-transformation.js)|Easy| 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| From 86b31af16baf094cf269f8f3a89b39bb027459f7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:08:13 -0600 Subject: [PATCH 424/485] Add solution #2677 --- 2677-chunk-array.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2677-chunk-array.js diff --git a/2677-chunk-array.js b/2677-chunk-array.js new file mode 100644 index 00000000..60c72d6c --- /dev/null +++ b/2677-chunk-array.js @@ -0,0 +1,31 @@ +/** + * 2677. Chunk Array + * https://leetcode.com/problems/chunk-array/ + * Difficulty: Easy + * + * Given an array arr and a chunk size size, return a chunked array. + * + * A chunked array contains the original elements in arr, but consists of subarrays each of + * length size. The length of the last subarray may be less than size if arr.length is not + * evenly divisible by size. + * + * You may assume the array is the output of JSON.parse. In other words, it is valid JSON. + * + * Please solve it without using lodash's _.chunk function. + */ + +/** + * @param {Array} arr + * @param {number} size + * @return {Array} + */ +var chunk = function(arr, size) { + var result = []; + + for (let index = 0; index < arr.length;) { + result.push(arr.slice(index, index + size)); + index += size; + } + + return result; +}; diff --git a/README.md b/README.md index 0769ebab..94db1ec2 100644 --- a/README.md +++ b/README.md @@ -398,6 +398,7 @@ 2665|[Counter II](./2665-counter-ii.js)|Easy| 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| +2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 5e604510fc0b8d5c968b3254bd86863336bad35c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:09:46 -0600 Subject: [PATCH 425/485] Add solution #2695 --- 2695-array-wrapper.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 2695-array-wrapper.js diff --git a/2695-array-wrapper.js b/2695-array-wrapper.js new file mode 100644 index 00000000..e7838250 --- /dev/null +++ b/2695-array-wrapper.js @@ -0,0 +1,35 @@ +/** + * 2695. Array Wrapper + * https://leetcode.com/problems/array-wrapper/ + * Difficulty: Easy + * + * Create a class ArrayWrapper that accepts an array of integers in its constructor. + * + * This class should have two features: + * - 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. + * - When the String() function is called on the instance, it will return a comma separated + * string surrounded by brackets. For example, [1,2,3]. + */ + +/** + * @param {number[]} nums + * @return {void} + */ +var ArrayWrapper = function(nums) { + this.nums = nums; +}; + +/** + * @return {number} + */ +ArrayWrapper.prototype.valueOf = function() { + return this.nums.reduce((sum, n) => sum + n, 0); +}; + +/** + * @return {string} + */ +ArrayWrapper.prototype.toString = function() { + return JSON.stringify(this.nums); +}; diff --git a/README.md b/README.md index 94db1ec2..78c187bc 100644 --- a/README.md +++ b/README.md @@ -399,6 +399,7 @@ 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2677|[Chunk Array](./2677-chunk-array.js)|Easy| +2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 7b01305ef4b12d864bc1c99e7ea0f13f311e6550 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:04:12 -0600 Subject: [PATCH 426/485] Add solution #85 --- 0085-maximal-rectangle.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0085-maximal-rectangle.js diff --git a/0085-maximal-rectangle.js b/0085-maximal-rectangle.js new file mode 100644 index 00000000..9831d2fb --- /dev/null +++ b/0085-maximal-rectangle.js @@ -0,0 +1,38 @@ +/** + * 85. Maximal Rectangle + * https://leetcode.com/problems/maximal-rectangle/ + * Difficulty: Hard + * + * Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle + * containing only 1's and return its area. + */ + +/** + * @param {character[][]} matrix + * @return {number} + */ +var maximalRectangle = function(matrix) { + if (!matrix?.length) return 0; + let maxArea = 0; + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] === '1') { + let minWidth = matrix[0].length; + + for (let k = i; k < matrix.length && matrix[k][j] === '1'; k++) { + let width = 0; + + while (width < minWidth && j + width < matrix[0].length && matrix[k][j + width] === '1') { + width++; + } + + minWidth = Math.min(minWidth, width); + maxArea = Math.max(maxArea, minWidth * (k - i + 1)); + } + } + } + } + + return maxArea; +}; diff --git a/README.md b/README.md index 78c187bc..c8dda8d1 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| +85|[Maximal Rectangle](./0085-maximal-rectangle.js)|Hard| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 89|[Gray Code](./0089-gray-code.js)|Medium| From aea8839e574b095240fe30ea5a886d0cfb41e2eb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:04:54 -0600 Subject: [PATCH 427/485] Add solution #84 --- 0084-largest-rectangle-in-histogram.js | 32 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0084-largest-rectangle-in-histogram.js diff --git a/0084-largest-rectangle-in-histogram.js b/0084-largest-rectangle-in-histogram.js new file mode 100644 index 00000000..6b25ab6f --- /dev/null +++ b/0084-largest-rectangle-in-histogram.js @@ -0,0 +1,32 @@ +/** + * 84. Largest Rectangle in Histogram + * https://leetcode.com/problems/largest-rectangle-in-histogram/ + * Difficulty: Hard + * + * Given an array of integers heights representing the histogram's bar height where the + * width of each bar is 1, return the area of the largest rectangle in the histogram. + */ + +/** + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights) { + const entries = [...heights, 0]; + const stack = []; + let area = 0; + + for (let i = 0; i < entries.length; i++) { + let updatedHeight = i; + + while (stack.length && stack[stack.length - 1][1] > entries[i]) { + const [x, y] = stack.pop(); + area = Math.max(area, (i - x) * y); + updatedHeight = x; + } + + stack.push([updatedHeight, entries[i]]); + } + + return area; +}; diff --git a/README.md b/README.md index c8dda8d1..3f635eb3 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| +84|[Largest Rectangle in Histogram](./0084-largest-rectangle-in-histogram.js)|Hard| 85|[Maximal Rectangle](./0085-maximal-rectangle.js)|Hard| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| From 7c0681224c00bad575e478e677adc6691acc08a6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:06:29 -0600 Subject: [PATCH 428/485] Add solution #71 --- 0071-simplify-path.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0071-simplify-path.js diff --git a/0071-simplify-path.js b/0071-simplify-path.js new file mode 100644 index 00000000..a769b26c --- /dev/null +++ b/0071-simplify-path.js @@ -0,0 +1,40 @@ +/** + * 71. Simplify Path + * https://leetcode.com/problems/simplify-path/ + * Difficulty: Medium + * + * You are given an absolute path for a Unix-style file system, which always begins + * with a slash '/'. Your task is to transform this absolute path into its simplified + * canonical path. + * + * The rules of a Unix-style file system are as follows: + * - A single period '.' represents the current directory. + * - A double period '..' represents the previous/parent directory. + * - Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'. + * - Any sequence of periods that does not match the rules above should be treated as a + * valid directory or file name. For example, '...' and '....' are valid directory or + * file names. + * + * The simplified canonical path should follow these rules: + * - The path must start with a single slash '/'. + * - Directories within the path must be separated by exactly one slash '/'. + * - The path must not end with a slash '/', unless it is the root directory. + * - The path must not have any single or double periods ('.' and '..') used to denote + * current or parent directories. + * + * Return the simplified canonical path. + */ + +/** + * @param {string} path + * @return {string} + */ +var simplifyPath = function(path) { + const stack = []; + for (const segment of path.split('/')) { + if (segment === '.' || segment === '') continue; + if (segment === '..') stack.pop(); + else stack.push(segment); + } + return `/${stack.join('/')}`; +}; diff --git a/README.md b/README.md index 3f635eb3..9a380413 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| +71|[Simplify Path](./0071-simplify-path.js)|Medium| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 75|[Sort Colors](./0075-sort-colors.js)|Medium| From 2a0829895b5a077561b99827b078627fd7cba8c9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:07:25 -0600 Subject: [PATCH 429/485] Add solution #1047 --- ...emove-all-adjacent-duplicates-in-string.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1047-remove-all-adjacent-duplicates-in-string.js diff --git a/1047-remove-all-adjacent-duplicates-in-string.js b/1047-remove-all-adjacent-duplicates-in-string.js new file mode 100644 index 00000000..12dae9b8 --- /dev/null +++ b/1047-remove-all-adjacent-duplicates-in-string.js @@ -0,0 +1,27 @@ +/** + * 1047. Remove All Adjacent Duplicates In String + * https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ + * Difficulty: Easy + * + * You are given a string s consisting of lowercase English letters. A duplicate removal + * consists of choosing two adjacent and equal letters and removing them. + * + * We repeatedly make duplicate removals on s until we no longer can. + * + * Return the final string after all such duplicate removals have been made. It can be + * proven that the answer is unique. + */ + +/** + * @param {string} s + * @return {string} + */ +var removeDuplicates = function(s) { + const stack = []; + + for (const char of s) { + stack[stack.length - 1] === char ? stack.pop() : stack.push(char); + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index 9a380413..717080b4 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,7 @@ 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| +1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| 1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| From ddf3aee7429375cb5e456be692cd08b170e1213c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:08:42 -0600 Subject: [PATCH 430/485] Add solution #3042 --- 3042-count-prefix-and-suffix-pairs-i.js | 35 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 3042-count-prefix-and-suffix-pairs-i.js diff --git a/3042-count-prefix-and-suffix-pairs-i.js b/3042-count-prefix-and-suffix-pairs-i.js new file mode 100644 index 00000000..5c01d64a --- /dev/null +++ b/3042-count-prefix-and-suffix-pairs-i.js @@ -0,0 +1,35 @@ +/** + * 3042. Count Prefix and Suffix Pairs I + * https://leetcode.com/problems/count-prefix-and-suffix-pairs-i/ + * Difficulty: Easy + * + * You are given a 0-indexed string array words. + * + * Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2: + * - isPrefixAndSuffix(str1, str2) returns true if str1 is both a prefix and a suffix of + * str2, and false otherwise. + * + * For example, isPrefixAndSuffix("aba", "ababa") is true because "aba" is a prefix of + * "ababa" and also a suffix, but isPrefixAndSuffix("abc", "abcd") is false. + * + * Return an integer denoting the number of index pairs (i, j) such that i < j, and + * isPrefixAndSuffix(words[i], words[j]) is true. + */ + +/** + * @param {string[]} words + * @return {number} + */ +var countPrefixSuffixPairs = function(words) { + let count = 0; + + for (let i = 0; i < words.length; i++) { + for (let j = i + 1; j < words.length; j++) { + if (words[j].startsWith(words[i]) && words[j].endsWith(words[i])) { + count++; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index 717080b4..de121785 100644 --- a/README.md +++ b/README.md @@ -405,6 +405,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From abb4369d0f818352157798022e01285c70cf2926 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:10:42 -0600 Subject: [PATCH 431/485] Add solution #901 --- 0901-online-stock-span.js | 46 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0901-online-stock-span.js diff --git a/0901-online-stock-span.js b/0901-online-stock-span.js new file mode 100644 index 00000000..311295de --- /dev/null +++ b/0901-online-stock-span.js @@ -0,0 +1,46 @@ +/** + * 901. Online Stock Span + * https://leetcode.com/problems/online-stock-span/ + * Difficulty: Medium + * + * Design an algorithm that collects daily price quotes for some stock and returns the + * span of that stock's price for the current day. + * + * The span of the stock's price in one day is the maximum number of consecutive days + * (starting from that day and going backward) for which the stock price was less than + * or equal to the price of that day. + * + * - For example, if the prices of the stock in the last four days is [7,2,1,2] and the + * price of the stock today is 2, then the span of today is 4 because starting from + * today, the price of the stock was less than or equal 2 for 4 consecutive days. + * + * - Also, if the prices of the stock in the last four days is [7,34,1,2] and the price + * of the stock today is 8, then the span of today is 3 because starting from today, + * the price of the stock was less than or equal 8 for 3 consecutive days. + * + * Implement the StockSpanner class: + * - StockSpanner() Initializes the object of the class. + * - int next(int price) Returns the span of the stock's price given that today's + * price is price. + */ + +var StockSpanner = function() { + this.stack = []; +}; + +/** + * @param {number} price + * @return {number} + */ +StockSpanner.prototype.next = function(price) { + let count = 1; + + while (this.stack.length && price >= this.stack[this.stack.length - 1][0]) { + count += this.stack[this.stack.length - 1][1]; + this.stack.pop(); + } + + this.stack.push([price, count]); + + return count; +}; diff --git a/README.md b/README.md index de121785..e5f7a5f2 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,7 @@ 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| +901|[Online Stock Span](./0901-online-stock-span.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| 914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From 82e765b5b4471c7a0169b81a4c556751c35dd9cd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:11:35 -0600 Subject: [PATCH 432/485] Add solution #435 --- 0435-non-overlapping-intervals.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0435-non-overlapping-intervals.js diff --git a/0435-non-overlapping-intervals.js b/0435-non-overlapping-intervals.js new file mode 100644 index 00000000..0fdc5c0a --- /dev/null +++ b/0435-non-overlapping-intervals.js @@ -0,0 +1,31 @@ +/** + * 435. Non-overlapping Intervals + * https://leetcode.com/problems/non-overlapping-intervals/ + * Difficulty: Medium + * + * Given an array of intervals intervals where intervals[i] = [starti, endi], return the + * minimum number of intervals you need to remove to make the rest of the intervals + * non-overlapping. + * + * Note that intervals which only touch at a point are non-overlapping. For example, + * [1, 2] and [2, 3] are non-overlapping. + */ + +/** + * @param {number[][]} intervals + * @return {number} + */ +var eraseOverlapIntervals = function(intervals) { + let count = 0; + + intervals.sort((a, b) => a[1] - b[1]); + let prevEnd = intervals[0][1]; + + for (let i = 1; i < intervals.length; i++) { + const [start, end] = intervals[i]; + if (prevEnd > start) count++; + else prevEnd = end; + } + + return count; +}; diff --git a/README.md b/README.md index e5f7a5f2..9e41dcec 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| +435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| From a28e5dc0f89f7bfb0b17b8975b8af0541e4b4bcb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:15:53 -0600 Subject: [PATCH 433/485] Add solution #2721 --- ...cute-asynchronous-functions-in-parallel.js | 41 +++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 2721-execute-asynchronous-functions-in-parallel.js diff --git a/2721-execute-asynchronous-functions-in-parallel.js b/2721-execute-asynchronous-functions-in-parallel.js new file mode 100644 index 00000000..b4b9890f --- /dev/null +++ b/2721-execute-asynchronous-functions-in-parallel.js @@ -0,0 +1,41 @@ +/** + * 2721. Execute Asynchronous Functions in Parallel + * https://leetcode.com/problems/execute-asynchronous-functions-in-parallel/ + * Difficulty: Medium + * + * Given an array of asynchronous functions functions, return a new promise promise. + * Each function in the array accepts no arguments and returns a promise. All the + * promises should be executed in parallel. + * + * promise resolves: + * - When all the promises returned from functions were resolved successfully in + * parallel. The resolved value of promise should be an array of all the resolved + * values of promises in the same order as they were in the functions. The promise + * should resolve when all the asynchronous functions in the array have completed + * execution in parallel. + * + * promise rejects: + * When any of the promises returned from functions were rejected. promise should + * also reject with the reason of the first rejection. + * + * Please solve it without using the built-in Promise.all function. + */ + +/** + * @param {Array} functions + * @return {Promise} + */ +var promiseAll = function(functions) { + return new Promise((resolve, reject) => { + const promises = new Array(functions.length); + let count = 0; + functions.forEach((fn, i) => { + fn().then(result => { + promises[i] = result; + if (++count === promises.length) { + resolve(promises); + } + }).catch(reject); + }); + }); +}; diff --git a/README.md b/README.md index 9e41dcec..bb61bbfc 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 756d71536299c585fe21c8f6af879a6292894aa4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:16:55 -0600 Subject: [PATCH 434/485] Add solution #2724 --- 2724-sort-by.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2724-sort-by.js diff --git a/2724-sort-by.js b/2724-sort-by.js new file mode 100644 index 00000000..58dc39e3 --- /dev/null +++ b/2724-sort-by.js @@ -0,0 +1,21 @@ +/** + * 2724. Sort By + * https://leetcode.com/problems/sort-by/ + * Difficulty: Easy + * + * Given an array arr and a function fn, return a sorted array sortedArr. + * You can assume fn only returns numbers and those numbers determine the + * sort order of sortedArr. sortedArr must be sorted in ascending order + * by fn output. + * + * You may assume that fn will never duplicate numbers for a given array. + */ + +/** + * @param {Array} arr + * @param {Function} fn + * @return {Array} + */ +var sortBy = function(arr, fn) { + return arr.sort((a, b) => fn(a) - fn(b)); +}; diff --git a/README.md b/README.md index bb61bbfc..b48b69c6 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,7 @@ 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| +2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From faff54f706b4975327fbbd9dd642fb1f3a4e7c63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:18:07 -0600 Subject: [PATCH 435/485] Add solution #2722 --- 2722-join-two-arrays-by-id.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2722-join-two-arrays-by-id.js diff --git a/2722-join-two-arrays-by-id.js b/2722-join-two-arrays-by-id.js new file mode 100644 index 00000000..5e81dde1 --- /dev/null +++ b/2722-join-two-arrays-by-id.js @@ -0,0 +1,32 @@ +/** + * 2722. Join Two Arrays by ID + * https://leetcode.com/problems/join-two-arrays-by-id/ + * Difficulty: Medium + * + * Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each + * of the two inputs arrays will contain an id field that has an integer value. + * + * joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length + * of joinedArray should be the length of unique values of id. The returned array should be + * sorted in ascending order based on the id key. + * + * If a given id exists in one array but not the other, the single object with that id should + * be included in the result array without modification. + * + * If two objects share an id, their properties should be merged into a single object: + * - If a key only exists in one object, that single key-value pair should be included in + * the object. + * - If a key is included in both objects, the value in the object from arr2 should override + * the value from arr1. + */ + +/** + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ +var join = function(arr1, arr2) { + const map = new Map(); + [...arr1, ...arr2].forEach(obj => map.set(obj.id, { ...map.get(obj.id), ...obj })); + return Array.from(map.values()).sort((a, b) => a.id - b.id); +}; diff --git a/README.md b/README.md index b48b69c6..1343b221 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,7 @@ 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| +2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From 5b6b182563840e708bb6fd0182f206c62dbdcf28 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:20:50 -0600 Subject: [PATCH 436/485] Add solution #2715 --- 2715-timeout-cancellation.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2715-timeout-cancellation.js diff --git a/2715-timeout-cancellation.js b/2715-timeout-cancellation.js new file mode 100644 index 00000000..3f16a299 --- /dev/null +++ b/2715-timeout-cancellation.js @@ -0,0 +1,28 @@ +/** + * 2715. Timeout Cancellation + * https://leetcode.com/problems/timeout-cancellation/ + * Difficulty: Easy + * + * Given a function fn, an array of arguments args, and a timeout t in milliseconds, + * return a cancel function cancelFn. + * + * After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. + * > setTimeout(cancelFn, cancelTimeMs) + * + * Initially, the execution of the function fn should be delayed by t milliseconds. + * + * If, before the delay of t milliseconds, the function cancelFn is invoked, it should + * cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the + * specified delay t, fn should be executed with the provided args as arguments. + */ + +/** + * @param {Function} fn + * @param {Array} args + * @param {number} t + * @return {Function} + */ +var cancellable = function(fn, args, t) { + const timeoutId = setTimeout(() => fn(...args), t); + return () => clearTimeout(timeoutId); +}; diff --git a/README.md b/README.md index 1343b221..149d6c7b 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2724|[Sort By](./2724-sort-by.js)|Easy| From 685eb426bb00e465c332859bbee1d73e9290e5fb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:21:38 -0600 Subject: [PATCH 437/485] Add solution #2705 --- 2705-compact-object.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2705-compact-object.js diff --git a/2705-compact-object.js b/2705-compact-object.js new file mode 100644 index 00000000..2a997132 --- /dev/null +++ b/2705-compact-object.js @@ -0,0 +1,32 @@ +/** + * 2705. Compact Object + * https://leetcode.com/problems/compact-object/ + * Difficulty: Medium + * + * Given an object or array obj, return a compact object. + * + * A compact object is the same as the original object, except with keys containing falsy + * values removed. This operation applies to the object and any nested objects. Arrays are + * considered objects where the indices are keys. A value is considered falsy when + * Boolean(value) returns false. + * + * You may assume the obj is the output of JSON.parse. In other words, it is valid JSON. + */ + +/** + * @param {Object|Array} obj + * @return {Object|Array} + */ +var compactObject = function(obj) { + if (obj === null) return null; + if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject); + if (typeof obj !== 'object') return obj; + + return Object.keys(obj).reduce((result, key) => { + const value = compactObject(obj[key]); + if (value) { + result[key] = value; + } + return result; + }, {}); +}; diff --git a/README.md b/README.md index 149d6c7b..e44b1d32 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2705|[Compact Object](./2705-compact-object.js)|Medium| 2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| From 3b1de07c912a391498b4c850722d235948060e64 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:28:14 -0600 Subject: [PATCH 438/485] Add solution #2704 --- 2704-to-be-or-not-to-be.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2704-to-be-or-not-to-be.js diff --git a/2704-to-be-or-not-to-be.js b/2704-to-be-or-not-to-be.js new file mode 100644 index 00000000..8dd27441 --- /dev/null +++ b/2704-to-be-or-not-to-be.js @@ -0,0 +1,28 @@ +/** + * 2704. To Be Or Not To Be + * https://leetcode.com/problems/to-be-or-not-to-be/ + * Difficulty: Easy + * + * Write a function expect that helps developers test their code. It should take in any + * value val and return an object with the following two functions. + * + * - toBe(val) accepts another value and returns true if the two values === each other. + * If they are not equal, it should throw an error "Not Equal". + * - notToBe(val) accepts another value and returns true if the two values !== each + * other. If they are equal, it should throw an error "Equal". + */ + +/** + * @param {string} val + * @return {Object} + */ +var expect = function(val) { + const compareHelper = (error, fn) => { + if (fn()) throw new Error(error); + return true; + }; + return { + toBe: input => compareHelper('Not Equal', () => input !== val), + notToBe: input => compareHelper('Equal', () => input === val), + }; +}; diff --git a/README.md b/README.md index e44b1d32..4d2a0d24 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy| 2705|[Compact Object](./2705-compact-object.js)|Medium| 2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| From 50d123dc8fd5649f5bb85155e2d7daa545a51897 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:28:50 -0600 Subject: [PATCH 439/485] Add solution #2185 --- 2185-counting-words-with-a-given-prefix.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 2185-counting-words-with-a-given-prefix.js diff --git a/2185-counting-words-with-a-given-prefix.js b/2185-counting-words-with-a-given-prefix.js new file mode 100644 index 00000000..acd59f98 --- /dev/null +++ b/2185-counting-words-with-a-given-prefix.js @@ -0,0 +1,20 @@ +/** + * 2185. Counting Words With a Given Prefix + * https://leetcode.com/problems/counting-words-with-a-given-prefix/ + * Difficulty: Easy + * + * You are given an array of strings words and a string pref. + * + * Return the number of strings in words that contain pref as a prefix. + * + * A prefix of a string s is any leading contiguous substring of s. + */ + +/** + * @param {string[]} words + * @param {string} pref + * @return {number} + */ +var prefixCount = function(words, pref) { + return words.filter(word => word.startsWith(pref)).length; +}; diff --git a/README.md b/README.md index 4d2a0d24..af21b548 100644 --- a/README.md +++ b/README.md @@ -372,6 +372,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| From 0a9256a335d833db1de57c7a9c497d3edfc1a9f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:09:12 -0600 Subject: [PATCH 440/485] Add solution #274 --- 0274-h-index.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0274-h-index.js diff --git a/0274-h-index.js b/0274-h-index.js new file mode 100644 index 00000000..b506f1c0 --- /dev/null +++ b/0274-h-index.js @@ -0,0 +1,26 @@ +/** + * 274. H-Index + * https://leetcode.com/problems/h-index/ + * Difficulty: Medium + * + * Given an array of integers citations where citations[i] is the number of citations + * a researcher received for their ith paper, return the researcher's h-index. + * + * According to the definition of h-index on Wikipedia: The h-index is defined as the + * maximum value of h such that the given researcher has published at least h papers + * that have each been cited at least h times. + */ + +/** + * @param {number[]} citations + * @return {number} + */ +var hIndex = function(citations) { + citations.sort((a, b) => a - b); + for (let i = 0; i < citations.length; i++) { + if (citations[i] >= citations.length - i) { + return citations.length - i; + } + } + return 0; +}; diff --git a/README.md b/README.md index af21b548..5329886f 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| +274|[H-Index](./0274-h-index.js)|Medium| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| From 303dae1e83855d2869760bdc287aaceffe8e106d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:10:50 -0600 Subject: [PATCH 441/485] Add solution #916 --- 0916-word-subsets.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/0916-word-subsets.js b/0916-word-subsets.js index 0456e435..1f1e5d62 100644 --- a/0916-word-subsets.js +++ b/0916-word-subsets.js @@ -3,28 +3,29 @@ * https://leetcode.com/problems/word-subsets/ * Difficulty: Medium * - * We are given two arrays A and B of words. Each word is a string of lowercase letters. + * You are given two string arrays words1 and words2. * - * Now, say that word b is a subset of word a if every letter in b occurs in a, including - * multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world". + * A string b is a subset of string a if every letter in b occurs in a including multiplicity. * - * Now say a word a from A is universal if for every b in B, b is a subset of a. + * For example, "wrr" is a subset of "warrior" but is not a subset of "world". * - * Return a list of all universal words in A. You can return the words in any order. + * A string a from words1 is universal if for every string b in words2, b is a subset of a. + * + * Return an array of all the universal strings in words1. You may return the answer in any order. */ /** - * @param {string[]} A - * @param {string[]} B + * @param {string[]} words1 + * @param {string[]} words2 * @return {string[]} */ -var wordSubsets = function(A, B) { +var wordSubsets = function(words1, words2) { const count = (string, char) => string.split(char).length - 1; - const subset = Array.from(B.reduce((map, b) => { + const subset = Array.from(words2.reduce((map, b) => { b.split('').forEach(char => { map.set(char, (map.get(char) || 0) > count(b, char) ? map.get(char) : count(b, char)); }); return map; }, new Map())); - return A.filter(a => subset.every(match => count(a, match[0]) >= match[1])); + return words1.filter(a => subset.every(match => count(a, match[0]) >= match[1])); }; From 773d464a6d41ac383f1a54f1a64a582a39b84696 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:13:12 -0600 Subject: [PATCH 442/485] Add solution #912 --- 0912-sort-an-array.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0912-sort-an-array.js diff --git a/0912-sort-an-array.js b/0912-sort-an-array.js new file mode 100644 index 00000000..d11d5b32 --- /dev/null +++ b/0912-sort-an-array.js @@ -0,0 +1,34 @@ +/** + * 912. Sort an Array + * https://leetcode.com/problems/sort-an-array/ + * Difficulty: Medium + * + * Given an array of integers nums, sort the array in ascending order and return it. + * + * You must solve the problem without using any built-in functions in O(nlog(n)) time + * complexity and with the smallest space complexity possible. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArray = function(nums) { + if (nums.length <= 1) { + return nums; + } + + const min = Math.min(...nums); + const max = Math.max(...nums); + const count = new Array(max - min + 1).fill(0); + + nums.forEach(n => count[n - min]++); + + for (let i = 0, j = 0; i < count.length; i++) { + while (count[i]-- > 0) { + nums[j++] = i + min; + } + } + + return nums; +}; diff --git a/README.md b/README.md index 5329886f..59955b80 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 901|[Online Stock Span](./0901-online-stock-span.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| +912|[Sort an Array](./0912-sort-an-array.js)|Medium| 914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| From bc40ad58fd47ce65095eec515f0473f73e32e4f6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:13:55 -0600 Subject: [PATCH 443/485] Add solution #1122 --- 1122-relative-sort-array.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1122-relative-sort-array.js diff --git a/1122-relative-sort-array.js b/1122-relative-sort-array.js new file mode 100644 index 00000000..9a1ebafb --- /dev/null +++ b/1122-relative-sort-array.js @@ -0,0 +1,22 @@ +/** + * 1122. Relative Sort Array + * https://leetcode.com/problems/relative-sort-array/ + * Difficulty: Easy + * + * Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all + * elements in arr2 are also in arr1. + * + * Sort the elements of arr1 such that the relative ordering of items in arr1 + * are the same as in arr2. Elements that do not appear in arr2 should be + * placed at the end of arr1 in ascending order. + */ + +/** + * @param {number[]} arr1 + * @param {number[]} arr2 + * @return {number[]} + */ +var relativeSortArray = function(arr1, arr2) { + const map = new Map(arr2.map((v, i) => [v, i])); + return arr1.sort((a, b) => (map.get(a) ?? arr2.length + a) - (map.get(b) ?? arr2.length + b)); +}; diff --git a/README.md b/README.md index 59955b80..41adb6ad 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| +1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| From 244f2904a6a70be4a54ba99f16dd41ac5941a026 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:14:39 -0600 Subject: [PATCH 444/485] Add solution #1051 --- 1051-height-checker.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1051-height-checker.js diff --git a/1051-height-checker.js b/1051-height-checker.js new file mode 100644 index 00000000..38cd63fb --- /dev/null +++ b/1051-height-checker.js @@ -0,0 +1,25 @@ +/** + * 1051. Height Checker + * https://leetcode.com/problems/height-checker/ + * Difficulty: Easy + * + * A school is trying to take an annual photo of all the students. The students are asked + * to stand in a single file line in non-decreasing order by height. Let this ordering be + * represented by the integer array expected where expected[i] is the expected height of + * the ith student in line. + * + * You are given an integer array heights representing the current order that the students + * are standing in. Each heights[i] is the height of the ith student in line (0-indexed). + * + * Return the number of indices where heights[i] != expected[i]. + */ + +/** + * @param {number[]} heights + * @return {number} + */ +var heightChecker = function(heights) { + return [...heights] + .sort((a, b) => a - b) + .filter((expected, i) => heights[i] !== expected).length; +}; diff --git a/README.md b/README.md index 41adb6ad..e52e511b 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,7 @@ 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| +1051|[Height Checker](./1051-height-checker.js)|Easy| 1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| From f6bc2562ec247f128b7999415da588d4fc9983e9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:15:43 -0600 Subject: [PATCH 445/485] Add solution #2037 --- ...inimum-number-of-moves-to-seat-everyone.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 2037-minimum-number-of-moves-to-seat-everyone.js diff --git a/2037-minimum-number-of-moves-to-seat-everyone.js b/2037-minimum-number-of-moves-to-seat-everyone.js new file mode 100644 index 00000000..04c54286 --- /dev/null +++ b/2037-minimum-number-of-moves-to-seat-everyone.js @@ -0,0 +1,29 @@ +/** + * 2037. Minimum Number of Moves to Seat Everyone + * https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/ + * Difficulty: Easy + * + * There are n availabe seats and n students standing in a room. You are given an array + * seats of length n, where seats[i] is the position of the ith seat. You are also given + * the array students of length n, where students[j] is the position of the jth student. + * + * You may perform the following move any number of times: + * - Increase or decrease the position of the ith student by 1 (i.e., moving the ith + * student from position x to x + 1 or x - 1) + * + * Return the minimum number of moves required to move each student to a seat such that + * no two students are in the same seat. + * + * Note that there may be multiple seats or students in the same position at the beginning. + */ + +/** + * @param {number[]} seats + * @param {number[]} students + * @return {number} + */ +var minMovesToSeat = function(seats, students) { + seats.sort((a, b) => a - b); + students.sort((a, b) => a - b); + return seats.reduce((a, b, i) => a += Math.abs(seats[i] - students[i]), 0); +}; diff --git a/README.md b/README.md index e52e511b..1bfed356 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2027|[Minimum Moves to Convert String](./2027-minimum-moves-to-convert-string.js)|Easy| +2037|[Minimum Number of Moves to Seat Everyone](./2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| From f611bc5575e2f43bb57d7b6996e5b5568ab0dbad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:17:05 -0600 Subject: [PATCH 446/485] Add solution #1833 --- 1833-maximum-ice-cream-bars.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 1833-maximum-ice-cream-bars.js diff --git a/1833-maximum-ice-cream-bars.js b/1833-maximum-ice-cream-bars.js new file mode 100644 index 00000000..e8952086 --- /dev/null +++ b/1833-maximum-ice-cream-bars.js @@ -0,0 +1,33 @@ +/** + * 1833. Maximum Ice Cream Bars + * https://leetcode.com/problems/maximum-ice-cream-bars/ + * Difficulty: Medium + * + * It is a sweltering summer day, and a boy wants to buy some ice cream bars. + * + * At the store, there are n ice cream bars. You are given an array costs of + * length n, where costs[i] is the price of the ith ice cream bar in coins. + * The boy initially has coins coins to spend, and he wants to buy as many + * ice cream bars as possible. + * + * Note: The boy can buy the ice cream bars in any order. + * + * Return the maximum number of ice cream bars the boy can buy with coins. + */ + +/** + * @param {number[]} costs + * @param {number} coins + * @return {number} + */ +var maxIceCream = function(costs, coins) { + let count = 0; + costs.sort((a, b) => a - b); + for (let i = 0; i < costs.length; i++) { + if (costs[i] <= coins) { + count++; + coins -= costs[i]; + } + } + return count; +}; diff --git a/README.md b/README.md index 1bfed356..c01b7eda 100644 --- a/README.md +++ b/README.md @@ -358,6 +358,7 @@ 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| +1833|[Maximum Ice Cream Bars](./1833-maximum-ice-cream-bars.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| From b5b7f0f14137a7ea5dfa4dd78e571e97377bd164 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:15:36 -0600 Subject: [PATCH 447/485] Add solution #1400 --- 1400-construct-k-palindrome-strings.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1400-construct-k-palindrome-strings.js diff --git a/1400-construct-k-palindrome-strings.js b/1400-construct-k-palindrome-strings.js new file mode 100644 index 00000000..d53e6316 --- /dev/null +++ b/1400-construct-k-palindrome-strings.js @@ -0,0 +1,21 @@ +/** + * 1400. Construct K Palindrome Strings + * https://leetcode.com/problems/construct-k-palindrome-strings/ + * Difficulty: Medium + * + * Given a string s and an integer k, return true if you can use all the characters in s to + * construct k palindrome strings or false otherwise. + */ + +/** + * @param {string} s + * @param {number} k + * @return {boolean} + */ +var canConstruct = function(s, k) { + const occurrences = new Array(26).fill(0); + s.split('').forEach(c => occurrences[c.charCodeAt(0) - 'a'.charCodeAt(0)]++); + + const oddCount = occurrences.filter(n => n % 2 !== 0).length; + return k <= s.length && oddCount <= k; +}; diff --git a/README.md b/README.md index c01b7eda..fd9cdc12 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,7 @@ 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| +1400|[Construct K Palindrome Strings](./1400-construct-k-palindrome-strings.js)|Medium| 1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| From 4b13914b4903a8ce88873eded3b1eab980932a91 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:16:12 -0600 Subject: [PATCH 448/485] Add solution #1679 --- 1679-max-number-of-k-sum-pairs.js | 35 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1679-max-number-of-k-sum-pairs.js diff --git a/1679-max-number-of-k-sum-pairs.js b/1679-max-number-of-k-sum-pairs.js new file mode 100644 index 00000000..cdeb517d --- /dev/null +++ b/1679-max-number-of-k-sum-pairs.js @@ -0,0 +1,35 @@ +/** + * 1679. Max Number of K-Sum Pairs + * https://leetcode.com/problems/max-number-of-k-sum-pairs/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer k. + * + * In one operation, you can pick two numbers from the array whose sum equals k and + * remove them from the array. + * + * Return the maximum number of operations you can perform on the array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxOperations = function(nums, k) { + const map = new Map(); + let result = 0; + + nums.forEach(n => { + const diff = k - n; + + if (map.get(diff)) { + result++; + map.set(diff, map.get(diff) - 1); + } else { + map.set(n, (map.get(n) ?? 0) + 1); + } + }); + + return result; +}; diff --git a/README.md b/README.md index fd9cdc12..4e594b47 100644 --- a/README.md +++ b/README.md @@ -351,6 +351,7 @@ 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| +1679|[Max Number of K-Sum Pairs](./1679-max-number-of-k-sum-pairs.js)|Medium| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| From 12cafd05ada9a91ec2dcb9a23255d0e2fd592094 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:16:51 -0600 Subject: [PATCH 449/485] Add solution #643 --- 0643-maximum-average-subarray-i.js | 31 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0643-maximum-average-subarray-i.js diff --git a/0643-maximum-average-subarray-i.js b/0643-maximum-average-subarray-i.js new file mode 100644 index 00000000..413edd4f --- /dev/null +++ b/0643-maximum-average-subarray-i.js @@ -0,0 +1,31 @@ +/** + * 643. Maximum Average Subarray I + * https://leetcode.com/problems/maximum-average-subarray-i/ + * Difficulty: Easy + * + * You are given an integer array nums consisting of n elements, and an integer k. + * + * Find a contiguous subarray whose length is equal to k that has the maximum average + * value and return this value. Any answer with a calculation error less than 10-5 + * will be accepted. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findMaxAverage = function(nums, k) { + let sum = 0; + for (let i = 0; i < k; i++) { + sum += nums[i]; + } + + let max = sum; + for (let i = k; i < nums.length; i++) { + sum = sum - nums[i - k] + nums[i]; + max = Math.max(max, sum); + } + + return max / k; +}; diff --git a/README.md b/README.md index 4e594b47..8581a639 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| +643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| From cbcfa18259d5e9a8e641b5c2cc53549318665403 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:17:18 -0600 Subject: [PATCH 450/485] Add solution #485 --- 0485-max-consecutive-ones.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0485-max-consecutive-ones.js diff --git a/0485-max-consecutive-ones.js b/0485-max-consecutive-ones.js new file mode 100644 index 00000000..8bc16ffa --- /dev/null +++ b/0485-max-consecutive-ones.js @@ -0,0 +1,20 @@ +/** + * 485. Max Consecutive Ones + * https://leetcode.com/problems/max-consecutive-ones/ + * Difficulty: Easy + * + * Given a binary array nums, return the maximum number of consecutive 1's in the array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function(nums) { + let max = 0; + for (let i = 0, count = 0; i < nums.length; i++) { + count = nums[i] ? count + 1 : 0; + max = Math.max(max, count); + } + return max; +}; diff --git a/README.md b/README.md index 8581a639..5865b193 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| From ae64efe7e0bd41889994cca859ff2bd9633f0a42 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:17:56 -0600 Subject: [PATCH 451/485] Add solution #1004 --- 1004-max-consecutive-ones-iii.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1004-max-consecutive-ones-iii.js diff --git a/1004-max-consecutive-ones-iii.js b/1004-max-consecutive-ones-iii.js new file mode 100644 index 00000000..ec74165e --- /dev/null +++ b/1004-max-consecutive-ones-iii.js @@ -0,0 +1,29 @@ +/** + * 1004. Max Consecutive Ones III + * https://leetcode.com/problems/max-consecutive-ones-iii/ + * Difficulty: Medium + * + * Given a binary array nums and an integer k, return the maximum number of consecutive 1's + * in the array if you can flip at most k 0's. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var longestOnes = function(nums, k) { + let left = 0; + let right = 0; + + while (right < nums.length) { + if (!nums[right]) k--; + if (k < 0) { + if (!nums[left]) k++; + left++; + } + right++; + } + + return right - left; +}; diff --git a/README.md b/README.md index 5865b193..7321642a 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,7 @@ 994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium| 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1002|[Find Common Characters](./1002-find-common-characters.js)|Easy| +1004|[Max Consecutive Ones III](./1004-max-consecutive-ones-iii.js)|Medium| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| From da0356e87b6a64c66778ac881296a9763b43397d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:18:40 -0600 Subject: [PATCH 452/485] Add solution #724 --- 0724-find-pivot-index.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0724-find-pivot-index.js diff --git a/0724-find-pivot-index.js b/0724-find-pivot-index.js new file mode 100644 index 00000000..2d8c28a2 --- /dev/null +++ b/0724-find-pivot-index.js @@ -0,0 +1,34 @@ +/** + * 724. Find Pivot Index + * https://leetcode.com/problems/find-pivot-index/ + * Difficulty: Easy + * + * Given an array of integers nums, calculate the pivot index of this array. + * + * The pivot index is the index where the sum of all the numbers strictly to the left + * of the index is equal to the sum of all the numbers strictly to the index's right. + * + * If the index is on the left edge of the array, then the left sum is 0 because there + * are no elements to the left. This also applies to the right edge of the array. + * + * Return the leftmost pivot index. If no such index exists, return -1. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var pivotIndex = function(nums) { + let left = 0; + let right = nums.reduce((sum, n) => sum + n, 0); + + for (let i = 0; i < nums.length; i++) { + left += nums[i]; + right -= nums[i]; + if (left - nums[i] === right) { + return i; + } + } + + return -1; +}; diff --git a/README.md b/README.md index 7321642a..9ea33f78 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,7 @@ 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| +724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| From cdc40b089b8edf914468011c3c9ba0259141f6dc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:20:06 -0600 Subject: [PATCH 453/485] Add solution #1732 --- 1732-find-the-highest-altitude.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1732-find-the-highest-altitude.js diff --git a/1732-find-the-highest-altitude.js b/1732-find-the-highest-altitude.js new file mode 100644 index 00000000..4f461551 --- /dev/null +++ b/1732-find-the-highest-altitude.js @@ -0,0 +1,19 @@ +/** + * 1732. Find the Highest Altitude + * https://leetcode.com/problems/find-the-highest-altitude/ + * Difficulty: Easy + * + * There is a biker going on a road trip. The road trip consists of n + 1 points at different + * altitudes. The biker starts his trip on point 0 with altitude equal 0. + * + * You are given an integer array gain of length n where gain[i] is the net gain in altitude + * between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. + */ + +/** + * @param {number[]} gain + * @return {number} + */ +var largestAltitude = function(gain) { + return Math.max(...gain.reduce((all, n, i) => all.push(all[i] - n * -1) && all, [0])); +}; diff --git a/README.md b/README.md index 9ea33f78..0149f0f9 100644 --- a/README.md +++ b/README.md @@ -357,6 +357,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1679|[Max Number of K-Sum Pairs](./1679-max-number-of-k-sum-pairs.js)|Medium| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| +1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From ef164402f4e49a06c0de6bb12c16a7c7abcd2d99 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:10:59 -0600 Subject: [PATCH 454/485] Add solution #2116 --- ...ck-if-a-parentheses-string-can-be-valid.js | 54 +++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 2116-check-if-a-parentheses-string-can-be-valid.js diff --git a/2116-check-if-a-parentheses-string-can-be-valid.js b/2116-check-if-a-parentheses-string-can-be-valid.js new file mode 100644 index 00000000..1b54dd3a --- /dev/null +++ b/2116-check-if-a-parentheses-string-can-be-valid.js @@ -0,0 +1,54 @@ +/** + * 2116. Check if a Parentheses String Can Be Valid + * https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/ + * Difficulty: Medium + * + * A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid + * if any of the following conditions is true: + * - It is (). + * - It can be written as AB (A concatenated with B), where A and B are valid parentheses + * strings. + * - It can be written as (A), where A is a valid parentheses string. + * + * You are given a parentheses string s and a string locked, both of length n. locked is a + * binary string consisting only of '0's and '1's. For each index i of locked, + * - If locked[i] is '1', you cannot change s[i]. + * - But if locked[i] is '0', you can change s[i] to either '(' or ')'. + * + * Return true if you can make s a valid parentheses string. Otherwise, return false. + */ + +/** + * @param {string} s + * @param {string} locked + * @return {boolean} + */ +var canBeValid = function(s, locked) { + if (s.length % 2) return false; + + let symmetrical = 0; + for (let i = 0; i < s.length; i++) { + if (locked[i] === '0' || s[i] === '(') { + symmetrical++; + } else { + symmetrical--; + } + if (symmetrical < 0) { + return false; + } + } + + symmetrical = 0; + for (let i = s.length - 1; i >= 0; i--) { + if (locked[i] === '0' || s[i] === ')') { + symmetrical++; + } else { + symmetrical--; + } + if (symmetrical < 0) { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 0149f0f9..89957306 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| +2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| From 4e67038bcdeb7f8482f7fd4af1439d9a52a8e99c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:11:59 -0600 Subject: [PATCH 455/485] Add solution #2390 --- 2390-removing-stars-from-a-string.js | 33 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 2390-removing-stars-from-a-string.js diff --git a/2390-removing-stars-from-a-string.js b/2390-removing-stars-from-a-string.js new file mode 100644 index 00000000..1130802e --- /dev/null +++ b/2390-removing-stars-from-a-string.js @@ -0,0 +1,33 @@ +/** + * 2390. Removing Stars From a String + * https://leetcode.com/problems/removing-stars-from-a-string/ + * Difficulty: Medium + * + * You are given a string s, which contains stars *. + * + * In one operation, you can: + * - Choose a star in s. + * - Remove the closest non-star character to its left, as well as remove the star itself. + * + * Return the string after all stars have been removed. + * + * Note: + * - The input will be generated such that the operation is always possible. + * - It can be shown that the resulting string will always be unique. + */ + +/** + * @param {string} s + * @return {string} + */ +var removeStars = function(s) { + const result = []; + for (let i = 0; i < s.length; i++) { + if (s[i] !== '*') { + result.push(s[i]); + } else { + result.pop(); + } + } + return result.join(''); +}; diff --git a/README.md b/README.md index 89957306..e6bd4ee3 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| From 0fe8aaf5c1703762f40f4916c77bef100668e7e0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:12:33 -0600 Subject: [PATCH 456/485] Add solution #2352 --- 2352-equal-row-and-column-pairs.js | 34 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2352-equal-row-and-column-pairs.js diff --git a/2352-equal-row-and-column-pairs.js b/2352-equal-row-and-column-pairs.js new file mode 100644 index 00000000..5a890518 --- /dev/null +++ b/2352-equal-row-and-column-pairs.js @@ -0,0 +1,34 @@ +/** + * 2352. Equal Row and Column Pairs + * https://leetcode.com/problems/equal-row-and-column-pairs/ + * Difficulty: Medium + * + * Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) + * such that row ri and column cj are equal. + * + * A row and column pair is considered equal if they contain the same elements in the + * same order (i.e., an equal array). + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var equalPairs = function(grid) { + const columns = new Map(); + let count = 0; + + for (let i = 0; i < grid.length; i++) { + const column = []; + for (let j = 0; j < grid[i].length; j++) { + column.push(grid[j][i]); + } + columns.set(column.join(), (columns.get(column.join()) ?? 0) + 1); + } + + for (let i = 0; i < grid.length; i++) { + count += columns.get(grid[i].join()) ?? 0; + } + + return count; +}; diff --git a/README.md b/README.md index e6bd4ee3..c03293a3 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| From a594bbebae6b3cc39a643b93227ae474ce2788a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:14:20 -0600 Subject: [PATCH 457/485] Add solution #649 --- 0649-dota2-senate.js | 53 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 0649-dota2-senate.js diff --git a/0649-dota2-senate.js b/0649-dota2-senate.js new file mode 100644 index 00000000..d47cf36c --- /dev/null +++ b/0649-dota2-senate.js @@ -0,0 +1,53 @@ +/** + * 649. Dota2 Senate + * https://leetcode.com/problems/dota2-senate/ + * Difficulty: Medium + * + * In the world of Dota2, there are two parties: the Radiant and the Dire. + * + * The Dota2 senate consists of senators coming from two parties. Now the Senate wants + * to decide on a change in the Dota2 game. The voting for this change is a round-based + * procedure. In each round, each senator can exercise one of the two rights: + * - Ban one senator's right: A senator can make another senator lose all his rights in + * this and all the following rounds. + * - Announce the victory: If this senator found the senators who still have rights to + * vote are all from the same party, he can announce the victory and decide on the + * change in the game. + * + * Given a string senate representing each senator's party belonging. The character 'R' + * and 'D' represent the Radiant party and the Dire party. Then if there are n senators, + * the size of the given string will be n. + * + * The round-based procedure starts from the first senator to the last senator in the + * given order. This procedure will last until the end of voting. All the senators who + * have lost their rights will be skipped during the procedure. + * + * Suppose every senator is smart enough and will play the best strategy for his own + * party. Predict which party will finally announce the victory and change the Dota2 + * game. The output should be "Radiant" or "Dire". +*/ + +/** + * @param {string} senate + * @return {string} + */ +var predictPartyVictory = function(senate) { + const rQueue = []; + const dQueue = []; + + for (let i = 0; i < senate.length; i++) { + if (senate[i] === 'R') rQueue.push(i); + else dQueue.push(i); + } + + while (rQueue.length && dQueue.length) { + const [rIndex, dIndex] = [rQueue.shift(), dQueue.shift()]; + if (rIndex < dIndex) { + rQueue.push(rIndex + senate.length); + } else { + dQueue.push(dIndex + senate.length); + } + } + + return rQueue.length > 0 ? 'Radiant' : 'Dire'; +}; diff --git a/README.md b/README.md index c03293a3..4b765927 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,7 @@ 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| +649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 1c752e63f44d70936f8a3ff71925921abfe5d6a0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:15:30 -0600 Subject: [PATCH 458/485] Add solution #933 --- 0933-number-of-recent-calls.js | 35 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0933-number-of-recent-calls.js diff --git a/0933-number-of-recent-calls.js b/0933-number-of-recent-calls.js new file mode 100644 index 00000000..8af36eb7 --- /dev/null +++ b/0933-number-of-recent-calls.js @@ -0,0 +1,35 @@ +/** + * 933. Number of Recent Calls + * https://leetcode.com/problems/number-of-recent-calls/ + * Difficulty: Easy + * + * You have a RecentCounter class which counts the number of recent requests within + * a certain time frame. + * + * Implement the RecentCounter class: + * - RecentCounter() Initializes the counter with zero recent requests. + * - int ping(int t) Adds a new request at time t, where t represents some time in + * milliseconds, and returns the number of requests that has happened in the past + * 3000 milliseconds (including the new request). Specifically, return the number + * of requests that have happened in the inclusive range [t - 3000, t]. + * + * It is guaranteed that every call to ping uses a strictly larger value of t than + * the previous call. + */ + + +var RecentCounter = function() { + this.queue = []; +}; + +/** + * @param {number} t + * @return {number} + */ +RecentCounter.prototype.ping = function(t) { + this.queue.push(t); + while (this.queue[0] < t - 3000) { + this.queue.shift(); + } + return this.queue.length; +}; diff --git a/README.md b/README.md index 4b765927..b1790e0c 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,7 @@ 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| +933|[Number of Recent Calls](./0933-number-of-recent-calls.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| 976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| From c4a7750c3b989ebcd12a06d3cf5997b529a23375 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:17:03 -0600 Subject: [PATCH 459/485] Add solution #394 --- 0394-decode-string.js | 45 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0394-decode-string.js diff --git a/0394-decode-string.js b/0394-decode-string.js new file mode 100644 index 00000000..0dda623f --- /dev/null +++ b/0394-decode-string.js @@ -0,0 +1,45 @@ +/** + * 394. Decode String + * https://leetcode.com/problems/decode-string/ + * Difficulty: Medium + * + * Given an encoded string, return its decoded string. + * + * The encoding rule is: k[encoded_string], where the encoded_string inside the square + * brackets is being repeated exactly k times. Note that k is guaranteed to be a + * positive integer. + * + * You may assume that the input string is always valid; there are no extra white spaces, + * square brackets are well-formed, etc. Furthermore, you may assume that the original + * data does not contain any digits and that digits are only for those repeat numbers, k. + * For example, there will not be input like 3a or 2[4]. + * + * The test cases are generated so that the length of the output will never exceed 105. + */ + +/** + * @param {string} s + * @return {string} + */ +var decodeString = function(s) { + const stack = []; + let result = ''; + let decoder = 0; + + for (const c of s) { + if (!isNaN(c) && Number(c) >= 0 && Number(c) <= 9) { + decoder = Number(c) + decoder * 10; + } else if (c === '[') { + stack.push([result, decoder]); + result = ''; + decoder = 0; + } else if (c === ']') { + const [previous, count] = stack.pop(); + result = previous + result.repeat(count); + } else { + result += c; + } + } + + return result; +}; diff --git a/README.md b/README.md index b1790e0c..d272ba9f 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| +394|[Decode String](./0394-decode-string.js)|Medium| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From b0f103ba7cafec028bb1f9a88a39bb0fd41de2ff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:17:47 -0600 Subject: [PATCH 460/485] Add solution #735 --- 0735-asteroid-collision.js | 40 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0735-asteroid-collision.js diff --git a/0735-asteroid-collision.js b/0735-asteroid-collision.js new file mode 100644 index 00000000..f1712014 --- /dev/null +++ b/0735-asteroid-collision.js @@ -0,0 +1,40 @@ +/** + * 735. Asteroid Collision + * https://leetcode.com/problems/asteroid-collision/ + * Difficulty: Medium + * + * We are given an array asteroids of integers representing asteroids in a row. The indices + * of the asteriod in the array represent their relative position in space. + * + * For each asteroid, the absolute value represents its size, and the sign represents its + * direction (positive meaning right, negative meaning left). Each asteroid moves at the + * same speed. + * + * Find out the state of the asteroids after all collisions. If two asteroids meet, the + * smaller one will explode. If both are the same size, both will explode. Two asteroids + * moving in the same direction will never meet. + */ + +/** + * @param {number[]} asteroids + * @return {number[]} + */ +var asteroidCollision = function(asteroids) { + const result = []; + + for (let i = 0; i < asteroids.length; i++) { + const previous = result[result.length - 1]; + const current = asteroids[i]; + + if (!result.length || previous < 0 || current > 0) { + result.push(current); + } else if (-current === previous) { + result.pop(); + } else if (-current > previous) { + result.pop(); + i--; + } + } + + return result; +}; diff --git a/README.md b/README.md index d272ba9f..98580f3f 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| +735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| From da63bad8909221e6b1e98a187cbca27b30186a8e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:30:11 -0600 Subject: [PATCH 461/485] Add solution #415 --- 0415-add-strings.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0415-add-strings.js diff --git a/0415-add-strings.js b/0415-add-strings.js new file mode 100644 index 00000000..219fe302 --- /dev/null +++ b/0415-add-strings.js @@ -0,0 +1,33 @@ +/** + * 415. Add Strings + * https://leetcode.com/problems/add-strings/ + * Difficulty: Easy + * + * Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and + * num2 as a string. + * + * You must solve the problem without using any built-in library for handling large integers (such + * as BigInteger). You must also not convert the inputs to integers directly. + */ + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var addStrings = function(num1, num2) { + let result = ''; + + for (let i = num1.length - 1, j = num2.length - 1, carry = 0; i > -1 || j > -1 || carry === 1;) { + if (i > -1) { + carry += num1.charCodeAt(i--) - 48; + } + if (j > -1) { + carry += num2.charCodeAt(j--) - 48; + } + result = (carry % 10) + result; + carry = Math.floor(carry / 10); + } + + return result; +}; diff --git a/README.md b/README.md index 98580f3f..66e3319d 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,7 @@ 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| +415|[Add Strings](./0415-add-strings.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From 6f7e40ba82f98736b9503912c429960b8e1a4b79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:31:35 -0600 Subject: [PATCH 462/485] Add solution #1466 --- ...to-make-all-paths-lead-to-the-city-zero.js | 49 +++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js diff --git a/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js new file mode 100644 index 00000000..a94de6fd --- /dev/null +++ b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js @@ -0,0 +1,49 @@ +/** + * 1466. Reorder Routes to Make All Paths Lead to the City Zero + * https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/ + * Difficulty: Medium + * + * There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way + * to travel between two different cities (this network form a tree). Last year, The ministry + * of transport decided to orient the roads in one direction because they are too narrow. + * + * Roads are represented by connections where connections[i] = [ai, bi] represents a road from + * city ai to city bi. + * + * This year, there will be a big event in the capital (city 0), and many people want to travel + * to this city. + * + * Your task consists of reorienting some roads such that each city can visit the city 0. Return + * the minimum number of edges changed. + +It's guaranteed that each city can reach city 0 after reorder. + */ + +/** + * @param {number} n + * @param {number[][]} connections + * @return {number} + */ +var minReorder = function(n, connections) { + const graph = new Array(n).fill(null).map(() => []); + + connections.forEach(([k, v]) => { + graph[k].push([v, 1]); + graph[v].push([k, 0]); + }); + + function dfs(node, parent) { + let count = 0; + + graph[node].forEach(([k, v]) => { + if (k !== parent) { + count += v; + count += dfs(k, node); + } + }); + + return count; + } + + return dfs(0, -1); +}; diff --git a/README.md b/README.md index 66e3319d..edf0ab5e 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,7 @@ 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| +1466|[Reorder Routes to Make All Paths Lead to the City Zero](./1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js)|Medium| 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| From 638d08f491a567d4020f877ac933ee30e46f6751 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:32:44 -0600 Subject: [PATCH 463/485] Add solution #547 --- 0547-number-of-provinces.js | 44 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0547-number-of-provinces.js diff --git a/0547-number-of-provinces.js b/0547-number-of-provinces.js new file mode 100644 index 00000000..d0e3bff6 --- /dev/null +++ b/0547-number-of-provinces.js @@ -0,0 +1,44 @@ +/** + * 547. Number of Provinces + * https://leetcode.com/problems/number-of-provinces/ + * Difficulty: Medium + * + * There are n cities. Some of them are connected, while some are not. If city a is connected + * directly with city b, and city b is connected directly with city c, then city a is connected + * indirectly with city c. + * + * A province is a group of directly or indirectly connected cities and no other cities outside + * of the group. + * + * You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the + * jth city are directly connected, and isConnected[i][j] = 0 otherwise. + +Return the total number of provinces. + */ + +/** + * @param {number[][]} isConnected + * @return {number} + */ +var findCircleNum = function(isConnected) { + const seen = new Array(isConnected.length).fill(0); + let result = 0; + + function dfs(node) { + seen[node] = 1; + for (let i = 0; i < isConnected.length; i++) { + if (isConnected[node][i] === 1 && !seen[i]) { + dfs(i); + } + } + } + + for (let i = 0; i < isConnected.length; i++) { + if (!seen[i]) { + result++; + dfs(i); + } + } + + return result; +}; diff --git a/README.md b/README.md index edf0ab5e..caa38382 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ 520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| +547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| From 3dad2b52b7eeba4590b7287f5ababf2614a15b8c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:33:34 -0600 Subject: [PATCH 464/485] Add solution #841 --- 0841-keys-and-rooms.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0841-keys-and-rooms.js diff --git a/0841-keys-and-rooms.js b/0841-keys-and-rooms.js new file mode 100644 index 00000000..dc07a591 --- /dev/null +++ b/0841-keys-and-rooms.js @@ -0,0 +1,28 @@ +/** + * 841. Keys and Rooms + * https://leetcode.com/problems/keys-and-rooms/ + * Difficulty: Medium + * + * There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. + * Your goal is to visit all the rooms. However, you cannot enter a locked room without + * having its key. + * + * When you visit a room, you may find a set of distinct keys in it. Each key has a number + * on it, denoting which room it unlocks, and you can take all of them with you to unlock + * the other rooms. + * + * Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited + * room i, return true if you can visit all the rooms, or false otherwise. + */ + +/** + * @param {number[][]} rooms + * @return {boolean} + */ +var canVisitAllRooms = function(rooms) { + const set = new Set([0]); + for (const key of set) { + rooms[key].forEach(value => set.add(value)); + } + return set.size === rooms.length; +}; diff --git a/README.md b/README.md index caa38382..b8ae353c 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| +841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| From f0f2d90566500982f0fbc9aacb5e8711a87ab216 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:34:27 -0600 Subject: [PATCH 465/485] Add solution #2130 --- 2130-maximum-twin-sum-of-a-linked-list.js | 41 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 2130-maximum-twin-sum-of-a-linked-list.js diff --git a/2130-maximum-twin-sum-of-a-linked-list.js b/2130-maximum-twin-sum-of-a-linked-list.js new file mode 100644 index 00000000..038554da --- /dev/null +++ b/2130-maximum-twin-sum-of-a-linked-list.js @@ -0,0 +1,41 @@ +/** + * 2130. Maximum Twin Sum of a Linked List + * https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ + * Difficulty: Medium + * + * In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known + * as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. + * + * For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These + * are the only nodes with twins for n = 4. + * + * The twin sum is defined as the sum of a node and its twin. + * + * Given the head of a linked list with even length, return the maximum twin sum of the linked list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {number} + */ +var pairSum = function(head) { + const stack = []; + while (head) { + stack.push(head.val); + head = head.next; + } + + let max = 0; + for (let i = 0; i < stack.length; i++) { + max = Math.max(max, stack[i] + stack[stack.length - 1 - i]); + } + + return max; +}; diff --git a/README.md b/README.md index b8ae353c..f97213b8 100644 --- a/README.md +++ b/README.md @@ -393,6 +393,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2130|[Maximum Twin Sum of a Linked List](./2130-maximum-twin-sum-of-a-linked-list.js)|Medium| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| From ad1b9b94024d91de0967ee7326300063c89e01a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:35:18 -0600 Subject: [PATCH 466/485] Add solution #328 --- 0328-odd-even-linked-list.js | 43 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0328-odd-even-linked-list.js diff --git a/0328-odd-even-linked-list.js b/0328-odd-even-linked-list.js new file mode 100644 index 00000000..ca962d4e --- /dev/null +++ b/0328-odd-even-linked-list.js @@ -0,0 +1,43 @@ +/** + * 328. Odd Even Linked List + * https://leetcode.com/problems/odd-even-linked-list/ + * Difficulty: Medium + * + * Given the head of a singly linked list, group all the nodes with odd indices together followed + * by the nodes with even indices, and return the reordered list. + * + * The first node is considered odd, and the second node is even, and so on. + * + * Note that the relative order inside both the even and odd groups should remain as it was in + * the input. + * + * You must solve the problem in O(1) extra space complexity and O(n) time complexity. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var oddEvenList = function(head) { + if (!head) return head; + + const even = head.next; + let odd = head; + + while (odd.next && odd.next.next) { + const pointer = odd.next; + odd.next = odd.next.next; + odd = odd.next; + pointer.next = odd.next; + } + + odd.next = even; + return head; +}; diff --git a/README.md b/README.md index f97213b8..62f94c6b 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ 290|[Word Pattern](./0290-word-pattern.js)|Easy| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| +328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| From b5b3a7dfbe2d7ae24a791b31af0ca320c30485f5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:36:15 -0600 Subject: [PATCH 467/485] Add solution #3223 --- ...nimum-length-of-string-after-operations.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 3223-minimum-length-of-string-after-operations.js diff --git a/3223-minimum-length-of-string-after-operations.js b/3223-minimum-length-of-string-after-operations.js new file mode 100644 index 00000000..9eb7f0e1 --- /dev/null +++ b/3223-minimum-length-of-string-after-operations.js @@ -0,0 +1,29 @@ +/** + * 3223. Minimum Length of String After Operations + * https://leetcode.com/problems/minimum-length-of-string-after-operations/ + * Difficulty: Medium + * + * You are given a string s. + * + * You can perform the following process on s any number of times: + * - Choose an index i in the string such that there is at least one character to the left of + * index i that is equal to s[i], and at least one character to the right that is also equal + * to s[i]. + * - Delete the closest character to the left of index i that is equal to s[i]. + * - Delete the closest character to the right of index i that is equal to s[i]. + * + * Return the minimum length of the final string s that you can achieve. + */ + +/** + * @param {string} s + * @return {number} + */ +var minimumLength = function(s) { + if (s.length < 3) return s.length; + + const map = new Map(); + s.split('').forEach(c => map.set(c, (map.get(c) ?? 0) + 1)); + + return [...map.values()].reduce((count, n) => count + (n % 2 ? n % 2 : 2), 0); +}; diff --git a/README.md b/README.md index 62f94c6b..48cb50ef 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,7 @@ 2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| +3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From f99746256aa81814f7b9b81023799a8254044f23 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:23:02 -0600 Subject: [PATCH 468/485] Add solution #872 --- 0872-leaf-similar-trees.js | 45 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0872-leaf-similar-trees.js diff --git a/0872-leaf-similar-trees.js b/0872-leaf-similar-trees.js new file mode 100644 index 00000000..6fa8fcf0 --- /dev/null +++ b/0872-leaf-similar-trees.js @@ -0,0 +1,45 @@ +/** + * 872. Leaf-Similar Trees + * https://leetcode.com/problems/leaf-similar-trees/ + * Difficulty: Easy + * + * Consider all the leaves of a binary tree, from left to right order, the values of + * those leaves form a leaf value sequence. + * + * For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). + * + * Two binary trees are considered leaf-similar if their leaf value sequence is the same. + * + * Return true if and only if the two given trees with head nodes root1 and root2 are + * leaf-similar. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root1 + * @param {TreeNode} root2 + * @return {boolean} + */ +var leafSimilar = function(root1, root2) { + return traverse(root1, []).toString() === traverse(root2, []).toString(); +}; + +function traverse(root, result) { + if (!root.left && !root.right) { + result.push(root.val); + } + if (root.left) { + traverse(root.left, result); + } + if (root.right) { + traverse(root.right, result); + } + return result; +} diff --git a/README.md b/README.md index 48cb50ef..e88028e2 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy| 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| From 15239ff4b2f1792187067f8394f3dd43da897670 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:23:39 -0600 Subject: [PATCH 469/485] Add solution #2723 --- 2723-add-two-promises.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 2723-add-two-promises.js diff --git a/2723-add-two-promises.js b/2723-add-two-promises.js new file mode 100644 index 00000000..13fe5612 --- /dev/null +++ b/2723-add-two-promises.js @@ -0,0 +1,18 @@ +/** + * 2723. Add Two Promises + * https://leetcode.com/problems/add-two-promises/ + * Difficulty: Easy + * + * Given two promises promise1 and promise2, return a new promise. promise1 and promise2 + * will both resolve with a number. The returned promise should resolve with the sum of + * the two numbers. + */ + +/** + * @param {Promise} promise1 + * @param {Promise} promise2 + * @return {Promise} + */ +var addTwoPromises = async function(promise1, promise2) { + return Promise.all([promise1, promise2]).then(([a, b]) => a + b); +}; diff --git a/README.md b/README.md index e88028e2..9cfee7bd 100644 --- a/README.md +++ b/README.md @@ -440,6 +440,7 @@ 2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| +2723|[Add Two Promises](./2723-add-two-promises.js)|Easy| 2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From 4e0a1bd2594f8923abaa1dd46f817ed50ec01f84 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:25:04 -0600 Subject: [PATCH 470/485] Add solution #2693 --- 2693-call-function-with-custom-context.js | 35 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 2693-call-function-with-custom-context.js diff --git a/2693-call-function-with-custom-context.js b/2693-call-function-with-custom-context.js new file mode 100644 index 00000000..34e60f9b --- /dev/null +++ b/2693-call-function-with-custom-context.js @@ -0,0 +1,35 @@ +/** + * 2693. Call Function with Custom Context + * https://leetcode.com/problems/call-function-with-custom-context/ + * Difficulty: Medium + * + * Enhance all functions to have the callPolyfill method. The method accepts an object obj as + * its first parameter and any number of additional arguments. The obj becomes the this context + * for the function. The additional arguments are passed to the function (that the callPolyfill + * method belongs on). + * + * For example if you had the function: + * + * function tax(price, taxRate) { + * const totalCost = price * (1 + taxRate); + * console.log(`The cost of ${this.item} is ${totalCost}`); + * } + * + * Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is + * because the this context was not defined. + * + * However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The + * cost of salad is 11". The this context was appropriately set, and the function logged an + * appropriate output. + * + * Please solve this without using the built-in Function.call method. + */ + +/** + * @param {Object} context + * @param {Array} args + * @return {null|boolean|number|string|Array|Object} + */ +Function.prototype.callPolyfill = function(context, ...args) { + return this.bind(context)(...args); +} diff --git a/README.md b/README.md index 9cfee7bd..12ca3efb 100644 --- a/README.md +++ b/README.md @@ -433,6 +433,7 @@ 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2677|[Chunk Array](./2677-chunk-array.js)|Easy| +2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy| From a6de9398e5c31a130b6f2fe3d1fd3a2f5ec5713d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:26:28 -0600 Subject: [PATCH 471/485] Add solution #1005 --- ...maximize-sum-of-array-after-k-negations.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1005-maximize-sum-of-array-after-k-negations.js diff --git a/1005-maximize-sum-of-array-after-k-negations.js b/1005-maximize-sum-of-array-after-k-negations.js new file mode 100644 index 00000000..c8a65c88 --- /dev/null +++ b/1005-maximize-sum-of-array-after-k-negations.js @@ -0,0 +1,27 @@ +/** + * 1005. Maximize Sum Of Array After K Negations + * https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/ + * Difficulty: Easy + * + * Given an integer array nums and an integer k, modify the array in the following way: + * - choose an index i and replace nums[i] with -nums[i]. + * + * You should apply this process exactly k times. You may choose the same index i + * multiple times. + * + * Return the largest possible sum of the array after modifying it in this way. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var largestSumAfterKNegations = function(nums, k) { + while (k) { + const i = nums.indexOf(Math.min(...nums)); + nums[i] *= -1; + k--; + } + return nums.reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 12ca3efb..18600c84 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,7 @@ 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1002|[Find Common Characters](./1002-find-common-characters.js)|Easy| 1004|[Max Consecutive Ones III](./1004-max-consecutive-ones-iii.js)|Medium| +1005|[Maximize Sum Of Array After K Negations](./1005-maximize-sum-of-array-after-k-negations.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| From cf53d29ef1f1c77313ec9415df73df13aeb24033 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:27:01 -0600 Subject: [PATCH 472/485] Add solution #338 --- 0338-counting-bits.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0338-counting-bits.js diff --git a/0338-counting-bits.js b/0338-counting-bits.js new file mode 100644 index 00000000..728daff1 --- /dev/null +++ b/0338-counting-bits.js @@ -0,0 +1,20 @@ +/** + * 338. Counting Bits + * https://leetcode.com/problems/counting-bits/ + * Difficulty: Easy + * + * Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), + * ans[i] is the number of 1's in the binary representation of i. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var countBits = function(n) { + const result = new Array(n + 1).fill(0); + for (let i = 0; i <= n; i++) { + result[i] = result[i >> 1] + (i & 1); + } + return result; +}; diff --git a/README.md b/README.md index 18600c84..1278d521 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| +338|[Counting Bits](./0338-counting-bits.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| From 9b136bda364607e8e6707788bdf0a5a2475d7306 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:28:37 -0600 Subject: [PATCH 473/485] Add solution #2657 --- ...d-the-prefix-common-array-of-two-arrays.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2657-find-the-prefix-common-array-of-two-arrays.js diff --git a/2657-find-the-prefix-common-array-of-two-arrays.js b/2657-find-the-prefix-common-array-of-two-arrays.js new file mode 100644 index 00000000..e284d390 --- /dev/null +++ b/2657-find-the-prefix-common-array-of-two-arrays.js @@ -0,0 +1,34 @@ +/** + * 2657. Find the Prefix Common Array of Two Arrays + * https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/ + * Difficulty: Medium + * + * You are given two 0-indexed integer permutations A and B of length n. + * + * A prefix common array of A and B is an array C such that C[i] is equal to the count of + * numbers that are present at or before the index i in both A and B. + * + * Return the prefix common array of A and B. + * + * A sequence of n integers is called a permutation if it contains all integers from 1 to + * n exactly once. + */ + +/** + * @param {number[]} A + * @param {number[]} B + * @return {number[]} + */ +var findThePrefixCommonArray = function(A, B) { + const result = []; + + for (let i = 0, count = 0, set = new Set(); i < A.length; i++) { + if (set.has(A[i])) count++; + if (set.has(B[i])) count++; + if (A[i] === B[i]) count++; + [A[i], B[i]].forEach(n => set.add(n)); + result.push(count); + } + + return result; +}; diff --git a/README.md b/README.md index 1278d521..562454c0 100644 --- a/README.md +++ b/README.md @@ -431,6 +431,7 @@ 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| +2657|[Find the Prefix Common Array of Two Arrays](./2657-find-the-prefix-common-array-of-two-arrays.js)|Medium| 2665|[Counter II](./2665-counter-ii.js)|Easy| 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| From 3bef726bef95d187cc1e28ff95b32f00a9e76c74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:40:41 -0600 Subject: [PATCH 474/485] Add solution #621 --- 0621-task-scheduler.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0621-task-scheduler.js diff --git a/0621-task-scheduler.js b/0621-task-scheduler.js new file mode 100644 index 00000000..d28cbd2b --- /dev/null +++ b/0621-task-scheduler.js @@ -0,0 +1,37 @@ +/** + * 621. Task Scheduler + * https://leetcode.com/problems/task-scheduler/ + * Difficulty: Medium + * + * You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. + * Each CPU interval can be idle or allow the completion of one task. Tasks can be completed + * in any order, but there's a constraint: there has to be a gap of at least n intervals + * between two tasks with the same label. + * + * Return the minimum number of CPU intervals required to complete all tasks. + */ + +/** + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function(tasks, n) { + const map = new Map(); + let maxValue = 0; + let maxCount = 0; + + tasks.forEach(key => { + const value = map.has(key) ? map.get(key) + 1 : 1; + map.set(key, value); + + if (value > maxValue) { + maxValue = value; + maxCount = 1; + } else if (value === maxValue) { + maxCount++; + } + }); + + return Math.max(tasks.length, (maxValue - 1) * (n + 1) + maxCount); +}; diff --git a/README.md b/README.md index 562454c0..305e245a 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,7 @@ 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| From 8c6712855e7b03fb69f6fb85b39c6ba06c3c8acf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:47:53 -0600 Subject: [PATCH 475/485] Add solution #496 --- 0496-next-greater-element-i.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0496-next-greater-element-i.js diff --git a/0496-next-greater-element-i.js b/0496-next-greater-element-i.js new file mode 100644 index 00000000..aad8d9e8 --- /dev/null +++ b/0496-next-greater-element-i.js @@ -0,0 +1,33 @@ +/** + * 496. Next Greater Element I + * https://leetcode.com/problems/next-greater-element-i/ + * Difficulty: Easy + * + * The next greater element of some element x in an array is the first greater element + * that is to the right of x in the same array. + * + * You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is + * a subset of nums2. + * + * For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and + * determine the next greater element of nums2[j] in nums2. If there is no next greater + * element, then the answer for this query is -1. + * + * Return an array ans of length nums1.length such that ans[i] is the next greater + * element as described above. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function(nums1, nums2) { + return nums1.map(n => { + let index = nums2.indexOf(n); + while (nums2[index] <= n) { + index++; + } + return index >= nums2.length ? -1 : nums2[index]; + }); +}; diff --git a/README.md b/README.md index 305e245a..67285140 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| +496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| From 405f6ac0384260d9eeaef7b097ee342f37483e99 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:48:32 -0600 Subject: [PATCH 476/485] Add solution #395 --- ...ng-with-at-least-k-repeating-characters.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0395-longest-substring-with-at-least-k-repeating-characters.js diff --git a/0395-longest-substring-with-at-least-k-repeating-characters.js b/0395-longest-substring-with-at-least-k-repeating-characters.js new file mode 100644 index 00000000..1df885e3 --- /dev/null +++ b/0395-longest-substring-with-at-least-k-repeating-characters.js @@ -0,0 +1,24 @@ +/** + * 395. Longest Substring with At Least K Repeating Characters + * https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ + * Difficulty: Medium + * + * Given a string s and an integer k, return the length of the longest substring of s such + * that the frequency of each character in this substring is greater than or equal to k. + * + * If no such substring exists, return 0. + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var longestSubstring = function(s, k) { + for (const char of Array.from(new Set(s))) { + if (s.match(new RegExp(char, 'g')).length < k) { + return Math.max(...s.split(char).map(str => longestSubstring(str, k))); + } + } + return s.length; +}; diff --git a/README.md b/README.md index 67285140..a476ef2b 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| +395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From 4ea5752e7815182eca3561a5c948a666f79aeafc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:49:23 -0600 Subject: [PATCH 477/485] Add solution #389 --- 0389-find-the-difference.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0389-find-the-difference.js diff --git a/0389-find-the-difference.js b/0389-find-the-difference.js new file mode 100644 index 00000000..d789a16e --- /dev/null +++ b/0389-find-the-difference.js @@ -0,0 +1,24 @@ +/** + * 389. Find the Difference + * https://leetcode.com/problems/find-the-difference/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} s + * @param {string} t + * @return {character} + */ +var findTheDifference = function(s, t) { + const map = new Map(); + t.split('').forEach(c => map.set(c, (map.get(c) ?? 0) + 1)); + s.split('').forEach(c => map.set(c, map.get(c) - 1)); + return Array.from(map).find(([letter, count]) => count)[0]; +}; diff --git a/README.md b/README.md index a476ef2b..6e4e16b7 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +389|[Find the Difference](./0389-find-the-difference.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| From 96a6a652b1032c80739f09f9c9efddc47c34f7c4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:50:36 -0600 Subject: [PATCH 478/485] Add solution #2429 --- 2429-minimize-xor.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 2429-minimize-xor.js diff --git a/2429-minimize-xor.js b/2429-minimize-xor.js new file mode 100644 index 00000000..568f19fc --- /dev/null +++ b/2429-minimize-xor.js @@ -0,0 +1,37 @@ +/** + * 2429. Minimize XOR + * https://leetcode.com/problems/minimize-xor/ + * Difficulty: Medium + * + * Given two positive integers num1 and num2, find the positive integer x such that: + * - x has the same number of set bits as num2, and + * - The value x XOR num1 is minimal. + * + * Note that XOR is the bitwise XOR operation. + * + * Return the integer x. The test cases are generated such that x is uniquely determined. + * + * The number of set bits of an integer is the number of 1's in its binary representation. + */ + +/** + * @param {number} num1 + * @param {number} num2 + * @return {number} + */ +var minimizeXor = function(num1, num2) { + let count1 = num1.toString(2).split('1').length - 1; + const count2 = num2.toString(2).split('1').length - 1; + + while (count1 > count2) { + num1 &= (num1 - 1); + count1--; + } + + while (count1 < count2) { + num1 |= (num1 + 1); + count1++; + } + + return num1; +}; diff --git a/README.md b/README.md index 6e4e16b7..1a5d05cb 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,7 @@ 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| +2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| From 171e82445be47e9db4bc4662e11298b577f0d78a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:51:24 -0600 Subject: [PATCH 479/485] Add solution #575 --- 0575-distribute-candies.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0575-distribute-candies.js diff --git a/0575-distribute-candies.js b/0575-distribute-candies.js new file mode 100644 index 00000000..7d265797 --- /dev/null +++ b/0575-distribute-candies.js @@ -0,0 +1,23 @@ +/** + * 575. Distribute Candies + * https://leetcode.com/problems/distribute-candies/ + * Difficulty: Easy + * + * Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that + * she started to gain weight, so she visited a doctor. + * + * The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). + * Alice likes her candies very much, and she wants to eat the maximum number of different + * types of candies while still following the doctor's advice. + * + * Given the integer array candyType of length n, return the maximum number of different + * types of candies she can eat if she only eats n / 2 of them. + */ + +/** + * @param {number[]} candyType + * @return {number} + */ +var distributeCandies = function(candyType) { + return Math.min(new Set(candyType).size, candyType.length / 2); +}; diff --git a/README.md b/README.md index 1a5d05cb..3896b83c 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| +575|[Distribute Candies](./0575-distribute-candies.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From e9c3a312f959846569611e381abfff21d7694d66 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:43:56 -0600 Subject: [PATCH 480/485] Add solution #72 --- 0072-edit-distance.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0072-edit-distance.js diff --git a/0072-edit-distance.js b/0072-edit-distance.js new file mode 100644 index 00000000..c3e7a227 --- /dev/null +++ b/0072-edit-distance.js @@ -0,0 +1,38 @@ +/** + * 72. Edit Distance + * https://leetcode.com/problems/edit-distance/ + * Difficulty: Medium + * + * 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: + * - Insert a character + * - Delete a character + * - Replace a character + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ +var minDistance = function(word1, word2) { + const cache = new Array(word1.length + 1).fill(0).map(() => new Array(word2.length + 1)); + + for (let i = 0; i <= word1.length; i++) { + for (let j = 0; j <= word2.length; j++) { + if (i === 0) { + cache[0][j] = j; + } else if (j === 0) { + cache[i][0] = i; + } else if (word1[i - 1] == word2[j - 1]) { + cache[i][j] = cache[i - 1][j - 1]; + } else { + cache[i][j] = Math.min(cache[i][j - 1], cache[i - 1][j - 1], cache[i - 1][j]) + 1; + } + } + } + + return cache[word1.length][word2.length]; +}; diff --git a/README.md b/README.md index 3896b83c..c1e264e9 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 71|[Simplify Path](./0071-simplify-path.js)|Medium| +72|[Edit Distance](./0072-edit-distance.js)|Medium| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 75|[Sort Colors](./0075-sort-colors.js)|Medium| From a45ddfd2acc97e4a3638745eec8d4ac9b9554a23 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:45:17 -0600 Subject: [PATCH 481/485] Add solution #68 --- 0068-text-justification.js | 63 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 0068-text-justification.js diff --git a/0068-text-justification.js b/0068-text-justification.js new file mode 100644 index 00000000..eb74a4ce --- /dev/null +++ b/0068-text-justification.js @@ -0,0 +1,63 @@ +/** + * 68. Text Justification + * https://leetcode.com/problems/text-justification/ + * Difficulty: Hard + * + * Given an array of strings words and a width maxWidth, format the text such that each + * line has exactly maxWidth characters and is fully (left and right) justified. + * + * You should pack your words in a greedy approach; that is, pack as many words as you + * can in each line. Pad extra spaces ' ' when necessary so that each line has exactly + * maxWidth characters. + * + * Extra spaces between words should be distributed as evenly as possible. If the number + * of spaces on a line does not divide evenly between words, the empty slots on the left + * will be assigned more spaces than the slots on the right. + * + * For the last line of text, it should be left-justified, and no extra space is inserted + * between words. + * + * Note: + * - A word is defined as a character sequence consisting of non-space characters only. + * - Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. + * - The input array words contains at least one word. + */ + +/** + * @param {string[]} words + * @param {number} maxWidth + * @return {string[]} + */ +var fullJustify = function(words, maxWidth) { + const result = [[]]; + result[0].count = 0; + + for (const word of words) { + let row = result[result.length - 1]; + if (row.length && row.count + row.length + word.length > maxWidth) { + result.push([]); + row = result[result.length - 1]; + row.count = 0; + } + row.push(word); + row.count += word.length; + } + + for (let i = 0; i < result.length; i++) { + const row = result[i]; + if (row.length === 1 || i === result.length - 1) { + result[i] = row.join(' ') + ' '.repeat(maxWidth - row.count - row.length + 1); + continue; + } + + const min = ' '.repeat(Math.floor((maxWidth - row.count) / (row.length - 1))); + for (let j = 1; j < row.length; j++) { + const delimiter = j <= (maxWidth - row.count) % (row.length - 1) ? ' ' : ''; + row[0] += min + delimiter + row[j]; + } + + result[i] = row[0]; + } + + return result; +}; diff --git a/README.md b/README.md index c1e264e9..c6b7f5c2 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ 65|[Valid Number](./0065-valid-number.js)|Hard| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +68|[Text Justification](./0068-text-justification.js)|Hard| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 71|[Simplify Path](./0071-simplify-path.js)|Medium| From 4eb54a3be90c9f4ea3d84c6a2367743e80f8bd65 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:46:41 -0600 Subject: [PATCH 482/485] Add solution #63 --- 0063-unique-paths-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0063-unique-paths-ii.js diff --git a/0063-unique-paths-ii.js b/0063-unique-paths-ii.js new file mode 100644 index 00000000..a63c96da --- /dev/null +++ b/0063-unique-paths-ii.js @@ -0,0 +1,37 @@ +/** + * 63. Unique Paths II + * https://leetcode.com/problems/unique-paths-ii/ + * Difficulty: Medium + * + * You are given an m x n integer array grid. There is a robot initially located at + * the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right + * corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at + * any point in time. + * + * An obstacle and space are marked as 1 or 0 respectively in grid. A path that the + * robot takes cannot include any square that is an obstacle. + * + * Return the number of possible unique paths that the robot can take to reach the + * bottom-right corner. + * + * The testcases are generated so that the answer will be less than or equal to 2 * 109. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var uniquePathsWithObstacles = function(grid) { + const cache = new Array(grid.length).fill(0).map(v => new Array(grid[0].length).fill(0)); + + function traverse(x, y) { + if (grid[x] === undefined || grid[x][y] === undefined || grid[x][y] === 1) return 0; + if (x === grid.length - 1 && y === grid[0].length - 1) return 1; + if (!cache[x][y]) { + cache[x][y] = traverse(x + 1, y) + traverse(x, y + 1); + } + return cache[x][y]; + } + + return traverse(0, 0); +}; diff --git a/README.md b/README.md index c6b7f5c2..4b31f76f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ 60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| 61|[Rotate List](./0061-rotate-list.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| +63|[Unique Paths II](./0063-unique-paths-ii.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 65|[Valid Number](./0065-valid-number.js)|Hard| 66|[Plus One](./0066-plus-one.js)|Easy| From fb7121167c394e854b732750fad284d12b251fca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:47:35 -0600 Subject: [PATCH 483/485] Add solution #482 --- 0482-license-key-formatting.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0482-license-key-formatting.js diff --git a/0482-license-key-formatting.js b/0482-license-key-formatting.js new file mode 100644 index 00000000..1f4a87e7 --- /dev/null +++ b/0482-license-key-formatting.js @@ -0,0 +1,33 @@ +/** + * 482. License Key Formatting + * https://leetcode.com/problems/license-key-formatting/ + * Difficulty: Easy + * + * You are given a license key represented as a string s that consists of only alphanumeric + * characters and dashes. The string is separated into n + 1 groups by n dashes. You are + * also given an integer k. + * + * We want to reformat the string s such that each group contains exactly k characters, + * except for the first group, which could be shorter than k but still must contain at + * least one character. Furthermore, there must be a dash inserted between two groups, + * and you should convert all lowercase letters to uppercase. + * + * Return the reformatted license key. + */ + +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var licenseKeyFormatting = function(s, k) { + const result = []; + s = s.toUpperCase().replace(/\-+/g, ''); + if (s.length % k) { + result.push(s.substring(0, s.length % k)); + } + for (let i = s.length % k; i < s.length; i += k) { + result.push(s.substring(i, i + k)); + } + return result.join('-'); +}; diff --git a/README.md b/README.md index 4b31f76f..71bdbe3a 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| From 2150b582540f341dc2f5a487e8d0ae7ce7493be4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:48:12 -0600 Subject: [PATCH 484/485] Add solution #2425 --- 2425-bitwise-xor-of-all-pairings.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2425-bitwise-xor-of-all-pairings.js diff --git a/2425-bitwise-xor-of-all-pairings.js b/2425-bitwise-xor-of-all-pairings.js new file mode 100644 index 00000000..2ef59ed9 --- /dev/null +++ b/2425-bitwise-xor-of-all-pairings.js @@ -0,0 +1,22 @@ +/** + * 2425. Bitwise XOR of All Pairings + * https://leetcode.com/problems/bitwise-xor-of-all-pairings/ + * Difficulty: Medium + * + * You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. + * There exists another array, nums3, which contains the bitwise XOR of all pairings of + * integers between nums1 and nums2 (every integer in nums1 is paired with every integer + * in nums2 exactly once). + * + * Return the bitwise XOR of all integers in nums3. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var xorAllNums = function(nums1, nums2) { + const xor = (a, b) => a.length % 2 ? b.reduce((x, y) => x ^ y): 0; + return xor(nums1, nums2) ^ xor(nums2, nums1); +}; diff --git a/README.md b/README.md index 71bdbe3a..73f9a2f0 100644 --- a/README.md +++ b/README.md @@ -416,6 +416,7 @@ 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| +2425|[Bitwise XOR of All Pairings](./2425-bitwise-xor-of-all-pairings.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| From b1d14ff7eef292fe89006143c33570b38282cf3b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 20:20:12 -0600 Subject: [PATCH 485/485] Add solution #2683 --- 2683-neighboring-bitwise-xor.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2683-neighboring-bitwise-xor.js diff --git a/2683-neighboring-bitwise-xor.js b/2683-neighboring-bitwise-xor.js new file mode 100644 index 00000000..523905d5 --- /dev/null +++ b/2683-neighboring-bitwise-xor.js @@ -0,0 +1,26 @@ +/** + * 2683. Neighboring Bitwise XOR + * https://leetcode.com/problems/neighboring-bitwise-xor/ + * Difficulty: Medium + * + * A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) + * of adjacent values in a binary array original of length n. + * + * Specifically, for each index i in the range [0, n - 1]: + * - If i = n - 1, then derived[i] = original[i] ⊕ original[0]. + * - Otherwise, derived[i] = original[i] ⊕ original[i + 1]. + * + * Given an array derived, your task is to determine whether there exists a valid binary + * array original that could have formed derived. + * + * Return true if such an array exists or false otherwise. + * - A binary array is an array containing only 0's and 1's + */ + +/** + * @param {number[]} derived + * @return {boolean} + */ +var doesValidArrayExist = function(derived) { + return derived.reduce((xor, n) => xor ^ n, 0) === 0; +}; diff --git a/README.md b/README.md index 73f9a2f0..46fe2f4a 100644 --- a/README.md +++ b/README.md @@ -447,6 +447,7 @@ 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2677|[Chunk Array](./2677-chunk-array.js)|Easy| +2683|[Neighboring Bitwise XOR](./2683-neighboring-bitwise-xor.js)|Medium| 2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy|