diff --git a/solutions/0001-two-sum.js b/0001-two-sum.js similarity index 100% rename from solutions/0001-two-sum.js rename to 0001-two-sum.js diff --git a/0002-add-two-numbers.js b/0002-add-two-numbers.js new file mode 100644 index 00000000..63ca74dc --- /dev/null +++ b/0002-add-two-numbers.js @@ -0,0 +1,60 @@ +/** + * 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(); + + for (let tail = result, carry = 0; l1 || l2 || carry;) { + const value = (l1?.val ?? 0) + (l2?.val ?? 0) + carry; + tail.next = new ListNode(value % 10); + tail = tail.next; + carry = value >= 10 ? 1 : 0; + [l1, l2] = [l1 && l1.next, l2 && l2.next]; + } + + return result.next; +}; + +// var addTwoNumbers = function(l1, l2) { +// const dummy = new LinkedListNode(); +// let cur = dummy; + +// let carry = 0; +// while (l1 || l2 || carry) { +// const v1 = l1 ? l1.val : 0; +// const v2 = l2 ? l2.val : 0; + +// let val = v1 + v2 + carry; +// carry = Math.floor(val / 10); +// val = val % 10; +// cur.next = new LinkedListNode(val); + +// cur = cur.next; +// l1 = l1 ? l1.next : null; +// l2 = l2 ? l2.next : null; +// } + +// return dummy.next; +// }; diff --git a/0003-longest-substring-without-repeating-characters.js b/0003-longest-substring-without-repeating-characters.js new file mode 100644 index 00000000..d8a3ff48 --- /dev/null +++ b/0003-longest-substring-without-repeating-characters.js @@ -0,0 +1,38 @@ +/** + * 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); +}; + +// var lengthOfLongestSubstring = function(s) { +// let begin = 0; +// const window_state = new Set(); // charSet +// let result = 0; + +// for (let end = 0; end < s.length; end++) { +// while (window_state.has(s[end])) { +// window_state.delete(s[begin]); +// begin++; +// } +// window_state.add(s[end]); +// result = Math.max(result, end - begin + 1); +// } +// return result; +// }; diff --git a/solutions/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js similarity index 100% rename from solutions/0004-median-of-two-sorted-arrays.js rename to 0004-median-of-two-sorted-arrays.js diff --git a/solutions/0005-longest-palindromic-substring.js b/0005-longest-palindromic-substring.js similarity index 100% rename from solutions/0005-longest-palindromic-substring.js rename to 0005-longest-palindromic-substring.js diff --git a/solutions/0006-zigzag-conversion.js b/0006-zigzag-conversion.js similarity index 100% rename from solutions/0006-zigzag-conversion.js rename to 0006-zigzag-conversion.js diff --git a/solutions/0007-reverse-integer.js b/0007-reverse-integer.js similarity index 100% rename from solutions/0007-reverse-integer.js rename to 0007-reverse-integer.js diff --git a/solutions/0008-string-to-integer-atoi.js b/0008-string-to-integer-atoi.js similarity index 100% rename from solutions/0008-string-to-integer-atoi.js rename to 0008-string-to-integer-atoi.js diff --git a/0009-palindrome-number.js b/0009-palindrome-number.js new file mode 100644 index 00000000..172bec71 --- /dev/null +++ b/0009-palindrome-number.js @@ -0,0 +1,36 @@ +/** + * 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; +}; + +// var isPalindrome = function (x) { +// if (x < 0) return false; + +// const strNum = x.toString(); +// let left = 0; +// let right = strNum.length - 1; + +// while (left < right) { +// if (strNum[left] !== strNum[right]) { +// return false; +// } +// left++; +// right--; +// } +// return true; +// }; diff --git a/solutions/0010-regular-expression-matching.js b/0010-regular-expression-matching.js similarity index 100% rename from solutions/0010-regular-expression-matching.js rename to 0010-regular-expression-matching.js diff --git a/solutions/0011-container-with-most-water.js b/0011-container-with-most-water.js similarity index 100% rename from solutions/0011-container-with-most-water.js rename to 0011-container-with-most-water.js diff --git a/solutions/0012-integer-to-roman.js b/0012-integer-to-roman.js similarity index 100% rename from solutions/0012-integer-to-roman.js rename to 0012-integer-to-roman.js diff --git a/solutions/0013-roman-to-integer.js b/0013-roman-to-integer.js similarity index 77% rename from solutions/0013-roman-to-integer.js rename to 0013-roman-to-integer.js index acbb22f8..98fc3a39 100644 --- a/solutions/0013-roman-to-integer.js +++ b/0013-roman-to-integer.js @@ -46,3 +46,26 @@ var romanToInt = function(s) { return result; }, 0); }; + +// var romanToInt = function(s) { +// let res = 0; +// const roman = { +// 'I': 1, +// 'V': 5, +// 'X': 10, +// 'L': 50, +// 'C': 100, +// 'D': 500, +// 'M': 1000 +// }; + +// for (let i = 0; i < s.length - 1; i++) { +// if (roman[s[i]] < roman[s[i + 1]]) { +// res -= roman[s[i]]; +// } else { +// res += roman[s[i]]; +// } +// } + +// return res + roman[s[s.length - 1]]; +// }; diff --git a/solutions/0014-longest-common-prefix.js b/0014-longest-common-prefix.js similarity index 100% rename from solutions/0014-longest-common-prefix.js rename to 0014-longest-common-prefix.js diff --git a/0015-3sum.js b/0015-3sum.js new file mode 100644 index 00000000..565ee7b5 --- /dev/null +++ b/0015-3sum.js @@ -0,0 +1,103 @@ +/** + * 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 = []; + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 2; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + let j = i + 1; + let k = nums.length - 1; + while (j < k) { + const sum = nums[i] + nums[j] + nums[k]; + if (!sum) { + result.push([nums[i], nums[j], nums[k]]); + j++; + k--; + while (j < k && nums[j] === nums[j - 1]) { + j++; + } + while (j < k && nums[k] === nums[k + 1]) { + k--; + } + } else { + sum < 0 ? j++ : k--; + } + } + } + + return result; +}; + +// var threeSum = function(nums) { +// nums.sort((a, b) => a - b); +// const result = []; + +// for (let i = 0; i < nums.length - 2; i++) { +// if (i > 0 && nums[i] === nums[i - 1]) continue; // Пропускаем дубли + +// let left = i + 1, right = nums.length - 1; + +// while (left < right) { +// const sum = nums[i] + nums[left] + nums[right]; + +// if (sum === 0) { +// result.push([nums[i], nums[left], nums[right]]); +// left++; +// right--; + +// while (left < right && nums[left] === nums[left - 1]) left++; // Пропуск дубликатов слева +// while (left < right && nums[right] === nums[right + 1]) right--; // Пропуск дубликатов справа +// } else if (sum < 0) { +// left++; +// } else { +// right--; +// } +// } +// } + +// return result; +// }; + +// O(n^2) +// с = - (a + b) +// var threeSum = function(nums) { +// nums.sort((a, b) => a - b); // O(n log n) +// const result = new Set(); +// const n = nums.length; + +// for (let i = 0; i < n; i++) { +// let target = -nums[i]; +// let left = i + 1; +// let right = n - 1; + +// while (left < right) { +// let currentSum = nums[left] + nums[right]; + +// if (currentSum === target) { +// result.add(JSON.stringify([nums[i], nums[left], nums[right]])); +// left++; +// right--; +// } else if (currentSum > target) { +// right--; +// } else { +// left++; +// } +// } +// } + +// return Array.from(result, JSON.parse); // Преобразуем Set обратно в массив +// }; \ No newline at end of file diff --git a/solutions/0016-3sum-closest.js b/0016-3sum-closest.js similarity index 100% rename from solutions/0016-3sum-closest.js rename to 0016-3sum-closest.js diff --git a/solutions/0017-letter-combinations-of-a-phone-number.js b/0017-letter-combinations-of-a-phone-number.js similarity index 100% rename from solutions/0017-letter-combinations-of-a-phone-number.js rename to 0017-letter-combinations-of-a-phone-number.js diff --git a/solutions/0018-4sum.js b/0018-4sum.js similarity index 100% rename from solutions/0018-4sum.js rename to 0018-4sum.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..707ba41e --- /dev/null +++ b/0019-remove-nth-node-from-end-of-list.js @@ -0,0 +1,82 @@ +/** + * 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; +}; + +// var removeNthFromEnd = function(head, n) { +// const result = new LinkedListNode(); +// 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; +// }; + + +// var removeNthFromEnd = function(head, n) { +// const dummy = new LinkedListNode(); +// dummy.next = head + +// first = dummy +// second = dummy + +// for (let i = 0; i <= n; i++) { +// first = first.next; +// } + +// while (first) { +// first = first.next; +// second = second.next; +// } + +// second.next = second.next.next; + +// return dummy.next; +// }; diff --git a/solutions/0020-valid-parentheses.js b/0020-valid-parentheses.js similarity index 100% rename from solutions/0020-valid-parentheses.js rename to 0020-valid-parentheses.js diff --git a/0021-merge-two-sorted-lists.js b/0021-merge-two-sorted-lists.js new file mode 100644 index 00000000..b1e9b07d --- /dev/null +++ b/0021-merge-two-sorted-lists.js @@ -0,0 +1,63 @@ +/** + * 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; +}; + +// var mergeTwoLists = function(list1, list2) { +// const dummy = new LinkedListNode(); +// current = dummy + +// p1 = list1 +// p2 = list2 + +// while (p1 && p2) { +// if (p1.val < p2.val) { +// current.next = p1 +// p1 = p1.next +// } else { +// current.next = p2 +// p2 = p2.next +// } + +// current = current.next +// } + +// if (p1) { +// current.next = p1 +// } else { +// current.next = p2 +// } + +// return dummy.next +// }; \ No newline at end of file diff --git a/solutions/0022-generate-parentheses.js b/0022-generate-parentheses.js similarity index 100% rename from solutions/0022-generate-parentheses.js rename to 0022-generate-parentheses.js diff --git a/solutions/0023-merge-k-sorted-lists.js b/0023-merge-k-sorted-lists.js similarity index 100% rename from solutions/0023-merge-k-sorted-lists.js rename to 0023-merge-k-sorted-lists.js diff --git a/0024-swap-nodes-in-pairs.js b/0024-swap-nodes-in-pairs.js new file mode 100644 index 00000000..13ec0679 --- /dev/null +++ b/0024-swap-nodes-in-pairs.js @@ -0,0 +1,51 @@ +/** + * 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; +}; + +// var swapPairs = function(head) { +// let dummy = new LinkedListNode() +// dummy.next = head + +// current = dummy + +// while (current.next && current.next.next) { +// first = current.next +// second = current.next.next + +// first.next = second.next +// second.next = first +// current.next = second + +// current = first +// } + +// return dummy.next +// }; \ No newline at end of file diff --git a/solutions/0025-reverse-nodes-in-k-group.js b/0025-reverse-nodes-in-k-group.js similarity index 100% rename from solutions/0025-reverse-nodes-in-k-group.js rename to 0025-reverse-nodes-in-k-group.js diff --git a/solutions/0026-remove-duplicates-from-sorted-array.js b/0026-remove-duplicates-from-sorted-array.js similarity index 84% rename from solutions/0026-remove-duplicates-from-sorted-array.js rename to 0026-remove-duplicates-from-sorted-array.js index 326d46ef..ad3696ca 100644 --- a/solutions/0026-remove-duplicates-from-sorted-array.js +++ b/0026-remove-duplicates-from-sorted-array.js @@ -32,3 +32,14 @@ var removeDuplicates = function(nums) { } return ++i; }; + +// var removeDuplicates = function(nums) { +// let k = 0; +// for (let i = 0; i < nums.length; i++) { +// if (nums[k] !== nums[i]) { +// k=k+1 +// nums[k] = nums[i]; +// } +// } +// return k+1; +// }; diff --git a/solutions/0027-remove-element.js b/0027-remove-element.js similarity index 100% rename from solutions/0027-remove-element.js rename to 0027-remove-element.js diff --git a/solutions/0028-implement-strstr.js b/0028-implement-strstr.js similarity index 89% rename from solutions/0028-implement-strstr.js rename to 0028-implement-strstr.js index f7cc484e..47d6f8d8 100644 --- a/solutions/0028-implement-strstr.js +++ b/0028-implement-strstr.js @@ -24,3 +24,7 @@ var strStr = function(haystack, needle) { const split = haystack.split(needle); return split.length > 1 ? split[0].length : -1; }; + +// var strStr = function(haystack, needle) { +// return haystack.indexOf(needle) +// }; \ No newline at end of file diff --git a/solutions/0029-divide-two-integers.js b/0029-divide-two-integers.js similarity index 100% rename from solutions/0029-divide-two-integers.js rename to 0029-divide-two-integers.js diff --git a/solutions/0030-substring-with-concatenation-of-all-words.js b/0030-substring-with-concatenation-of-all-words.js similarity index 100% rename from solutions/0030-substring-with-concatenation-of-all-words.js rename to 0030-substring-with-concatenation-of-all-words.js diff --git a/solutions/0031-next-permutation.js b/0031-next-permutation.js similarity index 100% rename from solutions/0031-next-permutation.js rename to 0031-next-permutation.js diff --git a/solutions/0032-longest-valid-parentheses.js b/0032-longest-valid-parentheses.js similarity index 100% rename from solutions/0032-longest-valid-parentheses.js rename to 0032-longest-valid-parentheses.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..0f360821 --- /dev/null +++ b/0033-search-in-rotated-sorted-array.js @@ -0,0 +1,81 @@ +/** + * 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; +}; + +// var search = function(nums, target) { +// let l = 0; +// let r = nums.length - 1; + +// while (l < r) { +// const m = Math.floor((l + r) / 2); +// if (nums[m] > nums[r]) { +// l = m + 1; +// } else { +// r = m; +// } +// } + +// const pivot = l; + +// const result = binarySearch(nums, target, 0, pivot - 1); +// if (result !== -1) { +// return result; +// } + +// return binarySearch(nums, target, pivot, nums.length - 1); +// }; + +// var binarySearch = function(nums, target, left, right) { +// while (left <= right) { +// const mid = Math.floor((left + right) / 2); +// if (nums[mid] === target) { +// return mid; +// } else if (nums[mid] < target) { +// left = mid + 1; +// } else { +// right = mid - 1; +// } +// } +// return -1; +// } diff --git a/solutions/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 similarity index 100% rename from solutions/0034-find-first-and-last-position-of-element-in-sorted-array.js rename to 0034-find-first-and-last-position-of-element-in-sorted-array.js diff --git a/solutions/0035-search-insert-position.js b/0035-search-insert-position.js similarity index 100% rename from solutions/0035-search-insert-position.js rename to 0035-search-insert-position.js diff --git a/solutions/0036-valid-sudoku.js b/0036-valid-sudoku.js similarity index 100% rename from solutions/0036-valid-sudoku.js rename to 0036-valid-sudoku.js diff --git a/solutions/0037-sudoku-solver.js b/0037-sudoku-solver.js similarity index 100% rename from solutions/0037-sudoku-solver.js rename to 0037-sudoku-solver.js diff --git a/solutions/0038-count-and-say.js b/0038-count-and-say.js similarity index 100% rename from solutions/0038-count-and-say.js rename to 0038-count-and-say.js diff --git a/solutions/0039-combination-sum.js b/0039-combination-sum.js similarity index 100% rename from solutions/0039-combination-sum.js rename to 0039-combination-sum.js diff --git a/solutions/0040-combination-sum-ii.js b/0040-combination-sum-ii.js similarity index 100% rename from solutions/0040-combination-sum-ii.js rename to 0040-combination-sum-ii.js diff --git a/solutions/0041-first-missing-positive.js b/0041-first-missing-positive.js similarity index 100% rename from solutions/0041-first-missing-positive.js rename to 0041-first-missing-positive.js diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js new file mode 100644 index 00000000..1d60097b --- /dev/null +++ b/0042-trapping-rain-water.js @@ -0,0 +1,47 @@ +/** + * 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) { + let result = 0; + + for (let left = 0, right = height.length - 1, maxL = 0, maxR = 0; left < right;) { + maxL = Math.max(maxL, height[left]); + maxR = Math.max(maxR, height[right]); + result += maxL < maxR ? maxL - height[left++] : maxR - height[right--]; + } + + return result; +}; + +// var trap = function(height) { +// let res = 0 +// let left = 0 +// let right = height.length - 1 +// let maxLeft = height[left] +// let maxRight = height[right] + +// while (left < right) { +// if (maxLeft < maxRight) { +// left++ +// maxLeft = Math.max(maxLeft, height[left]) +// res = res + (maxLeft - height[left]) +// // +// } else { +// right-- +// maxRight = Math.max(maxRight, height[right]) +// res = res + (maxRight - height[right]) +// } +// } + +// return res +// }; \ No newline at end of file diff --git a/solutions/0043-multiply-strings.js b/0043-multiply-strings.js similarity index 100% rename from solutions/0043-multiply-strings.js rename to 0043-multiply-strings.js diff --git a/solutions/0044-wildcard-matching.js b/0044-wildcard-matching.js similarity index 100% rename from solutions/0044-wildcard-matching.js rename to 0044-wildcard-matching.js diff --git a/solutions/0045-jump-game-ii.js b/0045-jump-game-ii.js similarity index 100% rename from solutions/0045-jump-game-ii.js rename to 0045-jump-game-ii.js diff --git a/solutions/0046-permutations.js b/0046-permutations.js similarity index 100% rename from solutions/0046-permutations.js rename to 0046-permutations.js diff --git a/solutions/0047-permutations-ii.js b/0047-permutations-ii.js similarity index 100% rename from solutions/0047-permutations-ii.js rename to 0047-permutations-ii.js diff --git a/solutions/0048-rotate-image.js b/0048-rotate-image.js similarity index 100% rename from solutions/0048-rotate-image.js rename to 0048-rotate-image.js diff --git a/0049-group-anagrams.js b/0049-group-anagrams.js new file mode 100644 index 00000000..0b237f12 --- /dev/null +++ b/0049-group-anagrams.js @@ -0,0 +1,43 @@ +/** + * 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); +}; + +// var groupAnagrams = function(strs) { +// const res = {}; +// for (let s of strs) { +// // Создаем массив частот букв +// const count = new Array(26).fill(0); +// for (let c of s) { +// count[c.charCodeAt(0) - 'a'.charCodeAt(0)] += 1; +// } +// const key = count.join(','); +// if (!res[key]) { +// res[key] = []; +// } +// res[key].push(s); +// } +// return Object.values(res); +// } diff --git a/solutions/0050-powx-n.js b/0050-powx-n.js similarity index 100% rename from solutions/0050-powx-n.js rename to 0050-powx-n.js diff --git a/solutions/0051-n-queens.js b/0051-n-queens.js similarity index 100% rename from solutions/0051-n-queens.js rename to 0051-n-queens.js diff --git a/solutions/0052-n-queens-ii.js b/0052-n-queens-ii.js similarity index 100% rename from solutions/0052-n-queens-ii.js rename to 0052-n-queens-ii.js diff --git a/solutions/0053-maximum-subarray.js b/0053-maximum-subarray.js similarity index 100% rename from solutions/0053-maximum-subarray.js rename to 0053-maximum-subarray.js diff --git a/solutions/0054-spiral-matrix.js b/0054-spiral-matrix.js similarity index 100% rename from solutions/0054-spiral-matrix.js rename to 0054-spiral-matrix.js diff --git a/solutions/0055-jump-game.js b/0055-jump-game.js similarity index 100% rename from solutions/0055-jump-game.js rename to 0055-jump-game.js diff --git a/solutions/0056-merge-intervals.js b/0056-merge-intervals.js similarity index 100% rename from solutions/0056-merge-intervals.js rename to 0056-merge-intervals.js diff --git a/solutions/0057-insert-interval.js b/0057-insert-interval.js similarity index 100% rename from solutions/0057-insert-interval.js rename to 0057-insert-interval.js diff --git a/0058-length-of-last-word.js b/0058-length-of-last-word.js new file mode 100644 index 00000000..d57d3a84 --- /dev/null +++ b/0058-length-of-last-word.js @@ -0,0 +1,38 @@ +/** + * 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; +}; + +// var lengthOfLastWord = function(s) { +// let end = s.length - 1; + +// while (end >= 0 && s[end] === ' ') { +// end--; +// } + +// let start = end; +// while (start >= 0 && s[start] !== ' ') { +// start--; +// } + +// return end - start; +// }; diff --git a/solutions/0059-spiral-matrix-ii.js b/0059-spiral-matrix-ii.js similarity index 100% rename from solutions/0059-spiral-matrix-ii.js rename to 0059-spiral-matrix-ii.js diff --git a/solutions/0060-permutation-sequence.js b/0060-permutation-sequence.js similarity index 100% rename from solutions/0060-permutation-sequence.js rename to 0060-permutation-sequence.js diff --git a/solutions/0061-rotate-list.js b/0061-rotate-list.js similarity index 100% rename from solutions/0061-rotate-list.js rename to 0061-rotate-list.js diff --git a/solutions/0062-unique-paths.js b/0062-unique-paths.js similarity index 100% rename from solutions/0062-unique-paths.js rename to 0062-unique-paths.js diff --git a/solutions/0063-unique-paths-ii.js b/0063-unique-paths-ii.js similarity index 100% rename from solutions/0063-unique-paths-ii.js rename to 0063-unique-paths-ii.js diff --git a/solutions/0064-minimum-path-sum.js b/0064-minimum-path-sum.js similarity index 100% rename from solutions/0064-minimum-path-sum.js rename to 0064-minimum-path-sum.js diff --git a/solutions/0065-valid-number.js b/0065-valid-number.js similarity index 100% rename from solutions/0065-valid-number.js rename to 0065-valid-number.js diff --git a/solutions/0066-plus-one.js b/0066-plus-one.js similarity index 90% rename from solutions/0066-plus-one.js rename to 0066-plus-one.js index 20987a33..712d5b5e 100644 --- a/solutions/0066-plus-one.js +++ b/0066-plus-one.js @@ -39,3 +39,7 @@ var plusOne = function(digits) { var plusOne = function(digits) { return String(BigInt(digits.join('')) + BigInt(1)).split(''); }; + +// var plusOne = function(digits) { +// return String(parseInt(digits.join('')) + 1).split(''); +// }; \ No newline at end of file diff --git a/solutions/0067-add-binary.js b/0067-add-binary.js similarity index 100% rename from solutions/0067-add-binary.js rename to 0067-add-binary.js diff --git a/solutions/0068-text-justification.js b/0068-text-justification.js similarity index 100% rename from solutions/0068-text-justification.js rename to 0068-text-justification.js diff --git a/solutions/0069-sqrtx.js b/0069-sqrtx.js similarity index 100% rename from solutions/0069-sqrtx.js rename to 0069-sqrtx.js diff --git a/solutions/0070-climbing-stairs.js b/0070-climbing-stairs.js similarity index 100% rename from solutions/0070-climbing-stairs.js rename to 0070-climbing-stairs.js diff --git a/solutions/0071-simplify-path.js b/0071-simplify-path.js similarity index 100% rename from solutions/0071-simplify-path.js rename to 0071-simplify-path.js diff --git a/solutions/0072-edit-distance.js b/0072-edit-distance.js similarity index 100% rename from solutions/0072-edit-distance.js rename to 0072-edit-distance.js diff --git a/solutions/0073-set-matrix-zeroes.js b/0073-set-matrix-zeroes.js similarity index 100% rename from solutions/0073-set-matrix-zeroes.js rename to 0073-set-matrix-zeroes.js diff --git a/0074-search-a-2d-matrix.js b/0074-search-a-2d-matrix.js new file mode 100644 index 00000000..1c2e4f75 --- /dev/null +++ b/0074-search-a-2d-matrix.js @@ -0,0 +1,123 @@ +/** + * 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; +}; + +// var searchMatrix = function(matrix, target) { +// const ROWS = matrix.length; +// const COLS = matrix[0].length; + +// let top = 0; +// let bot = ROWS - 1; +// while (top <= bot) { +// const row = Math.floor((top + bot) / 2); +// if (target > matrix[row][COLS - 1]) { +// top = row + 1; +// } else if (target < matrix[row][0]) { +// bot = row - 1; +// } else { +// break; +// } +// } + +// if (!(top <= bot)) { +// return false; +// } +// const row = Math.floor((top + bot) / 2); +// let l = 0; +// let r = COLS - 1; +// while (l <= r) { +// const m = Math.floor((l + r) / 2); +// if (target > matrix[row][m]) { +// l = m + 1; +// } else if (target < matrix[row][m]) { +// r = m - 1; +// } else { +// return true; +// } +// } +// return false; +// }; + + + + +// const searchMatrix = function (matrix, target) { +// const rowIndex = findRow(); +// if (rowIndex === true) { +// return true; +// } +// if (rowIndex < 0) { +// return false; +// } + +// return findNumInRow(matrix[rowIndex]); + +// function findRow() { +// let start = 0; +// let end = matrix.length - 1; + +// while (start <= end) { +// const middle = Math.floor((start + end) / 2); +// const potentialRow = matrix[middle]; +// const firstNumInRow = potentialRow[0]; +// const lastNumInRow = potentialRow[potentialRow.length - 1]; + +// if (firstNumInRow === target || lastNumInRow === target) { +// return true; +// } + +// if (firstNumInRow < target && lastNumInRow > target) { +// return middle; +// } + +// if (target > lastNumInRow) { +// start = middle + 1; +// } else { +// end = middle - 1; +// } +// } + +// return -1; +// } + +// function findNumInRow(row) { +// let start = 0; +// let end = row.length - 1; + +// while (start <= end) { +// const middle = Math.floor((start + end) / 2); +// const potentialResult = row[middle]; + +// if (potentialResult === target) { +// return true; +// } + +// if (target > potentialResult) { +// start = middle + 1; +// } else { +// end = middle - 1; +// } +// } + +// return false; +// } +// }; diff --git a/solutions/0075-sort-colors.js b/0075-sort-colors.js similarity index 100% rename from solutions/0075-sort-colors.js rename to 0075-sort-colors.js diff --git a/0076-minimum-window-substring.js b/0076-minimum-window-substring.js new file mode 100644 index 00000000..7a5edc9c --- /dev/null +++ b/0076-minimum-window-substring.js @@ -0,0 +1,88 @@ +/** + * 76. Minimum Window Substring + * https://leetcode.com/problems/minimum-window-substring/ + * Difficulty: Hard + * + * Given two strings s and t of lengths m and n respectively, return the minimum window substring + * of s such that every character in t (including duplicates) is included in the window. If there + * is no such substring, return the empty string "". + * + * The testcases will be generated such that the answer is unique. + */ + +/** + * @param {string} s + * @param {string} t + * @return {string} + */ +var minWindow = function(s, t) { + const values = new Array(128).fill(0); + let [start, end] = [-Infinity, Infinity]; + + for (let i = 0; i < t.length; i++) { + values[t.charCodeAt(i)]++; + } + + for (let i = 0, j = 0, total = t.length; i < s.length; i++) { + if (values[s.charCodeAt(i)] > 0) { + total--; + } + values[s.charCodeAt(i)]--; + while (!total) { + if (end - start > i - j) { + [start, end] = [j, i]; + } + values[s.charCodeAt(j)]++; + if (values[s.charCodeAt(j)] > 0) { + total++; + } + j++; + } + } + + return end !== Infinity ? s.slice(start, end + 1) : ''; +}; + +// var minWindow = function(s, t) { +// if (s.length < t.length) { +// return ""; +// } + +// const charCount = new Map(); +// for (const ch of t) { +// charCount.set(ch, (charCount.get(ch) || 0) + 1); +// } + +// let targetCharsRemaining = t.length; +// let minWindow = [0, Number.POSITIVE_INFINITY]; +// let startIndex = 0; + +// for (let endIndex = 0; endIndex < s.length; endIndex++) { +// const ch = s[endIndex]; +// if (charCount.has(ch) && charCount.get(ch) > 0) { +// targetCharsRemaining--; +// } +// charCount.set(ch, (charCount.get(ch) || 0) - 1); + +// if (targetCharsRemaining === 0) { +// while (true) { +// const charAtStart = s[startIndex]; +// if (charCount.has(charAtStart) && charCount.get(charAtStart) === 0) { +// break; +// } +// charCount.set(charAtStart, (charCount.get(charAtStart) || 0) + 1); +// startIndex++; +// } + +// if (endIndex - startIndex < minWindow[1] - minWindow[0]) { +// minWindow = [startIndex, endIndex]; +// } + +// charCount.set(s[startIndex], (charCount.get(s[startIndex]) || 0) + 1); +// targetCharsRemaining++; +// startIndex++; +// } +// } + +// return minWindow[1] >= s.length ? "" : s.slice(minWindow[0], minWindow[1] + 1); +// }; diff --git a/solutions/0077-combinations.js b/0077-combinations.js similarity index 100% rename from solutions/0077-combinations.js rename to 0077-combinations.js diff --git a/solutions/0078-subsets.js b/0078-subsets.js similarity index 100% rename from solutions/0078-subsets.js rename to 0078-subsets.js diff --git a/solutions/0079-word-search.js b/0079-word-search.js similarity index 100% rename from solutions/0079-word-search.js rename to 0079-word-search.js diff --git a/solutions/0080-remove-duplicates-from-sorted-array-ii.js b/0080-remove-duplicates-from-sorted-array-ii.js similarity index 100% rename from solutions/0080-remove-duplicates-from-sorted-array-ii.js rename to 0080-remove-duplicates-from-sorted-array-ii.js diff --git a/solutions/0081-search-in-rotated-sorted-array-ii.js b/0081-search-in-rotated-sorted-array-ii.js similarity index 100% rename from solutions/0081-search-in-rotated-sorted-array-ii.js rename to 0081-search-in-rotated-sorted-array-ii.js diff --git a/solutions/0082-remove-duplicates-from-sorted-list-ii.js b/0082-remove-duplicates-from-sorted-list-ii.js similarity index 100% rename from solutions/0082-remove-duplicates-from-sorted-list-ii.js rename to 0082-remove-duplicates-from-sorted-list-ii.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..4ab63de3 --- /dev/null +++ b/0083-remove-duplicates-from-sorted-list.js @@ -0,0 +1,49 @@ +/** + * 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(); + let tail = result; + + while (head) { + if (head.val !== head.next?.val) { + tail.next = new ListNode(head.val); + tail = tail.next; + } + previous = head.val; + head = head.next; + } + + return result.next; +}; + +// var deleteDuplicates = function(head) { +// let current = head + +// while (current && current.next) { +// if (current.val === current.next.val) { +// current.next = current.next.next +// } else { +// current = current.next +// } +// } + +// return head +// }; diff --git a/solutions/0084-largest-rectangle-in-histogram.js b/0084-largest-rectangle-in-histogram.js similarity index 100% rename from solutions/0084-largest-rectangle-in-histogram.js rename to 0084-largest-rectangle-in-histogram.js diff --git a/solutions/0085-maximal-rectangle.js b/0085-maximal-rectangle.js similarity index 100% rename from solutions/0085-maximal-rectangle.js rename to 0085-maximal-rectangle.js diff --git a/solutions/0086-partition-list.js b/0086-partition-list.js similarity index 100% rename from solutions/0086-partition-list.js rename to 0086-partition-list.js diff --git a/solutions/0087-scramble-string.js b/0087-scramble-string.js similarity index 100% rename from solutions/0087-scramble-string.js rename to 0087-scramble-string.js diff --git a/0088-merge-sorted-array.js b/0088-merge-sorted-array.js new file mode 100644 index 00000000..fd547a93 --- /dev/null +++ b/0088-merge-sorted-array.js @@ -0,0 +1,94 @@ +/** + * 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--]; + } +}; + +// FOWARD +// var merge = function(nums1, m, nums2, n) { +// let result = []; +// let p1 = 0; +// let p2 = 0; + +// while (p1 < m && p2 < n) { +// if (nums1[p1] < nums2[p2]) { +// result.push(nums1[p1]); +// p1++; +// } else { +// result.push(nums2[p2]); +// p2++; +// } +// } + +// while (p1 < m) { +// result.push(nums1[p1]); +// p1++; +// } + +// while (p2 < n) { +// result.push(nums2[p2]); +// p2++; +// } + +// for (let i = 0; i < result.length; i++) { +// nums1[i] = result[i]; +// } + +// return nums1 +// }; + + +// BACKWARD +// var merge = function(nums1, m, nums2, n) { +// let p1 = m - 1; +// let p2 = n - 1; +// let result = m + n - 1; + +// while (p1 >= 0 && p2 >= 0) { +// if (nums1[p1] > nums2[p2]) { +// nums1[result] = nums1[p1]; +// p1--; +// } else { +// nums1[result] = nums2[p2]; +// p2--; +// } +// result--; +// } + +// while (p2 >= 0) { +// nums1[result] = nums2[p2]; +// p2--; +// result--; +// } + +// return nums1 +// }; \ No newline at end of file diff --git a/solutions/0089-gray-code.js b/0089-gray-code.js similarity index 100% rename from solutions/0089-gray-code.js rename to 0089-gray-code.js diff --git a/solutions/0090-subsets-ii.js b/0090-subsets-ii.js similarity index 100% rename from solutions/0090-subsets-ii.js rename to 0090-subsets-ii.js diff --git a/solutions/0091-decode-ways.js b/0091-decode-ways.js similarity index 100% rename from solutions/0091-decode-ways.js rename to 0091-decode-ways.js diff --git a/solutions/0092-reverse-linked-list-ii.js b/0092-reverse-linked-list-ii.js similarity index 100% rename from solutions/0092-reverse-linked-list-ii.js rename to 0092-reverse-linked-list-ii.js diff --git a/solutions/0093-restore-ip-addresses.js b/0093-restore-ip-addresses.js similarity index 100% rename from solutions/0093-restore-ip-addresses.js rename to 0093-restore-ip-addresses.js diff --git a/solutions/0094-binary-tree-inorder-traversal.js b/0094-binary-tree-inorder-traversal.js similarity index 100% rename from solutions/0094-binary-tree-inorder-traversal.js rename to 0094-binary-tree-inorder-traversal.js diff --git a/solutions/0095-unique-binary-search-trees-ii.js b/0095-unique-binary-search-trees-ii.js similarity index 100% rename from solutions/0095-unique-binary-search-trees-ii.js rename to 0095-unique-binary-search-trees-ii.js diff --git a/solutions/0096-unique-binary-search-trees.js b/0096-unique-binary-search-trees.js similarity index 100% rename from solutions/0096-unique-binary-search-trees.js rename to 0096-unique-binary-search-trees.js diff --git a/solutions/0097-interleaving-string.js b/0097-interleaving-string.js similarity index 100% rename from solutions/0097-interleaving-string.js rename to 0097-interleaving-string.js diff --git a/0098-validate-binary-search-tree.js b/0098-validate-binary-search-tree.js new file mode 100644 index 00000000..864276fc --- /dev/null +++ b/0098-validate-binary-search-tree.js @@ -0,0 +1,60 @@ +/** + * 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); +} + +// function isValidBST(root) { +// if (!root) return true; + +// let stack = [[root, -Infinity, Infinity]]; + +// while (stack.length) { +// let [node, minR, maxR] = stack.pop(); +// if (!node) continue; + +// if (node.val <= minR || node.val >= maxR) { +// return false; +// } + +// stack.push([node.left, minR, node.val]); +// stack.push([node.right, node.val, maxR]); +// } + +// return true; +// } diff --git a/solutions/0099-recover-binary-search-tree.js b/0099-recover-binary-search-tree.js similarity index 100% rename from solutions/0099-recover-binary-search-tree.js rename to 0099-recover-binary-search-tree.js diff --git a/solutions/0100-same-tree.js b/0100-same-tree.js similarity index 100% rename from solutions/0100-same-tree.js rename to 0100-same-tree.js diff --git a/0101-symmetric-tree.js b/0101-symmetric-tree.js new file mode 100644 index 00000000..bda84d1b --- /dev/null +++ b/0101-symmetric-tree.js @@ -0,0 +1,57 @@ +/** + * 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); +} + +// Top solver not working +// function isSymmetric(root) { +// if (!root) return true; + +// let stack = [root.left, root.right]; + +// while (stack.length) { +// let right = stack.pop(); +// let left = stack.pop(); + +// if (!left && !right) continue; +// if (!left || !right) return false; +// if (left.val !== right.val) return false; + +// stack.push(left.left); +// stack.push(right.right); +// stack.push(left.right); +// stack.push(right.left); +// } + +// return true; +// } \ No newline at end of file diff --git a/0102-binary-tree-level-order-traversal.js b/0102-binary-tree-level-order-traversal.js new file mode 100644 index 00000000..113f00a4 --- /dev/null +++ b/0102-binary-tree-level-order-traversal.js @@ -0,0 +1,65 @@ +/** + * 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); +} + +// function levelOrder(root) { +// if (!root) return []; + +// let result = []; +// let queue = [root]; + +// while (queue.length) { +// let levelSize = queue.length; +// let currentLevel = []; + +// for (let i = 0; i < levelSize; i++) { +// let node = queue.shift(); +// currentLevel.push(node.val); + +// if (node.left) queue.push(node.left); +// if (node.right) queue.push(node.right); +// } + +// result.push(currentLevel); +// } + +// return result; +// } + diff --git a/solutions/0103-binary-tree-zigzag-level-order-traversal.js b/0103-binary-tree-zigzag-level-order-traversal.js similarity index 100% rename from solutions/0103-binary-tree-zigzag-level-order-traversal.js rename to 0103-binary-tree-zigzag-level-order-traversal.js diff --git a/solutions/0104-maximum-depth-of-binary-tree.js b/0104-maximum-depth-of-binary-tree.js similarity index 82% rename from solutions/0104-maximum-depth-of-binary-tree.js rename to 0104-maximum-depth-of-binary-tree.js index 8b7858e0..388e3912 100644 --- a/solutions/0104-maximum-depth-of-binary-tree.js +++ b/0104-maximum-depth-of-binary-tree.js @@ -28,3 +28,10 @@ var maxDepth = function(root) { const [left, right] = [root.left, root.right].map(maxDepth); return 1 + Math.max(left, right); }; + +// var maxDepth = function(root) { +// if (!root) return 0; +// left = maxDepth(root.left) +// right = maxDepth(root.right) +// return 1 + Math.max(left, right); +// }; diff --git a/solutions/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js b/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js similarity index 100% rename from solutions/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js rename to 0105-construct-binary-tree-from-preorder-and-inorder-traversal.js diff --git a/solutions/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js b/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js similarity index 100% rename from solutions/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js rename to 0106-construct-binary-tree-from-inorder-and-postorder-traversal.js diff --git a/solutions/0107-binary-tree-level-order-traversal-ii.js b/0107-binary-tree-level-order-traversal-ii.js similarity index 100% rename from solutions/0107-binary-tree-level-order-traversal-ii.js rename to 0107-binary-tree-level-order-traversal-ii.js diff --git a/solutions/0108-convert-sorted-array-to-binary-search-tree.js b/0108-convert-sorted-array-to-binary-search-tree.js similarity index 100% rename from solutions/0108-convert-sorted-array-to-binary-search-tree.js rename to 0108-convert-sorted-array-to-binary-search-tree.js diff --git a/solutions/0109-convert-sorted-list-to-binary-search-tree.js b/0109-convert-sorted-list-to-binary-search-tree.js similarity index 100% rename from solutions/0109-convert-sorted-list-to-binary-search-tree.js rename to 0109-convert-sorted-list-to-binary-search-tree.js diff --git a/0110-balanced-binary-tree.js b/0110-balanced-binary-tree.js new file mode 100644 index 00000000..371361f3 --- /dev/null +++ b/0110-balanced-binary-tree.js @@ -0,0 +1,47 @@ +/** + * 110. Balanced Binary Tree + * https://leetcode.com/problems/balanced-binary-tree/ + * Difficulty: Easy + * + * Given a binary tree, determine if it is height-balanced. + */ + +/** + * 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 isBalanced = function(root) { + if (!root) return true; + return isBalanced(root.right) && isBalanced(root.left) + && Math.abs(traverse(root.right) - traverse(root.left)) < 2; +}; + +function traverse(node, depth = 0) { + if (!node) return depth; + return Math.max(traverse(node.right, depth + 1), traverse(node.left, depth + 1)); +} + +// function isBalanced(root) { +// function height(node) { +// if (!node) return 0; +// return 1 + Math.max(height(node.left), height(node.right)); +// } + +// if (!root) return true; + +// let leftH = height(root.left); +// let rightH = height(root.right); + +// if (Math.abs(leftH - rightH) > 1) return false; + +// return isBalanced(root.left) && isBalanced(root.right); +// } + diff --git a/solutions/0111-minimum-depth-of-binary-tree.js b/0111-minimum-depth-of-binary-tree.js similarity index 100% rename from solutions/0111-minimum-depth-of-binary-tree.js rename to 0111-minimum-depth-of-binary-tree.js diff --git a/0112-path-sum.js b/0112-path-sum.js new file mode 100644 index 00000000..d02cb4c8 --- /dev/null +++ b/0112-path-sum.js @@ -0,0 +1,66 @@ +/** + * 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); +} + +// function hasPathSum(root, targetSum) { +// if (!root) return false; + +// let stack = [[root, 0]]; + +// while (stack.length) { +// let [node, currentSum] = stack.pop(); +// if (!node) continue; + +// currentSum += node.val; + +// if (!node.left && !node.right && currentSum === targetSum) { +// return true; +// } + +// stack.push([node.left, currentSum]); +// stack.push([node.right, currentSum]); +// } + +// return false; +// } diff --git a/solutions/0113-path-sum-ii.js b/0113-path-sum-ii.js similarity index 100% rename from solutions/0113-path-sum-ii.js rename to 0113-path-sum-ii.js diff --git a/solutions/0114-flatten-binary-tree-to-linked-list.js b/0114-flatten-binary-tree-to-linked-list.js similarity index 100% rename from solutions/0114-flatten-binary-tree-to-linked-list.js rename to 0114-flatten-binary-tree-to-linked-list.js diff --git a/solutions/0115-distinct-subsequences.js b/0115-distinct-subsequences.js similarity index 100% rename from solutions/0115-distinct-subsequences.js rename to 0115-distinct-subsequences.js diff --git a/solutions/0116-populating-next-right-pointers-in-each-node.js b/0116-populating-next-right-pointers-in-each-node.js similarity index 100% rename from solutions/0116-populating-next-right-pointers-in-each-node.js rename to 0116-populating-next-right-pointers-in-each-node.js diff --git a/solutions/0117-populating-next-right-pointers-in-each-node-ii.js b/0117-populating-next-right-pointers-in-each-node-ii.js similarity index 100% rename from solutions/0117-populating-next-right-pointers-in-each-node-ii.js rename to 0117-populating-next-right-pointers-in-each-node-ii.js diff --git a/solutions/0118-pascals-triangle.js b/0118-pascals-triangle.js similarity index 100% rename from solutions/0118-pascals-triangle.js rename to 0118-pascals-triangle.js diff --git a/solutions/0119-pascals-triangle-ii.js b/0119-pascals-triangle-ii.js similarity index 100% rename from solutions/0119-pascals-triangle-ii.js rename to 0119-pascals-triangle-ii.js diff --git a/solutions/0120-triangle.js b/0120-triangle.js similarity index 100% rename from solutions/0120-triangle.js rename to 0120-triangle.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..d95424ed --- /dev/null +++ b/0121-best-time-to-buy-and-sell-stock.js @@ -0,0 +1,42 @@ +/** + * 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; +}; + +// var maxProfit = function(prices) { +// let max_Profit = 0 +// let current_min = prices[0] + +// for (let i = 0; i < prices.length; i++) { +// let price = prices[i] +// max_Profit = Math.max(max_Profit, price - current_min) +// current_min = Math.min(current_min, price) +// } + +// return max_Profit +// }; \ No newline at end of file diff --git a/solutions/0122-best-time-to-buy-and-sell-stock-ii.js b/0122-best-time-to-buy-and-sell-stock-ii.js similarity index 75% rename from solutions/0122-best-time-to-buy-and-sell-stock-ii.js rename to 0122-best-time-to-buy-and-sell-stock-ii.js index 5f963d71..137657c0 100644 --- a/solutions/0122-best-time-to-buy-and-sell-stock-ii.js +++ b/0122-best-time-to-buy-and-sell-stock-ii.js @@ -22,3 +22,15 @@ var maxProfit = function(prices) { return prices[i - 1] < price ? result + (price - prices[i - 1]) : result; }, 0); }; + +// var maxProfit = function(prices) { +// let profit = 0 + +// for (let i = 1; i < prices.length; i++) { +// if (prices[i] > prices[i - 1]) { +// profit += prices[i] - prices[i - 1] +// } +// } + +// return profit +// }; diff --git a/solutions/0123-best-time-to-buy-and-sell-stock-iii.js b/0123-best-time-to-buy-and-sell-stock-iii.js similarity index 100% rename from solutions/0123-best-time-to-buy-and-sell-stock-iii.js rename to 0123-best-time-to-buy-and-sell-stock-iii.js diff --git a/solutions/0124-binary-tree-maximum-path-sum.js b/0124-binary-tree-maximum-path-sum.js similarity index 100% rename from solutions/0124-binary-tree-maximum-path-sum.js rename to 0124-binary-tree-maximum-path-sum.js diff --git a/0125-valid-palindrome.js b/0125-valid-palindrome.js new file mode 100644 index 00000000..c3a24c19 --- /dev/null +++ b/0125-valid-palindrome.js @@ -0,0 +1,32 @@ +/** + * 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; +}; + + +// s = s.replace(/[^A-Za-z0-9]/g, '').toLowerCase(); +// let left = 0, right = s.length - 1; + +// while (left < right) { +// if (s[left] !== s[right]) return false; +// left++; +// right--; +// } + +// return true; \ No newline at end of file diff --git a/solutions/0126-word-ladder-ii.js b/0126-word-ladder-ii.js similarity index 100% rename from solutions/0126-word-ladder-ii.js rename to 0126-word-ladder-ii.js diff --git a/solutions/0127-word-ladder.js b/0127-word-ladder.js similarity index 100% rename from solutions/0127-word-ladder.js rename to 0127-word-ladder.js diff --git a/solutions/0128-longest-consecutive-sequence.js b/0128-longest-consecutive-sequence.js similarity index 100% rename from solutions/0128-longest-consecutive-sequence.js rename to 0128-longest-consecutive-sequence.js diff --git a/solutions/0129-sum-root-to-leaf-numbers.js b/0129-sum-root-to-leaf-numbers.js similarity index 100% rename from solutions/0129-sum-root-to-leaf-numbers.js rename to 0129-sum-root-to-leaf-numbers.js diff --git a/solutions/0130-surrounded-regions.js b/0130-surrounded-regions.js similarity index 100% rename from solutions/0130-surrounded-regions.js rename to 0130-surrounded-regions.js diff --git a/solutions/0131-palindrome-partitioning.js b/0131-palindrome-partitioning.js similarity index 100% rename from solutions/0131-palindrome-partitioning.js rename to 0131-palindrome-partitioning.js diff --git a/solutions/0132-palindrome-partitioning-ii.js b/0132-palindrome-partitioning-ii.js similarity index 100% rename from solutions/0132-palindrome-partitioning-ii.js rename to 0132-palindrome-partitioning-ii.js diff --git a/solutions/0133-clone-graph.js b/0133-clone-graph.js similarity index 100% rename from solutions/0133-clone-graph.js rename to 0133-clone-graph.js diff --git a/solutions/0134-gas-station.js b/0134-gas-station.js similarity index 100% rename from solutions/0134-gas-station.js rename to 0134-gas-station.js diff --git a/solutions/0135-candy.js b/0135-candy.js similarity index 100% rename from solutions/0135-candy.js rename to 0135-candy.js diff --git a/solutions/0136-single-number.js b/0136-single-number.js similarity index 100% rename from solutions/0136-single-number.js rename to 0136-single-number.js diff --git a/solutions/0137-single-number-ii.js b/0137-single-number-ii.js similarity index 100% rename from solutions/0137-single-number-ii.js rename to 0137-single-number-ii.js diff --git a/solutions/0138-copy-list-with-random-pointer.js b/0138-copy-list-with-random-pointer.js similarity index 100% rename from solutions/0138-copy-list-with-random-pointer.js rename to 0138-copy-list-with-random-pointer.js diff --git a/solutions/0139-word-break.js b/0139-word-break.js similarity index 100% rename from solutions/0139-word-break.js rename to 0139-word-break.js diff --git a/solutions/0140-word-break-ii.js b/0140-word-break-ii.js similarity index 100% rename from solutions/0140-word-break-ii.js rename to 0140-word-break-ii.js diff --git a/solutions/0141-linked-list-cycle.js b/0141-linked-list-cycle.js similarity index 100% rename from solutions/0141-linked-list-cycle.js rename to 0141-linked-list-cycle.js diff --git a/solutions/0142-linked-list-cycle-ii.js b/0142-linked-list-cycle-ii.js similarity index 100% rename from solutions/0142-linked-list-cycle-ii.js rename to 0142-linked-list-cycle-ii.js diff --git a/solutions/0143-reorder-list.js b/0143-reorder-list.js similarity index 76% rename from solutions/0143-reorder-list.js rename to 0143-reorder-list.js index e1739ce2..1838188e 100644 --- a/solutions/0143-reorder-list.js +++ b/0143-reorder-list.js @@ -55,3 +55,27 @@ var reorderList = function(head) { list2 = center1.next; } }; + +// var reorderList = function(head) { +// if (!head) return; + +// const nodes = []; +// let cur = head; +// while (cur) { +// nodes.push(cur); +// cur = cur.next; +// } + +// let i = 0, j = nodes.length - 1; +// while (i < j) { +// nodes[i].next = nodes[j]; +// i++; +// if (i >= j) break; +// nodes[j].next = nodes[i]; +// j--; +// } + +// nodes[i].next = null; + +// return head +// }; diff --git a/solutions/0144-binary-tree-preorder-traversal.js b/0144-binary-tree-preorder-traversal.js similarity index 100% rename from solutions/0144-binary-tree-preorder-traversal.js rename to 0144-binary-tree-preorder-traversal.js diff --git a/solutions/0145-binary-tree-postorder-traversal.js b/0145-binary-tree-postorder-traversal.js similarity index 100% rename from solutions/0145-binary-tree-postorder-traversal.js rename to 0145-binary-tree-postorder-traversal.js diff --git a/solutions/0146-lru-cache.js b/0146-lru-cache.js similarity index 100% rename from solutions/0146-lru-cache.js rename to 0146-lru-cache.js diff --git a/solutions/0147-insertion-sort-list.js b/0147-insertion-sort-list.js similarity index 100% rename from solutions/0147-insertion-sort-list.js rename to 0147-insertion-sort-list.js diff --git a/solutions/0148-sort-list.js b/0148-sort-list.js similarity index 100% rename from solutions/0148-sort-list.js rename to 0148-sort-list.js diff --git a/solutions/0149-max-points-on-a-line.js b/0149-max-points-on-a-line.js similarity index 100% rename from solutions/0149-max-points-on-a-line.js rename to 0149-max-points-on-a-line.js diff --git a/solutions/0150-evaluate-reverse-polish-notation.js b/0150-evaluate-reverse-polish-notation.js similarity index 100% rename from solutions/0150-evaluate-reverse-polish-notation.js rename to 0150-evaluate-reverse-polish-notation.js diff --git a/solutions/0151-reverse-words-in-a-string.js b/0151-reverse-words-in-a-string.js similarity index 100% rename from solutions/0151-reverse-words-in-a-string.js rename to 0151-reverse-words-in-a-string.js diff --git a/solutions/0152-maximum-product-subarray.js b/0152-maximum-product-subarray.js similarity index 100% rename from solutions/0152-maximum-product-subarray.js rename to 0152-maximum-product-subarray.js diff --git a/0153-find-minimum-in-rotated-sorted-array.js b/0153-find-minimum-in-rotated-sorted-array.js new file mode 100644 index 00000000..30fad009 --- /dev/null +++ b/0153-find-minimum-in-rotated-sorted-array.js @@ -0,0 +1,62 @@ +/** + * 153. Find Minimum in Rotated Sorted Array + * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ + * Difficulty: Medium + * + * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. + * For example, the array nums = [0,1,2,4,5,6,7] might become: + * - [4,5,6,7,0,1,2] if it was rotated 4 times. + * - [0,1,2,4,5,6,7] if it was rotated 7 times. + * + * Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array + * [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + * + * Given the sorted rotated array nums of unique elements, return the minimum element of this + * array. + * + * You must write an algorithm that runs in O(log n) time. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function(nums) { + let left = 0; + let right = nums.length - 1; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + + if (nums[mid] <= nums[right]) { + right = mid; + } else { + left = mid + 1; + } + } + + return nums[left]; +}; + +// var findMin = function(nums) { +// let l = 0; +// let r = nums.length - 1; +// let res = nums[0]; + +// while (l <= r) { +// if (nums[l] <= nums[r]) { +// res = Math.min(res, nums[l]); +// break; +// } + +// // let m = l + Math.floor((r - l) / 2); +// let m = Math.floor((l + r) / 2); +// res = Math.min(res, nums[m]); +// if (nums[m] >= nums[l]) { +// l = m + 1; +// } else { +// r = m - 1; +// } +// } +// return res; +// }; diff --git a/solutions/0154-find-minimum-in-rotated-sorted-array-ii.js b/0154-find-minimum-in-rotated-sorted-array-ii.js similarity index 100% rename from solutions/0154-find-minimum-in-rotated-sorted-array-ii.js rename to 0154-find-minimum-in-rotated-sorted-array-ii.js diff --git a/solutions/0155-min-stack.js b/0155-min-stack.js similarity index 100% rename from solutions/0155-min-stack.js rename to 0155-min-stack.js diff --git a/solutions/0160-intersection-of-two-linked-lists.js b/0160-intersection-of-two-linked-lists.js similarity index 100% rename from solutions/0160-intersection-of-two-linked-lists.js rename to 0160-intersection-of-two-linked-lists.js diff --git a/solutions/0162-find-peak-element.js b/0162-find-peak-element.js similarity index 100% rename from solutions/0162-find-peak-element.js rename to 0162-find-peak-element.js diff --git a/solutions/0164-maximum-gap.js b/0164-maximum-gap.js similarity index 100% rename from solutions/0164-maximum-gap.js rename to 0164-maximum-gap.js diff --git a/solutions/0165-compare-version-numbers.js b/0165-compare-version-numbers.js similarity index 100% rename from solutions/0165-compare-version-numbers.js rename to 0165-compare-version-numbers.js diff --git a/solutions/0166-fraction-to-recurring-decimal.js b/0166-fraction-to-recurring-decimal.js similarity index 100% rename from solutions/0166-fraction-to-recurring-decimal.js rename to 0166-fraction-to-recurring-decimal.js diff --git a/solutions/0167-two-sum-ii-input-array-is-sorted.js b/0167-two-sum-ii-input-array-is-sorted.js similarity index 100% rename from solutions/0167-two-sum-ii-input-array-is-sorted.js rename to 0167-two-sum-ii-input-array-is-sorted.js diff --git a/solutions/0168-excel-sheet-column-title.js b/0168-excel-sheet-column-title.js similarity index 100% rename from solutions/0168-excel-sheet-column-title.js rename to 0168-excel-sheet-column-title.js diff --git a/solutions/0169-majority-element.js b/0169-majority-element.js similarity index 100% rename from solutions/0169-majority-element.js rename to 0169-majority-element.js diff --git a/solutions/0171-excel-sheet-column-number.js b/0171-excel-sheet-column-number.js similarity index 100% rename from solutions/0171-excel-sheet-column-number.js rename to 0171-excel-sheet-column-number.js diff --git a/solutions/0172-factorial-trailing-zeroes.js b/0172-factorial-trailing-zeroes.js similarity index 100% rename from solutions/0172-factorial-trailing-zeroes.js rename to 0172-factorial-trailing-zeroes.js diff --git a/solutions/0173-binary-search-tree-iterator.js b/0173-binary-search-tree-iterator.js similarity index 100% rename from solutions/0173-binary-search-tree-iterator.js rename to 0173-binary-search-tree-iterator.js diff --git a/solutions/0174-dungeon-game.js b/0174-dungeon-game.js similarity index 100% rename from solutions/0174-dungeon-game.js rename to 0174-dungeon-game.js diff --git a/solutions/0179-largest-number.js b/0179-largest-number.js similarity index 100% rename from solutions/0179-largest-number.js rename to 0179-largest-number.js diff --git a/solutions/0187-repeated-dna-sequences.js b/0187-repeated-dna-sequences.js similarity index 100% rename from solutions/0187-repeated-dna-sequences.js rename to 0187-repeated-dna-sequences.js diff --git a/solutions/0188-best-time-to-buy-and-sell-stock-iv.js b/0188-best-time-to-buy-and-sell-stock-iv.js similarity index 100% rename from solutions/0188-best-time-to-buy-and-sell-stock-iv.js rename to 0188-best-time-to-buy-and-sell-stock-iv.js diff --git a/0189-rotate-array.js b/0189-rotate-array.js new file mode 100644 index 00000000..9fed54f0 --- /dev/null +++ b/0189-rotate-array.js @@ -0,0 +1,30 @@ +/** + * 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)); +}; + +// var rotate = function(nums, k) { +// const n = nums.length; +// k = k % n; +// const rotated = new Array(n).fill(0); + +// for (let i = 0; i < n; i++) { +// rotated[(i + k) % n] = nums[i]; +// } + +// for (let i = 0; i < n; i++) { +// nums[i] = rotated[i]; +// } +// }; \ No newline at end of file diff --git a/solutions/0190-reverse-bits.js b/0190-reverse-bits.js similarity index 100% rename from solutions/0190-reverse-bits.js rename to 0190-reverse-bits.js diff --git a/solutions/0191-number-of-1-bits.js b/0191-number-of-1-bits.js similarity index 100% rename from solutions/0191-number-of-1-bits.js rename to 0191-number-of-1-bits.js diff --git a/solutions/0198-house-robber.js b/0198-house-robber.js similarity index 100% rename from solutions/0198-house-robber.js rename to 0198-house-robber.js diff --git a/solutions/0199-binary-tree-right-side-view.js b/0199-binary-tree-right-side-view.js similarity index 100% rename from solutions/0199-binary-tree-right-side-view.js rename to 0199-binary-tree-right-side-view.js diff --git a/solutions/0200-number-of-islands.js b/0200-number-of-islands.js similarity index 100% rename from solutions/0200-number-of-islands.js rename to 0200-number-of-islands.js diff --git a/solutions/0201-bitwise-and-of-numbers-range.js b/0201-bitwise-and-of-numbers-range.js similarity index 100% rename from solutions/0201-bitwise-and-of-numbers-range.js rename to 0201-bitwise-and-of-numbers-range.js diff --git a/solutions/0202-happy-number.js b/0202-happy-number.js similarity index 100% rename from solutions/0202-happy-number.js rename to 0202-happy-number.js diff --git a/solutions/0203-remove-linked-list-elements.js b/0203-remove-linked-list-elements.js similarity index 100% rename from solutions/0203-remove-linked-list-elements.js rename to 0203-remove-linked-list-elements.js diff --git a/solutions/0204-count-primes.js b/0204-count-primes.js similarity index 100% rename from solutions/0204-count-primes.js rename to 0204-count-primes.js diff --git a/solutions/0205-isomorphic-strings.js b/0205-isomorphic-strings.js similarity index 100% rename from solutions/0205-isomorphic-strings.js rename to 0205-isomorphic-strings.js diff --git a/solutions/0206-reverse-linked-list.js b/0206-reverse-linked-list.js similarity index 100% rename from solutions/0206-reverse-linked-list.js rename to 0206-reverse-linked-list.js diff --git a/solutions/0207-course-schedule.js b/0207-course-schedule.js similarity index 100% rename from solutions/0207-course-schedule.js rename to 0207-course-schedule.js diff --git a/solutions/0208-implement-trie-prefix-tree.js b/0208-implement-trie-prefix-tree.js similarity index 100% rename from solutions/0208-implement-trie-prefix-tree.js rename to 0208-implement-trie-prefix-tree.js diff --git a/0209-minimum-size-subarray-sum.js b/0209-minimum-size-subarray-sum.js new file mode 100644 index 00000000..884019d9 --- /dev/null +++ b/0209-minimum-size-subarray-sum.js @@ -0,0 +1,49 @@ +/** + * 209. Minimum Size Subarray Sum + * https://leetcode.com/problems/minimum-size-subarray-sum/ + * Difficulty: Medium + * + * Given an array of positive integers nums and a positive integer target, return the + * minimal length of a subarray whose sum is greater than or equal to target. If there + * is no such subarray, return 0 instead. + */ + +/** + * @param {number} target + * @param {number[]} nums + * @return {number} + */ +var minSubArrayLen = function(target, nums) { + let result = Infinity; + + for (let right = 0, sum = 0, left = 0; right < nums.length; right++) { + sum += nums[right]; + while (sum >= target) { + result = Math.min(result, right - left + 1); + sum -= nums[left]; + left++; + } + } + + return result === Infinity ? 0 : result; +}; + +// var minSubArrayLen = function(target, nums) { +// let begin = 0 +// let window_state = 0 +// let result = Infinity; + +// for (let end = 0; end < nums.length; end++) { +// window_state += nums[end] + +// while (window_state >= target) { +// let window_size = end - begin + 1 +// result = Math.min(result, window_size) +// window_state -= nums[begin] +// begin++ +// } +// } + +// if (result === Infinity) return 0 +// return result +// }; \ No newline at end of file diff --git a/solutions/0210-course-schedule-ii.js b/0210-course-schedule-ii.js similarity index 100% rename from solutions/0210-course-schedule-ii.js rename to 0210-course-schedule-ii.js diff --git a/solutions/0211-design-add-and-search-words-data-structure.js b/0211-design-add-and-search-words-data-structure.js similarity index 100% rename from solutions/0211-design-add-and-search-words-data-structure.js rename to 0211-design-add-and-search-words-data-structure.js diff --git a/solutions/0212-word-search-ii.js b/0212-word-search-ii.js similarity index 100% rename from solutions/0212-word-search-ii.js rename to 0212-word-search-ii.js diff --git a/solutions/0213-house-robber-ii.js b/0213-house-robber-ii.js similarity index 100% rename from solutions/0213-house-robber-ii.js rename to 0213-house-robber-ii.js diff --git a/solutions/0214-shortest-palindrome.js b/0214-shortest-palindrome.js similarity index 100% rename from solutions/0214-shortest-palindrome.js rename to 0214-shortest-palindrome.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..3f2558ce --- /dev/null +++ b/0215-kth-largest-element-in-an-array.js @@ -0,0 +1,48 @@ +/** + * 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]; +}; + +// var findKthLargest = function(nums, k) { + +// const min_heap = new MinHeapAdhoc(); + +// for (const num of nums) { +// min_heap.add(num) +// if (min_heap.heap.length > k) { +// min_heap.poll(); +// } +// } + +// return min_heap.heap[0] +// }; + + +// var findKthLargest = function(nums, k) { + +// const max_heap = new MaxHeapAdhoc(); + +// for (const num of nums) { +// max_heap.add(num) +// } + +// for (let i = 0; i < k - 1; i++) { +// max_heap.poll(); +// } + +// return max_heap.heap[0] +// }; diff --git a/solutions/0216-combination-sum-iii.js b/0216-combination-sum-iii.js similarity index 100% rename from solutions/0216-combination-sum-iii.js rename to 0216-combination-sum-iii.js diff --git a/0217-contains-duplicate.js b/0217-contains-duplicate.js new file mode 100644 index 00000000..4b2bae35 --- /dev/null +++ b/0217-contains-duplicate.js @@ -0,0 +1,27 @@ +/** + * 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; +}; + +// var containsDuplicate = function(nums) { +// const set = new Set() +// for (let i = 0; i < nums.length; i++) { +// if (set.has(nums[i])) { +// return true +// } +// set.add(nums[i], i) +// } +// return false +// } diff --git a/solutions/0218-the-skyline-problem.js b/0218-the-skyline-problem.js similarity index 100% rename from solutions/0218-the-skyline-problem.js rename to 0218-the-skyline-problem.js diff --git a/solutions/0219-contains-duplicate-ii.js b/0219-contains-duplicate-ii.js similarity index 100% rename from solutions/0219-contains-duplicate-ii.js rename to 0219-contains-duplicate-ii.js diff --git a/solutions/0220-contains-duplicate-iii.js b/0220-contains-duplicate-iii.js similarity index 100% rename from solutions/0220-contains-duplicate-iii.js rename to 0220-contains-duplicate-iii.js diff --git a/solutions/0221-maximal-square.js b/0221-maximal-square.js similarity index 100% rename from solutions/0221-maximal-square.js rename to 0221-maximal-square.js diff --git a/solutions/0222-count-complete-tree-nodes.js b/0222-count-complete-tree-nodes.js similarity index 100% rename from solutions/0222-count-complete-tree-nodes.js rename to 0222-count-complete-tree-nodes.js diff --git a/solutions/0223-rectangle-area.js b/0223-rectangle-area.js similarity index 100% rename from solutions/0223-rectangle-area.js rename to 0223-rectangle-area.js diff --git a/solutions/0224-basic-calculator.js b/0224-basic-calculator.js similarity index 100% rename from solutions/0224-basic-calculator.js rename to 0224-basic-calculator.js diff --git a/solutions/0225-implement-stack-using-queues.js b/0225-implement-stack-using-queues.js similarity index 100% rename from solutions/0225-implement-stack-using-queues.js rename to 0225-implement-stack-using-queues.js diff --git a/0226-invert-binary-tree.js b/0226-invert-binary-tree.js new file mode 100644 index 00000000..940c6d95 --- /dev/null +++ b/0226-invert-binary-tree.js @@ -0,0 +1,46 @@ +/** + * 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; +}; + +// var invertTree = function(root) { +// if (root === null) return null; + +// const node = new TreeNode(root.value); + +// node.right = invertTree(root.left); +// node.left = invertTree(root.right); + +// return node; +// }; + +// var invertTree = function(root) { +// if (root == null) return null; +// const queue = new Queue([root]); +// while (!queue.isEmpty()) { +// let node = queue.pop(); +// [node.left, node.right] = [node.right, node.left]; +// if (node.left != null) queue.push(node.left); +// if (node.right != null) queue.push(node.right); +// } +// return root; +// } diff --git a/solutions/0227-basic-calculator-ii.js b/0227-basic-calculator-ii.js similarity index 100% rename from solutions/0227-basic-calculator-ii.js rename to 0227-basic-calculator-ii.js diff --git a/solutions/0228-summary-ranges.js b/0228-summary-ranges.js similarity index 100% rename from solutions/0228-summary-ranges.js rename to 0228-summary-ranges.js diff --git a/solutions/0229-majority-element-ii.js b/0229-majority-element-ii.js similarity index 100% rename from solutions/0229-majority-element-ii.js rename to 0229-majority-element-ii.js diff --git a/solutions/0230-kth-smallest-element-in-a-bst.js b/0230-kth-smallest-element-in-a-bst.js similarity index 100% rename from solutions/0230-kth-smallest-element-in-a-bst.js rename to 0230-kth-smallest-element-in-a-bst.js diff --git a/solutions/0231-power-of-two.js b/0231-power-of-two.js similarity index 100% rename from solutions/0231-power-of-two.js rename to 0231-power-of-two.js diff --git a/solutions/0232-implement-queue-using-stacks.js b/0232-implement-queue-using-stacks.js similarity index 100% rename from solutions/0232-implement-queue-using-stacks.js rename to 0232-implement-queue-using-stacks.js diff --git a/solutions/0233-number-of-digit-one.js b/0233-number-of-digit-one.js similarity index 100% rename from solutions/0233-number-of-digit-one.js rename to 0233-number-of-digit-one.js diff --git a/0234-palindrome-linked-list.js b/0234-palindrome-linked-list.js new file mode 100644 index 00000000..bed51189 --- /dev/null +++ b/0234-palindrome-linked-list.js @@ -0,0 +1,73 @@ +/** + * 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; +}; + +// var isPalindrome = function(head) { +// var middle = function(head) { +// let slow = head; +// let fast = head; + +// while (fast && fast.next) { +// slow = slow.next; +// fast = fast.next.next; +// } + +// return slow; +// } + +// var reverse = function(head) { +// let prev = null; +// let tail = head; + +// while (tail) { +// const next = tail.next; +// tail.next = prev; +// prev = tail; +// tail = next; +// } + +// return prev; +// } + +// mid = middle(head) +// second = reverse(mid) +// first = head + +// while (first && second) { +// // !!! value, val +// if (first.value !== second.value) { +// return false +// } +// first = first.next +// second = second.next +// } + +// return true +// }; \ No newline at end of file diff --git a/solutions/0235-lowest-common-ancestor-of-a-binary-search-tree.js b/0235-lowest-common-ancestor-of-a-binary-search-tree.js similarity index 100% rename from solutions/0235-lowest-common-ancestor-of-a-binary-search-tree.js rename to 0235-lowest-common-ancestor-of-a-binary-search-tree.js diff --git a/solutions/0236-lowest-common-ancestor-of-a-binary-tree.js b/0236-lowest-common-ancestor-of-a-binary-tree.js similarity index 100% rename from solutions/0236-lowest-common-ancestor-of-a-binary-tree.js rename to 0236-lowest-common-ancestor-of-a-binary-tree.js diff --git a/solutions/0237-delete-node-in-a-linked-list.js b/0237-delete-node-in-a-linked-list.js similarity index 100% rename from solutions/0237-delete-node-in-a-linked-list.js rename to 0237-delete-node-in-a-linked-list.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..79914964 --- /dev/null +++ b/0238-product-of-array-except-self.js @@ -0,0 +1,56 @@ +/** + * 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); +}; + +// https://leetcode.com/discuss/study-guide/5119937/prefix-sum-problems + +// Brute Force +// var productExceptSelf = function (nums) { +// const n = nums.length; +// const res = new Array(n); + +// for (let i = 0; i < n; i++) { +// let prod = 1; +// for (let j = 0; j < n; j++) { +// if (i !== j) { +// prod *= nums[j]; +// } +// } +// res[i] = prod; +// } +// return res; +// }; + +// https://neetcode.io/problems/products-of-array-discluding-self +// https://www.youtube.com/watch?v=yuws7YK0Yng + +// 2. Division +// 3. Prefix & Suffix +// 4. Prefix & Suffix (Optimal) \ No newline at end of file diff --git a/0239-sliding-window-maximum.js b/0239-sliding-window-maximum.js new file mode 100644 index 00000000..45ab46fb --- /dev/null +++ b/0239-sliding-window-maximum.js @@ -0,0 +1,60 @@ +/** + * 239. Sliding Window Maximum + * https://leetcode.com/problems/sliding-window-maximum/ + * Difficulty: Hard + * + * You are given an array of integers nums, there is a sliding window of size k which is moving + * from the very left of the array to the very right. You can only see the k numbers in the + * window. Each time the sliding window moves right by one position. + * + * Return the max sliding window. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function(nums, k) { + const result = []; + const queue = []; + + for (let i = 0; i < nums.length; i++) { + while (queue.length && queue[0] < i - k + 1) { + queue.shift(); + } + while (queue.length && nums[queue[queue.length - 1]] < nums[i]) { + queue.pop(); + } + queue.push(i); + if (i >= k - 1) { + result.push(nums[queue[0]]); + } + } + + return result; +}; + +// var maxSlidingWindow = function(nums, k) { +// let res = []; +// let deque = []; + +// for (let idx = 0; idx < nums.length; idx++) { +// let num = nums[idx]; + +// while (deque.length && deque[deque.length - 1] < num) { +// deque.pop(); +// } +// deque.push(num); + +// if (idx >= k && nums[idx - k] === deque[0]) { +// deque.shift(); +// } + +// if (idx >= k - 1) { +// res.push(deque[0]); +// } +// } + +// return res; +// }; diff --git a/solutions/0240-search-a-2d-matrix-ii.js b/0240-search-a-2d-matrix-ii.js similarity index 100% rename from solutions/0240-search-a-2d-matrix-ii.js rename to 0240-search-a-2d-matrix-ii.js diff --git a/solutions/0241-different-ways-to-add-parentheses.js b/0241-different-ways-to-add-parentheses.js similarity index 100% rename from solutions/0241-different-ways-to-add-parentheses.js rename to 0241-different-ways-to-add-parentheses.js diff --git a/0242-valid-anagram.js b/0242-valid-anagram.js new file mode 100644 index 00000000..4a5403a8 --- /dev/null +++ b/0242-valid-anagram.js @@ -0,0 +1,37 @@ +/** + * 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); +}; + +// var isAnagram = function(s, t) { +// if (s.length !== t.length) { +// return false; +// } + +// const countS = {}; +// const countT = {}; +// for (let i = 0; i < s.length; i++) { +// countS[s[i]] = (countS[s[i]] || 0) + 1; +// countT[t[i]] = (countT[t[i]] || 0) + 1; +// } + +// for (const key in countS) { +// if (countS[key] !== countT[key]) { +// return false; +// } +// } +// return true; +// } diff --git a/solutions/0257-binary-tree-paths.js b/0257-binary-tree-paths.js similarity index 100% rename from solutions/0257-binary-tree-paths.js rename to 0257-binary-tree-paths.js diff --git a/solutions/0258-add-digits.js b/0258-add-digits.js similarity index 100% rename from solutions/0258-add-digits.js rename to 0258-add-digits.js diff --git a/solutions/0260-single-number-iii.js b/0260-single-number-iii.js similarity index 100% rename from solutions/0260-single-number-iii.js rename to 0260-single-number-iii.js diff --git a/solutions/0263-ugly-number.js b/0263-ugly-number.js similarity index 100% rename from solutions/0263-ugly-number.js rename to 0263-ugly-number.js diff --git a/solutions/0264-ugly-number-ii.js b/0264-ugly-number-ii.js similarity index 100% rename from solutions/0264-ugly-number-ii.js rename to 0264-ugly-number-ii.js diff --git a/solutions/0268-missing-number.js b/0268-missing-number.js similarity index 100% rename from solutions/0268-missing-number.js rename to 0268-missing-number.js diff --git a/solutions/0273-integer-to-english-words.js b/0273-integer-to-english-words.js similarity index 100% rename from solutions/0273-integer-to-english-words.js rename to 0273-integer-to-english-words.js diff --git a/solutions/0274-h-index.js b/0274-h-index.js similarity index 100% rename from solutions/0274-h-index.js rename to 0274-h-index.js diff --git a/solutions/0275-h-index-ii.js b/0275-h-index-ii.js similarity index 100% rename from solutions/0275-h-index-ii.js rename to 0275-h-index-ii.js diff --git a/solutions/0278-first-bad-version.js b/0278-first-bad-version.js similarity index 100% rename from solutions/0278-first-bad-version.js rename to 0278-first-bad-version.js diff --git a/solutions/0279-perfect-squares.js b/0279-perfect-squares.js similarity index 100% rename from solutions/0279-perfect-squares.js rename to 0279-perfect-squares.js diff --git a/solutions/0282-expression-add-operators.js b/0282-expression-add-operators.js similarity index 100% rename from solutions/0282-expression-add-operators.js rename to 0282-expression-add-operators.js diff --git a/0283-move-zeroes.js b/0283-move-zeroes.js new file mode 100644 index 00000000..6a04291e --- /dev/null +++ b/0283-move-zeroes.js @@ -0,0 +1,35 @@ +/** + * 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) { + [nums[i], nums[j++]] = [nums[j], nums[i]]; + } + } +}; + +// write and reed +// var moveZeroes = function(nums) { +// let w = 0; +// for (let r = 0; r < nums.length; r++) { +// if (nums[r] !== 0) { +// [nums[w], nums[r]] = [nums[r], nums[w]]; +// w=w+1 +// } +// } + +// return nums +// }; \ No newline at end of file diff --git a/solutions/0284-peeking-iterator.js b/0284-peeking-iterator.js similarity index 100% rename from solutions/0284-peeking-iterator.js rename to 0284-peeking-iterator.js diff --git a/solutions/0287-find-the-duplicate-number.js b/0287-find-the-duplicate-number.js similarity index 100% rename from solutions/0287-find-the-duplicate-number.js rename to 0287-find-the-duplicate-number.js diff --git a/solutions/0289-game-of-life.js b/0289-game-of-life.js similarity index 100% rename from solutions/0289-game-of-life.js rename to 0289-game-of-life.js diff --git a/solutions/0290-word-pattern.js b/0290-word-pattern.js similarity index 100% rename from solutions/0290-word-pattern.js rename to 0290-word-pattern.js diff --git a/solutions/0292-nim-game.js b/0292-nim-game.js similarity index 100% rename from solutions/0292-nim-game.js rename to 0292-nim-game.js diff --git a/solutions/0295-find-median-from-data-stream.js b/0295-find-median-from-data-stream.js similarity index 100% rename from solutions/0295-find-median-from-data-stream.js rename to 0295-find-median-from-data-stream.js diff --git a/solutions/0297-serialize-and-deserialize-binary-tree.js b/0297-serialize-and-deserialize-binary-tree.js similarity index 100% rename from solutions/0297-serialize-and-deserialize-binary-tree.js rename to 0297-serialize-and-deserialize-binary-tree.js diff --git a/solutions/0299-bulls-and-cows.js b/0299-bulls-and-cows.js similarity index 100% rename from solutions/0299-bulls-and-cows.js rename to 0299-bulls-and-cows.js diff --git a/solutions/0300-longest-increasing-subsequence.js b/0300-longest-increasing-subsequence.js similarity index 100% rename from solutions/0300-longest-increasing-subsequence.js rename to 0300-longest-increasing-subsequence.js diff --git a/solutions/0301-remove-invalid-parentheses.js b/0301-remove-invalid-parentheses.js similarity index 100% rename from solutions/0301-remove-invalid-parentheses.js rename to 0301-remove-invalid-parentheses.js diff --git a/solutions/0303-range-sum-query-immutable.js b/0303-range-sum-query-immutable.js similarity index 100% rename from solutions/0303-range-sum-query-immutable.js rename to 0303-range-sum-query-immutable.js diff --git a/solutions/0304-range-sum-query-2d-immutable.js b/0304-range-sum-query-2d-immutable.js similarity index 100% rename from solutions/0304-range-sum-query-2d-immutable.js rename to 0304-range-sum-query-2d-immutable.js diff --git a/solutions/0306-additive-number.js b/0306-additive-number.js similarity index 100% rename from solutions/0306-additive-number.js rename to 0306-additive-number.js diff --git a/solutions/0307-range-sum-query-mutable.js b/0307-range-sum-query-mutable.js similarity index 100% rename from solutions/0307-range-sum-query-mutable.js rename to 0307-range-sum-query-mutable.js diff --git a/solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.js b/0309-best-time-to-buy-and-sell-stock-with-cooldown.js similarity index 100% rename from solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.js rename to 0309-best-time-to-buy-and-sell-stock-with-cooldown.js diff --git a/solutions/0310-minimum-height-trees.js b/0310-minimum-height-trees.js similarity index 100% rename from solutions/0310-minimum-height-trees.js rename to 0310-minimum-height-trees.js diff --git a/solutions/0312-burst-balloons.js b/0312-burst-balloons.js similarity index 100% rename from solutions/0312-burst-balloons.js rename to 0312-burst-balloons.js diff --git a/solutions/0313-super-ugly-number.js b/0313-super-ugly-number.js similarity index 100% rename from solutions/0313-super-ugly-number.js rename to 0313-super-ugly-number.js diff --git a/solutions/0315-count-of-smaller-numbers-after-self.js b/0315-count-of-smaller-numbers-after-self.js similarity index 100% rename from solutions/0315-count-of-smaller-numbers-after-self.js rename to 0315-count-of-smaller-numbers-after-self.js diff --git a/solutions/0316-remove-duplicate-letters.js b/0316-remove-duplicate-letters.js similarity index 100% rename from solutions/0316-remove-duplicate-letters.js rename to 0316-remove-duplicate-letters.js diff --git a/solutions/0318-maximum-product-of-word-lengths.js b/0318-maximum-product-of-word-lengths.js similarity index 100% rename from solutions/0318-maximum-product-of-word-lengths.js rename to 0318-maximum-product-of-word-lengths.js diff --git a/solutions/0319-bulb-switcher.js b/0319-bulb-switcher.js similarity index 100% rename from solutions/0319-bulb-switcher.js rename to 0319-bulb-switcher.js diff --git a/solutions/0321-create-maximum-number.js b/0321-create-maximum-number.js similarity index 100% rename from solutions/0321-create-maximum-number.js rename to 0321-create-maximum-number.js diff --git a/solutions/0322-coin-change.js b/0322-coin-change.js similarity index 100% rename from solutions/0322-coin-change.js rename to 0322-coin-change.js diff --git a/solutions/0324-wiggle-sort-ii.js b/0324-wiggle-sort-ii.js similarity index 100% rename from solutions/0324-wiggle-sort-ii.js rename to 0324-wiggle-sort-ii.js diff --git a/solutions/0326-power-of-three.js b/0326-power-of-three.js similarity index 100% rename from solutions/0326-power-of-three.js rename to 0326-power-of-three.js diff --git a/solutions/0327-count-of-range-sum.js b/0327-count-of-range-sum.js similarity index 100% rename from solutions/0327-count-of-range-sum.js rename to 0327-count-of-range-sum.js diff --git a/solutions/0328-odd-even-linked-list.js b/0328-odd-even-linked-list.js similarity index 100% rename from solutions/0328-odd-even-linked-list.js rename to 0328-odd-even-linked-list.js diff --git a/solutions/0329-longest-increasing-path-in-a-matrix.js b/0329-longest-increasing-path-in-a-matrix.js similarity index 100% rename from solutions/0329-longest-increasing-path-in-a-matrix.js rename to 0329-longest-increasing-path-in-a-matrix.js diff --git a/solutions/0330-patching-array.js b/0330-patching-array.js similarity index 100% rename from solutions/0330-patching-array.js rename to 0330-patching-array.js diff --git a/solutions/0331-verify-preorder-serialization-of-a-binary-tree.js b/0331-verify-preorder-serialization-of-a-binary-tree.js similarity index 100% rename from solutions/0331-verify-preorder-serialization-of-a-binary-tree.js rename to 0331-verify-preorder-serialization-of-a-binary-tree.js diff --git a/solutions/0332-reconstruct-itinerary.js b/0332-reconstruct-itinerary.js similarity index 100% rename from solutions/0332-reconstruct-itinerary.js rename to 0332-reconstruct-itinerary.js diff --git a/solutions/0334-increasing-triplet-subsequence.js b/0334-increasing-triplet-subsequence.js similarity index 100% rename from solutions/0334-increasing-triplet-subsequence.js rename to 0334-increasing-triplet-subsequence.js diff --git a/solutions/0335-self-crossing.js b/0335-self-crossing.js similarity index 100% rename from solutions/0335-self-crossing.js rename to 0335-self-crossing.js diff --git a/solutions/0336-palindrome-pairs.js b/0336-palindrome-pairs.js similarity index 100% rename from solutions/0336-palindrome-pairs.js rename to 0336-palindrome-pairs.js diff --git a/solutions/0337-house-robber-iii.js b/0337-house-robber-iii.js similarity index 100% rename from solutions/0337-house-robber-iii.js rename to 0337-house-robber-iii.js diff --git a/solutions/0338-counting-bits.js b/0338-counting-bits.js similarity index 100% rename from solutions/0338-counting-bits.js rename to 0338-counting-bits.js diff --git a/solutions/0341-flatten-nested-list-iterator.js b/0341-flatten-nested-list-iterator.js similarity index 100% rename from solutions/0341-flatten-nested-list-iterator.js rename to 0341-flatten-nested-list-iterator.js diff --git a/solutions/0342-power-of-four.js b/0342-power-of-four.js similarity index 100% rename from solutions/0342-power-of-four.js rename to 0342-power-of-four.js diff --git a/solutions/0343-integer-break.js b/0343-integer-break.js similarity index 100% rename from solutions/0343-integer-break.js rename to 0343-integer-break.js diff --git a/solutions/0344-reverse-string.js b/0344-reverse-string.js similarity index 77% rename from solutions/0344-reverse-string.js rename to 0344-reverse-string.js index e459e954..9685e42a 100644 --- a/solutions/0344-reverse-string.js +++ b/0344-reverse-string.js @@ -18,3 +18,11 @@ var reverseString = function(s) { [s[s.length - 1 - i], s[i]] = [s[i], s[s.length - 1 - i]]; } }; + +// let left = 0, right = s.length - 1; +// while (left < right) { +// [s[left], s[right]] = [s[right], s[left]]; +// left++; +// right--; +// } +// return s diff --git a/solutions/0345-reverse-vowels-of-a-string.js b/0345-reverse-vowels-of-a-string.js similarity index 100% rename from solutions/0345-reverse-vowels-of-a-string.js rename to 0345-reverse-vowels-of-a-string.js diff --git a/0347-top-k-frequent-elements.js b/0347-top-k-frequent-elements.js new file mode 100644 index 00000000..f98077e5 --- /dev/null +++ b/0347-top-k-frequent-elements.js @@ -0,0 +1,76 @@ +/** + * 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) +}; + +/** + * Почему Map + Sort быстрее на малых данных + * 1. Оптимизированные встроенные методы JS + * 2. Низкий константный оверхед + * 3. Быстродействие Map в JS + * 4. JS-движки оптимизируют Map + sort() + */ +// Bucket sort +// var topKFrequent = function (nums, k) { +// const count = {}; +// const freq = Array.from({ length: nums.length + 1 }, () => []); + +// for (const n of nums) { +// count[n] = (count[n] || 0) + 1; +// } +// for (const n in count) { +// freq[count[n]].push(parseInt(n)); +// } + +// const res = []; +// for (let i = freq.length - 1; i > 0; i--) { +// for (const n of freq[i]) { +// res.push(n); +// if (res.length === k) { +// return res; +// } +// } +// } +// }; + +// var topKFrequent = function(nums, k) { +// const freqMap = new Map(); + +// // Подсчёт частоты элементов +// for (const num of nums) { +// freqMap.set(num, (freqMap.get(num) || 0) + 1); +// } + +// const minHeap = new MinHeapAdhoc(); + +// // Заполняем хипу +// for (const [num, freq] of freqMap.entries()) { +// minHeap.add([freq, num]); +// if (minHeap.heap.length > k) { +// minHeap.poll(); +// } +// } + +// // Извлекаем k самых частых элементов +// return minHeap.heap.map(item => item[1]); +// }; diff --git a/solutions/0349-intersection-of-two-arrays.js b/0349-intersection-of-two-arrays.js similarity index 100% rename from solutions/0349-intersection-of-two-arrays.js rename to 0349-intersection-of-two-arrays.js diff --git a/solutions/0350-intersection-of-two-arrays-ii.js b/0350-intersection-of-two-arrays-ii.js similarity index 100% rename from solutions/0350-intersection-of-two-arrays-ii.js rename to 0350-intersection-of-two-arrays-ii.js diff --git a/solutions/0352-data-stream-as-disjoint-intervals.js b/0352-data-stream-as-disjoint-intervals.js similarity index 100% rename from solutions/0352-data-stream-as-disjoint-intervals.js rename to 0352-data-stream-as-disjoint-intervals.js diff --git a/solutions/0354-russian-doll-envelopes.js b/0354-russian-doll-envelopes.js similarity index 100% rename from solutions/0354-russian-doll-envelopes.js rename to 0354-russian-doll-envelopes.js diff --git a/solutions/0355-design-twitter.js b/0355-design-twitter.js similarity index 100% rename from solutions/0355-design-twitter.js rename to 0355-design-twitter.js diff --git a/solutions/0357-count-numbers-with-unique-digits.js b/0357-count-numbers-with-unique-digits.js similarity index 100% rename from solutions/0357-count-numbers-with-unique-digits.js rename to 0357-count-numbers-with-unique-digits.js diff --git a/solutions/0363-max-sum-of-rectangle-no-larger-than-k.js b/0363-max-sum-of-rectangle-no-larger-than-k.js similarity index 100% rename from solutions/0363-max-sum-of-rectangle-no-larger-than-k.js rename to 0363-max-sum-of-rectangle-no-larger-than-k.js diff --git a/solutions/0365-water-and-jug-problem.js b/0365-water-and-jug-problem.js similarity index 100% rename from solutions/0365-water-and-jug-problem.js rename to 0365-water-and-jug-problem.js diff --git a/solutions/0367-valid-perfect-square.js b/0367-valid-perfect-square.js similarity index 100% rename from solutions/0367-valid-perfect-square.js rename to 0367-valid-perfect-square.js diff --git a/solutions/0368-largest-divisible-subset.js b/0368-largest-divisible-subset.js similarity index 100% rename from solutions/0368-largest-divisible-subset.js rename to 0368-largest-divisible-subset.js diff --git a/solutions/0371-sum-of-two-integers.js b/0371-sum-of-two-integers.js similarity index 100% rename from solutions/0371-sum-of-two-integers.js rename to 0371-sum-of-two-integers.js diff --git a/solutions/0372-super-pow.js b/0372-super-pow.js similarity index 100% rename from solutions/0372-super-pow.js rename to 0372-super-pow.js diff --git a/solutions/0373-find-k-pairs-with-smallest-sums.js b/0373-find-k-pairs-with-smallest-sums.js similarity index 100% rename from solutions/0373-find-k-pairs-with-smallest-sums.js rename to 0373-find-k-pairs-with-smallest-sums.js diff --git a/solutions/0374-guess-number-higher-or-lower.js b/0374-guess-number-higher-or-lower.js similarity index 100% rename from solutions/0374-guess-number-higher-or-lower.js rename to 0374-guess-number-higher-or-lower.js diff --git a/solutions/0375-guess-number-higher-or-lower-ii.js b/0375-guess-number-higher-or-lower-ii.js similarity index 100% rename from solutions/0375-guess-number-higher-or-lower-ii.js rename to 0375-guess-number-higher-or-lower-ii.js diff --git a/solutions/0376-wiggle-subsequence.js b/0376-wiggle-subsequence.js similarity index 100% rename from solutions/0376-wiggle-subsequence.js rename to 0376-wiggle-subsequence.js diff --git a/solutions/0377-combination-sum-iv.js b/0377-combination-sum-iv.js similarity index 100% rename from solutions/0377-combination-sum-iv.js rename to 0377-combination-sum-iv.js diff --git a/solutions/0378-kth-smallest-element-in-a-sorted-matrix.js b/0378-kth-smallest-element-in-a-sorted-matrix.js similarity index 100% rename from solutions/0378-kth-smallest-element-in-a-sorted-matrix.js rename to 0378-kth-smallest-element-in-a-sorted-matrix.js diff --git a/solutions/0380-insert-delete-getrandom-o1.js b/0380-insert-delete-getrandom-o1.js similarity index 100% rename from solutions/0380-insert-delete-getrandom-o1.js rename to 0380-insert-delete-getrandom-o1.js diff --git a/solutions/0381-insert-delete-getrandom-o1-duplicates-allowed.js b/0381-insert-delete-getrandom-o1-duplicates-allowed.js similarity index 100% rename from solutions/0381-insert-delete-getrandom-o1-duplicates-allowed.js rename to 0381-insert-delete-getrandom-o1-duplicates-allowed.js diff --git a/solutions/0382-linked-list-random-node.js b/0382-linked-list-random-node.js similarity index 100% rename from solutions/0382-linked-list-random-node.js rename to 0382-linked-list-random-node.js diff --git a/solutions/0383-ransom-note.js b/0383-ransom-note.js similarity index 100% rename from solutions/0383-ransom-note.js rename to 0383-ransom-note.js diff --git a/solutions/0384-shuffle-an-array.js b/0384-shuffle-an-array.js similarity index 100% rename from solutions/0384-shuffle-an-array.js rename to 0384-shuffle-an-array.js diff --git a/solutions/0385-mini-parser.js b/0385-mini-parser.js similarity index 100% rename from solutions/0385-mini-parser.js rename to 0385-mini-parser.js diff --git a/solutions/0386-lexicographical-numbers.js b/0386-lexicographical-numbers.js similarity index 100% rename from solutions/0386-lexicographical-numbers.js rename to 0386-lexicographical-numbers.js diff --git a/solutions/0387-first-unique-character-in-a-string.js b/0387-first-unique-character-in-a-string.js similarity index 100% rename from solutions/0387-first-unique-character-in-a-string.js rename to 0387-first-unique-character-in-a-string.js diff --git a/solutions/0388-longest-absolute-file-path.js b/0388-longest-absolute-file-path.js similarity index 100% rename from solutions/0388-longest-absolute-file-path.js rename to 0388-longest-absolute-file-path.js diff --git a/0389-find-the-difference.js b/0389-find-the-difference.js new file mode 100644 index 00000000..4566e927 --- /dev/null +++ b/0389-find-the-difference.js @@ -0,0 +1,31 @@ +/** + * 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]; +}; + +// var findTheDifference = function(s, t) { +// const map = new Map() +// t.split('').forEach(char => map.set(char, (map.get(char) || 0 ) + 1)) +// s.split('').forEach(char => map.set(char, map.get(char) - 1)) +// return Array.from(map).find(([char, count]) => count)[0] +// }; diff --git a/solutions/0390-elimination-game.js b/0390-elimination-game.js similarity index 100% rename from solutions/0390-elimination-game.js rename to 0390-elimination-game.js diff --git a/solutions/0391-perfect-rectangle.js b/0391-perfect-rectangle.js similarity index 100% rename from solutions/0391-perfect-rectangle.js rename to 0391-perfect-rectangle.js diff --git a/solutions/0392-is-subsequence.js b/0392-is-subsequence.js similarity index 75% rename from solutions/0392-is-subsequence.js rename to 0392-is-subsequence.js index a041d570..310d34f8 100644 --- a/solutions/0392-is-subsequence.js +++ b/0392-is-subsequence.js @@ -25,3 +25,16 @@ var isSubsequence = function(s, t) { } return count === s.length; }; + +// var isSubsequence = function(sub, t) { +// let p1 = 0; +// let p2 = 0; +// while (p1 < sub.length && p2 < t.length) { +// if (sub[p1] === t[p2]) { +// p1 += 1 +// } +// p2 += 1 +// } + +// return p1 === sub.length +// }; diff --git a/solutions/0393-utf-8-validation.js b/0393-utf-8-validation.js similarity index 100% rename from solutions/0393-utf-8-validation.js rename to 0393-utf-8-validation.js diff --git a/solutions/0394-decode-string.js b/0394-decode-string.js similarity index 100% rename from solutions/0394-decode-string.js rename to 0394-decode-string.js diff --git a/solutions/0395-longest-substring-with-at-least-k-repeating-characters.js b/0395-longest-substring-with-at-least-k-repeating-characters.js similarity index 100% rename from solutions/0395-longest-substring-with-at-least-k-repeating-characters.js rename to 0395-longest-substring-with-at-least-k-repeating-characters.js diff --git a/solutions/0396-rotate-function.js b/0396-rotate-function.js similarity index 100% rename from solutions/0396-rotate-function.js rename to 0396-rotate-function.js diff --git a/solutions/0397-integer-replacement.js b/0397-integer-replacement.js similarity index 100% rename from solutions/0397-integer-replacement.js rename to 0397-integer-replacement.js diff --git a/solutions/0398-random-pick-index.js b/0398-random-pick-index.js similarity index 100% rename from solutions/0398-random-pick-index.js rename to 0398-random-pick-index.js diff --git a/solutions/0399-evaluate-division.js b/0399-evaluate-division.js similarity index 100% rename from solutions/0399-evaluate-division.js rename to 0399-evaluate-division.js diff --git a/solutions/0400-nth-digit.js b/0400-nth-digit.js similarity index 100% rename from solutions/0400-nth-digit.js rename to 0400-nth-digit.js diff --git a/solutions/0401-binary-watch.js b/0401-binary-watch.js similarity index 100% rename from solutions/0401-binary-watch.js rename to 0401-binary-watch.js diff --git a/solutions/0402-remove-k-digits.js b/0402-remove-k-digits.js similarity index 100% rename from solutions/0402-remove-k-digits.js rename to 0402-remove-k-digits.js diff --git a/solutions/0403-frog-jump.js b/0403-frog-jump.js similarity index 100% rename from solutions/0403-frog-jump.js rename to 0403-frog-jump.js diff --git a/solutions/0404-sum-of-left-leaves.js b/0404-sum-of-left-leaves.js similarity index 100% rename from solutions/0404-sum-of-left-leaves.js rename to 0404-sum-of-left-leaves.js diff --git a/solutions/0405-convert-a-number-to-hexadecimal.js b/0405-convert-a-number-to-hexadecimal.js similarity index 100% rename from solutions/0405-convert-a-number-to-hexadecimal.js rename to 0405-convert-a-number-to-hexadecimal.js diff --git a/solutions/0406-queue-reconstruction-by-height.js b/0406-queue-reconstruction-by-height.js similarity index 100% rename from solutions/0406-queue-reconstruction-by-height.js rename to 0406-queue-reconstruction-by-height.js diff --git a/solutions/0407-trapping-rain-water-ii.js b/0407-trapping-rain-water-ii.js similarity index 100% rename from solutions/0407-trapping-rain-water-ii.js rename to 0407-trapping-rain-water-ii.js diff --git a/solutions/0409-longest-palindrome.js b/0409-longest-palindrome.js similarity index 100% rename from solutions/0409-longest-palindrome.js rename to 0409-longest-palindrome.js diff --git a/solutions/0410-split-array-largest-sum.js b/0410-split-array-largest-sum.js similarity index 100% rename from solutions/0410-split-array-largest-sum.js rename to 0410-split-array-largest-sum.js diff --git a/0412-fizz-buzz.js b/0412-fizz-buzz.js new file mode 100644 index 00000000..7df71869 --- /dev/null +++ b/0412-fizz-buzz.js @@ -0,0 +1,38 @@ +/** + * 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) + ); +}; + +// var fizzBuzz = function(n) { +// const result = [] +// for (let i = 1; i <= n; i++) { +// if (i % 3 === 0 && i % 5 === 0) { +// result.push('FizzBuzz') +// } else if(i % 3 === 0) { +// result.push('Fizz') +// } else if(i % 5 === 0) { +// result.push('Buzz') +// } else { +// result.push(i+'') +// } +// } +// return result; +// }; \ No newline at end of file diff --git a/solutions/0413-arithmetic-slices.js b/0413-arithmetic-slices.js similarity index 100% rename from solutions/0413-arithmetic-slices.js rename to 0413-arithmetic-slices.js diff --git a/solutions/0414-third-maximum-number.js b/0414-third-maximum-number.js similarity index 100% rename from solutions/0414-third-maximum-number.js rename to 0414-third-maximum-number.js diff --git a/solutions/0415-add-strings.js b/0415-add-strings.js similarity index 100% rename from solutions/0415-add-strings.js rename to 0415-add-strings.js diff --git a/solutions/0416-partition-equal-subset-sum.js b/0416-partition-equal-subset-sum.js similarity index 100% rename from solutions/0416-partition-equal-subset-sum.js rename to 0416-partition-equal-subset-sum.js diff --git a/solutions/0417-pacific-atlantic-water-flow.js b/0417-pacific-atlantic-water-flow.js similarity index 100% rename from solutions/0417-pacific-atlantic-water-flow.js rename to 0417-pacific-atlantic-water-flow.js diff --git a/solutions/0419-battleships-in-a-board.js b/0419-battleships-in-a-board.js similarity index 100% rename from solutions/0419-battleships-in-a-board.js rename to 0419-battleships-in-a-board.js diff --git a/solutions/0420-strong-password-checker.js b/0420-strong-password-checker.js similarity index 100% rename from solutions/0420-strong-password-checker.js rename to 0420-strong-password-checker.js diff --git a/solutions/0421-maximum-xor-of-two-numbers-in-an-array.js b/0421-maximum-xor-of-two-numbers-in-an-array.js similarity index 100% rename from solutions/0421-maximum-xor-of-two-numbers-in-an-array.js rename to 0421-maximum-xor-of-two-numbers-in-an-array.js diff --git a/solutions/0423-reconstruct-original-digits-from-english.js b/0423-reconstruct-original-digits-from-english.js similarity index 100% rename from solutions/0423-reconstruct-original-digits-from-english.js rename to 0423-reconstruct-original-digits-from-english.js diff --git a/0424-longest-repeating-character-replacement.js b/0424-longest-repeating-character-replacement.js new file mode 100644 index 00000000..a635041e --- /dev/null +++ b/0424-longest-repeating-character-replacement.js @@ -0,0 +1,57 @@ +/** + * 424. Longest Repeating Character Replacement + * https://leetcode.com/problems/longest-repeating-character-replacement/ + * Difficulty: Medium + * + * You are given a string s and an integer k. You can choose any character of the string + * and change it to any other uppercase English character. You can perform this operation + * at most k times. + * + * Return the length of the longest substring containing the same letter you can get after + * performing the above operations. + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var characterReplacement = function(s, k) { + const count = new Map(); + let max = 0; + let left = 0; + + return s.split('').reduce((maxLength, char, right) => { + count.set(char, (count.get(char) || 0) + 1); + max = Math.max(max, count.get(char)); + if (right - left + 1 - max > k) { + count.set(s[left], count.get(s[left++]) - 1); + } + return Math.max(maxLength, right - left + 1); + }, 0); +}; + +// var characterReplacement = function(s, k) { +// const window_state = new Set(s); // charSet +// let result = 0; + +// for (let char of window_state) { +// let begin = 0; +// let count = 0 +// for (let end = 0; end < s.length; end++) { +// if (s[end] === char) { +// count++; +// } + +// while ((end - begin + 1) - count > k) { +// if (s[begin] === char) { +// count--; +// } +// begin++; +// } + +// result = Math.max(result, end - begin + 1); +// } +// } +// return result; +// }; diff --git a/solutions/0427-construct-quad-tree.js b/0427-construct-quad-tree.js similarity index 100% rename from solutions/0427-construct-quad-tree.js rename to 0427-construct-quad-tree.js diff --git a/solutions/0429-n-ary-tree-level-order-traversal.js b/0429-n-ary-tree-level-order-traversal.js similarity index 100% rename from solutions/0429-n-ary-tree-level-order-traversal.js rename to 0429-n-ary-tree-level-order-traversal.js diff --git a/solutions/0430-flatten-a-multilevel-doubly-linked-list.js b/0430-flatten-a-multilevel-doubly-linked-list.js similarity index 100% rename from solutions/0430-flatten-a-multilevel-doubly-linked-list.js rename to 0430-flatten-a-multilevel-doubly-linked-list.js diff --git a/solutions/0432-all-oone-data-structure.js b/0432-all-oone-data-structure.js similarity index 100% rename from solutions/0432-all-oone-data-structure.js rename to 0432-all-oone-data-structure.js diff --git a/solutions/0433-minimum-genetic-mutation.js b/0433-minimum-genetic-mutation.js similarity index 100% rename from solutions/0433-minimum-genetic-mutation.js rename to 0433-minimum-genetic-mutation.js diff --git a/solutions/0434-number-of-segments-in-a-string.js b/0434-number-of-segments-in-a-string.js similarity index 100% rename from solutions/0434-number-of-segments-in-a-string.js rename to 0434-number-of-segments-in-a-string.js diff --git a/solutions/0435-non-overlapping-intervals.js b/0435-non-overlapping-intervals.js similarity index 100% rename from solutions/0435-non-overlapping-intervals.js rename to 0435-non-overlapping-intervals.js diff --git a/solutions/0436-find-right-interval.js b/0436-find-right-interval.js similarity index 100% rename from solutions/0436-find-right-interval.js rename to 0436-find-right-interval.js diff --git a/solutions/0437-path-sum-iii.js b/0437-path-sum-iii.js similarity index 100% rename from solutions/0437-path-sum-iii.js rename to 0437-path-sum-iii.js diff --git a/solutions/0438-find-all-anagrams-in-a-string.js b/0438-find-all-anagrams-in-a-string.js similarity index 100% rename from solutions/0438-find-all-anagrams-in-a-string.js rename to 0438-find-all-anagrams-in-a-string.js diff --git a/solutions/0440-k-th-smallest-in-lexicographical-order.js b/0440-k-th-smallest-in-lexicographical-order.js similarity index 100% rename from solutions/0440-k-th-smallest-in-lexicographical-order.js rename to 0440-k-th-smallest-in-lexicographical-order.js diff --git a/solutions/0441-arranging-coins.js b/0441-arranging-coins.js similarity index 100% rename from solutions/0441-arranging-coins.js rename to 0441-arranging-coins.js diff --git a/solutions/0442-find-all-duplicates-in-an-array.js b/0442-find-all-duplicates-in-an-array.js similarity index 100% rename from solutions/0442-find-all-duplicates-in-an-array.js rename to 0442-find-all-duplicates-in-an-array.js diff --git a/solutions/0443-string-compression.js b/0443-string-compression.js similarity index 100% rename from solutions/0443-string-compression.js rename to 0443-string-compression.js diff --git a/solutions/0445-add-two-numbers-ii.js b/0445-add-two-numbers-ii.js similarity index 100% rename from solutions/0445-add-two-numbers-ii.js rename to 0445-add-two-numbers-ii.js diff --git a/solutions/0446-arithmetic-slices-ii-subsequence.js b/0446-arithmetic-slices-ii-subsequence.js similarity index 100% rename from solutions/0446-arithmetic-slices-ii-subsequence.js rename to 0446-arithmetic-slices-ii-subsequence.js diff --git a/solutions/0447-number-of-boomerangs.js b/0447-number-of-boomerangs.js similarity index 100% rename from solutions/0447-number-of-boomerangs.js rename to 0447-number-of-boomerangs.js diff --git a/solutions/0448-find-all-numbers-disappeared-in-an-array.js b/0448-find-all-numbers-disappeared-in-an-array.js similarity index 100% rename from solutions/0448-find-all-numbers-disappeared-in-an-array.js rename to 0448-find-all-numbers-disappeared-in-an-array.js diff --git a/solutions/0449-serialize-and-deserialize-bst.js b/0449-serialize-and-deserialize-bst.js similarity index 100% rename from solutions/0449-serialize-and-deserialize-bst.js rename to 0449-serialize-and-deserialize-bst.js diff --git a/solutions/0450-delete-node-in-a-bst.js b/0450-delete-node-in-a-bst.js similarity index 100% rename from solutions/0450-delete-node-in-a-bst.js rename to 0450-delete-node-in-a-bst.js diff --git a/0451-sort-characters-by-frequency.js b/0451-sort-characters-by-frequency.js new file mode 100644 index 00000000..ec9edf6b --- /dev/null +++ b/0451-sort-characters-by-frequency.js @@ -0,0 +1,50 @@ +/** + * 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(''); +}; + +// Doesno work with big string Why? +// var frequencySort = function(s) { +// const freqMap = new Map(); + +// // Подсчёт частоты символов +// for (const ch of s) { +// freqMap.set(ch, (freqMap.get(ch) || 0) + 1); +// } + +// const maxHeap = new MaxHeapAdhoc(); + +// // Заполняем макс-хипу (отрицательное значение для симуляции макс-хипы) +// for (const [ch, freq] of freqMap.entries()) { +// maxHeap.add([-freq, ch.repeat(freq)]); +// } + +// let result = ""; + +// // Извлекаем символы в порядке убывания частоты +// while (maxHeap.heap.length) { +// result += maxHeap.poll()[1]; +// } + +// return result; +// }; \ No newline at end of file diff --git a/solutions/0452-minimum-number-of-arrows-to-burst-balloons.js b/0452-minimum-number-of-arrows-to-burst-balloons.js similarity index 100% rename from solutions/0452-minimum-number-of-arrows-to-burst-balloons.js rename to 0452-minimum-number-of-arrows-to-burst-balloons.js diff --git a/solutions/0453-minimum-moves-to-equal-array-elements.js b/0453-minimum-moves-to-equal-array-elements.js similarity index 100% rename from solutions/0453-minimum-moves-to-equal-array-elements.js rename to 0453-minimum-moves-to-equal-array-elements.js diff --git a/solutions/0454-4sum-ii.js b/0454-4sum-ii.js similarity index 100% rename from solutions/0454-4sum-ii.js rename to 0454-4sum-ii.js diff --git a/solutions/0455-assign-cookies.js b/0455-assign-cookies.js similarity index 100% rename from solutions/0455-assign-cookies.js rename to 0455-assign-cookies.js diff --git a/solutions/0456-132-pattern.js b/0456-132-pattern.js similarity index 100% rename from solutions/0456-132-pattern.js rename to 0456-132-pattern.js diff --git a/solutions/0457-circular-array-loop.js b/0457-circular-array-loop.js similarity index 100% rename from solutions/0457-circular-array-loop.js rename to 0457-circular-array-loop.js diff --git a/solutions/0458-poor-pigs.js b/0458-poor-pigs.js similarity index 100% rename from solutions/0458-poor-pigs.js rename to 0458-poor-pigs.js diff --git a/solutions/0459-repeated-substring-pattern.js b/0459-repeated-substring-pattern.js similarity index 100% rename from solutions/0459-repeated-substring-pattern.js rename to 0459-repeated-substring-pattern.js diff --git a/solutions/0460-lfu-cache.js b/0460-lfu-cache.js similarity index 100% rename from solutions/0460-lfu-cache.js rename to 0460-lfu-cache.js diff --git a/solutions/0461-hamming-distance.js b/0461-hamming-distance.js similarity index 100% rename from solutions/0461-hamming-distance.js rename to 0461-hamming-distance.js diff --git a/solutions/0462-minimum-moves-to-equal-array-elements-ii.js b/0462-minimum-moves-to-equal-array-elements-ii.js similarity index 100% rename from solutions/0462-minimum-moves-to-equal-array-elements-ii.js rename to 0462-minimum-moves-to-equal-array-elements-ii.js diff --git a/solutions/0463-island-perimeter.js b/0463-island-perimeter.js similarity index 100% rename from solutions/0463-island-perimeter.js rename to 0463-island-perimeter.js diff --git a/solutions/0464-can-i-win.js b/0464-can-i-win.js similarity index 100% rename from solutions/0464-can-i-win.js rename to 0464-can-i-win.js diff --git a/solutions/0466-count-the-repetitions.js b/0466-count-the-repetitions.js similarity index 100% rename from solutions/0466-count-the-repetitions.js rename to 0466-count-the-repetitions.js diff --git a/solutions/0467-unique-substrings-in-wraparound-string.js b/0467-unique-substrings-in-wraparound-string.js similarity index 100% rename from solutions/0467-unique-substrings-in-wraparound-string.js rename to 0467-unique-substrings-in-wraparound-string.js diff --git a/solutions/0468-validate-ip-address.js b/0468-validate-ip-address.js similarity index 100% rename from solutions/0468-validate-ip-address.js rename to 0468-validate-ip-address.js diff --git a/solutions/0470-implement-rand10-using-rand7.js b/0470-implement-rand10-using-rand7.js similarity index 100% rename from solutions/0470-implement-rand10-using-rand7.js rename to 0470-implement-rand10-using-rand7.js diff --git a/solutions/0472-concatenated-words.js b/0472-concatenated-words.js similarity index 100% rename from solutions/0472-concatenated-words.js rename to 0472-concatenated-words.js diff --git a/solutions/0473-matchsticks-to-square.js b/0473-matchsticks-to-square.js similarity index 100% rename from solutions/0473-matchsticks-to-square.js rename to 0473-matchsticks-to-square.js diff --git a/solutions/0474-ones-and-zeroes.js b/0474-ones-and-zeroes.js similarity index 100% rename from solutions/0474-ones-and-zeroes.js rename to 0474-ones-and-zeroes.js diff --git a/solutions/0475-heaters.js b/0475-heaters.js similarity index 100% rename from solutions/0475-heaters.js rename to 0475-heaters.js diff --git a/solutions/0476-number-complement.js b/0476-number-complement.js similarity index 100% rename from solutions/0476-number-complement.js rename to 0476-number-complement.js diff --git a/solutions/0477-total-hamming-distance.js b/0477-total-hamming-distance.js similarity index 100% rename from solutions/0477-total-hamming-distance.js rename to 0477-total-hamming-distance.js diff --git a/solutions/0478-generate-random-point-in-a-circle.js b/0478-generate-random-point-in-a-circle.js similarity index 100% rename from solutions/0478-generate-random-point-in-a-circle.js rename to 0478-generate-random-point-in-a-circle.js diff --git a/solutions/0479-largest-palindrome-product.js b/0479-largest-palindrome-product.js similarity index 100% rename from solutions/0479-largest-palindrome-product.js rename to 0479-largest-palindrome-product.js diff --git a/solutions/0480-sliding-window-median.js b/0480-sliding-window-median.js similarity index 100% rename from solutions/0480-sliding-window-median.js rename to 0480-sliding-window-median.js diff --git a/solutions/0481-magical-string.js b/0481-magical-string.js similarity index 100% rename from solutions/0481-magical-string.js rename to 0481-magical-string.js diff --git a/solutions/0482-license-key-formatting.js b/0482-license-key-formatting.js similarity index 100% rename from solutions/0482-license-key-formatting.js rename to 0482-license-key-formatting.js diff --git a/solutions/0483-smallest-good-base.js b/0483-smallest-good-base.js similarity index 100% rename from solutions/0483-smallest-good-base.js rename to 0483-smallest-good-base.js diff --git a/solutions/0485-max-consecutive-ones.js b/0485-max-consecutive-ones.js similarity index 100% rename from solutions/0485-max-consecutive-ones.js rename to 0485-max-consecutive-ones.js diff --git a/solutions/0486-predict-the-winner.js b/0486-predict-the-winner.js similarity index 100% rename from solutions/0486-predict-the-winner.js rename to 0486-predict-the-winner.js diff --git a/solutions/0488-zuma-game.js b/0488-zuma-game.js similarity index 100% rename from solutions/0488-zuma-game.js rename to 0488-zuma-game.js diff --git a/solutions/0491-non-decreasing-subsequences.js b/0491-non-decreasing-subsequences.js similarity index 100% rename from solutions/0491-non-decreasing-subsequences.js rename to 0491-non-decreasing-subsequences.js diff --git a/solutions/0492-construct-the-rectangle.js b/0492-construct-the-rectangle.js similarity index 100% rename from solutions/0492-construct-the-rectangle.js rename to 0492-construct-the-rectangle.js diff --git a/solutions/0493-reverse-pairs.js b/0493-reverse-pairs.js similarity index 100% rename from solutions/0493-reverse-pairs.js rename to 0493-reverse-pairs.js diff --git a/solutions/0494-target-sum.js b/0494-target-sum.js similarity index 100% rename from solutions/0494-target-sum.js rename to 0494-target-sum.js diff --git a/solutions/0495-teemo-attacking.js b/0495-teemo-attacking.js similarity index 100% rename from solutions/0495-teemo-attacking.js rename to 0495-teemo-attacking.js diff --git a/solutions/0496-next-greater-element-i.js b/0496-next-greater-element-i.js similarity index 100% rename from solutions/0496-next-greater-element-i.js rename to 0496-next-greater-element-i.js diff --git a/solutions/0497-random-point-in-non-overlapping-rectangles.js b/0497-random-point-in-non-overlapping-rectangles.js similarity index 100% rename from solutions/0497-random-point-in-non-overlapping-rectangles.js rename to 0497-random-point-in-non-overlapping-rectangles.js diff --git a/solutions/0498-diagonal-traverse.js b/0498-diagonal-traverse.js similarity index 100% rename from solutions/0498-diagonal-traverse.js rename to 0498-diagonal-traverse.js diff --git a/solutions/0500-keyboard-row.js b/0500-keyboard-row.js similarity index 100% rename from solutions/0500-keyboard-row.js rename to 0500-keyboard-row.js diff --git a/solutions/0501-find-mode-in-binary-search-tree.js b/0501-find-mode-in-binary-search-tree.js similarity index 100% rename from solutions/0501-find-mode-in-binary-search-tree.js rename to 0501-find-mode-in-binary-search-tree.js diff --git a/solutions/0502-ipo.js b/0502-ipo.js similarity index 100% rename from solutions/0502-ipo.js rename to 0502-ipo.js diff --git a/solutions/0503-next-greater-element-ii.js b/0503-next-greater-element-ii.js similarity index 100% rename from solutions/0503-next-greater-element-ii.js rename to 0503-next-greater-element-ii.js diff --git a/solutions/0504-base-7.js b/0504-base-7.js similarity index 100% rename from solutions/0504-base-7.js rename to 0504-base-7.js diff --git a/solutions/0506-relative-ranks.js b/0506-relative-ranks.js similarity index 100% rename from solutions/0506-relative-ranks.js rename to 0506-relative-ranks.js diff --git a/solutions/0507-perfect-number.js b/0507-perfect-number.js similarity index 100% rename from solutions/0507-perfect-number.js rename to 0507-perfect-number.js diff --git a/solutions/0508-most-frequent-subtree-sum.js b/0508-most-frequent-subtree-sum.js similarity index 100% rename from solutions/0508-most-frequent-subtree-sum.js rename to 0508-most-frequent-subtree-sum.js diff --git a/solutions/0509-fibonacci-number.js b/0509-fibonacci-number.js similarity index 100% rename from solutions/0509-fibonacci-number.js rename to 0509-fibonacci-number.js diff --git a/solutions/0513-find-bottom-left-tree-value.js b/0513-find-bottom-left-tree-value.js similarity index 100% rename from solutions/0513-find-bottom-left-tree-value.js rename to 0513-find-bottom-left-tree-value.js diff --git a/solutions/0514-freedom-trail.js b/0514-freedom-trail.js similarity index 100% rename from solutions/0514-freedom-trail.js rename to 0514-freedom-trail.js diff --git a/solutions/0520-detect-capital.js b/0520-detect-capital.js similarity index 100% rename from solutions/0520-detect-capital.js rename to 0520-detect-capital.js diff --git a/solutions/0521-longest-uncommon-subsequence-i.js b/0521-longest-uncommon-subsequence-i.js similarity index 100% rename from solutions/0521-longest-uncommon-subsequence-i.js rename to 0521-longest-uncommon-subsequence-i.js diff --git a/solutions/0530-minimum-absolute-difference-in-bst.js b/0530-minimum-absolute-difference-in-bst.js similarity index 100% rename from solutions/0530-minimum-absolute-difference-in-bst.js rename to 0530-minimum-absolute-difference-in-bst.js diff --git a/solutions/0541-reverse-string-ii.js b/0541-reverse-string-ii.js similarity index 100% rename from solutions/0541-reverse-string-ii.js rename to 0541-reverse-string-ii.js diff --git a/solutions/0542-01-matrix.js b/0542-01-matrix.js similarity index 100% rename from solutions/0542-01-matrix.js rename to 0542-01-matrix.js diff --git a/solutions/0543-diameter-of-binary-tree.js b/0543-diameter-of-binary-tree.js similarity index 100% rename from solutions/0543-diameter-of-binary-tree.js rename to 0543-diameter-of-binary-tree.js diff --git a/solutions/0547-number-of-provinces.js b/0547-number-of-provinces.js similarity index 100% rename from solutions/0547-number-of-provinces.js rename to 0547-number-of-provinces.js diff --git a/solutions/0551-student-attendance-record-i.js b/0551-student-attendance-record-i.js similarity index 100% rename from solutions/0551-student-attendance-record-i.js rename to 0551-student-attendance-record-i.js diff --git a/solutions/0557-reverse-words-in-a-string-iii.js b/0557-reverse-words-in-a-string-iii.js similarity index 100% rename from solutions/0557-reverse-words-in-a-string-iii.js rename to 0557-reverse-words-in-a-string-iii.js diff --git a/solutions/0560-subarray-sum-equals-k.js b/0560-subarray-sum-equals-k.js similarity index 100% rename from solutions/0560-subarray-sum-equals-k.js rename to 0560-subarray-sum-equals-k.js diff --git a/solutions/0563-binary-tree-tilt.js b/0563-binary-tree-tilt.js similarity index 100% rename from solutions/0563-binary-tree-tilt.js rename to 0563-binary-tree-tilt.js diff --git a/solutions/0565-array-nesting.js b/0565-array-nesting.js similarity index 100% rename from solutions/0565-array-nesting.js rename to 0565-array-nesting.js diff --git a/solutions/0566-reshape-the-matrix.js b/0566-reshape-the-matrix.js similarity index 100% rename from solutions/0566-reshape-the-matrix.js rename to 0566-reshape-the-matrix.js diff --git a/0567-permutation-in-string.js b/0567-permutation-in-string.js new file mode 100644 index 00000000..44910e18 --- /dev/null +++ b/0567-permutation-in-string.js @@ -0,0 +1,74 @@ +/** + * 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); +}; + +// 6 solutions + +// var checkInclusion = function(s1, s2) { +// if (s1.length > s2.length) return false; + +// // Массивы для подсчета количества букв +// const s1arr = new Array(26).fill(0); +// const s2arr = new Array(26).fill(0); + +// // Заполняем массивы для первых символов +// for (let i = 0; i < s1.length; i++) { +// s1arr[s1.charCodeAt(i) - 'a'.charCodeAt(0)]++; +// s2arr[s2.charCodeAt(i) - 'a'.charCodeAt(0)]++; +// } + +// // Проверка на соответствие +// const matches = (s1arr, s2arr) => { +// for (let i = 0; i < 26; i++) { +// if (s1arr[i] !== s2arr[i]) return false; +// } +// return true; +// }; + +// // Сдвигаем окно по строке s2 +// for (let i = 0; i < s2.length - s1.length; i++) { +// if (matches(s1arr, s2arr)) return true; + +// // Обновляем массивы для следующего окна +// s2arr[s2.charCodeAt(i + s1.length) - 'a'.charCodeAt(0)]++; +// s2arr[s2.charCodeAt(i) - 'a'.charCodeAt(0)]--; +// } + +// // Последняя проверка на совпадение +// return matches(s1arr, s2arr); +// }; diff --git a/solutions/0575-distribute-candies.js b/0575-distribute-candies.js similarity index 100% rename from solutions/0575-distribute-candies.js rename to 0575-distribute-candies.js diff --git a/solutions/0589-n-ary-tree-preorder-traversal.js b/0589-n-ary-tree-preorder-traversal.js similarity index 100% rename from solutions/0589-n-ary-tree-preorder-traversal.js rename to 0589-n-ary-tree-preorder-traversal.js diff --git a/solutions/0594-longest-harmonious-subsequence.js b/0594-longest-harmonious-subsequence.js similarity index 100% rename from solutions/0594-longest-harmonious-subsequence.js rename to 0594-longest-harmonious-subsequence.js diff --git a/solutions/0599-minimum-index-sum-of-two-lists.js b/0599-minimum-index-sum-of-two-lists.js similarity index 100% rename from solutions/0599-minimum-index-sum-of-two-lists.js rename to 0599-minimum-index-sum-of-two-lists.js diff --git a/solutions/0605-can-place-flowers.js b/0605-can-place-flowers.js similarity index 100% rename from solutions/0605-can-place-flowers.js rename to 0605-can-place-flowers.js diff --git a/solutions/0606-construct-string-from-binary-tree.js b/0606-construct-string-from-binary-tree.js similarity index 100% rename from solutions/0606-construct-string-from-binary-tree.js rename to 0606-construct-string-from-binary-tree.js diff --git a/solutions/0617-merge-two-binary-trees.js b/0617-merge-two-binary-trees.js similarity index 100% rename from solutions/0617-merge-two-binary-trees.js rename to 0617-merge-two-binary-trees.js diff --git a/solutions/0621-task-scheduler.js b/0621-task-scheduler.js similarity index 100% rename from solutions/0621-task-scheduler.js rename to 0621-task-scheduler.js diff --git a/solutions/0628-maximum-product-of-three-numbers.js b/0628-maximum-product-of-three-numbers.js similarity index 100% rename from solutions/0628-maximum-product-of-three-numbers.js rename to 0628-maximum-product-of-three-numbers.js diff --git a/solutions/0637-average-of-levels-in-binary-tree.js b/0637-average-of-levels-in-binary-tree.js similarity index 100% rename from solutions/0637-average-of-levels-in-binary-tree.js rename to 0637-average-of-levels-in-binary-tree.js diff --git a/0643-maximum-average-subarray-i.js b/0643-maximum-average-subarray-i.js new file mode 100644 index 00000000..eb1913c8 --- /dev/null +++ b/0643-maximum-average-subarray-i.js @@ -0,0 +1,63 @@ +/** + * 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; +}; + +// gpt +// var findMaxAverage = function (nums, k) { +// let maxSum = nums.slice(0, k).reduce((acc, num) => acc + num, 0); +// let windowSum = maxSum; + +// for (let end = k; end < nums.length; end++) { +// windowSum += nums[end] - nums[end - k]; +// maxSum = Math.max(maxSum, windowSum); +// } + +// return maxSum / k; +// }; + +// var findMaxAverage = function(nums, k) { +// let begin = 0; // Begin +// let window_state = 0; // WindowState +// let result = -Infinity; + +// for (let end = 0; end < nums.length; end++) { +// window_state += nums[end]; + +// // end - begin = window size +// if (end - begin + 1 === k) { // Window condition +// result = Math.max(result, window_state); +// window_state -= nums[begin]; +// begin++; // Shrink window +// } +// } + +// return result/k; +// }; diff --git a/solutions/0645-set-mismatch.js b/0645-set-mismatch.js similarity index 100% rename from solutions/0645-set-mismatch.js rename to 0645-set-mismatch.js diff --git a/solutions/0648-replace-words.js b/0648-replace-words.js similarity index 100% rename from solutions/0648-replace-words.js rename to 0648-replace-words.js diff --git a/solutions/0649-dota2-senate.js b/0649-dota2-senate.js similarity index 100% rename from solutions/0649-dota2-senate.js rename to 0649-dota2-senate.js diff --git a/solutions/0653-two-sum-iv-input-is-a-bst.js b/0653-two-sum-iv-input-is-a-bst.js similarity index 100% rename from solutions/0653-two-sum-iv-input-is-a-bst.js rename to 0653-two-sum-iv-input-is-a-bst.js diff --git a/solutions/0654-maximum-binary-tree.js b/0654-maximum-binary-tree.js similarity index 100% rename from solutions/0654-maximum-binary-tree.js rename to 0654-maximum-binary-tree.js diff --git a/solutions/0680-valid-palindrome-ii.js b/0680-valid-palindrome-ii.js similarity index 100% rename from solutions/0680-valid-palindrome-ii.js rename to 0680-valid-palindrome-ii.js diff --git a/solutions/0684-redundant-connection.js b/0684-redundant-connection.js similarity index 100% rename from solutions/0684-redundant-connection.js rename to 0684-redundant-connection.js diff --git a/solutions/0686-repeated-string-match.js b/0686-repeated-string-match.js similarity index 100% rename from solutions/0686-repeated-string-match.js rename to 0686-repeated-string-match.js diff --git a/solutions/0693-binary-number-with-alternating-bits.js b/0693-binary-number-with-alternating-bits.js similarity index 100% rename from solutions/0693-binary-number-with-alternating-bits.js rename to 0693-binary-number-with-alternating-bits.js diff --git a/solutions/0695-max-area-of-island.js b/0695-max-area-of-island.js similarity index 100% rename from solutions/0695-max-area-of-island.js rename to 0695-max-area-of-island.js diff --git a/solutions/0696-count-binary-substrings.js b/0696-count-binary-substrings.js similarity index 100% rename from solutions/0696-count-binary-substrings.js rename to 0696-count-binary-substrings.js diff --git a/solutions/0697-degree-of-an-array.js b/0697-degree-of-an-array.js similarity index 100% rename from solutions/0697-degree-of-an-array.js rename to 0697-degree-of-an-array.js diff --git a/solutions/0700-search-in-a-binary-search-tree.js b/0700-search-in-a-binary-search-tree.js similarity index 95% rename from solutions/0700-search-in-a-binary-search-tree.js rename to 0700-search-in-a-binary-search-tree.js index 3de1c309..95de17bc 100644 --- a/solutions/0700-search-in-a-binary-search-tree.js +++ b/0700-search-in-a-binary-search-tree.js @@ -32,3 +32,6 @@ var searchBST = function(root, val) { return null; }; + +// Or recursive +// searchBST(root.left, val) diff --git a/solutions/0701-insert-into-a-binary-search-tree.js b/0701-insert-into-a-binary-search-tree.js similarity index 100% rename from solutions/0701-insert-into-a-binary-search-tree.js rename to 0701-insert-into-a-binary-search-tree.js diff --git a/0703-kth-largest-element-in-a-stream.js b/0703-kth-largest-element-in-a-stream.js new file mode 100644 index 00000000..2c245a7f --- /dev/null +++ b/0703-kth-largest-element-in-a-stream.js @@ -0,0 +1,73 @@ +/** + * 703. Kth Largest Element in a Stream + * https://leetcode.com/problems/kth-largest-element-in-a-stream/ + * Difficulty: Easy + * + * You are part of a university admissions office and need to keep track of the kth highest test + * score from applicants in real-time. This helps to determine cut-off marks for interviews and + * admissions dynamically as new applicants submit their scores. + * + * You are tasked to implement a class which, for a given integer k, maintains a stream of test + * scores and continuously returns the kth highest test score after a new score has been submitted. + * More specifically, we are looking for the kth highest score in the sorted list of all scores. + * + * Implement the KthLargest class: + * - KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of + * test scores nums. + * - int add(int val) Adds a new test score val to the stream and returns the element representing + * the kth largest element in the pool of test scores so far. + */ + +/** + * @param {number} k + * @param {number[]} nums + */ +var KthLargest = function(k, nums) { + this.main = new MinPriorityQueue(); + this.k = k; + + nums.forEach(n => this.main.enqueue(n)); + + while (this.main.size() > k) { + this.main.dequeue().element; + } +}; + +/** + * @param {number} val + * @return {number} + */ +KthLargest.prototype.add = function(val) { + this.main.enqueue(val); + + if (this.main.size() > this.k) { + this.main.dequeue().element; + } + + return this.main.front().element; +}; + +// var KthLargest = function(k, nums) { +// this.k = k; +// this.min_heap = new MinHeapAdhoc(); + +// // Добавляем элементы в хипу и оставляем только k наибольших +// for (const num of nums) { +// this.min_heap.add(num); +// if (this.min_heap.heap.length > k) { +// this.min_heap.poll(); +// } +// } +// }; + +// /** +// * @param {number} val +// * @return {number} +// */ +// KthLargest.prototype.add = function(val) { +// this.min_heap.add(val); +// if (this.min_heap.heap.length > this.k) { +// this.min_heap.poll(); +// } +// return this.min_heap.heap[0]; // k-й по величине элемент +// }; diff --git a/0704-binary-search.js b/0704-binary-search.js new file mode 100644 index 00000000..7ba581fd --- /dev/null +++ b/0704-binary-search.js @@ -0,0 +1,44 @@ +/** + * 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; +}; + +// var search = function(nums, target) { +// l = 0 +// r = nums.length + +// while (l <= r) { +// pivot = Math.floor((l + r) / 2) +// if (nums[pivot] === target) return pivot +// if (target < nums[pivot]) r = pivot - 1 +// else l = pivot + 1 +// } + +// return - 1 +// }; diff --git a/solutions/0705-design-hashset.js b/0705-design-hashset.js similarity index 100% rename from solutions/0705-design-hashset.js rename to 0705-design-hashset.js diff --git a/solutions/0706-design-hashmap.js b/0706-design-hashmap.js similarity index 100% rename from solutions/0706-design-hashmap.js rename to 0706-design-hashmap.js diff --git a/solutions/0713-subarray-product-less-than-k.js b/0713-subarray-product-less-than-k.js similarity index 100% rename from solutions/0713-subarray-product-less-than-k.js rename to 0713-subarray-product-less-than-k.js diff --git a/solutions/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js similarity index 100% rename from solutions/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js rename to 0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js diff --git a/solutions/0717-1-bit-and-2-bit-characters.js b/0717-1-bit-and-2-bit-characters.js similarity index 100% rename from solutions/0717-1-bit-and-2-bit-characters.js rename to 0717-1-bit-and-2-bit-characters.js diff --git a/solutions/0720-longest-word-in-dictionary.js b/0720-longest-word-in-dictionary.js similarity index 100% rename from solutions/0720-longest-word-in-dictionary.js rename to 0720-longest-word-in-dictionary.js diff --git a/solutions/0722-remove-comments.js b/0722-remove-comments.js similarity index 100% rename from solutions/0722-remove-comments.js rename to 0722-remove-comments.js diff --git a/solutions/0724-find-pivot-index.js b/0724-find-pivot-index.js similarity index 100% rename from solutions/0724-find-pivot-index.js rename to 0724-find-pivot-index.js diff --git a/solutions/0733-flood-fill.js b/0733-flood-fill.js similarity index 100% rename from solutions/0733-flood-fill.js rename to 0733-flood-fill.js diff --git a/solutions/0735-asteroid-collision.js b/0735-asteroid-collision.js similarity index 100% rename from solutions/0735-asteroid-collision.js rename to 0735-asteroid-collision.js diff --git a/solutions/0739-daily-temperatures.js b/0739-daily-temperatures.js similarity index 100% rename from solutions/0739-daily-temperatures.js rename to 0739-daily-temperatures.js diff --git a/solutions/0743-network-delay-time.js b/0743-network-delay-time.js similarity index 100% rename from solutions/0743-network-delay-time.js rename to 0743-network-delay-time.js diff --git a/solutions/0744-find-smallest-letter-greater-than-target.js b/0744-find-smallest-letter-greater-than-target.js similarity index 100% rename from solutions/0744-find-smallest-letter-greater-than-target.js rename to 0744-find-smallest-letter-greater-than-target.js diff --git a/solutions/0745-prefix-and-suffix-search.js b/0745-prefix-and-suffix-search.js similarity index 100% rename from solutions/0745-prefix-and-suffix-search.js rename to 0745-prefix-and-suffix-search.js diff --git a/solutions/0746-min-cost-climbing-stairs.js b/0746-min-cost-climbing-stairs.js similarity index 100% rename from solutions/0746-min-cost-climbing-stairs.js rename to 0746-min-cost-climbing-stairs.js diff --git a/solutions/0747-largest-number-at-least-twice-of-others.js b/0747-largest-number-at-least-twice-of-others.js similarity index 100% rename from solutions/0747-largest-number-at-least-twice-of-others.js rename to 0747-largest-number-at-least-twice-of-others.js diff --git a/solutions/0748-shortest-completing-word.js b/0748-shortest-completing-word.js similarity index 100% rename from solutions/0748-shortest-completing-word.js rename to 0748-shortest-completing-word.js diff --git a/solutions/0762-prime-number-of-set-bits-in-binary-representation.js b/0762-prime-number-of-set-bits-in-binary-representation.js similarity index 100% rename from solutions/0762-prime-number-of-set-bits-in-binary-representation.js rename to 0762-prime-number-of-set-bits-in-binary-representation.js diff --git a/solutions/0763-partition-labels.js b/0763-partition-labels.js similarity index 100% rename from solutions/0763-partition-labels.js rename to 0763-partition-labels.js diff --git a/solutions/0783-minimum-distance-between-bst-nodes.js b/0783-minimum-distance-between-bst-nodes.js similarity index 100% rename from solutions/0783-minimum-distance-between-bst-nodes.js rename to 0783-minimum-distance-between-bst-nodes.js diff --git a/solutions/0784-letter-case-permutation.js b/0784-letter-case-permutation.js similarity index 100% rename from solutions/0784-letter-case-permutation.js rename to 0784-letter-case-permutation.js diff --git a/solutions/0790-domino-and-tromino-tiling.js b/0790-domino-and-tromino-tiling.js similarity index 100% rename from solutions/0790-domino-and-tromino-tiling.js rename to 0790-domino-and-tromino-tiling.js diff --git a/solutions/0791-custom-sort-string.js b/0791-custom-sort-string.js similarity index 100% rename from solutions/0791-custom-sort-string.js rename to 0791-custom-sort-string.js diff --git a/solutions/0796-rotate-string.js b/0796-rotate-string.js similarity index 100% rename from solutions/0796-rotate-string.js rename to 0796-rotate-string.js diff --git a/solutions/0802-find-eventual-safe-states.js b/0802-find-eventual-safe-states.js similarity index 100% rename from solutions/0802-find-eventual-safe-states.js rename to 0802-find-eventual-safe-states.js diff --git a/solutions/0804-unique-morse-code-words.js b/0804-unique-morse-code-words.js similarity index 100% rename from solutions/0804-unique-morse-code-words.js rename to 0804-unique-morse-code-words.js diff --git a/solutions/0819-most-common-word.js b/0819-most-common-word.js similarity index 100% rename from solutions/0819-most-common-word.js rename to 0819-most-common-word.js diff --git a/solutions/0821-shortest-distance-to-a-character.js b/0821-shortest-distance-to-a-character.js similarity index 100% rename from solutions/0821-shortest-distance-to-a-character.js rename to 0821-shortest-distance-to-a-character.js diff --git a/solutions/0824-goat-latin.js b/0824-goat-latin.js similarity index 100% rename from solutions/0824-goat-latin.js rename to 0824-goat-latin.js diff --git a/solutions/0827-making-a-large-island.js b/0827-making-a-large-island.js similarity index 100% rename from solutions/0827-making-a-large-island.js rename to 0827-making-a-large-island.js diff --git a/solutions/0830-positions-of-large-groups.js b/0830-positions-of-large-groups.js similarity index 100% rename from solutions/0830-positions-of-large-groups.js rename to 0830-positions-of-large-groups.js diff --git a/solutions/0831-masking-personal-information.js b/0831-masking-personal-information.js similarity index 100% rename from solutions/0831-masking-personal-information.js rename to 0831-masking-personal-information.js diff --git a/solutions/0841-keys-and-rooms.js b/0841-keys-and-rooms.js similarity index 100% rename from solutions/0841-keys-and-rooms.js rename to 0841-keys-and-rooms.js diff --git a/0844-backspace-string-compare.js b/0844-backspace-string-compare.js new file mode 100644 index 00000000..a33f2a04 --- /dev/null +++ b/0844-backspace-string-compare.js @@ -0,0 +1,99 @@ +/** + * 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(''); +} + +// (сзади идем) +// O(n+m) O(1) +// var backspaceCompare = function(s, t) { +// n = s.length - 1 +// m = t.length - 1 +// skip_s = 0; +// skip_t = 0; + +// while (n >= 0 && m>= 0) { +// // todo: implement skip (if # or skip_counter > 0) + +// if (s[n] != s[m]) { +// return false +// } + +// n = n - 1 +// m = m - 1 +// } + +// return n === m +// }; + +// XXX:GPT +// var backspaceCompare = function(s, t) { +// let n = s.length - 1; +// let m = t.length - 1; +// let skip_s = 0; +// let skip_t = 0; + +// while (n >= 0 || m >= 0) { +// while (n >= 0) { // Обрабатываем backspace в `s` +// if (s[n] === '#') { +// skip_s++; +// n--; +// } else if (skip_s > 0) { +// skip_s--; +// n--; +// } else { +// break; +// } +// } + +// while (m >= 0) { // Обрабатываем backspace в `t` +// if (t[m] === '#') { +// skip_t++; +// m--; +// } else if (skip_t > 0) { +// skip_t--; +// m--; +// } else { +// break; +// } +// } + +// if (n >= 0 && m >= 0 && s[n] !== t[m]) { +// return false; +// } + +// if ((n >= 0) !== (m >= 0)) { +// return false; +// } + +// n--; +// m--; +// } + +// return true; +// }; \ No newline at end of file diff --git a/solutions/0846-hand-of-straights.js b/0846-hand-of-straights.js similarity index 100% rename from solutions/0846-hand-of-straights.js rename to 0846-hand-of-straights.js diff --git a/solutions/0867-transpose-matrix.js b/0867-transpose-matrix.js similarity index 100% rename from solutions/0867-transpose-matrix.js rename to 0867-transpose-matrix.js diff --git a/solutions/0868-binary-gap.js b/0868-binary-gap.js similarity index 100% rename from solutions/0868-binary-gap.js rename to 0868-binary-gap.js diff --git a/solutions/0872-leaf-similar-trees.js b/0872-leaf-similar-trees.js similarity index 100% rename from solutions/0872-leaf-similar-trees.js rename to 0872-leaf-similar-trees.js diff --git a/solutions/0873-length-of-longest-fibonacci-subsequence.js b/0873-length-of-longest-fibonacci-subsequence.js similarity index 100% rename from solutions/0873-length-of-longest-fibonacci-subsequence.js rename to 0873-length-of-longest-fibonacci-subsequence.js diff --git a/0875-koko-eating-bananas.js b/0875-koko-eating-bananas.js new file mode 100644 index 00000000..05875855 --- /dev/null +++ b/0875-koko-eating-bananas.js @@ -0,0 +1,65 @@ +/** + * 875. Koko Eating Bananas + * https://leetcode.com/problems/koko-eating-bananas/ + * Difficulty: Medium + * + * Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. + * The guards have gone and will come back in h hours. + * + * Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of + * bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats + * all of them instead and will not eat any more bananas during this hour. + * + * Koko likes to eat slowly but still wants to finish eating all the bananas before the guards + * return. + * + * Return the minimum integer k such that she can eat all the bananas within h hours. + */ + +/** + * @param {number[]} piles + * @param {number} h + * @return {number} + */ +var minEatingSpeed = function(piles, h) { + const fn = speed => piles.reduce((sum, pile) => sum + Math.ceil(pile / speed), 0); + let min = 1; + let max = Math.max(...piles); + let result = max; + + while (min <= max) { + const middle = Math.floor((min + max) / 2); + + if (fn(middle) <= h) { + result = middle; + max = middle - 1; + } else { + min = middle + 1; + } + } + + return result; +}; + +// var minEatingSpeed = function(piles, h) { +// l = 0 +// r = Math.max(...piles) +// res = r + +// while (l <= r) { +// m = Math.floor((l + r)/2) + +// totalTime = 0 +// for (const p of piles) { +// totalTime += Math.ceil( p / m) +// } + +// if (totalTime <= h) { +// res = m +// r = m - 1 +// } else { +// l = m + 1 +// } +// } +// return res +// }; diff --git a/solutions/0876-middle-of-the-linked-list.js b/0876-middle-of-the-linked-list.js similarity index 100% rename from solutions/0876-middle-of-the-linked-list.js rename to 0876-middle-of-the-linked-list.js diff --git a/solutions/0884-uncommon-words-from-two-sentences.js b/0884-uncommon-words-from-two-sentences.js similarity index 100% rename from solutions/0884-uncommon-words-from-two-sentences.js rename to 0884-uncommon-words-from-two-sentences.js diff --git a/solutions/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js b/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js similarity index 100% rename from solutions/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js rename to 0889-construct-binary-tree-from-preorder-and-postorder-traversal.js diff --git a/solutions/0890-find-and-replace-pattern.js b/0890-find-and-replace-pattern.js similarity index 100% rename from solutions/0890-find-and-replace-pattern.js rename to 0890-find-and-replace-pattern.js diff --git a/solutions/0901-online-stock-span.js b/0901-online-stock-span.js similarity index 100% rename from solutions/0901-online-stock-span.js rename to 0901-online-stock-span.js diff --git a/solutions/0905-sort-array-by-parity.js b/0905-sort-array-by-parity.js similarity index 100% rename from solutions/0905-sort-array-by-parity.js rename to 0905-sort-array-by-parity.js diff --git a/solutions/0909-snakes-and-ladders.js b/0909-snakes-and-ladders.js similarity index 100% rename from solutions/0909-snakes-and-ladders.js rename to 0909-snakes-and-ladders.js diff --git a/solutions/0912-sort-an-array.js b/0912-sort-an-array.js similarity index 100% rename from solutions/0912-sort-an-array.js rename to 0912-sort-an-array.js diff --git a/solutions/0914-x-of-a-kind-in-a-deck-of-cards.js b/0914-x-of-a-kind-in-a-deck-of-cards.js similarity index 100% rename from solutions/0914-x-of-a-kind-in-a-deck-of-cards.js rename to 0914-x-of-a-kind-in-a-deck-of-cards.js diff --git a/solutions/0916-word-subsets.js b/0916-word-subsets.js similarity index 100% rename from solutions/0916-word-subsets.js rename to 0916-word-subsets.js diff --git a/solutions/0918-maximum-sum-circular-subarray.js b/0918-maximum-sum-circular-subarray.js similarity index 100% rename from solutions/0918-maximum-sum-circular-subarray.js rename to 0918-maximum-sum-circular-subarray.js diff --git a/solutions/0922-sort-array-by-parity-ii.js b/0922-sort-array-by-parity-ii.js similarity index 100% rename from solutions/0922-sort-array-by-parity-ii.js rename to 0922-sort-array-by-parity-ii.js diff --git a/solutions/0925-long-pressed-name.js b/0925-long-pressed-name.js similarity index 100% rename from solutions/0925-long-pressed-name.js rename to 0925-long-pressed-name.js diff --git a/solutions/0926-flip-string-to-monotone-increasing.js b/0926-flip-string-to-monotone-increasing.js similarity index 100% rename from solutions/0926-flip-string-to-monotone-increasing.js rename to 0926-flip-string-to-monotone-increasing.js diff --git a/solutions/0929-unique-email-addresses.js b/0929-unique-email-addresses.js similarity index 100% rename from solutions/0929-unique-email-addresses.js rename to 0929-unique-email-addresses.js diff --git a/solutions/0933-number-of-recent-calls.js b/0933-number-of-recent-calls.js similarity index 100% rename from solutions/0933-number-of-recent-calls.js rename to 0933-number-of-recent-calls.js diff --git a/solutions/0937-reorder-data-in-log-files.js b/0937-reorder-data-in-log-files.js similarity index 100% rename from solutions/0937-reorder-data-in-log-files.js rename to 0937-reorder-data-in-log-files.js diff --git a/solutions/0966-vowel-spellchecker.js b/0966-vowel-spellchecker.js similarity index 100% rename from solutions/0966-vowel-spellchecker.js rename to 0966-vowel-spellchecker.js diff --git a/solutions/0970-powerful-integers.js b/0970-powerful-integers.js similarity index 100% rename from solutions/0970-powerful-integers.js rename to 0970-powerful-integers.js diff --git a/solutions/0976-largest-perimeter-triangle.js b/0976-largest-perimeter-triangle.js similarity index 100% rename from solutions/0976-largest-perimeter-triangle.js rename to 0976-largest-perimeter-triangle.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..a7747688 --- /dev/null +++ b/0977-squares-of-a-sorted-array.js @@ -0,0 +1,36 @@ +/** + * 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); +}; + +// O(n) without sorting +// var sortedSquares = function(nums) { +// let n = nums.length; +// let result = new Array(n); +// let left = 0, right = n - 1; + +// for (let i = n - 1; i >= 0; i--) { +// if (Math.abs(nums[left]) > Math.abs(nums[right])) { +// result[i] = nums[left] * nums[left]; +// left++; +// } else { +// result[i] = nums[right] * nums[right]; +// right--; +// } +// } + +// return result; +// }; \ No newline at end of file diff --git a/solutions/0985-sum-of-even-numbers-after-queries.js b/0985-sum-of-even-numbers-after-queries.js similarity index 100% rename from solutions/0985-sum-of-even-numbers-after-queries.js rename to 0985-sum-of-even-numbers-after-queries.js diff --git a/solutions/0989-add-to-array-form-of-integer.js b/0989-add-to-array-form-of-integer.js similarity index 100% rename from solutions/0989-add-to-array-form-of-integer.js rename to 0989-add-to-array-form-of-integer.js diff --git a/solutions/0994-rotting-oranges.js b/0994-rotting-oranges.js similarity index 100% rename from solutions/0994-rotting-oranges.js rename to 0994-rotting-oranges.js diff --git a/solutions/0997-find-the-town-judge.js b/0997-find-the-town-judge.js similarity index 100% rename from solutions/0997-find-the-town-judge.js rename to 0997-find-the-town-judge.js diff --git a/solutions/1002-find-common-characters.js b/1002-find-common-characters.js similarity index 100% rename from solutions/1002-find-common-characters.js rename to 1002-find-common-characters.js diff --git a/1004-max-consecutive-ones-iii.js b/1004-max-consecutive-ones-iii.js new file mode 100644 index 00000000..f73ea4d7 --- /dev/null +++ b/1004-max-consecutive-ones-iii.js @@ -0,0 +1,52 @@ +/** + * 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; +}; + +// var longestOnes = function(nums, k) { +// let begin = 0 +// let window_state = 0 // this is how many zeros you saw +// let result = 0 + +// for (let end = 0; end < nums.length; end++ ) { +// if (nums[end] === 0) { +// window_state += 1 +// } + +// // window condition - when count 0 > k +// while (window_state > k) { +// if (nums[begin] === 0) { +// window_state -= 1 +// } +// begin++ +// } +// result = Math.max(result, end - begin + 1) +// } + +// return result +// }; diff --git a/solutions/1005-maximize-sum-of-array-after-k-negations.js b/1005-maximize-sum-of-array-after-k-negations.js similarity index 100% rename from solutions/1005-maximize-sum-of-array-after-k-negations.js rename to 1005-maximize-sum-of-array-after-k-negations.js diff --git a/solutions/1009-complement-of-base-10-integer.js b/1009-complement-of-base-10-integer.js similarity index 100% rename from solutions/1009-complement-of-base-10-integer.js rename to 1009-complement-of-base-10-integer.js diff --git a/solutions/1010-pairs-of-songs-with-total-durations-divisible-by-60.js b/1010-pairs-of-songs-with-total-durations-divisible-by-60.js similarity index 100% rename from solutions/1010-pairs-of-songs-with-total-durations-divisible-by-60.js rename to 1010-pairs-of-songs-with-total-durations-divisible-by-60.js diff --git a/solutions/1022-sum-of-root-to-leaf-binary-numbers.js b/1022-sum-of-root-to-leaf-binary-numbers.js similarity index 100% rename from solutions/1022-sum-of-root-to-leaf-binary-numbers.js rename to 1022-sum-of-root-to-leaf-binary-numbers.js diff --git a/solutions/1023-camelcase-matching.js b/1023-camelcase-matching.js similarity index 100% rename from solutions/1023-camelcase-matching.js rename to 1023-camelcase-matching.js diff --git a/solutions/1028-recover-a-tree-from-preorder-traversal.js b/1028-recover-a-tree-from-preorder-traversal.js similarity index 100% rename from solutions/1028-recover-a-tree-from-preorder-traversal.js rename to 1028-recover-a-tree-from-preorder-traversal.js diff --git a/solutions/1037-valid-boomerang.js b/1037-valid-boomerang.js similarity index 100% rename from solutions/1037-valid-boomerang.js rename to 1037-valid-boomerang.js diff --git a/solutions/1041-robot-bounded-in-circle.js b/1041-robot-bounded-in-circle.js similarity index 100% rename from solutions/1041-robot-bounded-in-circle.js rename to 1041-robot-bounded-in-circle.js diff --git a/solutions/1047-remove-all-adjacent-duplicates-in-string.js b/1047-remove-all-adjacent-duplicates-in-string.js similarity index 100% rename from solutions/1047-remove-all-adjacent-duplicates-in-string.js rename to 1047-remove-all-adjacent-duplicates-in-string.js diff --git a/solutions/1051-height-checker.js b/1051-height-checker.js similarity index 100% rename from solutions/1051-height-checker.js rename to 1051-height-checker.js diff --git a/solutions/1071-greatest-common-divisor-of-strings.js b/1071-greatest-common-divisor-of-strings.js similarity index 100% rename from solutions/1071-greatest-common-divisor-of-strings.js rename to 1071-greatest-common-divisor-of-strings.js diff --git a/solutions/1079-letter-tile-possibilities.js b/1079-letter-tile-possibilities.js similarity index 100% rename from solutions/1079-letter-tile-possibilities.js rename to 1079-letter-tile-possibilities.js diff --git a/solutions/1081-smallest-subsequence-of-distinct-characters.js b/1081-smallest-subsequence-of-distinct-characters.js similarity index 100% rename from solutions/1081-smallest-subsequence-of-distinct-characters.js rename to 1081-smallest-subsequence-of-distinct-characters.js diff --git a/solutions/1092-shortest-common-supersequence.js b/1092-shortest-common-supersequence.js similarity index 100% rename from solutions/1092-shortest-common-supersequence.js rename to 1092-shortest-common-supersequence.js diff --git a/solutions/1103-distribute-candies-to-people.js b/1103-distribute-candies-to-people.js similarity index 100% rename from solutions/1103-distribute-candies-to-people.js rename to 1103-distribute-candies-to-people.js diff --git a/solutions/1108-defanging-an-ip-address.js b/1108-defanging-an-ip-address.js similarity index 100% rename from solutions/1108-defanging-an-ip-address.js rename to 1108-defanging-an-ip-address.js diff --git a/solutions/1122-relative-sort-array.js b/1122-relative-sort-array.js similarity index 100% rename from solutions/1122-relative-sort-array.js rename to 1122-relative-sort-array.js diff --git a/solutions/1137-n-th-tribonacci-number.js b/1137-n-th-tribonacci-number.js similarity index 100% rename from solutions/1137-n-th-tribonacci-number.js rename to 1137-n-th-tribonacci-number.js diff --git a/solutions/1143-longest-common-subsequence.js b/1143-longest-common-subsequence.js similarity index 100% rename from solutions/1143-longest-common-subsequence.js rename to 1143-longest-common-subsequence.js diff --git a/solutions/1161-maximum-level-sum-of-a-binary-tree.js b/1161-maximum-level-sum-of-a-binary-tree.js similarity index 100% rename from solutions/1161-maximum-level-sum-of-a-binary-tree.js rename to 1161-maximum-level-sum-of-a-binary-tree.js diff --git a/solutions/1189-maximum-number-of-balloons.js b/1189-maximum-number-of-balloons.js similarity index 100% rename from solutions/1189-maximum-number-of-balloons.js rename to 1189-maximum-number-of-balloons.js diff --git a/solutions/1200-minimum-absolute-difference.js b/1200-minimum-absolute-difference.js similarity index 100% rename from solutions/1200-minimum-absolute-difference.js rename to 1200-minimum-absolute-difference.js diff --git a/solutions/1206-design-skiplist.js b/1206-design-skiplist.js similarity index 100% rename from solutions/1206-design-skiplist.js rename to 1206-design-skiplist.js diff --git a/solutions/1207-unique-number-of-occurrences.js b/1207-unique-number-of-occurrences.js similarity index 100% rename from solutions/1207-unique-number-of-occurrences.js rename to 1207-unique-number-of-occurrences.js diff --git a/solutions/1208-get-equal-substrings-within-budget.js b/1208-get-equal-substrings-within-budget.js similarity index 100% rename from solutions/1208-get-equal-substrings-within-budget.js rename to 1208-get-equal-substrings-within-budget.js diff --git a/solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js b/1217-minimum-cost-to-move-chips-to-the-same-position.js similarity index 100% rename from solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js rename to 1217-minimum-cost-to-move-chips-to-the-same-position.js diff --git a/solutions/1232-check-if-it-is-a-straight-line.js b/1232-check-if-it-is-a-straight-line.js similarity index 100% rename from solutions/1232-check-if-it-is-a-straight-line.js rename to 1232-check-if-it-is-a-straight-line.js diff --git a/solutions/1233-remove-sub-folders-from-the-filesystem.js b/1233-remove-sub-folders-from-the-filesystem.js similarity index 100% rename from solutions/1233-remove-sub-folders-from-the-filesystem.js rename to 1233-remove-sub-folders-from-the-filesystem.js diff --git a/solutions/1249-minimum-remove-to-make-valid-parentheses.js b/1249-minimum-remove-to-make-valid-parentheses.js similarity index 100% rename from solutions/1249-minimum-remove-to-make-valid-parentheses.js rename to 1249-minimum-remove-to-make-valid-parentheses.js diff --git a/solutions/1252-cells-with-odd-values-in-a-matrix.js b/1252-cells-with-odd-values-in-a-matrix.js similarity index 100% rename from solutions/1252-cells-with-odd-values-in-a-matrix.js rename to 1252-cells-with-odd-values-in-a-matrix.js diff --git a/solutions/1261-find-elements-in-a-contaminated-binary-tree.js b/1261-find-elements-in-a-contaminated-binary-tree.js similarity index 100% rename from solutions/1261-find-elements-in-a-contaminated-binary-tree.js rename to 1261-find-elements-in-a-contaminated-binary-tree.js diff --git a/solutions/1267-count-servers-that-communicate.js b/1267-count-servers-that-communicate.js similarity index 100% rename from solutions/1267-count-servers-that-communicate.js rename to 1267-count-servers-that-communicate.js diff --git a/solutions/1268-search-suggestions-system.js b/1268-search-suggestions-system.js similarity index 100% rename from solutions/1268-search-suggestions-system.js rename to 1268-search-suggestions-system.js diff --git a/solutions/1287-element-appearing-more-than-25-in-sorted-array.js b/1287-element-appearing-more-than-25-in-sorted-array.js similarity index 100% rename from solutions/1287-element-appearing-more-than-25-in-sorted-array.js rename to 1287-element-appearing-more-than-25-in-sorted-array.js diff --git a/solutions/1290-convert-binary-number-in-a-linked-list-to-integer.js b/1290-convert-binary-number-in-a-linked-list-to-integer.js similarity index 100% rename from solutions/1290-convert-binary-number-in-a-linked-list-to-integer.js rename to 1290-convert-binary-number-in-a-linked-list-to-integer.js diff --git a/solutions/1291-sequential-digits.js b/1291-sequential-digits.js similarity index 100% rename from solutions/1291-sequential-digits.js rename to 1291-sequential-digits.js diff --git a/solutions/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 similarity index 100% rename from solutions/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js rename to 1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js diff --git a/solutions/1295-find-numbers-with-even-number-of-digits.js b/1295-find-numbers-with-even-number-of-digits.js similarity index 100% rename from solutions/1295-find-numbers-with-even-number-of-digits.js rename to 1295-find-numbers-with-even-number-of-digits.js diff --git a/solutions/1296-divide-array-in-sets-of-k-consecutive-numbers.js b/1296-divide-array-in-sets-of-k-consecutive-numbers.js similarity index 100% rename from solutions/1296-divide-array-in-sets-of-k-consecutive-numbers.js rename to 1296-divide-array-in-sets-of-k-consecutive-numbers.js diff --git a/solutions/1297-maximum-number-of-occurrences-of-a-substring.js b/1297-maximum-number-of-occurrences-of-a-substring.js similarity index 100% rename from solutions/1297-maximum-number-of-occurrences-of-a-substring.js rename to 1297-maximum-number-of-occurrences-of-a-substring.js diff --git a/solutions/1304-find-n-unique-integers-sum-up-to-zero.js b/1304-find-n-unique-integers-sum-up-to-zero.js similarity index 100% rename from solutions/1304-find-n-unique-integers-sum-up-to-zero.js rename to 1304-find-n-unique-integers-sum-up-to-zero.js diff --git a/solutions/1309-decrypt-string-from-alphabet-to-integer-mapping.js b/1309-decrypt-string-from-alphabet-to-integer-mapping.js similarity index 100% rename from solutions/1309-decrypt-string-from-alphabet-to-integer-mapping.js rename to 1309-decrypt-string-from-alphabet-to-integer-mapping.js diff --git a/solutions/1313-decompress-run-length-encoded-list.js b/1313-decompress-run-length-encoded-list.js similarity index 100% rename from solutions/1313-decompress-run-length-encoded-list.js rename to 1313-decompress-run-length-encoded-list.js diff --git a/solutions/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 similarity index 100% rename from solutions/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js rename to 1317-convert-integer-to-the-sum-of-two-no-zero-integers.js diff --git a/solutions/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 similarity index 100% rename from solutions/1318-minimum-flips-to-make-a-or-b-equal-to-c.js rename to 1318-minimum-flips-to-make-a-or-b-equal-to-c.js diff --git a/solutions/1319-number-of-operations-to-make-network-connected.js b/1319-number-of-operations-to-make-network-connected.js similarity index 100% rename from solutions/1319-number-of-operations-to-make-network-connected.js rename to 1319-number-of-operations-to-make-network-connected.js diff --git a/solutions/1323-maximum-69-number.js b/1323-maximum-69-number.js similarity index 100% rename from solutions/1323-maximum-69-number.js rename to 1323-maximum-69-number.js diff --git a/solutions/1324-print-words-vertically.js b/1324-print-words-vertically.js similarity index 100% rename from solutions/1324-print-words-vertically.js rename to 1324-print-words-vertically.js diff --git a/solutions/1331-rank-transform-of-an-array.js b/1331-rank-transform-of-an-array.js similarity index 100% rename from solutions/1331-rank-transform-of-an-array.js rename to 1331-rank-transform-of-an-array.js diff --git a/solutions/1332-remove-palindromic-subsequences.js b/1332-remove-palindromic-subsequences.js similarity index 100% rename from solutions/1332-remove-palindromic-subsequences.js rename to 1332-remove-palindromic-subsequences.js diff --git a/solutions/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js b/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js similarity index 100% rename from solutions/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js rename to 1333-filter-restaurants-by-vegan-friendly-price-and-distance.js diff --git a/solutions/1342-number-of-steps-to-reduce-a-number-to-zero.js b/1342-number-of-steps-to-reduce-a-number-to-zero.js similarity index 100% rename from solutions/1342-number-of-steps-to-reduce-a-number-to-zero.js rename to 1342-number-of-steps-to-reduce-a-number-to-zero.js diff --git a/solutions/1351-count-negative-numbers-in-a-sorted-matrix.js b/1351-count-negative-numbers-in-a-sorted-matrix.js similarity index 100% rename from solutions/1351-count-negative-numbers-in-a-sorted-matrix.js rename to 1351-count-negative-numbers-in-a-sorted-matrix.js diff --git a/solutions/1352-product-of-the-last-k-numbers.js b/1352-product-of-the-last-k-numbers.js similarity index 100% rename from solutions/1352-product-of-the-last-k-numbers.js rename to 1352-product-of-the-last-k-numbers.js diff --git a/solutions/1356-sort-integers-by-the-number-of-1-bits.js b/1356-sort-integers-by-the-number-of-1-bits.js similarity index 100% rename from solutions/1356-sort-integers-by-the-number-of-1-bits.js rename to 1356-sort-integers-by-the-number-of-1-bits.js diff --git a/solutions/1360-number-of-days-between-two-dates.js b/1360-number-of-days-between-two-dates.js similarity index 100% rename from solutions/1360-number-of-days-between-two-dates.js rename to 1360-number-of-days-between-two-dates.js diff --git a/solutions/1365-how-many-numbers-are-smaller-than-the-current-number.js b/1365-how-many-numbers-are-smaller-than-the-current-number.js similarity index 100% rename from solutions/1365-how-many-numbers-are-smaller-than-the-current-number.js rename to 1365-how-many-numbers-are-smaller-than-the-current-number.js diff --git a/solutions/1366-rank-teams-by-votes.js b/1366-rank-teams-by-votes.js similarity index 100% rename from solutions/1366-rank-teams-by-votes.js rename to 1366-rank-teams-by-votes.js diff --git a/solutions/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js b/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js similarity index 100% rename from solutions/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js rename to 1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js diff --git a/solutions/1372-longest-zigzag-path-in-a-binary-tree.js b/1372-longest-zigzag-path-in-a-binary-tree.js similarity index 100% rename from solutions/1372-longest-zigzag-path-in-a-binary-tree.js rename to 1372-longest-zigzag-path-in-a-binary-tree.js diff --git a/solutions/1374-generate-a-string-with-characters-that-have-odd-counts.js b/1374-generate-a-string-with-characters-that-have-odd-counts.js similarity index 100% rename from solutions/1374-generate-a-string-with-characters-that-have-odd-counts.js rename to 1374-generate-a-string-with-characters-that-have-odd-counts.js diff --git a/solutions/1380-lucky-numbers-in-a-matrix.js b/1380-lucky-numbers-in-a-matrix.js similarity index 100% rename from solutions/1380-lucky-numbers-in-a-matrix.js rename to 1380-lucky-numbers-in-a-matrix.js diff --git a/solutions/1389-create-target-array-in-the-given-order.js b/1389-create-target-array-in-the-given-order.js similarity index 100% rename from solutions/1389-create-target-array-in-the-given-order.js rename to 1389-create-target-array-in-the-given-order.js diff --git a/solutions/1400-construct-k-palindrome-strings.js b/1400-construct-k-palindrome-strings.js similarity index 100% rename from solutions/1400-construct-k-palindrome-strings.js rename to 1400-construct-k-palindrome-strings.js diff --git a/solutions/1402-reducing-dishes.js b/1402-reducing-dishes.js similarity index 100% rename from solutions/1402-reducing-dishes.js rename to 1402-reducing-dishes.js diff --git a/solutions/1408-string-matching-in-an-array.js b/1408-string-matching-in-an-array.js similarity index 100% rename from solutions/1408-string-matching-in-an-array.js rename to 1408-string-matching-in-an-array.js diff --git a/solutions/1410-html-entity-parser.js b/1410-html-entity-parser.js similarity index 100% rename from solutions/1410-html-entity-parser.js rename to 1410-html-entity-parser.js diff --git a/solutions/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js b/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js similarity index 100% rename from solutions/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js rename to 1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js diff --git a/solutions/1431-kids-with-the-greatest-number-of-candies.js b/1431-kids-with-the-greatest-number-of-candies.js similarity index 100% rename from solutions/1431-kids-with-the-greatest-number-of-candies.js rename to 1431-kids-with-the-greatest-number-of-candies.js diff --git a/solutions/1436-destination-city.js b/1436-destination-city.js similarity index 100% rename from solutions/1436-destination-city.js rename to 1436-destination-city.js diff --git a/solutions/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 similarity index 100% rename from solutions/1437-check-if-all-1s-are-at-least-length-k-places-away.js rename to 1437-check-if-all-1s-are-at-least-length-k-places-away.js diff --git a/solutions/1443-minimum-time-to-collect-all-apples-in-a-tree.js b/1443-minimum-time-to-collect-all-apples-in-a-tree.js similarity index 100% rename from solutions/1443-minimum-time-to-collect-all-apples-in-a-tree.js rename to 1443-minimum-time-to-collect-all-apples-in-a-tree.js diff --git a/solutions/1446-consecutive-characters.js b/1446-consecutive-characters.js similarity index 100% rename from solutions/1446-consecutive-characters.js rename to 1446-consecutive-characters.js diff --git a/solutions/1447-simplified-fractions.js b/1447-simplified-fractions.js similarity index 100% rename from solutions/1447-simplified-fractions.js rename to 1447-simplified-fractions.js diff --git a/solutions/1448-count-good-nodes-in-binary-tree.js b/1448-count-good-nodes-in-binary-tree.js similarity index 100% rename from solutions/1448-count-good-nodes-in-binary-tree.js rename to 1448-count-good-nodes-in-binary-tree.js diff --git a/solutions/1450-number-of-students-doing-homework-at-a-given-time.js b/1450-number-of-students-doing-homework-at-a-given-time.js similarity index 100% rename from solutions/1450-number-of-students-doing-homework-at-a-given-time.js rename to 1450-number-of-students-doing-homework-at-a-given-time.js diff --git a/solutions/1451-rearrange-words-in-a-sentence.js b/1451-rearrange-words-in-a-sentence.js similarity index 100% rename from solutions/1451-rearrange-words-in-a-sentence.js rename to 1451-rearrange-words-in-a-sentence.js diff --git a/solutions/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 similarity index 100% rename from solutions/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js rename to 1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js diff --git a/solutions/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 similarity index 100% rename from solutions/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js rename to 1456-maximum-number-of-vowels-in-a-substring-of-given-length.js diff --git a/solutions/1460-make-two-arrays-equal-by-reversing-sub-arrays.js b/1460-make-two-arrays-equal-by-reversing-sub-arrays.js similarity index 100% rename from solutions/1460-make-two-arrays-equal-by-reversing-sub-arrays.js rename to 1460-make-two-arrays-equal-by-reversing-sub-arrays.js diff --git a/solutions/1462-course-schedule-iv.js b/1462-course-schedule-iv.js similarity index 100% rename from solutions/1462-course-schedule-iv.js rename to 1462-course-schedule-iv.js diff --git a/solutions/1464-maximum-product-of-two-elements-in-an-array.js b/1464-maximum-product-of-two-elements-in-an-array.js similarity index 100% rename from solutions/1464-maximum-product-of-two-elements-in-an-array.js rename to 1464-maximum-product-of-two-elements-in-an-array.js diff --git a/solutions/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 similarity index 100% rename from solutions/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js rename to 1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js diff --git a/solutions/1470-shuffle-the-array.js b/1470-shuffle-the-array.js similarity index 100% rename from solutions/1470-shuffle-the-array.js rename to 1470-shuffle-the-array.js diff --git a/solutions/1472-design-browser-history.js b/1472-design-browser-history.js similarity index 100% rename from solutions/1472-design-browser-history.js rename to 1472-design-browser-history.js diff --git a/solutions/1475-final-prices-with-a-special-discount-in-a-shop.js b/1475-final-prices-with-a-special-discount-in-a-shop.js similarity index 100% rename from solutions/1475-final-prices-with-a-special-discount-in-a-shop.js rename to 1475-final-prices-with-a-special-discount-in-a-shop.js diff --git a/solutions/1480-running-sum-of-1d-array.js b/1480-running-sum-of-1d-array.js similarity index 100% rename from solutions/1480-running-sum-of-1d-array.js rename to 1480-running-sum-of-1d-array.js diff --git a/solutions/1481-least-number-of-unique-integers-after-k-removals.js b/1481-least-number-of-unique-integers-after-k-removals.js similarity index 100% rename from solutions/1481-least-number-of-unique-integers-after-k-removals.js rename to 1481-least-number-of-unique-integers-after-k-removals.js diff --git a/solutions/1486-xor-operation-in-an-array.js b/1486-xor-operation-in-an-array.js similarity index 100% rename from solutions/1486-xor-operation-in-an-array.js rename to 1486-xor-operation-in-an-array.js diff --git a/solutions/1491-average-salary-excluding-the-minimum-and-maximum-salary.js b/1491-average-salary-excluding-the-minimum-and-maximum-salary.js similarity index 100% rename from solutions/1491-average-salary-excluding-the-minimum-and-maximum-salary.js rename to 1491-average-salary-excluding-the-minimum-and-maximum-salary.js diff --git a/solutions/1492-the-kth-factor-of-n.js b/1492-the-kth-factor-of-n.js similarity index 100% rename from solutions/1492-the-kth-factor-of-n.js rename to 1492-the-kth-factor-of-n.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..b6729832 --- /dev/null +++ b/1493-longest-subarray-of-1s-after-deleting-one-element.js @@ -0,0 +1,53 @@ +/** + * 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); +}; + +// 1004. +// var longestSubarray = function(nums) { +// const k = 1 +// let begin = 0 +// let window_state = 0 +// let result = 0 + +// for (let end = 0; end < nums.length; end++ ) { +// if (nums[end] === 0) { +// window_state += 1 +// } + +// while (window_state > k) { +// if (nums[begin] === 0) { +// window_state -= 1 +// } +// begin++ +// } +// result = Math.max(result, end - begin + 1) +// } + +// return result - 1 +// }; \ No newline at end of file diff --git a/solutions/1496-path-crossing.js b/1496-path-crossing.js similarity index 100% rename from solutions/1496-path-crossing.js rename to 1496-path-crossing.js diff --git a/solutions/1502-can-make-arithmetic-progression-from-sequence.js b/1502-can-make-arithmetic-progression-from-sequence.js similarity index 100% rename from solutions/1502-can-make-arithmetic-progression-from-sequence.js rename to 1502-can-make-arithmetic-progression-from-sequence.js diff --git a/solutions/1507-reformat-date.js b/1507-reformat-date.js similarity index 100% rename from solutions/1507-reformat-date.js rename to 1507-reformat-date.js diff --git a/solutions/1512-number-of-good-pairs.js b/1512-number-of-good-pairs.js similarity index 100% rename from solutions/1512-number-of-good-pairs.js rename to 1512-number-of-good-pairs.js diff --git a/solutions/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 similarity index 100% rename from solutions/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js rename to 1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js diff --git a/solutions/1524-number-of-sub-arrays-with-odd-sum.js b/1524-number-of-sub-arrays-with-odd-sum.js similarity index 100% rename from solutions/1524-number-of-sub-arrays-with-odd-sum.js rename to 1524-number-of-sub-arrays-with-odd-sum.js diff --git a/solutions/1528-shuffle-string.js b/1528-shuffle-string.js similarity index 100% rename from solutions/1528-shuffle-string.js rename to 1528-shuffle-string.js diff --git a/solutions/1535-find-the-winner-of-an-array-game.js b/1535-find-the-winner-of-an-array-game.js similarity index 100% rename from solutions/1535-find-the-winner-of-an-array-game.js rename to 1535-find-the-winner-of-an-array-game.js diff --git a/solutions/1550-three-consecutive-odds.js b/1550-three-consecutive-odds.js similarity index 100% rename from solutions/1550-three-consecutive-odds.js rename to 1550-three-consecutive-odds.js diff --git a/solutions/1551-minimum-operations-to-make-array-equal.js b/1551-minimum-operations-to-make-array-equal.js similarity index 100% rename from solutions/1551-minimum-operations-to-make-array-equal.js rename to 1551-minimum-operations-to-make-array-equal.js diff --git a/solutions/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 similarity index 100% rename from solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js rename to 1566-detect-pattern-of-length-m-repeated-k-or-more-times.js diff --git a/solutions/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js b/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js similarity index 100% rename from solutions/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js rename to 1576-replace-all-s-to-avoid-consecutive-repeating-characters.js diff --git a/solutions/1598-crawler-log-folder.js b/1598-crawler-log-folder.js similarity index 100% rename from solutions/1598-crawler-log-folder.js rename to 1598-crawler-log-folder.js diff --git a/solutions/1657-determine-if-two-strings-are-close.js b/1657-determine-if-two-strings-are-close.js similarity index 100% rename from solutions/1657-determine-if-two-strings-are-close.js rename to 1657-determine-if-two-strings-are-close.js diff --git a/solutions/1668-maximum-repeating-substring.js b/1668-maximum-repeating-substring.js similarity index 100% rename from solutions/1668-maximum-repeating-substring.js rename to 1668-maximum-repeating-substring.js diff --git a/solutions/1669-merge-in-between-linked-lists.js b/1669-merge-in-between-linked-lists.js similarity index 100% rename from solutions/1669-merge-in-between-linked-lists.js rename to 1669-merge-in-between-linked-lists.js diff --git a/solutions/1672-richest-customer-wealth.js b/1672-richest-customer-wealth.js similarity index 100% rename from solutions/1672-richest-customer-wealth.js rename to 1672-richest-customer-wealth.js diff --git a/solutions/1679-max-number-of-k-sum-pairs.js b/1679-max-number-of-k-sum-pairs.js similarity index 100% rename from solutions/1679-max-number-of-k-sum-pairs.js rename to 1679-max-number-of-k-sum-pairs.js diff --git a/solutions/1716-calculate-money-in-leetcode-bank.js b/1716-calculate-money-in-leetcode-bank.js similarity index 100% rename from solutions/1716-calculate-money-in-leetcode-bank.js rename to 1716-calculate-money-in-leetcode-bank.js diff --git a/solutions/1718-construct-the-lexicographically-largest-valid-sequence.js b/1718-construct-the-lexicographically-largest-valid-sequence.js similarity index 100% rename from solutions/1718-construct-the-lexicographically-largest-valid-sequence.js rename to 1718-construct-the-lexicographically-largest-valid-sequence.js diff --git a/solutions/1726-tuple-with-same-product.js b/1726-tuple-with-same-product.js similarity index 100% rename from solutions/1726-tuple-with-same-product.js rename to 1726-tuple-with-same-product.js diff --git a/solutions/1732-find-the-highest-altitude.js b/1732-find-the-highest-altitude.js similarity index 100% rename from solutions/1732-find-the-highest-altitude.js rename to 1732-find-the-highest-altitude.js diff --git a/solutions/1748-sum-of-unique-elements.js b/1748-sum-of-unique-elements.js similarity index 100% rename from solutions/1748-sum-of-unique-elements.js rename to 1748-sum-of-unique-elements.js diff --git a/solutions/1749-maximum-absolute-sum-of-any-subarray.js b/1749-maximum-absolute-sum-of-any-subarray.js similarity index 100% rename from solutions/1749-maximum-absolute-sum-of-any-subarray.js rename to 1749-maximum-absolute-sum-of-any-subarray.js diff --git a/solutions/1752-check-if-array-is-sorted-and-rotated.js b/1752-check-if-array-is-sorted-and-rotated.js similarity index 100% rename from solutions/1752-check-if-array-is-sorted-and-rotated.js rename to 1752-check-if-array-is-sorted-and-rotated.js diff --git a/solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js b/1764-form-array-by-concatenating-subarrays-of-another-array.js similarity index 100% rename from solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js rename to 1764-form-array-by-concatenating-subarrays-of-another-array.js diff --git a/solutions/1765-map-of-highest-peak.js b/1765-map-of-highest-peak.js similarity index 100% rename from solutions/1765-map-of-highest-peak.js rename to 1765-map-of-highest-peak.js diff --git a/solutions/1768-merge-strings-alternately.js b/1768-merge-strings-alternately.js similarity index 100% rename from solutions/1768-merge-strings-alternately.js rename to 1768-merge-strings-alternately.js diff --git a/solutions/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js b/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js similarity index 100% rename from solutions/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js rename to 1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js diff --git a/solutions/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 similarity index 100% rename from solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js rename to 1780-check-if-number-is-a-sum-of-powers-of-three.js diff --git a/solutions/1790-check-if-one-string-swap-can-make-strings-equal.js b/1790-check-if-one-string-swap-can-make-strings-equal.js similarity index 100% rename from solutions/1790-check-if-one-string-swap-can-make-strings-equal.js rename to 1790-check-if-one-string-swap-can-make-strings-equal.js diff --git a/solutions/1791-find-center-of-star-graph.js b/1791-find-center-of-star-graph.js similarity index 100% rename from solutions/1791-find-center-of-star-graph.js rename to 1791-find-center-of-star-graph.js diff --git a/solutions/1800-maximum-ascending-subarray-sum.js b/1800-maximum-ascending-subarray-sum.js similarity index 100% rename from solutions/1800-maximum-ascending-subarray-sum.js rename to 1800-maximum-ascending-subarray-sum.js diff --git a/solutions/1812-determine-color-of-a-chessboard-square.js b/1812-determine-color-of-a-chessboard-square.js similarity index 100% rename from solutions/1812-determine-color-of-a-chessboard-square.js rename to 1812-determine-color-of-a-chessboard-square.js diff --git a/solutions/1817-finding-the-users-active-minutes.js b/1817-finding-the-users-active-minutes.js similarity index 100% rename from solutions/1817-finding-the-users-active-minutes.js rename to 1817-finding-the-users-active-minutes.js diff --git a/solutions/1832-check-if-the-sentence-is-pangram.js b/1832-check-if-the-sentence-is-pangram.js similarity index 100% rename from solutions/1832-check-if-the-sentence-is-pangram.js rename to 1832-check-if-the-sentence-is-pangram.js diff --git a/solutions/1833-maximum-ice-cream-bars.js b/1833-maximum-ice-cream-bars.js similarity index 100% rename from solutions/1833-maximum-ice-cream-bars.js rename to 1833-maximum-ice-cream-bars.js diff --git a/solutions/1880-check-if-word-equals-summation-of-two-words.js b/1880-check-if-word-equals-summation-of-two-words.js similarity index 100% rename from solutions/1880-check-if-word-equals-summation-of-two-words.js rename to 1880-check-if-word-equals-summation-of-two-words.js diff --git a/solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js b/1886-determine-whether-matrix-can-be-obtained-by-rotation.js similarity index 100% rename from solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js rename to 1886-determine-whether-matrix-can-be-obtained-by-rotation.js diff --git a/solutions/1910-remove-all-occurrences-of-a-substring.js b/1910-remove-all-occurrences-of-a-substring.js similarity index 100% rename from solutions/1910-remove-all-occurrences-of-a-substring.js rename to 1910-remove-all-occurrences-of-a-substring.js diff --git a/solutions/1920-build-array-from-permutation.js b/1920-build-array-from-permutation.js similarity index 100% rename from solutions/1920-build-array-from-permutation.js rename to 1920-build-array-from-permutation.js diff --git a/solutions/1926-nearest-exit-from-entrance-in-maze.js b/1926-nearest-exit-from-entrance-in-maze.js similarity index 100% rename from solutions/1926-nearest-exit-from-entrance-in-maze.js rename to 1926-nearest-exit-from-entrance-in-maze.js diff --git a/solutions/1929-concatenation-of-array.js b/1929-concatenation-of-array.js similarity index 100% rename from solutions/1929-concatenation-of-array.js rename to 1929-concatenation-of-array.js diff --git a/solutions/1930-unique-length-3-palindromic-subsequences.js b/1930-unique-length-3-palindromic-subsequences.js similarity index 100% rename from solutions/1930-unique-length-3-palindromic-subsequences.js rename to 1930-unique-length-3-palindromic-subsequences.js diff --git a/solutions/1935-maximum-number-of-words-you-can-type.js b/1935-maximum-number-of-words-you-can-type.js similarity index 100% rename from solutions/1935-maximum-number-of-words-you-can-type.js rename to 1935-maximum-number-of-words-you-can-type.js diff --git a/solutions/1980-find-unique-binary-string.js b/1980-find-unique-binary-string.js similarity index 100% rename from solutions/1980-find-unique-binary-string.js rename to 1980-find-unique-binary-string.js diff --git a/solutions/1985-find-the-kth-largest-integer-in-the-array.js b/1985-find-the-kth-largest-integer-in-the-array.js similarity index 100% rename from solutions/1985-find-the-kth-largest-integer-in-the-array.js rename to 1985-find-the-kth-largest-integer-in-the-array.js diff --git a/solutions/1996-the-number-of-weak-characters-in-the-game.js b/1996-the-number-of-weak-characters-in-the-game.js similarity index 100% rename from solutions/1996-the-number-of-weak-characters-in-the-game.js rename to 1996-the-number-of-weak-characters-in-the-game.js diff --git a/solutions/2000-reverse-prefix-of-word.js b/2000-reverse-prefix-of-word.js similarity index 100% rename from solutions/2000-reverse-prefix-of-word.js rename to 2000-reverse-prefix-of-word.js diff --git a/solutions/2011-final-value-of-variable-after-performing-operations.js b/2011-final-value-of-variable-after-performing-operations.js similarity index 100% rename from solutions/2011-final-value-of-variable-after-performing-operations.js rename to 2011-final-value-of-variable-after-performing-operations.js diff --git a/solutions/2016-maximum-difference-between-increasing-elements.js b/2016-maximum-difference-between-increasing-elements.js similarity index 100% rename from solutions/2016-maximum-difference-between-increasing-elements.js rename to 2016-maximum-difference-between-increasing-elements.js diff --git a/solutions/2017-grid-game.js b/2017-grid-game.js similarity index 100% rename from solutions/2017-grid-game.js rename to 2017-grid-game.js diff --git a/solutions/2027-minimum-moves-to-convert-string.js b/2027-minimum-moves-to-convert-string.js similarity index 100% rename from solutions/2027-minimum-moves-to-convert-string.js rename to 2027-minimum-moves-to-convert-string.js diff --git a/solutions/2037-minimum-number-of-moves-to-seat-everyone.js b/2037-minimum-number-of-moves-to-seat-everyone.js similarity index 100% rename from solutions/2037-minimum-number-of-moves-to-seat-everyone.js rename to 2037-minimum-number-of-moves-to-seat-everyone.js diff --git a/solutions/2047-number-of-valid-words-in-a-sentence.js b/2047-number-of-valid-words-in-a-sentence.js similarity index 100% rename from solutions/2047-number-of-valid-words-in-a-sentence.js rename to 2047-number-of-valid-words-in-a-sentence.js diff --git a/solutions/2053-kth-distinct-string-in-an-array.js b/2053-kth-distinct-string-in-an-array.js similarity index 100% rename from solutions/2053-kth-distinct-string-in-an-array.js rename to 2053-kth-distinct-string-in-an-array.js diff --git a/solutions/2085-count-common-words-with-one-occurrence.js b/2085-count-common-words-with-one-occurrence.js similarity index 100% rename from solutions/2085-count-common-words-with-one-occurrence.js rename to 2085-count-common-words-with-one-occurrence.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..e4408b38 --- /dev/null +++ b/2095-delete-the-middle-node-of-a-linked-list.js @@ -0,0 +1,44 @@ +/** + * 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) { + // slow = head + // fast = head.next.next + let slow = new Node(0, null, 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/solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js b/2099-find-subsequence-of-length-k-with-the-largest-sum.js similarity index 100% rename from solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js rename to 2099-find-subsequence-of-length-k-with-the-largest-sum.js diff --git a/solutions/2114-maximum-number-of-words-found-in-sentences.js b/2114-maximum-number-of-words-found-in-sentences.js similarity index 100% rename from solutions/2114-maximum-number-of-words-found-in-sentences.js rename to 2114-maximum-number-of-words-found-in-sentences.js diff --git a/solutions/2116-check-if-a-parentheses-string-can-be-valid.js b/2116-check-if-a-parentheses-string-can-be-valid.js similarity index 100% rename from solutions/2116-check-if-a-parentheses-string-can-be-valid.js rename to 2116-check-if-a-parentheses-string-can-be-valid.js diff --git a/solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js b/2127-maximum-employees-to-be-invited-to-a-meeting.js similarity index 100% rename from solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js rename to 2127-maximum-employees-to-be-invited-to-a-meeting.js diff --git a/solutions/2129-capitalize-the-title.js b/2129-capitalize-the-title.js similarity index 100% rename from solutions/2129-capitalize-the-title.js rename to 2129-capitalize-the-title.js diff --git a/solutions/2130-maximum-twin-sum-of-a-linked-list.js b/2130-maximum-twin-sum-of-a-linked-list.js similarity index 100% rename from solutions/2130-maximum-twin-sum-of-a-linked-list.js rename to 2130-maximum-twin-sum-of-a-linked-list.js diff --git a/solutions/2154-keep-multiplying-found-values-by-two.js b/2154-keep-multiplying-found-values-by-two.js similarity index 100% rename from solutions/2154-keep-multiplying-found-values-by-two.js rename to 2154-keep-multiplying-found-values-by-two.js diff --git a/solutions/2161-partition-array-according-to-given-pivot.js b/2161-partition-array-according-to-given-pivot.js similarity index 100% rename from solutions/2161-partition-array-according-to-given-pivot.js rename to 2161-partition-array-according-to-given-pivot.js diff --git a/solutions/2185-counting-words-with-a-given-prefix.js b/2185-counting-words-with-a-given-prefix.js similarity index 100% rename from solutions/2185-counting-words-with-a-given-prefix.js rename to 2185-counting-words-with-a-given-prefix.js diff --git a/solutions/2215-find-the-difference-of-two-arrays.js b/2215-find-the-difference-of-two-arrays.js similarity index 100% rename from solutions/2215-find-the-difference-of-two-arrays.js rename to 2215-find-the-difference-of-two-arrays.js diff --git a/solutions/2235-add-two-integers.js b/2235-add-two-integers.js similarity index 100% rename from solutions/2235-add-two-integers.js rename to 2235-add-two-integers.js diff --git a/solutions/2244-minimum-rounds-to-complete-all-tasks.js b/2244-minimum-rounds-to-complete-all-tasks.js similarity index 100% rename from solutions/2244-minimum-rounds-to-complete-all-tasks.js rename to 2244-minimum-rounds-to-complete-all-tasks.js diff --git a/solutions/2300-successful-pairs-of-spells-and-potions.js b/2300-successful-pairs-of-spells-and-potions.js similarity index 100% rename from solutions/2300-successful-pairs-of-spells-and-potions.js rename to 2300-successful-pairs-of-spells-and-potions.js diff --git a/solutions/2336-smallest-number-in-infinite-set.js b/2336-smallest-number-in-infinite-set.js similarity index 100% rename from solutions/2336-smallest-number-in-infinite-set.js rename to 2336-smallest-number-in-infinite-set.js diff --git a/solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js b/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js similarity index 100% rename from solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js rename to 2342-max-sum-of-a-pair-with-equal-sum-of-digits.js diff --git a/solutions/2349-design-a-number-container-system.js b/2349-design-a-number-container-system.js similarity index 100% rename from solutions/2349-design-a-number-container-system.js rename to 2349-design-a-number-container-system.js diff --git a/solutions/2352-equal-row-and-column-pairs.js b/2352-equal-row-and-column-pairs.js similarity index 100% rename from solutions/2352-equal-row-and-column-pairs.js rename to 2352-equal-row-and-column-pairs.js diff --git a/solutions/2364-count-number-of-bad-pairs.js b/2364-count-number-of-bad-pairs.js similarity index 100% rename from solutions/2364-count-number-of-bad-pairs.js rename to 2364-count-number-of-bad-pairs.js diff --git a/solutions/2375-construct-smallest-number-from-di-string.js b/2375-construct-smallest-number-from-di-string.js similarity index 100% rename from solutions/2375-construct-smallest-number-from-di-string.js rename to 2375-construct-smallest-number-from-di-string.js diff --git a/solutions/2381-shifting-letters-ii.js b/2381-shifting-letters-ii.js similarity index 100% rename from solutions/2381-shifting-letters-ii.js rename to 2381-shifting-letters-ii.js diff --git a/solutions/2390-removing-stars-from-a-string.js b/2390-removing-stars-from-a-string.js similarity index 81% rename from solutions/2390-removing-stars-from-a-string.js rename to 2390-removing-stars-from-a-string.js index 1130802e..942a0a0c 100644 --- a/solutions/2390-removing-stars-from-a-string.js +++ b/2390-removing-stars-from-a-string.js @@ -31,3 +31,13 @@ var removeStars = function(s) { } return result.join(''); }; + +// var removeStars = function(s) { +// const stack = []; + +// for (const char of s) { +// char === '*' ? stack.pop(): stack.push(char) +// } + +// return stack.join(''); +// }; diff --git a/solutions/2396-strictly-palindromic-number.js b/2396-strictly-palindromic-number.js similarity index 100% rename from solutions/2396-strictly-palindromic-number.js rename to 2396-strictly-palindromic-number.js diff --git a/solutions/2413-smallest-even-multiple.js b/2413-smallest-even-multiple.js similarity index 100% rename from solutions/2413-smallest-even-multiple.js rename to 2413-smallest-even-multiple.js diff --git a/solutions/2425-bitwise-xor-of-all-pairings.js b/2425-bitwise-xor-of-all-pairings.js similarity index 100% rename from solutions/2425-bitwise-xor-of-all-pairings.js rename to 2425-bitwise-xor-of-all-pairings.js diff --git a/solutions/2427-number-of-common-factors.js b/2427-number-of-common-factors.js similarity index 100% rename from solutions/2427-number-of-common-factors.js rename to 2427-number-of-common-factors.js diff --git a/solutions/2429-minimize-xor.js b/2429-minimize-xor.js similarity index 100% rename from solutions/2429-minimize-xor.js rename to 2429-minimize-xor.js diff --git a/solutions/2460-apply-operations-to-an-array.js b/2460-apply-operations-to-an-array.js similarity index 100% rename from solutions/2460-apply-operations-to-an-array.js rename to 2460-apply-operations-to-an-array.js diff --git a/solutions/2462-total-cost-to-hire-k-workers.js b/2462-total-cost-to-hire-k-workers.js similarity index 100% rename from solutions/2462-total-cost-to-hire-k-workers.js rename to 2462-total-cost-to-hire-k-workers.js diff --git a/solutions/2467-most-profitable-path-in-a-tree.js b/2467-most-profitable-path-in-a-tree.js similarity index 100% rename from solutions/2467-most-profitable-path-in-a-tree.js rename to 2467-most-profitable-path-in-a-tree.js diff --git a/solutions/2469-convert-the-temperature.js b/2469-convert-the-temperature.js similarity index 100% rename from solutions/2469-convert-the-temperature.js rename to 2469-convert-the-temperature.js diff --git a/solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js b/2482-difference-between-ones-and-zeros-in-row-and-column.js similarity index 100% rename from solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js rename to 2482-difference-between-ones-and-zeros-in-row-and-column.js diff --git a/solutions/2490-circular-sentence.js b/2490-circular-sentence.js similarity index 100% rename from solutions/2490-circular-sentence.js rename to 2490-circular-sentence.js diff --git a/solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js b/2493-divide-nodes-into-the-maximum-number-of-groups.js similarity index 100% rename from solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js rename to 2493-divide-nodes-into-the-maximum-number-of-groups.js diff --git a/solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js b/2529-maximum-count-of-positive-integer-and-negative-integer.js similarity index 100% rename from solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js rename to 2529-maximum-count-of-positive-integer-and-negative-integer.js diff --git a/solutions/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 similarity index 100% rename from solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js rename to 2535-difference-between-element-sum-and-digit-sum-of-an-array.js diff --git a/solutions/2542-maximum-subsequence-score.js b/2542-maximum-subsequence-score.js similarity index 100% rename from solutions/2542-maximum-subsequence-score.js rename to 2542-maximum-subsequence-score.js diff --git a/solutions/2570-merge-two-2d-arrays-by-summing-values.js b/2570-merge-two-2d-arrays-by-summing-values.js similarity index 100% rename from solutions/2570-merge-two-2d-arrays-by-summing-values.js rename to 2570-merge-two-2d-arrays-by-summing-values.js diff --git a/solutions/2618-check-if-object-instance-of-class.js b/2618-check-if-object-instance-of-class.js similarity index 100% rename from solutions/2618-check-if-object-instance-of-class.js rename to 2618-check-if-object-instance-of-class.js diff --git a/solutions/2619-array-prototype-last.js b/2619-array-prototype-last.js similarity index 100% rename from solutions/2619-array-prototype-last.js rename to 2619-array-prototype-last.js diff --git a/solutions/2620-counter.js b/2620-counter.js similarity index 100% rename from solutions/2620-counter.js rename to 2620-counter.js diff --git a/solutions/2621-sleep.js b/2621-sleep.js similarity index 100% rename from solutions/2621-sleep.js rename to 2621-sleep.js diff --git a/solutions/2622-cache-with-time-limit.js b/2622-cache-with-time-limit.js similarity index 100% rename from solutions/2622-cache-with-time-limit.js rename to 2622-cache-with-time-limit.js diff --git a/solutions/2623-memoize.js b/2623-memoize.js similarity index 100% rename from solutions/2623-memoize.js rename to 2623-memoize.js diff --git a/solutions/2625-flatten-deeply-nested-array.js b/2625-flatten-deeply-nested-array.js similarity index 100% rename from solutions/2625-flatten-deeply-nested-array.js rename to 2625-flatten-deeply-nested-array.js diff --git a/solutions/2626-array-reduce-transformation.js b/2626-array-reduce-transformation.js similarity index 100% rename from solutions/2626-array-reduce-transformation.js rename to 2626-array-reduce-transformation.js diff --git a/solutions/2627-debounce.js b/2627-debounce.js similarity index 100% rename from solutions/2627-debounce.js rename to 2627-debounce.js diff --git a/solutions/2629-function-composition.js b/2629-function-composition.js similarity index 100% rename from solutions/2629-function-composition.js rename to 2629-function-composition.js diff --git a/solutions/2630-memoize-ii.js b/2630-memoize-ii.js similarity index 100% rename from solutions/2630-memoize-ii.js rename to 2630-memoize-ii.js diff --git a/solutions/2631-group-by.js b/2631-group-by.js similarity index 100% rename from solutions/2631-group-by.js rename to 2631-group-by.js diff --git a/solutions/2634-filter-elements-from-array.js b/2634-filter-elements-from-array.js similarity index 100% rename from solutions/2634-filter-elements-from-array.js rename to 2634-filter-elements-from-array.js diff --git a/solutions/2635-apply-transform-over-each-element-in-array.js b/2635-apply-transform-over-each-element-in-array.js similarity index 100% rename from solutions/2635-apply-transform-over-each-element-in-array.js rename to 2635-apply-transform-over-each-element-in-array.js diff --git a/solutions/2637-promise-time-limit.js b/2637-promise-time-limit.js similarity index 100% rename from solutions/2637-promise-time-limit.js rename to 2637-promise-time-limit.js diff --git a/solutions/2648-generate-fibonacci-sequence.js b/2648-generate-fibonacci-sequence.js similarity index 100% rename from solutions/2648-generate-fibonacci-sequence.js rename to 2648-generate-fibonacci-sequence.js diff --git a/solutions/2649-nested-array-generator.js b/2649-nested-array-generator.js similarity index 100% rename from solutions/2649-nested-array-generator.js rename to 2649-nested-array-generator.js diff --git a/solutions/2650-design-cancellable-function.js b/2650-design-cancellable-function.js similarity index 100% rename from solutions/2650-design-cancellable-function.js rename to 2650-design-cancellable-function.js diff --git a/solutions/2657-find-the-prefix-common-array-of-two-arrays.js b/2657-find-the-prefix-common-array-of-two-arrays.js similarity index 100% rename from solutions/2657-find-the-prefix-common-array-of-two-arrays.js rename to 2657-find-the-prefix-common-array-of-two-arrays.js diff --git a/solutions/2658-maximum-number-of-fish-in-a-grid.js b/2658-maximum-number-of-fish-in-a-grid.js similarity index 100% rename from solutions/2658-maximum-number-of-fish-in-a-grid.js rename to 2658-maximum-number-of-fish-in-a-grid.js diff --git a/solutions/2661-first-completely-painted-row-or-column.js b/2661-first-completely-painted-row-or-column.js similarity index 100% rename from solutions/2661-first-completely-painted-row-or-column.js rename to 2661-first-completely-painted-row-or-column.js diff --git a/solutions/2665-counter-ii.js b/2665-counter-ii.js similarity index 100% rename from solutions/2665-counter-ii.js rename to 2665-counter-ii.js diff --git a/2666-allow-one-function-call.js b/2666-allow-one-function-call.js new file mode 100644 index 00000000..bc1da524 --- /dev/null +++ b/2666-allow-one-function-call.js @@ -0,0 +1,36 @@ +/** + * 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]; +}; + +// var once = function(fn) { + +// let hasBeenCalled = false; +// let result; + +// return function(...args) { +// if (!hasBeenCalled) { +// result = fn(...args); +// hasBeenCalled = true; +// return result; +// } else { +// return undefined; +// } +// } + +// }; diff --git a/solutions/2667-create-hello-world-function.js b/2667-create-hello-world-function.js similarity index 100% rename from solutions/2667-create-hello-world-function.js rename to 2667-create-hello-world-function.js diff --git a/solutions/2677-chunk-array.js b/2677-chunk-array.js similarity index 100% rename from solutions/2677-chunk-array.js rename to 2677-chunk-array.js diff --git a/solutions/2683-neighboring-bitwise-xor.js b/2683-neighboring-bitwise-xor.js similarity index 100% rename from solutions/2683-neighboring-bitwise-xor.js rename to 2683-neighboring-bitwise-xor.js diff --git a/solutions/2693-call-function-with-custom-context.js b/2693-call-function-with-custom-context.js similarity index 100% rename from solutions/2693-call-function-with-custom-context.js rename to 2693-call-function-with-custom-context.js diff --git a/solutions/2694-event-emitter.js b/2694-event-emitter.js similarity index 100% rename from solutions/2694-event-emitter.js rename to 2694-event-emitter.js diff --git a/solutions/2695-array-wrapper.js b/2695-array-wrapper.js similarity index 100% rename from solutions/2695-array-wrapper.js rename to 2695-array-wrapper.js diff --git a/solutions/2698-find-the-punishment-number-of-an-integer.js b/2698-find-the-punishment-number-of-an-integer.js similarity index 100% rename from solutions/2698-find-the-punishment-number-of-an-integer.js rename to 2698-find-the-punishment-number-of-an-integer.js diff --git a/solutions/2703-return-length-of-arguments-passed.js b/2703-return-length-of-arguments-passed.js similarity index 100% rename from solutions/2703-return-length-of-arguments-passed.js rename to 2703-return-length-of-arguments-passed.js diff --git a/solutions/2704-to-be-or-not-to-be.js b/2704-to-be-or-not-to-be.js similarity index 100% rename from solutions/2704-to-be-or-not-to-be.js rename to 2704-to-be-or-not-to-be.js diff --git a/solutions/2705-compact-object.js b/2705-compact-object.js similarity index 100% rename from solutions/2705-compact-object.js rename to 2705-compact-object.js diff --git a/solutions/2715-timeout-cancellation.js b/2715-timeout-cancellation.js similarity index 100% rename from solutions/2715-timeout-cancellation.js rename to 2715-timeout-cancellation.js diff --git a/solutions/2721-execute-asynchronous-functions-in-parallel.js b/2721-execute-asynchronous-functions-in-parallel.js similarity index 100% rename from solutions/2721-execute-asynchronous-functions-in-parallel.js rename to 2721-execute-asynchronous-functions-in-parallel.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..fb3893fd --- /dev/null +++ b/2722-join-two-arrays-by-id.js @@ -0,0 +1,48 @@ +/** + * 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); +}; + +// var join = function(arr1, arr2) { +// const result = {}; +// for (let i = 0; i < arr1.length; i++) { +// result[arr1[i].id] = arr1[i]; +// } +// for (let i = 0; i < arr2.length; i++) { +// if (result[arr2[i].id]) { +// for (const key in arr2[i]) result[arr2[i].id][key] = arr2[i][key]; +// } else { +// result[arr2[i].id] = arr2[i]; +// } +// } + +// return Object.values(result); +// }; diff --git a/solutions/2723-add-two-promises.js b/2723-add-two-promises.js similarity index 100% rename from solutions/2723-add-two-promises.js rename to 2723-add-two-promises.js diff --git a/solutions/2724-sort-by.js b/2724-sort-by.js similarity index 100% rename from solutions/2724-sort-by.js rename to 2724-sort-by.js diff --git a/solutions/2725-interval-cancellation.js b/2725-interval-cancellation.js similarity index 100% rename from solutions/2725-interval-cancellation.js rename to 2725-interval-cancellation.js diff --git a/solutions/2726-calculator-with-method-chaining.js b/2726-calculator-with-method-chaining.js similarity index 100% rename from solutions/2726-calculator-with-method-chaining.js rename to 2726-calculator-with-method-chaining.js diff --git a/solutions/2727-is-object-empty.js b/2727-is-object-empty.js similarity index 100% rename from solutions/2727-is-object-empty.js rename to 2727-is-object-empty.js diff --git a/solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js b/2948-make-lexicographically-smallest-array-by-swapping-elements.js similarity index 100% rename from solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js rename to 2948-make-lexicographically-smallest-array-by-swapping-elements.js diff --git a/solutions/3042-count-prefix-and-suffix-pairs-i.js b/3042-count-prefix-and-suffix-pairs-i.js similarity index 100% rename from solutions/3042-count-prefix-and-suffix-pairs-i.js rename to 3042-count-prefix-and-suffix-pairs-i.js diff --git a/solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js b/3066-minimum-operations-to-exceed-threshold-value-ii.js similarity index 100% rename from solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js rename to 3066-minimum-operations-to-exceed-threshold-value-ii.js diff --git a/solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js b/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js similarity index 100% rename from solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js rename to 3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js diff --git a/solutions/3110-score-of-a-string.js b/3110-score-of-a-string.js similarity index 100% rename from solutions/3110-score-of-a-string.js rename to 3110-score-of-a-string.js diff --git a/solutions/3151-special-array-i.js b/3151-special-array-i.js similarity index 100% rename from solutions/3151-special-array-i.js rename to 3151-special-array-i.js diff --git a/solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js b/3160-find-the-number-of-distinct-colors-among-the-balls.js similarity index 100% rename from solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js rename to 3160-find-the-number-of-distinct-colors-among-the-balls.js diff --git a/solutions/3174-clear-digits.js b/3174-clear-digits.js similarity index 100% rename from solutions/3174-clear-digits.js rename to 3174-clear-digits.js diff --git a/solutions/3223-minimum-length-of-string-after-operations.js b/3223-minimum-length-of-string-after-operations.js similarity index 100% rename from solutions/3223-minimum-length-of-string-after-operations.js rename to 3223-minimum-length-of-string-after-operations.js diff --git a/solutions/3392-count-subarrays-of-length-three-with-a-condition.js b/3392-count-subarrays-of-length-three-with-a-condition.js similarity index 100% rename from solutions/3392-count-subarrays-of-length-three-with-a-condition.js rename to 3392-count-subarrays-of-length-three-with-a-condition.js diff --git a/solutions/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 similarity index 100% rename from solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js rename to 3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js diff --git a/solutions/3397-maximum-number-of-distinct-elements-after-operations.js b/3397-maximum-number-of-distinct-elements-after-operations.js similarity index 100% rename from solutions/3397-maximum-number-of-distinct-elements-after-operations.js rename to 3397-maximum-number-of-distinct-elements-after-operations.js diff --git a/solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js b/3402-minimum-operations-to-make-columns-strictly-increasing.js similarity index 100% rename from solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js rename to 3402-minimum-operations-to-make-columns-strictly-increasing.js diff --git a/solutions/3452-sum-of-good-numbers.js b/3452-sum-of-good-numbers.js similarity index 100% rename from solutions/3452-sum-of-good-numbers.js rename to 3452-sum-of-good-numbers.js diff --git a/README.md b/README.md index 183c5fe8..e67b78e8 100644 --- a/README.md +++ b/README.md @@ -1,1959 +1,56 @@ -# 1,945 LeetCode solutions in JavaScript +# LeetCode solutions in JavaScript -[https://leetcodejavascript.com](https://leetcodejavascript.com) +This is my way for learning algorithms on JS. -## Table of Contents: +Repository with prepared empty tasks for training in [Example folder](https://github.com/Barklim/leetcode-javascript/tree/master/example) with test cases. -|#|Title|Difficulty| -|:---|:---|:---| -1|[Two Sum](./solutions/0001-two-sum.js)|Easy| -2|[Add Two Numbers](./solutions/0002-add-two-numbers.js)|Medium| -3|[Longest Substring Without Repeating Characters](./solutions/0003-longest-substring-without-repeating-characters.js)|Medium| -4|[Median of Two Sorted Arrays](./solutions/0004-median-of-two-sorted-arrays.js)|Hard| -5|[Longest Palindromic Substring](./solutions/0005-longest-palindromic-substring.js)|Medium| -6|[ZigZag Conversion](./solutions/0006-zigzag-conversion.js)|Medium| -7|[Reverse Integer](./solutions/0007-reverse-integer.js)|Easy| -8|[String to Integer (atoi)](./solutions/0008-string-to-integer-atoi.js)|Medium| -9|[Palindrome Number](./solutions/0009-palindrome-number.js)|Easy| -10|[Regular Expression Matching](./solutions/0010-regular-expression-matching.js)|Hard| -11|[Container With Most Water](./solutions/0011-container-with-most-water.js)|Medium| -12|[Integer to Roman](./solutions/0012-integer-to-roman.js)|Medium| -13|[Roman to Integer](./solutions/0013-roman-to-integer.js)|Easy| -14|[Longest Common Prefix](./solutions/0014-longest-common-prefix.js)|Easy| -15|[3Sum](./solutions/0015-3sum.js)|Medium| -16|[3Sum Closest](./solutions/0016-3sum-closest.js)|Medium| -17|[Letter Combinations of a Phone Number](./solutions/0017-letter-combinations-of-a-phone-number.js)|Medium| -18|[4Sum](./solutions/0018-4sum.js)|Medium| -19|[Remove Nth Node From End of List](./solutions/0019-remove-nth-node-from-end-of-list.js)|Medium| -20|[Valid Parentheses](./solutions/0020-valid-parentheses.js)|Easy| -21|[Merge Two Sorted Lists](./solutions/0021-merge-two-sorted-lists.js)|Easy| -22|[Generate Parentheses](./solutions/0022-generate-parentheses.js)|Medium| -23|[Merge k Sorted Lists](./solutions/0023-merge-k-sorted-lists.js)|Hard| -24|[Swap Nodes in Pairs](./solutions/0024-swap-nodes-in-pairs.js)|Medium| -25|[Reverse Nodes in k-Group](./solutions/0025-reverse-nodes-in-k-group.js)|Hard| -26|[Remove Duplicates from Sorted Array](./solutions/0026-remove-duplicates-from-sorted-array.js)|Easy| -27|[Remove Element](./solutions/0027-remove-element.js)|Easy| -28|[Implement strStr()](./solutions/0028-implement-strstr.js)|Easy| -29|[Divide Two Integers](./solutions/0029-divide-two-integers.js)|Medium| -30|[Substring with Concatenation of All Words](./solutions/0030-substring-with-concatenation-of-all-words.js)|Hard| -31|[Next Permutation](./solutions/0031-next-permutation.js)|Medium| -32|[Longest Valid Parentheses](./solutions/0032-longest-valid-parentheses.js)|Hard| -33|[Search in Rotated Sorted Array](./solutions/0033-search-in-rotated-sorted-array.js)|Medium| -34|[Find First and Last Position of Element in Sorted Array](./solutions/0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| -35|[Search Insert Position](./solutions/0035-search-insert-position.js)|Easy| -36|[Valid Sudoku](./solutions/0036-valid-sudoku.js)|Medium| -37|[Sudoku Solver](./solutions/0037-sudoku-solver.js)|Hard| -38|[Count and Say](./solutions/0038-count-and-say.js)|Medium| -39|[Combination Sum](./solutions/0039-combination-sum.js)|Medium| -40|[Combination Sum II](./solutions/0040-combination-sum-ii.js)|Medium| -41|[First Missing Positive](./solutions/0041-first-missing-positive.js)|Hard| -42|[Trapping Rain Water](./solutions/0042-trapping-rain-water.js)|Hard| -43|[Multiply Strings](./solutions/0043-multiply-strings.js)|Medium| -44|[Wildcard Matching](./solutions/0044-wildcard-matching.js)|Hard| -45|[Jump Game II](./solutions/0045-jump-game-ii.js)|Medium| -46|[Permutations](./solutions/0046-permutations.js)|Medium| -47|[Permutations II](./solutions/0047-permutations-ii.js)|Medium| -48|[Rotate Image](./solutions/0048-rotate-image.js)|Medium| -49|[Group Anagrams](./solutions/0049-group-anagrams.js)|Medium| -50|[Pow(x, n)](./solutions/0050-powx-n.js)|Medium| -51|[N-Queens](./solutions/0051-n-queens.js)|Hard| -52|[N-Queens II](./solutions/0052-n-queens-ii.js)|Hard| -53|[Maximum Subarray](./solutions/0053-maximum-subarray.js)|Easy| -54|[Spiral Matrix](./solutions/0054-spiral-matrix.js)|Medium| -55|[Jump Game](./solutions/0055-jump-game.js)|Medium| -56|[Merge Intervals](./solutions/0056-merge-intervals.js)|Medium| -57|[Insert Interval](./solutions/0057-insert-interval.js)|Medium| -58|[Length of Last Word](./solutions/0058-length-of-last-word.js)|Easy| -59|[Spiral Matrix II](./solutions/0059-spiral-matrix-ii.js)|Medium| -60|[Permutation Sequence](./solutions/0060-permutation-sequence.js)|Hard| -61|[Rotate List](./solutions/0061-rotate-list.js)|Medium| -62|[Unique Paths](./solutions/0062-unique-paths.js)|Medium| -63|[Unique Paths II](./solutions/0063-unique-paths-ii.js)|Medium| -64|[Minimum Path Sum](./solutions/0064-minimum-path-sum.js)|Medium| -65|[Valid Number](./solutions/0065-valid-number.js)|Hard| -66|[Plus One](./solutions/0066-plus-one.js)|Easy| -67|[Add Binary](./solutions/0067-add-binary.js)|Easy| -68|[Text Justification](./solutions/0068-text-justification.js)|Hard| -69|[Sqrt(x)](./solutions/0069-sqrtx.js)|Medium| -70|[Climbing Stairs](./solutions/0070-climbing-stairs.js)|Easy| -71|[Simplify Path](./solutions/0071-simplify-path.js)|Medium| -72|[Edit Distance](./solutions/0072-edit-distance.js)|Medium| -73|[Set Matrix Zeroes](./solutions/0073-set-matrix-zeroes.js)|Medium| -74|[Search a 2D Matrix](./solutions/0074-search-a-2d-matrix.js)|Medium| -75|[Sort Colors](./solutions/0075-sort-colors.js)|Medium| -76|[Minimum Window Substring](./solutions/0076-minimum-window-substring.js)|Hard| -77|[Combinations](./solutions/0077-combinations.js)|Medium| -78|[Subsets](./solutions/0078-subsets.js)|Medium| -79|[Word Search](./solutions/0079-word-search.js)|Medium| -80|[Remove Duplicates from Sorted Array II](./solutions/0080-remove-duplicates-from-sorted-array-ii.js)|Medium| -81|[Search in Rotated Sorted Array II](./solutions/0081-search-in-rotated-sorted-array-ii.js)|Medium| -82|[Remove Duplicates from Sorted List II](./solutions/0082-remove-duplicates-from-sorted-list-ii.js)|Medium| -83|[Remove Duplicates from Sorted List](./solutions/0083-remove-duplicates-from-sorted-list.js)|Easy| -84|[Largest Rectangle in Histogram](./solutions/0084-largest-rectangle-in-histogram.js)|Hard| -85|[Maximal Rectangle](./solutions/0085-maximal-rectangle.js)|Hard| -86|[Partition List](./solutions/0086-partition-list.js)|Medium| -87|[Scramble String](./solutions/0087-scramble-string.js)|Hard| -88|[Merge Sorted Array](./solutions/0088-merge-sorted-array.js)|Easy| -89|[Gray Code](./solutions/0089-gray-code.js)|Medium| -90|[Subsets II](./solutions/0090-subsets-ii.js)|Medium| -91|[Decode Ways](./solutions/0091-decode-ways.js)|Medium| -92|[Reverse Linked List II](./solutions/0092-reverse-linked-list-ii.js)|Medium| -93|[Restore IP Addresses](./solutions/0093-restore-ip-addresses.js)|Medium| -94|[Binary Tree Inorder Traversal](./solutions/0094-binary-tree-inorder-traversal.js)|Easy| -95|[Unique Binary Search Trees II](./solutions/0095-unique-binary-search-trees-ii.js)|Medium| -96|[Unique Binary Search Trees](./solutions/0096-unique-binary-search-trees.js)|Medium| -97|[Interleaving String](./solutions/0097-interleaving-string.js)|Medium| -98|[Validate Binary Search Tree](./solutions/0098-validate-binary-search-tree.js)|Medium| -99|[Recover Binary Search Tree](./solutions/0099-recover-binary-search-tree.js)|Medium| -100|[Same Tree](./solutions/0100-same-tree.js)|Easy| -101|[Symmetric Tree](./solutions/0101-symmetric-tree.js)|Easy| -102|[Binary Tree Level Order Traversal](./solutions/0102-binary-tree-level-order-traversal.js)|Medium| -103|[Binary Tree Zigzag Level Order Traversal](./solutions/0103-binary-tree-zigzag-level-order-traversal.js)|Medium| -104|[Maximum Depth of Binary Tree](./solutions/0104-maximum-depth-of-binary-tree.js)|Easy| -105|[Construct Binary Tree from Preorder and Inorder Traversal](./solutions/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)|Medium| -106|[Construct Binary Tree from Inorder and Postorder Traversal](./solutions/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium| -107|[Binary Tree Level Order Traversal II](./solutions/0107-binary-tree-level-order-traversal-ii.js)|Medium| -108|[Convert Sorted Array to Binary Search Tree](./solutions/0108-convert-sorted-array-to-binary-search-tree.js)|Easy| -109|[Convert Sorted List to Binary Search Tree](./solutions/0109-convert-sorted-list-to-binary-search-tree.js)|Medium| -110|[Balanced Binary Tree](./solutions/0110-balanced-binary-tree.js)|Easy| -111|[Minimum Depth of Binary Tree](./solutions/0111-minimum-depth-of-binary-tree.js)|Easy| -112|[Path Sum](./solutions/0112-path-sum.js)|Easy| -113|[Path Sum II](./solutions/0113-path-sum-ii.js)|Medium| -114|[Flatten Binary Tree to Linked List](./solutions/0114-flatten-binary-tree-to-linked-list.js)|Medium| -115|[Distinct Subsequences](./solutions/0115-distinct-subsequences.js)|Hard| -116|[Populating Next Right Pointers in Each Node](./solutions/0116-populating-next-right-pointers-in-each-node.js)|Medium| -117|[Populating Next Right Pointers in Each Node II](./solutions/0117-populating-next-right-pointers-in-each-node-ii.js)|Medium| -118|[Pascal's Triangle](./solutions/0118-pascals-triangle.js)|Easy| -119|[Pascal's Triangle II](./solutions/0119-pascals-triangle-ii.js)|Easy| -120|[Triangle](./solutions/0120-triangle.js)|Medium| -121|[Best Time to Buy and Sell Stock](./solutions/0121-best-time-to-buy-and-sell-stock.js)|Easy| -122|[Best Time to Buy and Sell Stock II](./solutions/0122-best-time-to-buy-and-sell-stock-ii.js)|Medium| -123|[Best Time to Buy and Sell Stock III](./solutions/0123-best-time-to-buy-and-sell-stock-iii.js)|Hard| -124|[Binary Tree Maximum Path Sum](./solutions/0124-binary-tree-maximum-path-sum.js)|Hard| -125|[Valid Palindrome](./solutions/0125-valid-palindrome.js)|Easy| -126|[Word Ladder II](./solutions/0126-word-ladder-ii.js)|Hard| -127|[Word Ladder](./solutions/0127-word-ladder.js)|Hard| -128|[Longest Consecutive Sequence](./solutions/0128-longest-consecutive-sequence.js)|Medium| -129|[Sum Root to Leaf Numbers](./solutions/0129-sum-root-to-leaf-numbers.js)|Medium| -130|[Surrounded Regions](./solutions/0130-surrounded-regions.js)|Medium| -131|[Palindrome Partitioning](./solutions/0131-palindrome-partitioning.js)|Medium| -132|[Palindrome Partitioning II](./solutions/0132-palindrome-partitioning-ii.js)|Hard| -133|[Clone Graph](./solutions/0133-clone-graph.js)|Medium| -134|[Gas Station](./solutions/0134-gas-station.js)|Medium| -135|[Candy](./solutions/0135-candy.js)|Hard| -136|[Single Number](./solutions/0136-single-number.js)|Easy| -137|[Single Number II](./solutions/0137-single-number-ii.js)|Medium| -138|[Copy List with Random Pointer](./solutions/0138-copy-list-with-random-pointer.js)|Medium| -139|[Word Break](./solutions/0139-word-break.js)|Medium| -140|[Word Break II](./solutions/0140-word-break-ii.js)|Hard| -141|[Linked List Cycle](./solutions/0141-linked-list-cycle.js)|Easy| -142|[Linked List Cycle II](./solutions/0142-linked-list-cycle-ii.js)|Medium| -143|[Reorder List](./solutions/0143-reorder-list.js)|Medium| -144|[Binary Tree Preorder Traversal](./solutions/0144-binary-tree-preorder-traversal.js)|Easy| -145|[Binary Tree Postorder Traversal](./solutions/0145-binary-tree-postorder-traversal.js)|Easy| -146|[LRU Cache](./solutions/0146-lru-cache.js)|Medium| -147|[Insertion Sort List](./solutions/0147-insertion-sort-list.js)|Medium| -148|[Sort List](./solutions/0148-sort-list.js)|Medium| -149|[Max Points on a Line](./solutions/0149-max-points-on-a-line.js)|Hard| -150|[Evaluate Reverse Polish Notation](./solutions/0150-evaluate-reverse-polish-notation.js)|Medium| -151|[Reverse Words in a String](./solutions/0151-reverse-words-in-a-string.js)|Medium| -152|[Maximum Product Subarray](./solutions/0152-maximum-product-subarray.js)|Medium| -153|[Find Minimum in Rotated Sorted Array](./solutions/0153-find-minimum-in-rotated-sorted-array.js)|Medium| -154|[Find Minimum in Rotated Sorted Array II](./solutions/0154-find-minimum-in-rotated-sorted-array-ii.js)|Hard| -155|[Min Stack](./solutions/0155-min-stack.js)|Medium| -160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium| -162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium| -164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium| -165|[Compare Version Numbers](./solutions/0165-compare-version-numbers.js)|Medium| -166|[Fraction to Recurring Decimal](./solutions/0166-fraction-to-recurring-decimal.js)|Medium| -167|[Two Sum II - Input Array Is Sorted](./solutions/0167-two-sum-ii-input-array-is-sorted.js)|Easy| -168|[Excel Sheet Column Title](./solutions/0168-excel-sheet-column-title.js)|Easy| -169|[Majority Element](./solutions/0169-majority-element.js)|Easy| -171|[Excel Sheet Column Number](./solutions/0171-excel-sheet-column-number.js)|Easy| -172|[Factorial Trailing Zeroes](./solutions/0172-factorial-trailing-zeroes.js)|Medium| -173|[Binary Search Tree Iterator](./solutions/0173-binary-search-tree-iterator.js)|Medium| -174|[Dungeon Game](./solutions/0174-dungeon-game.js)|Hard| -179|[Largest Number](./solutions/0179-largest-number.js)|Medium| -187|[Repeated DNA Sequences](./solutions/0187-repeated-dna-sequences.js)|Medium| -188|[Best Time to Buy and Sell Stock IV](./solutions/0188-best-time-to-buy-and-sell-stock-iv.js)|Hard| -189|[Rotate Array](./solutions/0189-rotate-array.js)|Medium| -190|[Reverse Bits](./solutions/0190-reverse-bits.js)|Easy| -191|[Number of 1 Bits](./solutions/0191-number-of-1-bits.js)|Easy| -198|[House Robber](./solutions/0198-house-robber.js)|Medium| -199|[Binary Tree Right Side View](./solutions/0199-binary-tree-right-side-view.js)|Medium| -200|[Number of Islands](./solutions/0200-number-of-islands.js)|Medium| -201|[Bitwise AND of Numbers Range](./solutions/0201-bitwise-and-of-numbers-range.js)|Medium| -202|[Happy Number](./solutions/0202-happy-number.js)|Easy| -203|[Remove Linked List Elements](./solutions/0203-remove-linked-list-elements.js)|Easy| -204|[Count Primes](./solutions/0204-count-primes.js)|Medium| -205|[Isomorphic Strings](./solutions/0205-isomorphic-strings.js)|Easy| -206|[Reverse Linked List](./solutions/0206-reverse-linked-list.js)|Easy| -207|[Course Schedule](./solutions/0207-course-schedule.js)|Medium| -208|[Implement Trie (Prefix Tree)](./solutions/0208-implement-trie-prefix-tree.js)|Medium| -209|[Minimum Size Subarray Sum](./solutions/0209-minimum-size-subarray-sum.js)|Medium| -210|[Course Schedule II](./solutions/0210-course-schedule-ii.js)|Medium| -211|[Design Add and Search Words Data Structure](./solutions/0211-design-add-and-search-words-data-structure.js)|Medium| -212|[Word Search II](./solutions/0212-word-search-ii.js)|Hard| -213|[House Robber II](./solutions/0213-house-robber-ii.js)|Medium| -214|[Shortest Palindrome](./solutions/0214-shortest-palindrome.js)|Hard| -215|[Kth Largest Element in an Array](./solutions/0215-kth-largest-element-in-an-array.js)|Medium| -216|[Combination Sum III](./solutions/0216-combination-sum-iii.js)|Medium| -217|[Contains Duplicate](./solutions/0217-contains-duplicate.js)|Easy| -218|[The Skyline Problem](./solutions/0218-the-skyline-problem.js)|Hard| -219|[Contains Duplicate II](./solutions/0219-contains-duplicate-ii.js)|Easy| -220|[Contains Duplicate III](./solutions/0220-contains-duplicate-iii.js)|Hard| -221|[Maximal Square](./solutions/0221-maximal-square.js)|Medium| -222|[Count Complete Tree Nodes](./solutions/0222-count-complete-tree-nodes.js)|Easy| -223|[Rectangle Area](./solutions/0223-rectangle-area.js)|Medium| -224|[Basic Calculator](./solutions/0224-basic-calculator.js)|Hard| -225|[Implement Stack using Queues](./solutions/0225-implement-stack-using-queues.js)|Easy| -226|[Invert Binary Tree](./solutions/0226-invert-binary-tree.js)|Easy| -227|[Basic Calculator II](./solutions/0227-basic-calculator-ii.js)|Medium| -228|[Summary Ranges](./solutions/0228-summary-ranges.js)|Easy| -229|[Majority Element II](./solutions/0229-majority-element-ii.js)|Medium| -230|[Kth Smallest Element in a BST](./solutions/0230-kth-smallest-element-in-a-bst.js)|Medium| -231|[Power of Two](./solutions/0231-power-of-two.js)|Easy| -232|[Implement Queue using Stacks](./solutions/0232-implement-queue-using-stacks.js)|Easy| -233|[Number of Digit One](./solutions/0233-number-of-digit-one.js)|Hard| -234|[Palindrome Linked List](./solutions/0234-palindrome-linked-list.js)|Easy| -235|[Lowest Common Ancestor of a Binary Search Tree](./solutions/0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| -236|[Lowest Common Ancestor of a Binary Tree](./solutions/0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium| -237|[Delete Node in a Linked List](./solutions/0237-delete-node-in-a-linked-list.js)|Easy| -238|[Product of Array Except Self](./solutions/0238-product-of-array-except-self.js)|Medium| -239|[Sliding Window Maximum](./solutions/0239-sliding-window-maximum.js)|Hard| -240|[Search a 2D Matrix II](./solutions/0240-search-a-2d-matrix-ii.js)|Medium| -241|[Different Ways to Add Parentheses](./solutions/0241-different-ways-to-add-parentheses.js)|Medium| -242|[Valid Anagram](./solutions/0242-valid-anagram.js)|Easy| -257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy| -258|[Add Digits](./solutions/0258-add-digits.js)|Easy| -260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium| -263|[Ugly Number](./solutions/0263-ugly-number.js)|Easy| -264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium| -268|[Missing Number](./solutions/0268-missing-number.js)|Easy| -273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard| -274|[H-Index](./solutions/0274-h-index.js)|Medium| -275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium| -278|[First Bad Version](./solutions/0278-first-bad-version.js)|Medium| -279|[Perfect Squares](./solutions/0279-perfect-squares.js)|Medium| -282|[Expression Add Operators](./solutions/0282-expression-add-operators.js)|Hard| -283|[Move Zeroes](./solutions/0283-move-zeroes.js)|Easy| -284|[Peeking Iterator](./solutions/0284-peeking-iterator.js)|Medium| -287|[Find the Duplicate Number](./solutions/0287-find-the-duplicate-number.js)|Medium| -289|[Game of Life](./solutions/0289-game-of-life.js)|Medium| -290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy| -292|[Nim Game](./solutions/0292-nim-game.js)|Easy| -295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard| -297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard| -299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium| -300|[Longest Increasing Subsequence](./solutions/0300-longest-increasing-subsequence.js)|Medium| -301|[Remove Invalid Parentheses](./solutions/0301-remove-invalid-parentheses.js)|Hard| -303|[Range Sum Query - Immutable](./solutions/0303-range-sum-query-immutable.js)|Easy| -304|[Range Sum Query 2D - Immutable](./solutions/0304-range-sum-query-2d-immutable.js)|Medium| -306|[Additive Number](./solutions/0306-additive-number.js)|Medium| -307|[Range Sum Query - Mutable](./solutions/0307-range-sum-query-mutable.js)|Medium| -309|[Best Time to Buy and Sell Stock with Cooldown](./solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| -310|[Minimum Height Trees](./solutions/0310-minimum-height-trees.js)|Medium| -312|[Burst Balloons](./solutions/0312-burst-balloons.js)|Hard| -313|[Super Ugly Number](./solutions/0313-super-ugly-number.js)|Medium| -315|[Count of Smaller Numbers After Self](./solutions/0315-count-of-smaller-numbers-after-self.js)|Hard| -316|[Remove Duplicate Letters](./solutions/0316-remove-duplicate-letters.js)|Medium| -318|[Maximum Product of Word Lengths](./solutions/0318-maximum-product-of-word-lengths.js)|Medium| -319|[Bulb Switcher](./solutions/0319-bulb-switcher.js)|Medium| -321|[Create Maximum Number](./solutions/0321-create-maximum-number.js)|Hard| -322|[Coin Change](./solutions/0322-coin-change.js)|Medium| -324|[Wiggle Sort II](./solutions/0324-wiggle-sort-ii.js)|Medium| -326|[Power of Three](./solutions/0326-power-of-three.js)|Easy| -327|[Count of Range Sum](./solutions/0327-count-of-range-sum.js)|Hard| -328|[Odd Even Linked List](./solutions/0328-odd-even-linked-list.js)|Medium| -329|[Longest Increasing Path in a Matrix](./solutions/0329-longest-increasing-path-in-a-matrix.js)|Hard| -330|[Patching Array](./solutions/0330-patching-array.js)|Hard| -331|[Verify Preorder Serialization of a Binary Tree](./solutions/0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| -332|[Reconstruct Itinerary](./solutions/0332-reconstruct-itinerary.js)|Hard| -334|[Increasing Triplet Subsequence](./solutions/0334-increasing-triplet-subsequence.js)|Medium| -335|[Self Crossing](./solutions/0335-self-crossing.js)|Hard| -336|[Palindrome Pairs](./solutions/0336-palindrome-pairs.js)|Hard| -337|[House Robber III](./solutions/0337-house-robber-iii.js)|Medium| -338|[Counting Bits](./solutions/0338-counting-bits.js)|Easy| -341|[Flatten Nested List Iterator](./solutions/0341-flatten-nested-list-iterator.js)|Medium| -342|[Power of Four](./solutions/0342-power-of-four.js)|Easy| -343|[Integer Break](./solutions/0343-integer-break.js)|Medium| -344|[Reverse String](./solutions/0344-reverse-string.js)|Easy| -345|[Reverse Vowels of a String](./solutions/0345-reverse-vowels-of-a-string.js)|Easy| -347|[Top K Frequent Elements](./solutions/0347-top-k-frequent-elements.js)|Medium| -349|[Intersection of Two Arrays](./solutions/0349-intersection-of-two-arrays.js)|Easy| -350|[Intersection of Two Arrays II](./solutions/0350-intersection-of-two-arrays-ii.js)|Easy| -352|[Data Stream as Disjoint Intervals](./solutions/0352-data-stream-as-disjoint-intervals.js)|Hard| -354|[Russian Doll Envelopes](./solutions/0354-russian-doll-envelopes.js)|Hard| -355|[Design Twitter](./solutions/0355-design-twitter.js)|Medium| -357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium| -363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard| -365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium| -367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy| -368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium| -371|[Sum of Two Integers](./solutions/0371-sum-of-two-integers.js)|Medium| -372|[Super Pow](./solutions/0372-super-pow.js)|Medium| -373|[Find K Pairs with Smallest Sums](./solutions/0373-find-k-pairs-with-smallest-sums.js)|Medium| -374|[Guess Number Higher or Lower](./solutions/0374-guess-number-higher-or-lower.js)|Medium| -375|[Guess Number Higher or Lower II](./solutions/0375-guess-number-higher-or-lower-ii.js)|Medium| -376|[Wiggle Subsequence](./solutions/0376-wiggle-subsequence.js)|Medium| -377|[Combination Sum IV](./solutions/0377-combination-sum-iv.js)|Medium| -378|[Kth Smallest Element in a Sorted Matrix](./solutions/0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| -380|[Insert Delete GetRandom O(1)](./solutions/0380-insert-delete-getrandom-o1.js)|Medium| -381|[Insert Delete GetRandom O(1) - Duplicates allowed](./solutions/0381-insert-delete-getrandom-o1-duplicates-allowed.js)|Hard| -382|[Linked List Random Node](./solutions/0382-linked-list-random-node.js)|Medium| -383|[Ransom Note](./solutions/0383-ransom-note.js)|Easy| -384|[Shuffle an Array](./solutions/0384-shuffle-an-array.js)|Medium| -385|[Mini Parser](./solutions/0385-mini-parser.js)|Medium| -386|[Lexicographical Numbers](./solutions/0386-lexicographical-numbers.js)|Medium| -387|[First Unique Character in a String](./solutions/0387-first-unique-character-in-a-string.js)|Easy| -388|[Longest Absolute File Path](./solutions/0388-longest-absolute-file-path.js)|Medium| -389|[Find the Difference](./solutions/0389-find-the-difference.js)|Easy| -390|[Elimination Game](./solutions/0390-elimination-game.js)|Medium| -391|[Perfect Rectangle](./solutions/0391-perfect-rectangle.js)|Hard| -392|[Is Subsequence](./solutions/0392-is-subsequence.js)|Easy| -393|[UTF-8 Validation](./solutions/0393-utf-8-validation.js)|Medium| -394|[Decode String](./solutions/0394-decode-string.js)|Medium| -395|[Longest Substring with At Least K Repeating Characters](./solutions/0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| -396|[Rotate Function](./solutions/0396-rotate-function.js)|Medium| -397|[Integer Replacement](./solutions/0397-integer-replacement.js)|Medium| -398|[Random Pick Index](./solutions/0398-random-pick-index.js)|Medium| -399|[Evaluate Division](./solutions/0399-evaluate-division.js)|Medium| -400|[Nth Digit](./solutions/0400-nth-digit.js)|Medium| -401|[Binary Watch](./solutions/0401-binary-watch.js)|Easy| -402|[Remove K Digits](./solutions/0402-remove-k-digits.js)|Medium| -403|[Frog Jump](./solutions/0403-frog-jump.js)|Hard| -404|[Sum of Left Leaves](./solutions/0404-sum-of-left-leaves.js)|Easy| -405|[Convert a Number to Hexadecimal](./solutions/0405-convert-a-number-to-hexadecimal.js)|Easy| -406|[Queue Reconstruction by Height](./solutions/0406-queue-reconstruction-by-height.js)|Medium| -407|[Trapping Rain Water II](./solutions/0407-trapping-rain-water-ii.js)|Hard| -409|[Longest Palindrome](./solutions/0409-longest-palindrome.js)|Easy| -410|[Split Array Largest Sum](./solutions/0410-split-array-largest-sum.js)|Hard| -412|[Fizz Buzz](./solutions/0412-fizz-buzz.js)|Easy| -413|[Arithmetic Slices](./solutions/0413-arithmetic-slices.js)|Medium| -414|[Third Maximum Number](./solutions/0414-third-maximum-number.js)|Easy| -415|[Add Strings](./solutions/0415-add-strings.js)|Easy| -416|[Partition Equal Subset Sum](./solutions/0416-partition-equal-subset-sum.js)|Medium| -417|[Pacific Atlantic Water Flow](./solutions/0417-pacific-atlantic-water-flow.js)|Medium| -419|[Battleships in a Board](./solutions/0419-battleships-in-a-board.js)|Medium| -420|[Strong Password Checker](./solutions/0420-strong-password-checker.js)|Hard| -421|[Maximum XOR of Two Numbers in an Array](./solutions/0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium| -423|[Reconstruct Original Digits from English](./solutions/0423-reconstruct-original-digits-from-english.js)|Medium| -424|[Longest Repeating Character Replacement](./solutions/0424-longest-repeating-character-replacement.js)|Medium| -427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium| -429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium| -430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium| -432|[All O`one Data Structure](./solutions/0432-all-oone-data-structure.js)|Hard| -433|[Minimum Genetic Mutation](./solutions/0433-minimum-genetic-mutation.js)|Medium| -434|[Number of Segments in a String](./solutions/0434-number-of-segments-in-a-string.js)|Easy| -435|[Non-overlapping Intervals](./solutions/0435-non-overlapping-intervals.js)|Medium| -436|[Find Right Interval](./solutions/0436-find-right-interval.js)|Medium| -437|[Path Sum III](./solutions/0437-path-sum-iii.js)|Medium| -438|[Find All Anagrams in a String](./solutions/0438-find-all-anagrams-in-a-string.js)|Medium| -440|[K-th Smallest in Lexicographical Order](./solutions/0440-k-th-smallest-in-lexicographical-order.js)|Hard| -441|[Arranging Coins](./solutions/0441-arranging-coins.js)|Easy| -442|[Find All Duplicates in an Array](./solutions/0442-find-all-duplicates-in-an-array.js)|Medium| -443|[String Compression](./solutions/0443-string-compression.js)|Medium| -445|[Add Two Numbers II](./solutions/0445-add-two-numbers-ii.js)|Medium| -446|[Arithmetic Slices II - Subsequence](./solutions/0446-arithmetic-slices-ii-subsequence.js)|Hard| -447|[Number of Boomerangs](./solutions/0447-number-of-boomerangs.js)|Medium| -448|[Find All Numbers Disappeared in an Array](./solutions/0448-find-all-numbers-disappeared-in-an-array.js)|Easy| -449|[Serialize and Deserialize BST](./solutions/0449-serialize-and-deserialize-bst.js)|Medium| -450|[Delete Node in a BST](./solutions/0450-delete-node-in-a-bst.js)|Medium| -451|[Sort Characters By Frequency](./solutions/0451-sort-characters-by-frequency.js)|Medium| -452|[Minimum Number of Arrows to Burst Balloons](./solutions/0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| -453|[Minimum Moves to Equal Array Elements](./solutions/0453-minimum-moves-to-equal-array-elements.js)|Medium| -454|[4Sum II](./solutions/0454-4sum-ii.js)|Medium| -455|[Assign Cookies](./solutions/0455-assign-cookies.js)|Easy| -456|[132 Pattern](./solutions/0456-132-pattern.js)|Medium| -457|[Circular Array Loop](./solutions/0457-circular-array-loop.js)|Medium| -458|[Poor Pigs](./solutions/0458-poor-pigs.js)|Hard| -459|[Repeated Substring Pattern](./solutions/0459-repeated-substring-pattern.js)|Easy| -460|[LFU Cache](./solutions/0460-lfu-cache.js)|Hard| -461|[Hamming Distance](./solutions/0461-hamming-distance.js)|Easy| -462|[Minimum Moves to Equal Array Elements II](./solutions/0462-minimum-moves-to-equal-array-elements-ii.js)|Medium| -463|[Island Perimeter](./solutions/0463-island-perimeter.js)|Medium| -464|[Can I Win](./solutions/0464-can-i-win.js)|Medium| -466|[Count The Repetitions](./solutions/0466-count-the-repetitions.js)|Hard| -467|[Unique Substrings in Wraparound String](./solutions/0467-unique-substrings-in-wraparound-string.js)|Medium| -468|[Validate IP Address](./solutions/0468-validate-ip-address.js)|Medium| -470|[Implement Rand10() Using Rand7()](./solutions/0470-implement-rand10-using-rand7.js)|Medium| -472|[Concatenated Words](./solutions/0472-concatenated-words.js)|Hard| -473|[Matchsticks to Square](./solutions/0473-matchsticks-to-square.js)|Medium| -474|[Ones and Zeroes](./solutions/0474-ones-and-zeroes.js)|Medium| -475|[Heaters](./solutions/0475-heaters.js)|Medium| -476|[Number Complement](./solutions/0476-number-complement.js)|Easy| -477|[Total Hamming Distance](./solutions/0477-total-hamming-distance.js)|Medium| -478|[Generate Random Point in a Circle](./solutions/0478-generate-random-point-in-a-circle.js)|Medium| -479|[Largest Palindrome Product](./solutions/0479-largest-palindrome-product.js)|Hard| -480|[Sliding Window Median](./solutions/0480-sliding-window-median.js)|Hard| -481|[Magical String](./solutions/0481-magical-string.js)|Medium| -482|[License Key Formatting](./solutions/0482-license-key-formatting.js)|Easy| -483|[Smallest Good Base](./solutions/0483-smallest-good-base.js)|Hard| -485|[Max Consecutive Ones](./solutions/0485-max-consecutive-ones.js)|Easy| -486|[Predict the Winner](./solutions/0486-predict-the-winner.js)|Medium| -488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard| -491|[Non-decreasing Subsequences](./solutions/0491-non-decreasing-subsequences.js)|Medium| -492|[Construct the Rectangle](./solutions/0492-construct-the-rectangle.js)|Easy| -493|[Reverse Pairs](./solutions/0493-reverse-pairs.js)|Hard| -494|[Target Sum](./solutions/0494-target-sum.js)|Medium| -495|[Teemo Attacking](./solutions/0495-teemo-attacking.js)|Easy| -496|[Next Greater Element I](./solutions/0496-next-greater-element-i.js)|Easy| -497|[Random Point in Non-overlapping Rectangles](./solutions/0497-random-point-in-non-overlapping-rectangles.js)|Medium| -498|[Diagonal Traverse](./solutions/0498-diagonal-traverse.js)|Medium| -500|[Keyboard Row](./solutions/0500-keyboard-row.js)|Easy| -501|[Find Mode in Binary Search Tree](./solutions/0501-find-mode-in-binary-search-tree.js)|Easy| -502|[IPO](./solutions/0502-ipo.js)|Hard| -503|[Next Greater Element II](./solutions/0503-next-greater-element-ii.js)|Medium| -504|[Base 7](./solutions/0504-base-7.js)|Easy| -506|[Relative Ranks](./solutions/0506-relative-ranks.js)|Easy| -507|[Perfect Number](./solutions/0507-perfect-number.js)|Easy| -508|[Most Frequent Subtree Sum](./solutions/0508-most-frequent-subtree-sum.js)|Medium| -509|[Fibonacci Number](./solutions/0509-fibonacci-number.js)|Easy| -513|[Find Bottom Left Tree Value](./solutions/0513-find-bottom-left-tree-value.js)|Medium| -514|[Freedom Trail](./solutions/0514-freedom-trail.js)|Hard| -515|[Find Largest Value in Each Tree Row](./solutions/0515-find-largest-value-in-each-tree-row.js)|Medium| -516|[Longest Palindromic Subsequence](./solutions/0516-longest-palindromic-subsequence.js)|Medium| -517|[Super Washing Machines](./solutions/0517-super-washing-machines.js)|Hard| -518|[Coin Change II](./solutions/0518-coin-change-ii.js)|Medium| -519|[Random Flip Matrix](./solutions/0519-random-flip-matrix.js)|Medium| -520|[Detect Capital](./solutions/0520-detect-capital.js)|Easy| -521|[Longest Uncommon Subsequence I](./solutions/0521-longest-uncommon-subsequence-i.js)|Easy| -522|[Longest Uncommon Subsequence II](./solutions/0522-longest-uncommon-subsequence-ii.js)|Medium| -523|[Continuous Subarray Sum](./solutions/0523-continuous-subarray-sum.js)|Medium| -524|[Longest Word in Dictionary through Deleting](./solutions/0524-longest-word-in-dictionary-through-deleting.js)|Medium| -525|[Contiguous Array](./solutions/0525-contiguous-array.js)|Medium| -526|[Beautiful Arrangement](./solutions/0526-beautiful-arrangement.js)|Medium| -528|[Random Pick with Weight](./solutions/0528-random-pick-with-weight.js)|Medium| -529|[Minesweeper](./solutions/0529-minesweeper.js)|Medium| -530|[Minimum Absolute Difference in BST](./solutions/0530-minimum-absolute-difference-in-bst.js)|Easy| -532|[K-diff Pairs in an Array](./solutions/0532-k-diff-pairs-in-an-array.js)|Medium| -535|[Encode and Decode TinyURL](./solutions/0535-encode-and-decode-tinyurl.js)|Medium| -537|[Complex Number Multiplication](./solutions/0537-complex-number-multiplication.js)|Medium| -538|[Convert BST to Greater Tree](./solutions/0538-convert-bst-to-greater-tree.js)|Medium| -539|[Minimum Time Difference](./solutions/0539-minimum-time-difference.js)|Medium| -540|[Single Element in a Sorted Array](./solutions/0540-single-element-in-a-sorted-array.js)|Medium| -541|[Reverse String II](./solutions/0541-reverse-string-ii.js)|Easy| -542|[01 Matrix](./solutions/0542-01-matrix.js)|Medium| -543|[Diameter of Binary Tree](./solutions/0543-diameter-of-binary-tree.js)|Easy| -546|[Remove Boxes](./solutions/0546-remove-boxes.js)|Hard| -547|[Number of Provinces](./solutions/0547-number-of-provinces.js)|Medium| -551|[Student Attendance Record I](./solutions/0551-student-attendance-record-i.js)|Easy| -552|[Student Attendance Record II](./solutions/0552-student-attendance-record-ii.js)|Hard| -553|[Optimal Division](./solutions/0553-optimal-division.js)|Medium| -554|[Brick Wall](./solutions/0554-brick-wall.js)|Medium| -556|[Next Greater Element III](./solutions/0556-next-greater-element-iii.js)|Medium| -557|[Reverse Words in a String III](./solutions/0557-reverse-words-in-a-string-iii.js)|Easy| -558|[Logical OR of Two Binary Grids Represented as Quad-Trees](./solutions/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js)|Medium| -559|[Maximum Depth of N-ary Tree](./solutions/0559-maximum-depth-of-n-ary-tree.js)|Easy| -560|[Subarray Sum Equals K](./solutions/0560-subarray-sum-equals-k.js)|Medium| -561|[Array Partition](./solutions/0561-array-partition.js)|Easy| -563|[Binary Tree Tilt](./solutions/0563-binary-tree-tilt.js)|Easy| -564|[Find the Closest Palindrome](./solutions/0564-find-the-closest-palindrome.js)|Hard| -565|[Array Nesting](./solutions/0565-array-nesting.js)|Medium| -566|[Reshape the Matrix](./solutions/0566-reshape-the-matrix.js)|Easy| -567|[Permutation in String](./solutions/0567-permutation-in-string.js)|Medium| -572|[Subtree of Another Tree](./solutions/0572-subtree-of-another-tree.js)|Easy| -575|[Distribute Candies](./solutions/0575-distribute-candies.js)|Easy| -576|[Out of Boundary Paths](./solutions/0576-out-of-boundary-paths.js)|Medium| -581|[Shortest Unsorted Continuous Subarray](./solutions/0581-shortest-unsorted-continuous-subarray.js)|Medium| -583|[Delete Operation for Two Strings](./solutions/0583-delete-operation-for-two-strings.js)|Medium| -587|[Erect the Fence](./solutions/0587-erect-the-fence.js)|Hard| -589|[N-ary Tree Preorder Traversal](./solutions/0589-n-ary-tree-preorder-traversal.js)|Easy| -590|[N-ary Tree Postorder Traversal](./solutions/0590-n-ary-tree-postorder-traversal.js)|Easy| -591|[Tag Validator](./solutions/0591-tag-validator.js)|Hard| -592|[Fraction Addition and Subtraction](./solutions/0592-fraction-addition-and-subtraction.js)|Medium| -593|[Valid Square](./solutions/0593-valid-square.js)|Medium| -594|[Longest Harmonious Subsequence](./solutions/0594-longest-harmonious-subsequence.js)|Easy| -598|[Range Addition II](./solutions/0598-range-addition-ii.js)|Easy| -599|[Minimum Index Sum of Two Lists](./solutions/0599-minimum-index-sum-of-two-lists.js)|Easy| -600|[Non-negative Integers without Consecutive Ones](./solutions/0600-non-negative-integers-without-consecutive-ones.js)|Hard| -605|[Can Place Flowers](./solutions/0605-can-place-flowers.js)|Easy| -606|[Construct String from Binary Tree](./solutions/0606-construct-string-from-binary-tree.js)|Easy| -609|[Find Duplicate File in System](./solutions/0609-find-duplicate-file-in-system.js)|Medium| -611|[Valid Triangle Number](./solutions/0611-valid-triangle-number.js)|Medium| -617|[Merge Two Binary Trees](./solutions/0617-merge-two-binary-trees.js)|Easy| -621|[Task Scheduler](./solutions/0621-task-scheduler.js)|Medium| -622|[Design Circular Queue](./solutions/0622-design-circular-queue.js)|Medium| -623|[Add One Row to Tree](./solutions/0623-add-one-row-to-tree.js)|Medium| -624|[Maximum Distance in Arrays](./solutions/0624-maximum-distance-in-arrays.js)|Medium| -628|[Maximum Product of Three Numbers](./solutions/0628-maximum-product-of-three-numbers.js)|Easy| -629|[K Inverse Pairs Array](./solutions/0629-k-inverse-pairs-array.js)|Hard| -630|[Course Schedule III](./solutions/0630-course-schedule-iii.js)|Hard| -632|[Smallest Range Covering Elements from K Lists](./solutions/0632-smallest-range-covering-elements-from-k-lists.js)|Hard| -633|[Sum of Square Numbers](./solutions/0633-sum-of-square-numbers.js)|Medium| -636|[Exclusive Time of Functions](./solutions/0636-exclusive-time-of-functions.js)|Medium| -637|[Average of Levels in Binary Tree](./solutions/0637-average-of-levels-in-binary-tree.js)|Easy| -638|[Shopping Offers](./solutions/0638-shopping-offers.js)|Medium| -639|[Decode Ways II](./solutions/0639-decode-ways-ii.js)|Hard| -640|[Solve the Equation](./solutions/0640-solve-the-equation.js)|Medium| -641|[Design Circular Deque](./solutions/0641-design-circular-deque.js)|Medium| -643|[Maximum Average Subarray I](./solutions/0643-maximum-average-subarray-i.js)|Easy| -645|[Set Mismatch](./solutions/0645-set-mismatch.js)|Medium| -646|[Maximum Length of Pair Chain](./solutions/0646-maximum-length-of-pair-chain.js)|Medium| -647|[Palindromic Substrings](./solutions/0647-palindromic-substrings.js)|Medium| -648|[Replace Words](./solutions/0648-replace-words.js)|Medium| -649|[Dota2 Senate](./solutions/0649-dota2-senate.js)|Medium| -650|[2 Keys Keyboard](./solutions/0650-2-keys-keyboard.js)|Medium| -652|[Find Duplicate Subtrees](./solutions/0652-find-duplicate-subtrees.js)|Medium| -653|[Two Sum IV - Input is a BST](./solutions/0653-two-sum-iv-input-is-a-bst.js)|Easy| -654|[Maximum Binary Tree](./solutions/0654-maximum-binary-tree.js)|Medium| -655|[Print Binary Tree](./solutions/0655-print-binary-tree.js)|Medium| -657|[Robot Return to Origin](./solutions/0657-robot-return-to-origin.js)|Easy| -658|[Find K Closest Elements](./solutions/0658-find-k-closest-elements.js)|Medium| -659|[Split Array into Consecutive Subsequences](./solutions/0659-split-array-into-consecutive-subsequences.js)|Medium| -661|[Image Smoother](./solutions/0661-image-smoother.js)|Easy| -662|[Maximum Width of Binary Tree](./solutions/0662-maximum-width-of-binary-tree.js)|Medium| -664|[Strange Printer](./solutions/0664-strange-printer.js)|Hard| -665|[Non-decreasing Array](./solutions/0665-non-decreasing-array.js)|Medium| -667|[Beautiful Arrangement II](./solutions/0667-beautiful-arrangement-ii.js)|Medium| -668|[Kth Smallest Number in Multiplication Table](./solutions/0668-kth-smallest-number-in-multiplication-table.js)|Hard| -669|[Trim a Binary Search Tree](./solutions/0669-trim-a-binary-search-tree.js)|Medium| -670|[Maximum Swap](./solutions/0670-maximum-swap.js)|Medium| -671|[Second Minimum Node In a Binary Tree](./solutions/0671-second-minimum-node-in-a-binary-tree.js)|Easy| -672|[Bulb Switcher II](./solutions/0672-bulb-switcher-ii.js)|Medium| -673|[Number of Longest Increasing Subsequence](./solutions/0673-number-of-longest-increasing-subsequence.js)|Medium| -674|[Longest Continuous Increasing Subsequence](./solutions/0674-longest-continuous-increasing-subsequence.js)|Easy| -675|[Cut Off Trees for Golf Event](./solutions/0675-cut-off-trees-for-golf-event.js)|Hard| -676|[Implement Magic Dictionary](./solutions/0676-implement-magic-dictionary.js)|Medium| -677|[Map Sum Pairs](./solutions/0677-map-sum-pairs.js)|Medium| -678|[Valid Parenthesis String](./solutions/0678-valid-parenthesis-string.js)|Medium| -679|[24 Game](./solutions/0679-24-game.js)|Hard| -680|[Valid Palindrome II](./solutions/0680-valid-palindrome-ii.js)|Easy| -682|[Baseball Game](./solutions/0682-baseball-game.js)|Easy| -684|[Redundant Connection](./solutions/0684-redundant-connection.js)|Medium| -685|[Redundant Connection II](./solutions/0685-redundant-connection-ii.js)|Hard| -686|[Repeated String Match](./solutions/0686-repeated-string-match.js)|Easy| -687|[Longest Univalue Path](./solutions/0687-longest-univalue-path.js)|Medium| -688|[Knight Probability in Chessboard](./solutions/0688-knight-probability-in-chessboard.js)|Medium| -689|[Maximum Sum of 3 Non-Overlapping Subarrays](./solutions/0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard| -690|[Employee Importance](./solutions/0690-employee-importance.js)|Medium| -691|[Stickers to Spell Word](./solutions/0691-stickers-to-spell-word.js)|Hard| -692|[Top K Frequent Words](./solutions/0692-top-k-frequent-words.js)|Medium| -693|[Binary Number with Alternating Bits](./solutions/0693-binary-number-with-alternating-bits.js)|Easy| -695|[Max Area of Island](./solutions/0695-max-area-of-island.js)|Medium| -696|[Count Binary Substrings](./solutions/0696-count-binary-substrings.js)|Easy| -697|[Degree of an Array](./solutions/0697-degree-of-an-array.js)|Easy| -698|[Partition to K Equal Sum Subsets](./solutions/0698-partition-to-k-equal-sum-subsets.js)|Medium| -699|[Falling Squares](./solutions/0699-falling-squares.js)|Hard| -700|[Search in a Binary Search Tree](./solutions/0700-search-in-a-binary-search-tree.js)|Easy| -701|[Insert into a Binary Search Tree](./solutions/0701-insert-into-a-binary-search-tree.js)|Medium| -703|[Kth Largest Element in a Stream](./solutions/0703-kth-largest-element-in-a-stream.js)|Easy| -704|[Binary Search](./solutions/0704-binary-search.js)|Easy| -705|[Design HashSet](./solutions/0705-design-hashset.js)|Easy| -706|[Design HashMap](./solutions/0706-design-hashmap.js)|Easy| -707|[Design Linked List](./solutions/0707-design-linked-list.js)|Medium| -709|[To Lower Case](./solutions/0709-to-lower-case.js)|Easy| -710|[Random Pick with Blacklist](./solutions/0710-random-pick-with-blacklist.js)|Hard| -712|[Minimum ASCII Delete Sum for Two Strings](./solutions/0712-minimum-ascii-delete-sum-for-two-strings.js)|Medium| -713|[Subarray Product Less Than K](./solutions/0713-subarray-product-less-than-k.js)|Medium| -714|[Best Time to Buy and Sell Stock with Transaction Fee](./solutions/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| -715|[Range Module](./solutions/0715-range-module.js)|Hard| -717|[1-bit and 2-bit Characters](./solutions/0717-1-bit-and-2-bit-characters.js)|Easy| -718|[Maximum Length of Repeated Subarray](./solutions/0718-maximum-length-of-repeated-subarray.js)|Medium| -719|[Find K-th Smallest Pair Distance](./solutions/0719-find-k-th-smallest-pair-distance.js)|Hard| -720|[Longest Word in Dictionary](./solutions/0720-longest-word-in-dictionary.js)|Medium| -721|[Accounts Merge](./solutions/0721-accounts-merge.js)|Medium| -722|[Remove Comments](./solutions/0722-remove-comments.js)|Medium| -724|[Find Pivot Index](./solutions/0724-find-pivot-index.js)|Easy| -725|[Split Linked List in Parts](./solutions/0725-split-linked-list-in-parts.js)|Medium| -726|[Number of Atoms](./solutions/0726-number-of-atoms.js)|Hard| -728|[Self Dividing Numbers](./solutions/0728-self-dividing-numbers.js)|Easy| -729|[My Calendar I](./solutions/0729-my-calendar-i.js)|Medium| -730|[Count Different Palindromic Subsequences](./solutions/0730-count-different-palindromic-subsequences.js)|Hard| -731|[My Calendar II](./solutions/0731-my-calendar-ii.js)|Medium| -732|[My Calendar III](./solutions/0732-my-calendar-iii.js)|Hard| -733|[Flood Fill](./solutions/0733-flood-fill.js)|Easy| -735|[Asteroid Collision](./solutions/0735-asteroid-collision.js)|Medium| -736|[Parse Lisp Expression](./solutions/0736-parse-lisp-expression.js)|Hard| -738|[Monotone Increasing Digits](./solutions/0738-monotone-increasing-digits.js)|Medium| -739|[Daily Temperatures](./solutions/0739-daily-temperatures.js)|Medium| -740|[Delete and Earn](./solutions/0740-delete-and-earn.js)|Medium| -741|[Cherry Pickup](./solutions/0741-cherry-pickup.js)|Hard| -743|[Network Delay Time](./solutions/0743-network-delay-time.js)|Medium| -744|[Find Smallest Letter Greater Than Target](./solutions/0744-find-smallest-letter-greater-than-target.js)|Easy| -745|[Prefix and Suffix Search](./solutions/0745-prefix-and-suffix-search.js)|Hard| -746|[Min Cost Climbing Stairs](./solutions/0746-min-cost-climbing-stairs.js)|Easy| -747|[Largest Number At Least Twice of Others](./solutions/0747-largest-number-at-least-twice-of-others.js)|Easy| -748|[Shortest Completing Word](./solutions/0748-shortest-completing-word.js)|Easy| -749|[Contain Virus](./solutions/0749-contain-virus.js)|Hard| -752|[Open the Lock](./solutions/0752-open-the-lock.js)|Medium| -753|[Cracking the Safe](./solutions/0753-cracking-the-safe.js)|Hard| -754|[Reach a Number](./solutions/0754-reach-a-number.js)|Medium| -756|[Pyramid Transition Matrix](./solutions/0756-pyramid-transition-matrix.js)|Medium| -757|[Set Intersection Size At Least Two](./solutions/0757-set-intersection-size-at-least-two.js)|Hard| -761|[Special Binary String](./solutions/0761-special-binary-string.js)|Hard| -762|[Prime Number of Set Bits in Binary Representation](./solutions/0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| -763|[Partition Labels](./solutions/0763-partition-labels.js)|Medium| -764|[Largest Plus Sign](./solutions/0764-largest-plus-sign.js)|Medium| -765|[Couples Holding Hands](./solutions/0765-couples-holding-hands.js)|Hard| -766|[Toeplitz Matrix](./solutions/0766-toeplitz-matrix.js)|Easy| -767|[Reorganize String](./solutions/0767-reorganize-string.js)|Medium| -768|[Max Chunks To Make Sorted II](./solutions/0768-max-chunks-to-make-sorted-ii.js)|Hard| -769|[Max Chunks To Make Sorted](./solutions/0769-max-chunks-to-make-sorted.js)|Medium| -770|[Basic Calculator IV](./solutions/0770-basic-calculator-iv.js)|Hard| -771|[Jewels and Stones](./solutions/0771-jewels-and-stones.js)|Easy| -773|[Sliding Puzzle](./solutions/0773-sliding-puzzle.js)|Hard| -775|[Global and Local Inversions](./solutions/0775-global-and-local-inversions.js)|Medium| -777|[Swap Adjacent in LR String](./solutions/0777-swap-adjacent-in-lr-string.js)|Medium| -778|[Swim in Rising Water](./solutions/0778-swim-in-rising-water.js)|Hard| -779|[K-th Symbol in Grammar](./solutions/0779-k-th-symbol-in-grammar.js)|Medium| -780|[Reaching Points](./solutions/0780-reaching-points.js)|Hard| -781|[Rabbits in Forest](./solutions/0781-rabbits-in-forest.js)|Medium| -782|[Transform to Chessboard](./solutions/0782-transform-to-chessboard.js)|Hard| -783|[Minimum Distance Between BST Nodes](./solutions/0783-minimum-distance-between-bst-nodes.js)|Easy| -784|[Letter Case Permutation](./solutions/0784-letter-case-permutation.js)|Medium| -785|[Is Graph Bipartite?](./solutions/0785-is-graph-bipartite.js)|Medium| -786|[K-th Smallest Prime Fraction](./solutions/0786-k-th-smallest-prime-fraction.js)|Medium| -787|[Cheapest Flights Within K Stops](./solutions/0787-cheapest-flights-within-k-stops.js)|Medium| -788|[Rotated Digits](./solutions/0788-rotated-digits.js)|Medium| -789|[Escape The Ghosts](./solutions/0789-escape-the-ghosts.js)|Medium| -790|[Domino and Tromino Tiling](./solutions/0790-domino-and-tromino-tiling.js)|Medium| -791|[Custom Sort String](./solutions/0791-custom-sort-string.js)|Medium| -792|[Number of Matching Subsequences](./solutions/0792-number-of-matching-subsequences.js)|Medium| -793|[Preimage Size of Factorial Zeroes Function](./solutions/0793-preimage-size-of-factorial-zeroes-function.js)|Hard| -794|[Valid Tic-Tac-Toe State](./solutions/0794-valid-tic-tac-toe-state.js)|Medium| -795|[Number of Subarrays with Bounded Maximum](./solutions/0795-number-of-subarrays-with-bounded-maximum.js)|Medium| -796|[Rotate String](./solutions/0796-rotate-string.js)|Easy| -797|[All Paths From Source to Target](./solutions/0797-all-paths-from-source-to-target.js)|Medium| -798|[Smallest Rotation with Highest Score](./solutions/0798-smallest-rotation-with-highest-score.js)|Hard| -799|[Champagne Tower](./solutions/0799-champagne-tower.js)|Medium| -801|[Minimum Swaps To Make Sequences Increasing](./solutions/0801-minimum-swaps-to-make-sequences-increasing.js)|Hard| -802|[Find Eventual Safe States](./solutions/0802-find-eventual-safe-states.js)|Medium| -803|[Bricks Falling When Hit](./solutions/0803-bricks-falling-when-hit.js)|Hard| -804|[Unique Morse Code Words](./solutions/0804-unique-morse-code-words.js)|Easy| -805|[Split Array With Same Average](./solutions/0805-split-array-with-same-average.js)|Hard| -806|[Number of Lines To Write String](./solutions/0806-number-of-lines-to-write-string.js)|Easy| -807|[Max Increase to Keep City Skyline](./solutions/0807-max-increase-to-keep-city-skyline.js)|Medium| -808|[Soup Servings](./solutions/0808-soup-servings.js)|Medium| -809|[Expressive Words](./solutions/0809-expressive-words.js)|Medium| -810|[Chalkboard XOR Game](./solutions/0810-chalkboard-xor-game.js)|Hard| -811|[Subdomain Visit Count](./solutions/0811-subdomain-visit-count.js)|Medium| -812|[Largest Triangle Area](./solutions/0812-largest-triangle-area.js)|Easy| -813|[Largest Sum of Averages](./solutions/0813-largest-sum-of-averages.js)|Medium| -814|[Binary Tree Pruning](./solutions/0814-binary-tree-pruning.js)|Medium| -815|[Bus Routes](./solutions/0815-bus-routes.js)|Hard| -816|[Ambiguous Coordinates](./solutions/0816-ambiguous-coordinates.js)|Medium| -817|[Linked List Components](./solutions/0817-linked-list-components.js)|Medium| -818|[Race Car](./solutions/0818-race-car.js)|Hard| -819|[Most Common Word](./solutions/0819-most-common-word.js)|Easy| -820|[Short Encoding of Words](./solutions/0820-short-encoding-of-words.js)|Medium| -821|[Shortest Distance to a Character](./solutions/0821-shortest-distance-to-a-character.js)|Easy| -822|[Card Flipping Game](./solutions/0822-card-flipping-game.js)|Medium| -823|[Binary Trees With Factors](./solutions/0823-binary-trees-with-factors.js)|Medium| -824|[Goat Latin](./solutions/0824-goat-latin.js)|Easy| -825|[Friends Of Appropriate Ages](./solutions/0825-friends-of-appropriate-ages.js)|Medium| -826|[Most Profit Assigning Work](./solutions/0826-most-profit-assigning-work.js)|Medium| -827|[Making A Large Island](./solutions/0827-making-a-large-island.js)|Hard| -828|[Count Unique Characters of All Substrings of a Given String](./solutions/0828-count-unique-characters-of-all-substrings-of-a-given-string.js)|Hard| -829|[Consecutive Numbers Sum](./solutions/0829-consecutive-numbers-sum.js)|Hard| -830|[Positions of Large Groups](./solutions/0830-positions-of-large-groups.js)|Easy| -831|[Masking Personal Information](./solutions/0831-masking-personal-information.js)|Medium| -832|[Flipping an Image](./solutions/0832-flipping-an-image.js)|Easy| -833|[Find And Replace in String](./solutions/0833-find-and-replace-in-string.js)|Medium| -834|[Sum of Distances in Tree](./solutions/0834-sum-of-distances-in-tree.js)|Hard| -835|[Image Overlap](./solutions/0835-image-overlap.js)|Medium| -836|[Rectangle Overlap](./solutions/0836-rectangle-overlap.js)|Easy| -837|[New 21 Game](./solutions/0837-new-21-game.js)|Medium| -838|[Push Dominoes](./solutions/0838-push-dominoes.js)|Medium| -839|[Similar String Groups](./solutions/0839-similar-string-groups.js)|Hard| -840|[Magic Squares In Grid](./solutions/0840-magic-squares-in-grid.js)|Medium| -841|[Keys and Rooms](./solutions/0841-keys-and-rooms.js)|Medium| -842|[Split Array into Fibonacci Sequence](./solutions/0842-split-array-into-fibonacci-sequence.js)|Medium| -843|[Guess the Word](./solutions/0843-guess-the-word.js)|Hard| -844|[Backspace String Compare](./solutions/0844-backspace-string-compare.js)|Easy| -845|[Longest Mountain in Array](./solutions/0845-longest-mountain-in-array.js)|Medium| -846|[Hand of Straights](./solutions/0846-hand-of-straights.js)|Medium| -847|[Shortest Path Visiting All Nodes](./solutions/0847-shortest-path-visiting-all-nodes.js)|Hard| -848|[Shifting Letters](./solutions/0848-shifting-letters.js)|Medium| -849|[Maximize Distance to Closest Person](./solutions/0849-maximize-distance-to-closest-person.js)|Medium| -850|[Rectangle Area II](./solutions/0850-rectangle-area-ii.js)|Hard| -851|[Loud and Rich](./solutions/0851-loud-and-rich.js)|Medium| -852|[Peak Index in a Mountain Array](./solutions/0852-peak-index-in-a-mountain-array.js)|Medium| -853|[Car Fleet](./solutions/0853-car-fleet.js)|Medium| -854|[K-Similar Strings](./solutions/0854-k-similar-strings.js)|Hard| -855|[Exam Room](./solutions/0855-exam-room.js)|Medium| -856|[Score of Parentheses](./solutions/0856-score-of-parentheses.js)|Medium| -857|[Minimum Cost to Hire K Workers](./solutions/0857-minimum-cost-to-hire-k-workers.js)|Hard| -858|[Mirror Reflection](./solutions/0858-mirror-reflection.js)|Medium| -859|[Buddy Strings](./solutions/0859-buddy-strings.js)|Easy| -860|[Lemonade Change](./solutions/0860-lemonade-change.js)|Easy| -861|[Score After Flipping Matrix](./solutions/0861-score-after-flipping-matrix.js)|Medium| -862|[Shortest Subarray with Sum at Least K](./solutions/0862-shortest-subarray-with-sum-at-least-k.js)|Hard| -863|[All Nodes Distance K in Binary Tree](./solutions/0863-all-nodes-distance-k-in-binary-tree.js)|Medium| -864|[Shortest Path to Get All Keys](./solutions/0864-shortest-path-to-get-all-keys.js)|Hard| -865|[Smallest Subtree with all the Deepest Nodes](./solutions/0865-smallest-subtree-with-all-the-deepest-nodes.js)|Medium| -866|[Prime Palindrome](./solutions/0866-prime-palindrome.js)|Medium| -867|[Transpose Matrix](./solutions/0867-transpose-matrix.js)|Easy| -868|[Binary Gap](./solutions/0868-binary-gap.js)|Easy| -869|[Reordered Power of 2](./solutions/0869-reordered-power-of-2.js)|Medium| -870|[Advantage Shuffle](./solutions/0870-advantage-shuffle.js)|Medium| -871|[Minimum Number of Refueling Stops](./solutions/0871-minimum-number-of-refueling-stops.js)|Hard| -872|[Leaf-Similar Trees](./solutions/0872-leaf-similar-trees.js)|Easy| -873|[Length of Longest Fibonacci Subsequence](./solutions/0873-length-of-longest-fibonacci-subsequence.js)|Medium| -874|[Walking Robot Simulation](./solutions/0874-walking-robot-simulation.js)|Medium| -875|[Koko Eating Bananas](./solutions/0875-koko-eating-bananas.js)|Medium| -876|[Middle of the Linked List](./solutions/0876-middle-of-the-linked-list.js)|Easy| -877|[Stone Game](./solutions/0877-stone-game.js)|Medium| -878|[Nth Magical Number](./solutions/0878-nth-magical-number.js)|Hard| -879|[Profitable Schemes](./solutions/0879-profitable-schemes.js)|Hard| -880|[Decoded String at Index](./solutions/0880-decoded-string-at-index.js)|Medium| -881|[Boats to Save People](./solutions/0881-boats-to-save-people.js)|Medium| -882|[Reachable Nodes In Subdivided Graph](./solutions/0882-reachable-nodes-in-subdivided-graph.js)|Hard| -883|[Projection Area of 3D Shapes](./solutions/0883-projection-area-of-3d-shapes.js)|Easy| -884|[Uncommon Words from Two Sentences](./solutions/0884-uncommon-words-from-two-sentences.js)|Easy| -885|[Spiral Matrix III](./solutions/0885-spiral-matrix-iii.js)|Medium| -886|[Possible Bipartition](./solutions/0886-possible-bipartition.js)|Medium| -887|[Super Egg Drop](./solutions/0887-super-egg-drop.js)|Hard| -888|[Fair Candy Swap](./solutions/0888-fair-candy-swap.js)|Easy| -889|[Construct Binary Tree from Preorder and Postorder Traversal](./solutions/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js)|Medium| -890|[Find and Replace Pattern](./solutions/0890-find-and-replace-pattern.js)|Medium| -891|[Sum of Subsequence Widths](./solutions/0891-sum-of-subsequence-widths.js)|Hard| -892|[Surface Area of 3D Shapes](./solutions/0892-surface-area-of-3d-shapes.js)|Easy| -893|[Groups of Special-Equivalent Strings](./solutions/0893-groups-of-special-equivalent-strings.js)|Medium| -894|[All Possible Full Binary Trees](./solutions/0894-all-possible-full-binary-trees.js)|Medium| -895|[Maximum Frequency Stack](./solutions/0895-maximum-frequency-stack.js)|Hard| -896|[Monotonic Array](./solutions/0896-monotonic-array.js)|Easy| -897|[Increasing Order Search Tree](./solutions/0897-increasing-order-search-tree.js)|Easy| -898|[Bitwise ORs of Subarrays](./solutions/0898-bitwise-ors-of-subarrays.js)|Medium| -899|[Orderly Queue](./solutions/0899-orderly-queue.js)|Hard| -900|[RLE Iterator](./solutions/0900-rle-iterator.js)|Medium| -901|[Online Stock Span](./solutions/0901-online-stock-span.js)|Medium| -902|[Numbers At Most N Given Digit Set](./solutions/0902-numbers-at-most-n-given-digit-set.js)|Hard| -903|[Valid Permutations for DI Sequence](./solutions/0903-valid-permutations-for-di-sequence.js)|Hard| -904|[Fruit Into Baskets](./solutions/0904-fruit-into-baskets.js)|Medium| -905|[Sort Array By Parity](./solutions/0905-sort-array-by-parity.js)|Easy| -906|[Super Palindromes](./solutions/0906-super-palindromes.js)|Hard| -907|[Sum of Subarray Minimums](./solutions/0907-sum-of-subarray-minimums.js)|Medium| -908|[Smallest Range I](./solutions/0908-smallest-range-i.js)|Easy| -909|[Snakes and Ladders](./solutions/0909-snakes-and-ladders.js)|Medium| -910|[Smallest Range II](./solutions/0910-smallest-range-ii.js)|Medium| -911|[Online Election](./solutions/0911-online-election.js)|Medium| -912|[Sort an Array](./solutions/0912-sort-an-array.js)|Medium| -913|[Cat and Mouse](./solutions/0913-cat-and-mouse.js)|Hard| -914|[X of a Kind in a Deck of Cards](./solutions/0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| -915|[Partition Array into Disjoint Intervals](./solutions/0915-partition-array-into-disjoint-intervals.js)|Medium| -916|[Word Subsets](./solutions/0916-word-subsets.js)|Medium| -917|[Reverse Only Letters](./solutions/0917-reverse-only-letters.js)|Easy| -918|[Maximum Sum Circular Subarray](./solutions/0918-maximum-sum-circular-subarray.js)|Medium| -919|[Complete Binary Tree Inserter](./solutions/0919-complete-binary-tree-inserter.js)|Medium| -920|[Number of Music Playlists](./solutions/0920-number-of-music-playlists.js)|Hard| -921|[Minimum Add to Make Parentheses Valid](./solutions/0921-minimum-add-to-make-parentheses-valid.js)|Medium| -922|[Sort Array By Parity II](./solutions/0922-sort-array-by-parity-ii.js)|Easy| -923|[3Sum With Multiplicity](./solutions/0923-3sum-with-multiplicity.js)|Medium| -924|[Minimize Malware Spread](./solutions/0924-minimize-malware-spread.js)|Hard| -925|[Long Pressed Name](./solutions/0925-long-pressed-name.js)|Easy| -926|[Flip String to Monotone Increasing](./solutions/0926-flip-string-to-monotone-increasing.js)|Medium| -927|[Three Equal Parts](./solutions/0927-three-equal-parts.js)|Hard| -928|[Minimize Malware Spread II](./solutions/0928-minimize-malware-spread-ii.js)|Hard| -929|[Unique Email Addresses](./solutions/0929-unique-email-addresses.js)|Easy| -930|[Binary Subarrays With Sum](./solutions/0930-binary-subarrays-with-sum.js)|Medium| -931|[Minimum Falling Path Sum](./solutions/0931-minimum-falling-path-sum.js)|Medium| -932|[Beautiful Array](./solutions/0932-beautiful-array.js)|Medium| -933|[Number of Recent Calls](./solutions/0933-number-of-recent-calls.js)|Easy| -934|[Shortest Bridge](./solutions/0934-shortest-bridge.js)|Medium| -935|[Knight Dialer](./solutions/0935-knight-dialer.js)|Medium| -936|[Stamping The Sequence](./solutions/0936-stamping-the-sequence.js)|Hard| -937|[Reorder Data in Log Files](./solutions/0937-reorder-data-in-log-files.js)|Medium| -938|[Range Sum of BST](./solutions/0938-range-sum-of-bst.js)|Easy| -939|[Minimum Area Rectangle](./solutions/0939-minimum-area-rectangle.js)|Medium| -940|[Distinct Subsequences II](./solutions/0940-distinct-subsequences-ii.js)|Hard| -941|[Valid Mountain Array](./solutions/0941-valid-mountain-array.js)|Easy| -942|[DI String Match](./solutions/0942-di-string-match.js)|Easy| -943|[Find the Shortest Superstring](./solutions/0943-find-the-shortest-superstring.js)|Hard| -944|[Delete Columns to Make Sorted](./solutions/0944-delete-columns-to-make-sorted.js)|Easy| -945|[Minimum Increment to Make Array Unique](./solutions/0945-minimum-increment-to-make-array-unique.js)|Medium| -946|[Validate Stack Sequences](./solutions/0946-validate-stack-sequences.js)|Medium| -947|[Most Stones Removed with Same Row or Column](./solutions/0947-most-stones-removed-with-same-row-or-column.js)|Medium| -948|[Bag of Tokens](./solutions/0948-bag-of-tokens.js)|Medium| -949|[Largest Time for Given Digits](./solutions/0949-largest-time-for-given-digits.js)|Medium| -950|[Reveal Cards In Increasing Order](./solutions/0950-reveal-cards-in-increasing-order.js)|Medium| -951|[Flip Equivalent Binary Trees](./solutions/0951-flip-equivalent-binary-trees.js)|Medium| -952|[Largest Component Size by Common Factor](./solutions/0952-largest-component-size-by-common-factor.js)|Hard| -953|[Verifying an Alien Dictionary](./solutions/0953-verifying-an-alien-dictionary.js)|Easy| -954|[Array of Doubled Pairs](./solutions/0954-array-of-doubled-pairs.js)|Medium| -955|[Delete Columns to Make Sorted II](./solutions/0955-delete-columns-to-make-sorted-ii.js)|Medium| -956|[Tallest Billboard](./solutions/0956-tallest-billboard.js)|Hard| -957|[Prison Cells After N Days](./solutions/0957-prison-cells-after-n-days.js)|Medium| -958|[Check Completeness of a Binary Tree](./solutions/0958-check-completeness-of-a-binary-tree.js)|Medium| -959|[Regions Cut By Slashes](./solutions/0959-regions-cut-by-slashes.js)|Medium| -960|[Delete Columns to Make Sorted III](./solutions/0960-delete-columns-to-make-sorted-iii.js)|Hard| -961|[N-Repeated Element in Size 2N Array](./solutions/0961-n-repeated-element-in-size-2n-array.js)|Easy| -962|[Maximum Width Ramp](./solutions/0962-maximum-width-ramp.js)|Medium| -963|[Minimum Area Rectangle II](./solutions/0963-minimum-area-rectangle-ii.js)|Medium| -964|[Least Operators to Express Number](./solutions/0964-least-operators-to-express-number.js)|Hard| -965|[Univalued Binary Tree](./solutions/0965-univalued-binary-tree.js)|Easy| -966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium| -967|[Numbers With Same Consecutive Differences](./solutions/0967-numbers-with-same-consecutive-differences.js)|Medium| -968|[Binary Tree Cameras](./solutions/0968-binary-tree-cameras.js)|Hard| -969|[Pancake Sorting](./solutions/0969-pancake-sorting.js)|Medium| -970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy| -971|[Flip Binary Tree To Match Preorder Traversal](./solutions/0971-flip-binary-tree-to-match-preorder-traversal.js)|Medium| -972|[Equal Rational Numbers](./solutions/0972-equal-rational-numbers.js)|Hard| -973|[K Closest Points to Origin](./solutions/0973-k-closest-points-to-origin.js)|Medium| -974|[Subarray Sums Divisible by K](./solutions/0974-subarray-sums-divisible-by-k.js)|Medium| -975|[Odd Even Jump](./solutions/0975-odd-even-jump.js)|Hard| -976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy| -977|[Squares of a Sorted Array](./solutions/0977-squares-of-a-sorted-array.js)|Easy| -978|[Longest Turbulent Subarray](./solutions/0978-longest-turbulent-subarray.js)|Medium| -979|[Distribute Coins in Binary Tree](./solutions/0979-distribute-coins-in-binary-tree.js)|Medium| -980|[Unique Paths III](./solutions/0980-unique-paths-iii.js)|Hard| -981|[Time Based Key-Value Store](./solutions/0981-time-based-key-value-store.js)|Medium| -982|[Triples with Bitwise AND Equal To Zero](./solutions/0982-triples-with-bitwise-and-equal-to-zero.js)|Hard| -983|[Minimum Cost For Tickets](./solutions/0983-minimum-cost-for-tickets.js)|Medium| -984|[String Without AAA or BBB](./solutions/0984-string-without-aaa-or-bbb.js)|Medium| -985|[Sum of Even Numbers After Queries](./solutions/0985-sum-of-even-numbers-after-queries.js)|Easy| -986|[Interval List Intersections](./solutions/0986-interval-list-intersections.js)|Medium| -987|[Vertical Order Traversal of a Binary Tree](./solutions/0987-vertical-order-traversal-of-a-binary-tree.js)|Hard| -988|[Smallest String Starting From Leaf](./solutions/0988-smallest-string-starting-from-leaf.js)|Medium| -989|[Add to Array-Form of Integer](./solutions/0989-add-to-array-form-of-integer.js)|Easy| -990|[Satisfiability of Equality Equations](./solutions/0990-satisfiability-of-equality-equations.js)|Medium| -991|[Broken Calculator](./solutions/0991-broken-calculator.js)|Medium| -992|[Subarrays with K Different Integers](./solutions/0992-subarrays-with-k-different-integers.js)|Hard| -993|[Cousins in Binary Tree](./solutions/0993-cousins-in-binary-tree.js)|Easy| -994|[Rotting Oranges](./solutions/0994-rotting-oranges.js)|Medium| -995|[Minimum Number of K Consecutive Bit Flips](./solutions/0995-minimum-number-of-k-consecutive-bit-flips.js)|Hard| -996|[Number of Squareful Arrays](./solutions/0996-number-of-squareful-arrays.js)|Hard| -997|[Find the Town Judge](./solutions/0997-find-the-town-judge.js)|Easy| -998|[Maximum Binary Tree II](./solutions/0998-maximum-binary-tree-ii.js)|Medium| -999|[Available Captures for Rook](./solutions/0999-available-captures-for-rook.js)|Easy| -1000|[Minimum Cost to Merge Stones](./solutions/1000-minimum-cost-to-merge-stones.js)|Hard| -1001|[Grid Illumination](./solutions/1001-grid-illumination.js)|Hard| -1002|[Find Common Characters](./solutions/1002-find-common-characters.js)|Easy| -1003|[Check If Word Is Valid After Substitutions](./solutions/1003-check-if-word-is-valid-after-substitutions.js)|Medium| -1004|[Max Consecutive Ones III](./solutions/1004-max-consecutive-ones-iii.js)|Medium| -1005|[Maximize Sum Of Array After K Negations](./solutions/1005-maximize-sum-of-array-after-k-negations.js)|Easy| -1006|[Clumsy Factorial](./solutions/1006-clumsy-factorial.js)|Medium| -1007|[Minimum Domino Rotations For Equal Row](./solutions/1007-minimum-domino-rotations-for-equal-row.js)|Medium| -1008|[Construct Binary Search Tree from Preorder Traversal](./solutions/1008-construct-binary-search-tree-from-preorder-traversal.js)|Medium| -1009|[Complement of Base 10 Integer](./solutions/1009-complement-of-base-10-integer.js)|Easy| -1010|[Pairs of Songs With Total Durations Divisible by 60](./solutions/1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| -1011|[Capacity To Ship Packages Within D Days](./solutions/1011-capacity-to-ship-packages-within-d-days.js)|Medium| -1012|[Numbers With Repeated Digits](./solutions/1012-numbers-with-repeated-digits.js)|Hard| -1013|[Partition Array Into Three Parts With Equal Sum](./solutions/1013-partition-array-into-three-parts-with-equal-sum.js)|Easy| -1014|[Best Sightseeing Pair](./solutions/1014-best-sightseeing-pair.js)|Medium| -1015|[Smallest Integer Divisible by K](./solutions/1015-smallest-integer-divisible-by-k.js)|Medium| -1016|[Binary String With Substrings Representing 1 To N](./solutions/1016-binary-string-with-substrings-representing-1-to-n.js)|Medium| -1017|[Convert to Base -2](./solutions/1017-convert-to-base-2.js)|Medium| -1018|[Binary Prefix Divisible By 5](./solutions/1018-binary-prefix-divisible-by-5.js)|Easy| -1019|[Next Greater Node In Linked List](./solutions/1019-next-greater-node-in-linked-list.js)|Medium| -1020|[Number of Enclaves](./solutions/1020-number-of-enclaves.js)|Medium| -1021|[Remove Outermost Parentheses](./solutions/1021-remove-outermost-parentheses.js)|Easy| -1022|[Sum of Root To Leaf Binary Numbers](./solutions/1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| -1023|[Camelcase Matching](./solutions/1023-camelcase-matching.js)|Medium| -1024|[Video Stitching](./solutions/1024-video-stitching.js)|Medium| -1025|[Divisor Game](./solutions/1025-divisor-game.js)|Easy| -1026|[Maximum Difference Between Node and Ancestor](./solutions/1026-maximum-difference-between-node-and-ancestor.js)|Medium| -1027|[Longest Arithmetic Subsequence](./solutions/1027-longest-arithmetic-subsequence.js)|Medium| -1028|[Recover a Tree From Preorder Traversal](./solutions/1028-recover-a-tree-from-preorder-traversal.js)|Hard| -1029|[Two City Scheduling](./solutions/1029-two-city-scheduling.js)|Medium| -1030|[Matrix Cells in Distance Order](./solutions/1030-matrix-cells-in-distance-order.js)|Easy| -1031|[Maximum Sum of Two Non-Overlapping Subarrays](./solutions/1031-maximum-sum-of-two-non-overlapping-subarrays.js)|Medium| -1032|[Stream of Characters](./solutions/1032-stream-of-characters.js)|Hard| -1033|[Moving Stones Until Consecutive](./solutions/1033-moving-stones-until-consecutive.js)|Medium| -1034|[Coloring A Border](./solutions/1034-coloring-a-border.js)|Medium| -1035|[Uncrossed Lines](./solutions/1035-uncrossed-lines.js)|Medium| -1036|[Escape a Large Maze](./solutions/1036-escape-a-large-maze.js)|Hard| -1037|[Valid Boomerang](./solutions/1037-valid-boomerang.js)|Easy| -1038|[Binary Search Tree to Greater Sum Tree](./solutions/1038-binary-search-tree-to-greater-sum-tree.js)|Medium| -1039|[Minimum Score Triangulation of Polygon](./solutions/1039-minimum-score-triangulation-of-polygon.js)|Medium| -1040|[Moving Stones Until Consecutive II](./solutions/1040-moving-stones-until-consecutive-ii.js)|Medium| -1041|[Robot Bounded In Circle](./solutions/1041-robot-bounded-in-circle.js)|Medium| -1042|[Flower Planting With No Adjacent](./solutions/1042-flower-planting-with-no-adjacent.js)|Medium| -1043|[Partition Array for Maximum Sum](./solutions/1043-partition-array-for-maximum-sum.js)|Medium| -1044|[Longest Duplicate Substring](./solutions/1044-longest-duplicate-substring.js)|Hard| -1046|[Last Stone Weight](./solutions/1046-last-stone-weight.js)|Easy| -1047|[Remove All Adjacent Duplicates In String](./solutions/1047-remove-all-adjacent-duplicates-in-string.js)|Easy| -1048|[Longest String Chain](./solutions/1048-longest-string-chain.js)|Medium| -1049|[Last Stone Weight II](./solutions/1049-last-stone-weight-ii.js)|Medium| -1051|[Height Checker](./solutions/1051-height-checker.js)|Easy| -1052|[Grumpy Bookstore Owner](./solutions/1052-grumpy-bookstore-owner.js)|Medium| -1053|[Previous Permutation With One Swap](./solutions/1053-previous-permutation-with-one-swap.js)|Medium| -1054|[Distant Barcodes](./solutions/1054-distant-barcodes.js)|Medium| -1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium| -1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy| -1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium| -1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium| -1074|[Number of Submatrices That Sum to Target](./solutions/1074-number-of-submatrices-that-sum-to-target.js)|Hard| -1078|[Occurrences After Bigram](./solutions/1078-occurrences-after-bigram.js)|Easy| -1079|[Letter Tile Possibilities](./solutions/1079-letter-tile-possibilities.js)|Medium| -1080|[Insufficient Nodes in Root to Leaf Paths](./solutions/1080-insufficient-nodes-in-root-to-leaf-paths.js)|Medium| -1081|[Smallest Subsequence of Distinct Characters](./solutions/1081-smallest-subsequence-of-distinct-characters.js)|Medium| -1089|[Duplicate Zeros](./solutions/1089-duplicate-zeros.js)|Easy| -1090|[Largest Values From Labels](./solutions/1090-largest-values-from-labels.js)|Medium| -1091|[Shortest Path in Binary Matrix](./solutions/1091-shortest-path-in-binary-matrix.js)|Medium| -1092|[Shortest Common Supersequence](./solutions/1092-shortest-common-supersequence.js)|Hard| -1093|[Statistics from a Large Sample](./solutions/1093-statistics-from-a-large-sample.js)|Medium| -1094|[Car Pooling](./solutions/1094-car-pooling.js)|Medium| -1095|[Find in Mountain Array](./solutions/1095-find-in-mountain-array.js)|Hard| -1096|[Brace Expansion II](./solutions/1096-brace-expansion-ii.js)|Hard| -1103|[Distribute Candies to People](./solutions/1103-distribute-candies-to-people.js)|Easy| -1104|[Path In Zigzag Labelled Binary Tree](./solutions/1104-path-in-zigzag-labelled-binary-tree.js)|Medium| -1105|[Filling Bookcase Shelves](./solutions/1105-filling-bookcase-shelves.js)|Medium| -1106|[Parsing A Boolean Expression](./solutions/1106-parsing-a-boolean-expression.js)|Hard| -1108|[Defanging an IP Address](./solutions/1108-defanging-an-ip-address.js)|Easy| -1109|[Corporate Flight Bookings](./solutions/1109-corporate-flight-bookings.js)|Medium| -1110|[Delete Nodes And Return Forest](./solutions/1110-delete-nodes-and-return-forest.js)|Medium| -1111|[Maximum Nesting Depth of Two Valid Parentheses Strings](./solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js)|Medium| -1122|[Relative Sort Array](./solutions/1122-relative-sort-array.js)|Easy| -1123|[Lowest Common Ancestor of Deepest Leaves](./solutions/1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium| -1124|[Longest Well-Performing Interval](./solutions/1124-longest-well-performing-interval.js)|Medium| -1125|[Smallest Sufficient Team](./solutions/1125-smallest-sufficient-team.js)|Hard| -1128|[Number of Equivalent Domino Pairs](./solutions/1128-number-of-equivalent-domino-pairs.js)|Easy| -1129|[Shortest Path with Alternating Colors](./solutions/1129-shortest-path-with-alternating-colors.js)|Medium| -1130|[Minimum Cost Tree From Leaf Values](./solutions/1130-minimum-cost-tree-from-leaf-values.js)|Medium| -1131|[Maximum of Absolute Value Expression](./solutions/1131-maximum-of-absolute-value-expression.js)|Medium| -1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy| -1138|[Alphabet Board Path](./solutions/1138-alphabet-board-path.js)|Medium| -1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium| -1140|[Stone Game II](./solutions/1140-stone-game-ii.js)|Medium| -1143|[Longest Common Subsequence](./solutions/1143-longest-common-subsequence.js)|Medium| -1144|[Decrease Elements To Make Array Zigzag](./solutions/1144-decrease-elements-to-make-array-zigzag.js)|Medium| -1145|[Binary Tree Coloring Game](./solutions/1145-binary-tree-coloring-game.js)|Medium| -1146|[Snapshot Array](./solutions/1146-snapshot-array.js)|Medium| -1147|[Longest Chunked Palindrome Decomposition](./solutions/1147-longest-chunked-palindrome-decomposition.js)|Hard| -1154|[Day of the Year](./solutions/1154-day-of-the-year.js)|Easy| -1155|[Number of Dice Rolls With Target Sum](./solutions/1155-number-of-dice-rolls-with-target-sum.js)|Medium| -1156|[Swap For Longest Repeated Character Substring](./solutions/1156-swap-for-longest-repeated-character-substring.js)|Medium| -1157|[Online Majority Element In Subarray](./solutions/1157-online-majority-element-in-subarray.js)|Hard| -1160|[Find Words That Can Be Formed by Characters](./solutions/1160-find-words-that-can-be-formed-by-characters.js)|Easy| -1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium| -1162|[As Far from Land as Possible](./solutions/1162-as-far-from-land-as-possible.js)|Medium| -1163|[Last Substring in Lexicographical Order](./solutions/1163-last-substring-in-lexicographical-order.js)|Hard| -1169|[Invalid Transactions](./solutions/1169-invalid-transactions.js)|Medium| -1170|[Compare Strings by Frequency of the Smallest Character](./solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js)|Medium| -1171|[Remove Zero Sum Consecutive Nodes from Linked List](./solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js)|Medium| -1172|[Dinner Plate Stacks](./solutions/1172-dinner-plate-stacks.js)|Hard| -1175|[Prime Arrangements](./solutions/1175-prime-arrangements.js)|Easy| -1177|[Can Make Palindrome from Substring](./solutions/1177-can-make-palindrome-from-substring.js)|Medium| -1178|[Number of Valid Words for Each Puzzle](./solutions/1178-number-of-valid-words-for-each-puzzle.js)|Hard| -1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy| -1185|[Day of the Week](./solutions/1185-day-of-the-week.js)|Easy| -1186|[Maximum Subarray Sum with One Deletion](./solutions/1186-maximum-subarray-sum-with-one-deletion.js)|Medium| -1187|[Make Array Strictly Increasing](./solutions/1187-make-array-strictly-increasing.js)|Hard| -1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy| -1190|[Reverse Substrings Between Each Pair of Parentheses](./solutions/1190-reverse-substrings-between-each-pair-of-parentheses.js)|Medium| -1191|[K-Concatenation Maximum Sum](./solutions/1191-k-concatenation-maximum-sum.js)|Medium| -1192|[Critical Connections in a Network](./solutions/1192-critical-connections-in-a-network.js)|Hard| -1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy| -1201|[Ugly Number III](./solutions/1201-ugly-number-iii.js)|Medium| -1202|[Smallest String With Swaps](./solutions/1202-smallest-string-with-swaps.js)|Medium| -1203|[Sort Items by Groups Respecting Dependencies](./solutions/1203-sort-items-by-groups-respecting-dependencies.js)|Hard| -1206|[Design Skiplist](./solutions/1206-design-skiplist.js)|Hard| -1207|[Unique Number of Occurrences](./solutions/1207-unique-number-of-occurrences.js)|Easy| -1208|[Get Equal Substrings Within Budget](./solutions/1208-get-equal-substrings-within-budget.js)|Medium| -1209|[Remove All Adjacent Duplicates in String II](./solutions/1209-remove-all-adjacent-duplicates-in-string-ii.js)|Medium| -1210|[Minimum Moves to Reach Target with Rotations](./solutions/1210-minimum-moves-to-reach-target-with-rotations.js)|Hard| -1217|[Minimum Cost to Move Chips to The Same Position](./solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy| -1218|[Longest Arithmetic Subsequence of Given Difference](./solutions/1218-longest-arithmetic-subsequence-of-given-difference.js)|Medium| -1219|[Path with Maximum Gold](./solutions/1219-path-with-maximum-gold.js)|Medium| -1220|[Count Vowels Permutation](./solutions/1220-count-vowels-permutation.js)|Hard| -1221|[Split a String in Balanced Strings](./solutions/1221-split-a-string-in-balanced-strings.js)|Easy| -1222|[Queens That Can Attack the King](./solutions/1222-queens-that-can-attack-the-king.js)|Medium| -1223|[Dice Roll Simulation](./solutions/1223-dice-roll-simulation.js)|Hard| -1224|[Maximum Equal Frequency](./solutions/1224-maximum-equal-frequency.js)|Hard| -1227|[Airplane Seat Assignment Probability](./solutions/1227-airplane-seat-assignment-probability.js)|Medium| -1232|[Check If It Is a Straight Line](./solutions/1232-check-if-it-is-a-straight-line.js)|Easy| -1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium| -1234|[Replace the Substring for Balanced String](./solutions/1234-replace-the-substring-for-balanced-string.js)|Medium| -1235|[Maximum Profit in Job Scheduling](./solutions/1235-maximum-profit-in-job-scheduling.js)|Hard| -1237|[Find Positive Integer Solution for a Given Equation](./solutions/1237-find-positive-integer-solution-for-a-given-equation.js)|Medium| -1238|[Circular Permutation in Binary Representation](./solutions/1238-circular-permutation-in-binary-representation.js)|Medium| -1239|[Maximum Length of a Concatenated String with Unique Characters](./solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js)|Medium| -1240|[Tiling a Rectangle with the Fewest Squares](./solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js)|Hard| -1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium| -1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium| -1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium| -1250|[Check If It Is a Good Array](./solutions/1250-check-if-it-is-a-good-array.js)|Hard| -1252|[Cells with Odd Values in a Matrix](./solutions/1252-cells-with-odd-values-in-a-matrix.js)|Easy| -1253|[Reconstruct a 2-Row Binary Matrix](./solutions/1253-reconstruct-a-2-row-binary-matrix.js)|Medium| -1254|[Number of Closed Islands](./solutions/1254-number-of-closed-islands.js)|Medium| -1255|[Maximum Score Words Formed by Letters](./solutions/1255-maximum-score-words-formed-by-letters.js)|Hard| -1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy| -1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium| -1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium| -1263|[Minimum Moves to Move a Box to Their Target Location](./solutions/1263-minimum-moves-to-move-a-box-to-their-target-location.js)|Hard| -1266|[Minimum Time Visiting All Points](./solutions/1266-minimum-time-visiting-all-points.js)|Easy| -1267|[Count Servers that Communicate](./solutions/1267-count-servers-that-communicate.js)|Medium| -1268|[Search Suggestions System](./solutions/1268-search-suggestions-system.js)|Medium| -1269|[Number of Ways to Stay in the Same Place After Some Steps](./solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js)|Hard| -1275|[Find Winner on a Tic Tac Toe Game](./solutions/1275-find-winner-on-a-tic-tac-toe-game.js)|Easy| -1276|[Number of Burgers with No Waste of Ingredients](./solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js)|Medium| -1277|[Count Square Submatrices with All Ones](./solutions/1277-count-square-submatrices-with-all-ones.js)|Medium| -1278|[Palindrome Partitioning III](./solutions/1278-palindrome-partitioning-iii.js)|Hard| -1281|[Subtract the Product and Sum of Digits of an Integer](./solutions/1281-subtract-the-product-and-sum-of-digits-of-an-integer.js)|Easy| -1282|[Group the People Given the Group Size They Belong To](./solutions/1282-group-the-people-given-the-group-size-they-belong-to.js)|Medium| -1283|[Find the Smallest Divisor Given a Threshold](./solutions/1283-find-the-smallest-divisor-given-a-threshold.js)|Medium| -1284|[Minimum Number of Flips to Convert Binary Matrix to Zero Matrix](./solutions/1284-minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.js)|Hard| -1286|[Iterator for Combination](./solutions/1286-iterator-for-combination.js)|Medium| -1287|[Element Appearing More Than 25% In Sorted Array](./solutions/1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| -1288|[Remove Covered Intervals](./solutions/1288-remove-covered-intervals.js)|Medium| -1289|[Minimum Falling Path Sum II](./solutions/1289-minimum-falling-path-sum-ii.js)|Hard| -1290|[Convert Binary Number in a Linked List to Integer](./solutions/1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| -1291|[Sequential Digits](./solutions/1291-sequential-digits.js)|Medium| -1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./solutions/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| -1293|[Shortest Path in a Grid with Obstacles Elimination](./solutions/1293-shortest-path-in-a-grid-with-obstacles-elimination.js)|Hard| -1295|[Find Numbers with Even Number of Digits](./solutions/1295-find-numbers-with-even-number-of-digits.js)|Easy| -1296|[Divide Array in Sets of K Consecutive Numbers](./solutions/1296-divide-array-in-sets-of-k-consecutive-numbers.js)|Medium| -1297|[Maximum Number of Occurrences of a Substring](./solutions/1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| -1298|[Maximum Candies You Can Get from Boxes](./solutions/1298-maximum-candies-you-can-get-from-boxes.js)|Hard| -1299|[Replace Elements with Greatest Element on Right Side](./solutions/1299-replace-elements-with-greatest-element-on-right-side.js)|Easy| -1300|[Sum of Mutated Array Closest to Target](./solutions/1300-sum-of-mutated-array-closest-to-target.js)|Medium| -1301|[Number of Paths with Max Score](./solutions/1301-number-of-paths-with-max-score.js)|Hard| -1302|[Deepest Leaves Sum](./solutions/1302-deepest-leaves-sum.js)|Medium| -1304|[Find N Unique Integers Sum up to Zero](./solutions/1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| -1305|[All Elements in Two Binary Search Trees](./solutions/1305-all-elements-in-two-binary-search-trees.js)|Medium| -1306|[Jump Game III](./solutions/1306-jump-game-iii.js)|Medium| -1307|[Verbal Arithmetic Puzzle](./solutions/1307-verbal-arithmetic-puzzle.js)|Hard| -1309|[Decrypt String from Alphabet to Integer Mapping](./solutions/1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| -1310|[XOR Queries of a Subarray](./solutions/1310-xor-queries-of-a-subarray.js)|Medium| -1311|[Get Watched Videos by Your Friends](./solutions/1311-get-watched-videos-by-your-friends.js)|Medium| -1312|[Minimum Insertion Steps to Make a String Palindrome](./solutions/1312-minimum-insertion-steps-to-make-a-string-palindrome.js)|Hard| -1313|[Decompress Run-Length Encoded List](./solutions/1313-decompress-run-length-encoded-list.js)|Easy| -1314|[Matrix Block Sum](./solutions/1314-matrix-block-sum.js)|Medium| -1315|[Sum of Nodes with Even-Valued Grandparent](./solutions/1315-sum-of-nodes-with-even-valued-grandparent.js)|Medium| -1316|[Distinct Echo Substrings](./solutions/1316-distinct-echo-substrings.js)|Hard| -1317|[Convert Integer to the Sum of Two No-Zero Integers](./solutions/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| -1318|[Minimum Flips to Make a OR b Equal to c](./solutions/1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| -1319|[Number of Operations to Make Network Connected](./solutions/1319-number-of-operations-to-make-network-connected.js)|Medium| -1320|[Minimum Distance to Type a Word Using Two Fingers](./solutions/1320-minimum-distance-to-type-a-word-using-two-fingers.js)|Hard| -1323|[Maximum 69 Number](./solutions/1323-maximum-69-number.js)|Easy| -1324|[Print Words Vertically](./solutions/1324-print-words-vertically.js)|Medium| -1325|[Delete Leaves With a Given Value](./solutions/1325-delete-leaves-with-a-given-value.js)|Medium| -1326|[Minimum Number of Taps to Open to Water a Garden](./solutions/1326-minimum-number-of-taps-to-open-to-water-a-garden.js)|Hard| -1328|[Break a Palindrome](./solutions/1328-break-a-palindrome.js)|Medium| -1329|[Sort the Matrix Diagonally](./solutions/1329-sort-the-matrix-diagonally.js)|Medium| -1330|[Reverse Subarray To Maximize Array Value](./solutions/1330-reverse-subarray-to-maximize-array-value.js)|Hard| -1331|[Rank Transform of an Array](./solutions/1331-rank-transform-of-an-array.js)|Easy| -1332|[Remove Palindromic Subsequences](./solutions/1332-remove-palindromic-subsequences.js)|Easy| -1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./solutions/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| -1334|[Find the City With the Smallest Number of Neighbors at a Threshold Distance](./solutions/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.js)|Medium| -1335|[Minimum Difficulty of a Job Schedule](./solutions/1335-minimum-difficulty-of-a-job-schedule.js)|Hard| -1337|[The K Weakest Rows in a Matrix](./solutions/1337-the-k-weakest-rows-in-a-matrix.js)|Easy| -1338|[Reduce Array Size to The Half](./solutions/1338-reduce-array-size-to-the-half.js)|Medium| -1339|[Maximum Product of Splitted Binary Tree](./solutions/1339-maximum-product-of-splitted-binary-tree.js)|Medium| -1340|[Jump Game V](./solutions/1340-jump-game-v.js)|Hard| -1342|[Number of Steps to Reduce a Number to Zero](./solutions/1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy| -1343|[Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold](./solutions/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js)|Medium| -1344|[Angle Between Hands of a Clock](./solutions/1344-angle-between-hands-of-a-clock.js)|Medium| -1345|[Jump Game IV](./solutions/1345-jump-game-iv.js)|Hard| -1346|[Check If N and Its Double Exist](./solutions/1346-check-if-n-and-its-double-exist.js)|Easy| -1347|[Minimum Number of Steps to Make Two Strings Anagram](./solutions/1347-minimum-number-of-steps-to-make-two-strings-anagram.js)|Medium| -1348|[Tweet Counts Per Frequency](./solutions/1348-tweet-counts-per-frequency.js)|Medium| -1349|[Maximum Students Taking Exam](./solutions/1349-maximum-students-taking-exam.js)|Hard| -1351|[Count Negative Numbers in a Sorted Matrix](./solutions/1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| -1352|[Product of the Last K Numbers](./solutions/1352-product-of-the-last-k-numbers.js)|Medium| -1353|[Maximum Number of Events That Can Be Attended](./solutions/1353-maximum-number-of-events-that-can-be-attended.js)|Medium| -1354|[Construct Target Array With Multiple Sums](./solutions/1354-construct-target-array-with-multiple-sums.js)|Hard| -1356|[Sort Integers by The Number of 1 Bits](./solutions/1356-sort-integers-by-the-number-of-1-bits.js)|Easy| -1357|[Apply Discount Every n Orders](./solutions/1357-apply-discount-every-n-orders.js)|Medium| -1358|[Number of Substrings Containing All Three Characters](./solutions/1358-number-of-substrings-containing-all-three-characters.js)|Medium| -1359|[Count All Valid Pickup and Delivery Options](./solutions/1359-count-all-valid-pickup-and-delivery-options.js)|Hard| -1360|[Number of Days Between Two Dates](./solutions/1360-number-of-days-between-two-dates.js)|Easy| -1361|[Validate Binary Tree Nodes](./solutions/1361-validate-binary-tree-nodes.js)|Medium| -1362|[Closest Divisors](./solutions/1362-closest-divisors.js)|Medium| -1363|[Largest Multiple of Three](./solutions/1363-largest-multiple-of-three.js)|Hard| -1365|[How Many Numbers Are Smaller Than the Current Number](./solutions/1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| -1366|[Rank Teams by Votes](./solutions/1366-rank-teams-by-votes.js)|Medium| -1367|[Linked List in Binary Tree](./solutions/1367-linked-list-in-binary-tree.js)|Medium| -1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./solutions/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard| -1370|[Increasing Decreasing String](./solutions/1370-increasing-decreasing-string.js)|Easy| -1371|[Find the Longest Substring Containing Vowels in Even Counts](./solutions/1371-find-the-longest-substring-containing-vowels-in-even-counts.js)|Medium| -1372|[Longest ZigZag Path in a Binary Tree](./solutions/1372-longest-zigzag-path-in-a-binary-tree.js)|Medium| -1373|[Maximum Sum BST in Binary Tree](./solutions/1373-maximum-sum-bst-in-binary-tree.js)|Hard| -1374|[Generate a String With Characters That Have Odd Counts](./solutions/1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| -1375|[Number of Times Binary String Is Prefix-Aligned](./solutions/1375-number-of-times-binary-string-is-prefix-aligned.js)|Medium| -1376|[Time Needed to Inform All Employees](./solutions/1376-time-needed-to-inform-all-employees.js)|Medium| -1377|[Frog Position After T Seconds](./solutions/1377-frog-position-after-t-seconds.js)|Hard| -1379|[Find a Corresponding Node of a Binary Tree in a Clone of That Tree](./solutions/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.js)|Easy| -1380|[Lucky Numbers in a Matrix](./solutions/1380-lucky-numbers-in-a-matrix.js)|Easy| -1381|[Design a Stack With Increment Operation](./solutions/1381-design-a-stack-with-increment-operation.js)|Medium| -1382|[Balance a Binary Search Tree](./solutions/1382-balance-a-binary-search-tree.js)|Medium| -1383|[Maximum Performance of a Team](./solutions/1383-maximum-performance-of-a-team.js)|Hard| -1385|[Find the Distance Value Between Two Arrays](./solutions/1385-find-the-distance-value-between-two-arrays.js)|Easy| -1386|[Cinema Seat Allocation](./solutions/1386-cinema-seat-allocation.js)|Medium| -1387|[Sort Integers by The Power Value](./solutions/1387-sort-integers-by-the-power-value.js)|Medium| -1388|[Pizza With 3n Slices](./solutions/1388-pizza-with-3n-slices.js)|Hard| -1389|[Create Target Array in the Given Order](./solutions/1389-create-target-array-in-the-given-order.js)|Easy| -1390|[Four Divisors](./solutions/1390-four-divisors.js)|Medium| -1391|[Check if There is a Valid Path in a Grid](./solutions/1391-check-if-there-is-a-valid-path-in-a-grid.js)|Medium| -1392|[Longest Happy Prefix](./solutions/1392-longest-happy-prefix.js)|Hard| -1394|[Find Lucky Integer in an Array](./solutions/1394-find-lucky-integer-in-an-array.js)|Easy| -1395|[Count Number of Teams](./solutions/1395-count-number-of-teams.js)|Medium| -1396|[Design Underground System](./solutions/1396-design-underground-system.js)|Medium| -1397|[Find All Good Strings](./solutions/1397-find-all-good-strings.js)|Hard| -1399|[Count Largest Group](./solutions/1399-count-largest-group.js)|Easy| -1400|[Construct K Palindrome Strings](./solutions/1400-construct-k-palindrome-strings.js)|Medium| -1401|[Circle and Rectangle Overlapping](./solutions/1401-circle-and-rectangle-overlapping.js)|Medium| -1402|[Reducing Dishes](./solutions/1402-reducing-dishes.js)|Hard| -1403|[Minimum Subsequence in Non-Increasing Order](./solutions/1403-minimum-subsequence-in-non-increasing-order.js)|Easy| -1404|[Number of Steps to Reduce a Number in Binary Representation to One](./solutions/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.js)|Medium| -1405|[Longest Happy String](./solutions/1405-longest-happy-string.js)|Medium| -1406|[Stone Game III](./solutions/1406-stone-game-iii.js)|Hard| -1408|[String Matching in an Array](./solutions/1408-string-matching-in-an-array.js)|Easy| -1409|[Queries on a Permutation With Key](./solutions/1409-queries-on-a-permutation-with-key.js)|Medium| -1410|[HTML Entity Parser](./solutions/1410-html-entity-parser.js)|Medium| -1411|[Number of Ways to Paint N × 3 Grid](./solutions/1411-number-of-ways-to-paint-n-3-grid.js)|Hard| -1413|[Minimum Value to Get Positive Step by Step Sum](./solutions/1413-minimum-value-to-get-positive-step-by-step-sum.js)|Easy| -1414|[Find the Minimum Number of Fibonacci Numbers Whose Sum Is K](./solutions/1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.js)|Medium| -1415|[The k-th Lexicographical String of All Happy Strings of Length n](./solutions/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js)|Medium| -1416|[Restore The Array](./solutions/1416-restore-the-array.js)|Hard| -1417|[Reformat The String](./solutions/1417-reformat-the-string.js)|Easy| -1418|[Display Table of Food Orders in a Restaurant](./solutions/1418-display-table-of-food-orders-in-a-restaurant.js)|Medium| -1419|[Minimum Number of Frogs Croaking](./solutions/1419-minimum-number-of-frogs-croaking.js)|Medium| -1420|[Build Array Where You Can Find The Maximum Exactly K Comparisons](./solutions/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.js)|Hard| -1422|[Maximum Score After Splitting a String](./solutions/1422-maximum-score-after-splitting-a-string.js)|Easy| -1423|[Maximum Points You Can Obtain from Cards](./solutions/1423-maximum-points-you-can-obtain-from-cards.js)|Medium| -1424|[Diagonal Traverse II](./solutions/1424-diagonal-traverse-ii.js)|Medium| -1425|[Constrained Subsequence Sum](./solutions/1425-constrained-subsequence-sum.js)|Hard| -1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy| -1432|[Max Difference You Can Get From Changing an Integer](./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js)|Medium| -1433|[Check If a String Can Break Another String](./solutions/1433-check-if-a-string-can-break-another-string.js)|Medium| -1434|[Number of Ways to Wear Different Hats to Each Other](./solutions/1434-number-of-ways-to-wear-different-hats-to-each-other.js)|Hard| -1436|[Destination City](./solutions/1436-destination-city.js)|Easy| -1437|[Check If All 1's Are at Least Length K Places Away](./solutions/1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| -1438|[Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](./solutions/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js)|Medium| -1439|[Find the Kth Smallest Sum of a Matrix With Sorted Rows](./solutions/1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.js)|Hard| -1441|[Build an Array With Stack Operations](./solutions/1441-build-an-array-with-stack-operations.js)|Medium| -1442|[Count Triplets That Can Form Two Arrays of Equal XOR](./solutions/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.js)|Medium| -1443|[Minimum Time to Collect All Apples in a Tree](./solutions/1443-minimum-time-to-collect-all-apples-in-a-tree.js)|Medium| -1444|[Number of Ways of Cutting a Pizza](./solutions/1444-number-of-ways-of-cutting-a-pizza.js)|Hard| -1446|[Consecutive Characters](./solutions/1446-consecutive-characters.js)|Easy| -1447|[Simplified Fractions](./solutions/1447-simplified-fractions.js)|Medium| -1448|[Count Good Nodes in Binary Tree](./solutions/1448-count-good-nodes-in-binary-tree.js)|Medium| -1449|[Form Largest Integer With Digits That Add up to Target](./solutions/1449-form-largest-integer-with-digits-that-add-up-to-target.js)|Hard| -1450|[Number of Students Doing Homework at a Given Time](./solutions/1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| -1451|[Rearrange Words in a Sentence](./solutions/1451-rearrange-words-in-a-sentence.js)|Medium| -1452|[People Whose List of Favorite Companies Is Not a Subset of Another List](./solutions/1452-people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list.js)|Medium| -1453|[Maximum Number of Darts Inside of a Circular Dartboard](./solutions/1453-maximum-number-of-darts-inside-of-a-circular-dartboard.js)|Hard| -1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./solutions/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](./solutions/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| -1457|[Pseudo-Palindromic Paths in a Binary Tree](./solutions/1457-pseudo-palindromic-paths-in-a-binary-tree.js)|Medium| -1458|[Max Dot Product of Two Subsequences](./solutions/1458-max-dot-product-of-two-subsequences.js)|Hard| -1460|[Make Two Arrays Equal by Reversing Sub-arrays](./solutions/1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| -1461|[Check If a String Contains All Binary Codes of Size K](./solutions/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js)|Medium| -1462|[Course Schedule IV](./solutions/1462-course-schedule-iv.js)|Medium| -1463|[Cherry Pickup II](./solutions/1463-cherry-pickup-ii.js)|Hard| -1464|[Maximum Product of Two Elements in an Array](./solutions/1464-maximum-product-of-two-elements-in-an-array.js)|Easy| -1465|[Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts](./solutions/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.js)|Medium| -1466|[Reorder Routes to Make All Paths Lead to the City Zero](./solutions/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js)|Medium| -1467|[Probability of a Two Boxes Having The Same Number of Distinct Balls](./solutions/1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls.js)|Hard| -1470|[Shuffle the Array](./solutions/1470-shuffle-the-array.js)|Easy| -1471|[The k Strongest Values in an Array](./solutions/1471-the-k-strongest-values-in-an-array.js)|Medium| -1472|[Design Browser History](./solutions/1472-design-browser-history.js)|Medium| -1473|[Paint House III](./solutions/1473-paint-house-iii.js)|Hard| -1475|[Final Prices With a Special Discount in a Shop](./solutions/1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| -1476|[Subrectangle Queries](./solutions/1476-subrectangle-queries.js)|Medium| -1477|[Find Two Non-overlapping Sub-arrays Each With Target Sum](./solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js)|Medium| -1478|[Allocate Mailboxes](./solutions/1478-allocate-mailboxes.js)|Hard| -1480|[Running Sum of 1d Array](./solutions/1480-running-sum-of-1d-array.js)|Easy| -1481|[Least Number of Unique Integers after K Removals](./solutions/1481-least-number-of-unique-integers-after-k-removals.js)|Medium| -1482|[Minimum Number of Days to Make m Bouquets](./solutions/1482-minimum-number-of-days-to-make-m-bouquets.js)|Medium| -1483|[Kth Ancestor of a Tree Node](./solutions/1483-kth-ancestor-of-a-tree-node.js)|Hard| -1486|[XOR Operation in an Array](./solutions/1486-xor-operation-in-an-array.js)|Easy| -1487|[Making File Names Unique](./solutions/1487-making-file-names-unique.js)|Medium| -1488|[Avoid Flood in The City](./solutions/1488-avoid-flood-in-the-city.js)|Medium| -1489|[Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree](./solutions/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.js)|Hard| -1491|[Average Salary Excluding the Minimum and Maximum Salary](./solutions/1491-average-salary-excluding-the-minimum-and-maximum-salary.js)|Easy| -1492|[The kth Factor of n](./solutions/1492-the-kth-factor-of-n.js)|Medium| -1493|[Longest Subarray of 1's After Deleting One Element](./solutions/1493-longest-subarray-of-1s-after-deleting-one-element.js)|Medium| -1494|[Parallel Courses II](./solutions/1494-parallel-courses-ii.js)|Hard| -1496|[Path Crossing](./solutions/1496-path-crossing.js)|Easy| -1497|[Check If Array Pairs Are Divisible by k](./solutions/1497-check-if-array-pairs-are-divisible-by-k.js)|Medium| -1498|[Number of Subsequences That Satisfy the Given Sum Condition](./solutions/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.js)|Medium| -1499|[Max Value of Equation](./solutions/1499-max-value-of-equation.js)|Hard| -1502|[Can Make Arithmetic Progression From Sequence](./solutions/1502-can-make-arithmetic-progression-from-sequence.js)|Easy| -1503|[Last Moment Before All Ants Fall Out of a Plank](./solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js)|Medium| -1504|[Count Submatrices With All Ones](./solutions/1504-count-submatrices-with-all-ones.js)|Medium| -1505|[Minimum Possible Integer After at Most K Adjacent Swaps On Digits](./solutions/1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js)|Hard| -1507|[Reformat Date](./solutions/1507-reformat-date.js)|Easy| -1508|[Range Sum of Sorted Subarray Sums](./solutions/1508-range-sum-of-sorted-subarray-sums.js)|Medium| -1509|[Minimum Difference Between Largest and Smallest Value in Three Moves](./solutions/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.js)|Medium| -1510|[Stone Game IV](./solutions/1510-stone-game-iv.js)|Hard| -1512|[Number of Good Pairs](./solutions/1512-number-of-good-pairs.js)|Easy| -1513|[Number of Substrings With Only 1s](./solutions/1513-number-of-substrings-with-only-1s.js)|Medium| -1514|[Path with Maximum Probability](./solutions/1514-path-with-maximum-probability.js)|Medium| -1515|[Best Position for a Service Centre](./solutions/1515-best-position-for-a-service-centre.js)|Hard| -1518|[Water Bottles](./solutions/1518-water-bottles.js)|Easy| -1519|[Number of Nodes in the Sub-Tree With the Same Label](./solutions/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium| -1520|[Maximum Number of Non-Overlapping Substrings](./solutions/1520-maximum-number-of-non-overlapping-substrings.js)|Hard| -1521|[Find a Value of a Mysterious Function Closest to Target](./solutions/1521-find-a-value-of-a-mysterious-function-closest-to-target.js)|Hard| -1523|[Count Odd Numbers in an Interval Range](./solutions/1523-count-odd-numbers-in-an-interval-range.js)|Easy| -1524|[Number of Sub-arrays With Odd Sum](./solutions/1524-number-of-sub-arrays-with-odd-sum.js)|Medium| -1525|[Number of Good Ways to Split a String](./solutions/1525-number-of-good-ways-to-split-a-string.js)|Medium| -1526|[Minimum Number of Increments on Subarrays to Form a Target Array](./solutions/1526-minimum-number-of-increments-on-subarrays-to-form-a-target-array.js)|Hard| -1528|[Shuffle String](./solutions/1528-shuffle-string.js)|Easy| -1529|[Minimum Suffix Flips](./solutions/1529-minimum-suffix-flips.js)|Medium| -1530|[Number of Good Leaf Nodes Pairs](./solutions/1530-number-of-good-leaf-nodes-pairs.js)|Medium| -1531|[String Compression II](./solutions/1531-string-compression-ii.js)|Hard| -1534|[Count Good Triplets](./solutions/1534-count-good-triplets.js)|Easy| -1535|[Find the Winner of an Array Game](./solutions/1535-find-the-winner-of-an-array-game.js)|Medium| -1536|[Minimum Swaps to Arrange a Binary Grid](./solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js)|Medium| -1537|[Get the Maximum Score](./solutions/1537-get-the-maximum-score.js)|Hard| -1539|[Kth Missing Positive Number](./solutions/1539-kth-missing-positive-number.js)|Easy| -1540|[Can Convert String in K Moves](./solutions/1540-can-convert-string-in-k-moves.js)|Medium| -1541|[Minimum Insertions to Balance a Parentheses String](./solutions/1541-minimum-insertions-to-balance-a-parentheses-string.js)|Medium| -1542|[Find Longest Awesome Substring](./solutions/1542-find-longest-awesome-substring.js)|Hard| -1544|[Make The String Great](./solutions/1544-make-the-string-great.js)|Easy| -1545|[Find Kth Bit in Nth Binary String](./solutions/1545-find-kth-bit-in-nth-binary-string.js)|Medium| -1546|[Maximum Number of Non-Overlapping Subarrays With Sum Equals Target](./solutions/1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.js)|Medium| -1547|[Minimum Cost to Cut a Stick](./solutions/1547-minimum-cost-to-cut-a-stick.js)|Hard| -1550|[Three Consecutive Odds](./solutions/1550-three-consecutive-odds.js)|Easy| -1551|[Minimum Operations to Make Array Equal](./solutions/1551-minimum-operations-to-make-array-equal.js)|Medium| -1552|[Magnetic Force Between Two Balls](./solutions/1552-magnetic-force-between-two-balls.js)|Medium| -1553|[Minimum Number of Days to Eat N Oranges](./solutions/1553-minimum-number-of-days-to-eat-n-oranges.js)|Hard| -1556|[Thousand Separator](./solutions/1556-thousand-separator.js)|Easy| -1557|[Minimum Number of Vertices to Reach All Nodes](./solutions/1557-minimum-number-of-vertices-to-reach-all-nodes.js)|Medium| -1558|[Minimum Numbers of Function Calls to Make Target Array](./solutions/1558-minimum-numbers-of-function-calls-to-make-target-array.js)|Medium| -1559|[Detect Cycles in 2D Grid](./solutions/1559-detect-cycles-in-2d-grid.js)|Medium| -1560|[Most Visited Sector in a Circular Track](./solutions/1560-most-visited-sector-in-a-circular-track.js)|Easy| -1561|[Maximum Number of Coins You Can Get](./solutions/1561-maximum-number-of-coins-you-can-get.js)|Medium| -1562|[Find Latest Group of Size M](./solutions/1562-find-latest-group-of-size-m.js)|Medium| -1563|[Stone Game V](./solutions/1563-stone-game-v.js)|Hard| -1566|[Detect Pattern of Length M Repeated K or More Times](./solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| -1567|[Maximum Length of Subarray With Positive Product](./solutions/1567-maximum-length-of-subarray-with-positive-product.js)|Medium| -1568|[Minimum Number of Days to Disconnect Island](./solutions/1568-minimum-number-of-days-to-disconnect-island.js)|Hard| -1569|[Number of Ways to Reorder Array to Get Same BST](./solutions/1569-number-of-ways-to-reorder-array-to-get-same-bst.js)|Hard| -1572|[Matrix Diagonal Sum](./solutions/1572-matrix-diagonal-sum.js)|Easy| -1573|[Number of Ways to Split a String](./solutions/1573-number-of-ways-to-split-a-string.js)|Medium| -1574|[Shortest Subarray to be Removed to Make Array Sorted](./solutions/1574-shortest-subarray-to-be-removed-to-make-array-sorted.js)|Medium| -1575|[Count All Possible Routes](./solutions/1575-count-all-possible-routes.js)|Hard| -1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./solutions/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium| -1577|[Number of Ways Where Square of Number Is Equal to Product of Two Numbers](./solutions/1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.js)|Medium| -1578|[Minimum Time to Make Rope Colorful](./solutions/1578-minimum-time-to-make-rope-colorful.js)|Medium| -1579|[Remove Max Number of Edges to Keep Graph Fully Traversable](./solutions/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js)|Hard| -1582|[Special Positions in a Binary Matrix](./solutions/1582-special-positions-in-a-binary-matrix.js)|Easy| -1583|[Count Unhappy Friends](./solutions/1583-count-unhappy-friends.js)|Medium| -1584|[Min Cost to Connect All Points](./solutions/1584-min-cost-to-connect-all-points.js)|Medium| -1585|[Check If String Is Transformable With Substring Sort Operations](./solutions/1585-check-if-string-is-transformable-with-substring-sort-operations.js)|Hard| -1588|[Sum of All Odd Length Subarrays](./solutions/1588-sum-of-all-odd-length-subarrays.js)|Easy| -1589|[Maximum Sum Obtained of Any Permutation](./solutions/1589-maximum-sum-obtained-of-any-permutation.js)|Medium| -1590|[Make Sum Divisible by P](./solutions/1590-make-sum-divisible-by-p.js)|Medium| -1591|[Strange Printer II](./solutions/1591-strange-printer-ii.js)|Hard| -1592|[Rearrange Spaces Between Words](./solutions/1592-rearrange-spaces-between-words.js)|Easy| -1593|[Split a String Into the Max Number of Unique Substrings](./solutions/1593-split-a-string-into-the-max-number-of-unique-substrings.js)|Medium| -1594|[Maximum Non Negative Product in a Matrix](./solutions/1594-maximum-non-negative-product-in-a-matrix.js)|Medium| -1595|[Minimum Cost to Connect Two Groups of Points](./solutions/1595-minimum-cost-to-connect-two-groups-of-points.js)|Hard| -1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy| -1599|[Maximum Profit of Operating a Centennial Wheel](./solutions/1599-maximum-profit-of-operating-a-centennial-wheel.js)|Medium| -1600|[Throne Inheritance](./solutions/1600-throne-inheritance.js)|Medium| -1601|[Maximum Number of Achievable Transfer Requests](./solutions/1601-maximum-number-of-achievable-transfer-requests.js)|Hard| -1603|[Design Parking System](./solutions/1603-design-parking-system.js)|Easy| -1604|[Alert Using Same Key-Card Three or More Times in a One Hour Period](./solutions/1604-alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.js)|Medium| -1605|[Find Valid Matrix Given Row and Column Sums](./solutions/1605-find-valid-matrix-given-row-and-column-sums.js)|Medium| -1606|[Find Servers That Handled Most Number of Requests](./solutions/1606-find-servers-that-handled-most-number-of-requests.js)|Hard| -1608|[Special Array With X Elements Greater Than or Equal X](./solutions/1608-special-array-with-x-elements-greater-than-or-equal-x.js)|Easy| -1609|[Even Odd Tree](./solutions/1609-even-odd-tree.js)|Medium| -1610|[Maximum Number of Visible Points](./solutions/1610-maximum-number-of-visible-points.js)|Hard| -1611|[Minimum One Bit Operations to Make Integers Zero](./solutions/1611-minimum-one-bit-operations-to-make-integers-zero.js)|Hard| -1614|[Maximum Nesting Depth of the Parentheses](./solutions/1614-maximum-nesting-depth-of-the-parentheses.js)|Easy| -1615|[Maximal Network Rank](./solutions/1615-maximal-network-rank.js)|Medium| -1616|[Split Two Strings to Make Palindrome](./solutions/1616-split-two-strings-to-make-palindrome.js)|Medium| -1617|[Count Subtrees With Max Distance Between Cities](./solutions/1617-count-subtrees-with-max-distance-between-cities.js)|Hard| -1619|[Mean of Array After Removing Some Elements](./solutions/1619-mean-of-array-after-removing-some-elements.js)|Easy| -1620|[Coordinate With Maximum Network Quality](./solutions/1620-coordinate-with-maximum-network-quality.js)|Medium| -1621|[Number of Sets of K Non-Overlapping Line Segments](./solutions/1621-number-of-sets-of-k-non-overlapping-line-segments.js)|Medium| -1622|[Fancy Sequence](./solutions/1622-fancy-sequence.js)|Hard| -1624|[Largest Substring Between Two Equal Characters](./solutions/1624-largest-substring-between-two-equal-characters.js)|Easy| -1625|[Lexicographically Smallest String After Applying Operations](./solutions/1625-lexicographically-smallest-string-after-applying-operations.js)|Medium| -1626|[Best Team With No Conflicts](./solutions/1626-best-team-with-no-conflicts.js)|Medium| -1627|[Graph Connectivity With Threshold](./solutions/1627-graph-connectivity-with-threshold.js)|Hard| -1629|[Slowest Key](./solutions/1629-slowest-key.js)|Easy| -1630|[Arithmetic Subarrays](./solutions/1630-arithmetic-subarrays.js)|Medium| -1631|[Path With Minimum Effort](./solutions/1631-path-with-minimum-effort.js)|Medium| -1632|[Rank Transform of a Matrix](./solutions/1632-rank-transform-of-a-matrix.js)|Hard| -1636|[Sort Array by Increasing Frequency](./solutions/1636-sort-array-by-increasing-frequency.js)|Easy| -1637|[Widest Vertical Area Between Two Points Containing No Points](./solutions/1637-widest-vertical-area-between-two-points-containing-no-points.js)|Easy| -1638|[Count Substrings That Differ by One Character](./solutions/1638-count-substrings-that-differ-by-one-character.js)|Medium| -1639|[Number of Ways to Form a Target String Given a Dictionary](./solutions/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.js)|Hard| -1640|[Check Array Formation Through Concatenation](./solutions/1640-check-array-formation-through-concatenation.js)|Easy| -1641|[Count Sorted Vowel Strings](./solutions/1641-count-sorted-vowel-strings.js)|Medium| -1642|[Furthest Building You Can Reach](./solutions/1642-furthest-building-you-can-reach.js)|Medium| -1643|[Kth Smallest Instructions](./solutions/1643-kth-smallest-instructions.js)|Hard| -1646|[Get Maximum in Generated Array](./solutions/1646-get-maximum-in-generated-array.js)|Easy| -1647|[Minimum Deletions to Make Character Frequencies Unique](./solutions/1647-minimum-deletions-to-make-character-frequencies-unique.js)|Medium| -1648|[Sell Diminishing-Valued Colored Balls](./solutions/1648-sell-diminishing-valued-colored-balls.js)|Medium| -1649|[Create Sorted Array through Instructions](./solutions/1649-create-sorted-array-through-instructions.js)|Hard| -1652|[Defuse the Bomb](./solutions/1652-defuse-the-bomb.js)|Easy| -1653|[Minimum Deletions to Make String Balanced](./solutions/1653-minimum-deletions-to-make-string-balanced.js)|Medium| -1654|[Minimum Jumps to Reach Home](./solutions/1654-minimum-jumps-to-reach-home.js)|Medium| -1655|[Distribute Repeating Integers](./solutions/1655-distribute-repeating-integers.js)|Hard| -1656|[Design an Ordered Stream](./solutions/1656-design-an-ordered-stream.js)|Easy| -1657|[Determine if Two Strings Are Close](./solutions/1657-determine-if-two-strings-are-close.js)|Medium| -1658|[Minimum Operations to Reduce X to Zero](./solutions/1658-minimum-operations-to-reduce-x-to-zero.js)|Medium| -1659|[Maximize Grid Happiness](./solutions/1659-maximize-grid-happiness.js)|Hard| -1662|[Check If Two String Arrays are Equivalent](./solutions/1662-check-if-two-string-arrays-are-equivalent.js)|Easy| -1663|[Smallest String With A Given Numeric Value](./solutions/1663-smallest-string-with-a-given-numeric-value.js)|Medium| -1664|[Ways to Make a Fair Array](./solutions/1664-ways-to-make-a-fair-array.js)|Medium| -1665|[Minimum Initial Energy to Finish Tasks](./solutions/1665-minimum-initial-energy-to-finish-tasks.js)|Hard| -1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy| -1669|[Merge In Between Linked Lists](./solutions/1669-merge-in-between-linked-lists.js)|Medium| -1670|[Design Front Middle Back Queue](./solutions/1670-design-front-middle-back-queue.js)|Medium| -1671|[Minimum Number of Removals to Make Mountain Array](./solutions/1671-minimum-number-of-removals-to-make-mountain-array.js)|Hard| -1672|[Richest Customer Wealth](./solutions/1672-richest-customer-wealth.js)|Easy| -1673|[Find the Most Competitive Subsequence](./solutions/1673-find-the-most-competitive-subsequence.js)|Medium| -1674|[Minimum Moves to Make Array Complementary](./solutions/1674-minimum-moves-to-make-array-complementary.js)|Medium| -1675|[Minimize Deviation in Array](./solutions/1675-minimize-deviation-in-array.js)|Hard| -1678|[Goal Parser Interpretation](./solutions/1678-goal-parser-interpretation.js)|Easy| -1679|[Max Number of K-Sum Pairs](./solutions/1679-max-number-of-k-sum-pairs.js)|Medium| -1680|[Concatenation of Consecutive Binary Numbers](./solutions/1680-concatenation-of-consecutive-binary-numbers.js)|Medium| -1681|[Minimum Incompatibility](./solutions/1681-minimum-incompatibility.js)|Hard| -1684|[Count the Number of Consistent Strings](./solutions/1684-count-the-number-of-consistent-strings.js)|Easy| -1685|[Sum of Absolute Differences in a Sorted Array](./solutions/1685-sum-of-absolute-differences-in-a-sorted-array.js)|Medium| -1686|[Stone Game VI](./solutions/1686-stone-game-vi.js)|Medium| -1687|[Delivering Boxes from Storage to Ports](./solutions/1687-delivering-boxes-from-storage-to-ports.js)|Hard| -1688|[Count of Matches in Tournament](./solutions/1688-count-of-matches-in-tournament.js)|Easy| -1689|[Partitioning Into Minimum Number Of Deci-Binary Numbers](./solutions/1689-partitioning-into-minimum-number-of-deci-binary-numbers.js)|Medium| -1690|[Stone Game VII](./solutions/1690-stone-game-vii.js)|Medium| -1691|[Maximum Height by Stacking Cuboids](./solutions/1691-maximum-height-by-stacking-cuboids.js)|Hard| -1694|[Reformat Phone Number](./solutions/1694-reformat-phone-number.js)|Easy| -1695|[Maximum Erasure Value](./solutions/1695-maximum-erasure-value.js)|Medium| -1696|[Jump Game VI](./solutions/1696-jump-game-vi.js)|Medium| -1697|[Checking Existence of Edge Length Limited Paths](./solutions/1697-checking-existence-of-edge-length-limited-paths.js)|Hard| -1700|[Number of Students Unable to Eat Lunch](./solutions/1700-number-of-students-unable-to-eat-lunch.js)|Easy| -1701|[Average Waiting Time](./solutions/1701-average-waiting-time.js)|Medium| -1702|[Maximum Binary String After Change](./solutions/1702-maximum-binary-string-after-change.js)|Medium| -1703|[Minimum Adjacent Swaps for K Consecutive Ones](./solutions/1703-minimum-adjacent-swaps-for-k-consecutive-ones.js)|Hard| -1704|[Determine if String Halves Are Alike](./solutions/1704-determine-if-string-halves-are-alike.js)|Easy| -1705|[Maximum Number of Eaten Apples](./solutions/1705-maximum-number-of-eaten-apples.js)|Medium| -1706|[Where Will the Ball Fall](./solutions/1706-where-will-the-ball-fall.js)|Medium| -1707|[Maximum XOR With an Element From Array](./solutions/1707-maximum-xor-with-an-element-from-array.js)|Hard| -1710|[Maximum Units on a Truck](./solutions/1710-maximum-units-on-a-truck.js)|Easy| -1711|[Count Good Meals](./solutions/1711-count-good-meals.js)|Medium| -1712|[Ways to Split Array Into Three Subarrays](./solutions/1712-ways-to-split-array-into-three-subarrays.js)|Medium| -1713|[Minimum Operations to Make a Subsequence](./solutions/1713-minimum-operations-to-make-a-subsequence.js)|Hard| -1716|[Calculate Money in Leetcode Bank](./solutions/1716-calculate-money-in-leetcode-bank.js)|Easy| -1717|[Maximum Score From Removing Substrings](./solutions/1717-maximum-score-from-removing-substrings.js)|Medium| -1718|[Construct the Lexicographically Largest Valid Sequence](./solutions/1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium| -1719|[Number Of Ways To Reconstruct A Tree](./solutions/1719-number-of-ways-to-reconstruct-a-tree.js)|Hard| -1720|[Decode XORed Array](./solutions/1720-decode-xored-array.js)|Easy| -1721|[Swapping Nodes in a Linked List](./solutions/1721-swapping-nodes-in-a-linked-list.js)|Medium| -1722|[Minimize Hamming Distance After Swap Operations](./solutions/1722-minimize-hamming-distance-after-swap-operations.js)|Medium| -1723|[Find Minimum Time to Finish All Jobs](./solutions/1723-find-minimum-time-to-finish-all-jobs.js)|Hard| -1725|[Number Of Rectangles That Can Form The Largest Square](./solutions/1725-number-of-rectangles-that-can-form-the-largest-square.js)|Easy| -1726|[Tuple with Same Product](./solutions/1726-tuple-with-same-product.js)|Medium| -1727|[Largest Submatrix With Rearrangements](./solutions/1727-largest-submatrix-with-rearrangements.js)|Medium| -1728|[Cat and Mouse II](./solutions/1728-cat-and-mouse-ii.js)|Hard| -1732|[Find the Highest Altitude](./solutions/1732-find-the-highest-altitude.js)|Easy| -1733|[Minimum Number of People to Teach](./solutions/1733-minimum-number-of-people-to-teach.js)|Medium| -1734|[Decode XORed Permutation](./solutions/1734-decode-xored-permutation.js)|Medium| -1735|[Count Ways to Make Array With Product](./solutions/1735-count-ways-to-make-array-with-product.js)|Hard| -1736|[Latest Time by Replacing Hidden Digits](./solutions/1736-latest-time-by-replacing-hidden-digits.js)|Easy| -1737|[Change Minimum Characters to Satisfy One of Three Conditions](./solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js)|Medium| -1738|[Find Kth Largest XOR Coordinate Value](./solutions/1738-find-kth-largest-xor-coordinate-value.js)|Medium| -1739|[Building Boxes](./solutions/1739-building-boxes.js)|Hard| -1742|[Maximum Number of Balls in a Box](./solutions/1742-maximum-number-of-balls-in-a-box.js)|Easy| -1743|[Restore the Array From Adjacent Pairs](./solutions/1743-restore-the-array-from-adjacent-pairs.js)|Medium| -1744|[Can You Eat Your Favorite Candy on Your Favorite Day?](./solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js)|Medium| -1745|[Palindrome Partitioning IV](./solutions/1745-palindrome-partitioning-iv.js)|Hard| -1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| -1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| -1750|[Minimum Length of String After Deleting Similar Ends](./solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js)|Medium| -1751|[Maximum Number of Events That Can Be Attended II](./solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js)|Hard| -1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| -1753|[Maximum Score From Removing Stones](./solutions/1753-maximum-score-from-removing-stones.js)|Medium| -1754|[Largest Merge Of Two Strings](./solutions/1754-largest-merge-of-two-strings.js)|Medium| -1755|[Closest Subsequence Sum](./solutions/1755-closest-subsequence-sum.js)|Hard| -1758|[Minimum Changes To Make Alternating Binary String](./solutions/1758-minimum-changes-to-make-alternating-binary-string.js)|Easy| -1759|[Count Number of Homogenous Substrings](./solutions/1759-count-number-of-homogenous-substrings.js)|Medium| -1760|[Minimum Limit of Balls in a Bag](./solutions/1760-minimum-limit-of-balls-in-a-bag.js)|Medium| -1761|[Minimum Degree of a Connected Trio in a Graph](./solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js)|Hard| -1763|[Longest Nice Substring](./solutions/1763-longest-nice-substring.js)|Easy| -1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| -1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| -1766|[Tree of Coprimes](./solutions/1766-tree-of-coprimes.js)|Hard| -1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| -1769|[Minimum Number of Operations to Move All Balls to Each Box](./solutions/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js)|Medium| -1770|[Maximum Score from Performing Multiplication Operations](./solutions/1770-maximum-score-from-performing-multiplication-operations.js)|Hard| -1771|[Maximize Palindrome Length From Subsequences](./solutions/1771-maximize-palindrome-length-from-subsequences.js)|Hard| -1773|[Count Items Matching a Rule](./solutions/1773-count-items-matching-a-rule.js)|Easy| -1774|[Closest Dessert Cost](./solutions/1774-closest-dessert-cost.js)|Medium| -1775|[Equal Sum Arrays With Minimum Number of Operations](./solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js)|Medium| -1776|[Car Fleet II](./solutions/1776-car-fleet-ii.js)|Hard| -1779|[Find Nearest Point That Has the Same X or Y Coordinate](./solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js)|Easy| -1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| -1781|[Sum of Beauty of All Substrings](./solutions/1781-sum-of-beauty-of-all-substrings.js)|Medium| -1782|[Count Pairs Of Nodes](./solutions/1782-count-pairs-of-nodes.js)|Hard| -1784|[Check if Binary String Has at Most One Segment of Ones](./solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js)|Easy| -1785|[Minimum Elements to Add to Form a Given Sum](./solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js)|Medium| -1786|[Number of Restricted Paths From First to Last Node](./solutions/1786-number-of-restricted-paths-from-first-to-last-node.js)|Medium| -1787|[Make the XOR of All Segments Equal to Zero](./solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js)|Hard| -1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| -1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| -1792|[Maximum Average Pass Ratio](./solutions/1792-maximum-average-pass-ratio.js)|Medium| -1793|[Maximum Score of a Good Subarray](./solutions/1793-maximum-score-of-a-good-subarray.js)|Hard| -1796|[Second Largest Digit in a String](./solutions/1796-second-largest-digit-in-a-string.js)|Easy| -1797|[Design Authentication Manager](./solutions/1797-design-authentication-manager.js)|Medium| -1798|[Maximum Number of Consecutive Values You Can Make](./solutions/1798-maximum-number-of-consecutive-values-you-can-make.js)|Medium| -1799|[Maximize Score After N Operations](./solutions/1799-maximize-score-after-n-operations.js)|Hard| -1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| -1801|[Number of Orders in the Backlog](./solutions/1801-number-of-orders-in-the-backlog.js)|Medium| -1802|[Maximum Value at a Given Index in a Bounded Array](./solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js)|Medium| -1803|[Count Pairs With XOR in a Range](./solutions/1803-count-pairs-with-xor-in-a-range.js)|Hard| -1805|[Number of Different Integers in a String](./solutions/1805-number-of-different-integers-in-a-string.js)|Easy| -1806|[Minimum Number of Operations to Reinitialize a Permutation](./solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js)|Medium| -1807|[Evaluate the Bracket Pairs of a String](./solutions/1807-evaluate-the-bracket-pairs-of-a-string.js)|Medium| -1808|[Maximize Number of Nice Divisors](./solutions/1808-maximize-number-of-nice-divisors.js)|Hard| -1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| -1813|[Sentence Similarity III](./solutions/1813-sentence-similarity-iii.js)|Medium| -1814|[Count Nice Pairs in an Array](./solutions/1814-count-nice-pairs-in-an-array.js)|Medium| -1815|[Maximum Number of Groups Getting Fresh Donuts](./solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js)|Hard| -1816|[Truncate Sentence](./solutions/1816-truncate-sentence.js)|Easy| -1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| -1818|[Minimum Absolute Sum Difference](./solutions/1818-minimum-absolute-sum-difference.js)|Medium| -1819|[Number of Different Subsequences GCDs](./solutions/1819-number-of-different-subsequences-gcds.js)|Hard| -1822|[Sign of the Product of an Array](./solutions/1822-sign-of-the-product-of-an-array.js)|Easy| -1823|[Find the Winner of the Circular Game](./solutions/1823-find-the-winner-of-the-circular-game.js)|Medium| -1824|[Minimum Sideway Jumps](./solutions/1824-minimum-sideway-jumps.js)|Medium| -1825|[Finding MK Average](./solutions/1825-finding-mk-average.js)|Hard| -1827|[Minimum Operations to Make the Array Increasing](./solutions/1827-minimum-operations-to-make-the-array-increasing.js)|Easy| -1828|[Queries on Number of Points Inside a Circle](./solutions/1828-queries-on-number-of-points-inside-a-circle.js)|Medium| -1829|[Maximum XOR for Each Query](./solutions/1829-maximum-xor-for-each-query.js)|Medium| -1830|[Minimum Number of Operations to Make String Sorted](./solutions/1830-minimum-number-of-operations-to-make-string-sorted.js)|Hard| -1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| -1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| -1834|[Single-Threaded CPU](./solutions/1834-single-threaded-cpu.js)|Medium| -1835|[Find XOR Sum of All Pairs Bitwise AND](./solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js)|Hard| -1837|[Sum of Digits in Base K](./solutions/1837-sum-of-digits-in-base-k.js)|Easy| -1838|[Frequency of the Most Frequent Element](./solutions/1838-frequency-of-the-most-frequent-element.js)|Medium| -1839|[Longest Substring Of All Vowels in Order](./solutions/1839-longest-substring-of-all-vowels-in-order.js)|Medium| -1840|[Maximum Building Height](./solutions/1840-maximum-building-height.js)|Hard| -1844|[Replace All Digits with Characters](./solutions/1844-replace-all-digits-with-characters.js)|Easy| -1845|[Seat Reservation Manager](./solutions/1845-seat-reservation-manager.js)|Medium| -1846|[Maximum Element After Decreasing and Rearranging](./solutions/1846-maximum-element-after-decreasing-and-rearranging.js)|Medium| -1847|[Closest Room](./solutions/1847-closest-room.js)|Hard| -1848|[Minimum Distance to the Target Element](./solutions/1848-minimum-distance-to-the-target-element.js)|Easy| -1849|[Splitting a String Into Descending Consecutive Values](./solutions/1849-splitting-a-string-into-descending-consecutive-values.js)|Medium| -1850|[Minimum Adjacent Swaps to Reach the Kth Smallest Number](./solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js)|Medium| -1851|[Minimum Interval to Include Each Query](./solutions/1851-minimum-interval-to-include-each-query.js)|Hard| -1854|[Maximum Population Year](./solutions/1854-maximum-population-year.js)|Easy| -1855|[Maximum Distance Between a Pair of Values](./solutions/1855-maximum-distance-between-a-pair-of-values.js)|Medium| -1856|[Maximum Subarray Min-Product](./solutions/1856-maximum-subarray-min-product.js)|Medium| -1857|[Largest Color Value in a Directed Graph](./solutions/1857-largest-color-value-in-a-directed-graph.js)|Hard| -1859|[Sorting the Sentence](./solutions/1859-sorting-the-sentence.js)|Easy| -1860|[Incremental Memory Leak](./solutions/1860-incremental-memory-leak.js)|Medium| -1861|[Rotating the Box](./solutions/1861-rotating-the-box.js)|Medium| -1862|[Sum of Floored Pairs](./solutions/1862-sum-of-floored-pairs.js)|Hard| -1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| -1864|[Minimum Number of Swaps to Make the Binary String Alternating](./solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js)|Medium| -1865|[Finding Pairs With a Certain Sum](./solutions/1865-finding-pairs-with-a-certain-sum.js)|Medium| -1866|[Number of Ways to Rearrange Sticks With K Sticks Visible](./solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js)|Hard| -1869|[Longer Contiguous Segments of Ones than Zeros](./solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js)|Easy| -1870|[Minimum Speed to Arrive on Time](./solutions/1870-minimum-speed-to-arrive-on-time.js)|Medium| -1871|[Jump Game VII](./solutions/1871-jump-game-vii.js)|Medium| -1872|[Stone Game VIII](./solutions/1872-stone-game-viii.js)|Hard| -1876|[Substrings of Size Three with Distinct Characters](./solutions/1876-substrings-of-size-three-with-distinct-characters.js)|Easy| -1877|[Minimize Maximum Pair Sum in Array](./solutions/1877-minimize-maximum-pair-sum-in-array.js)|Medium| -1878|[Get Biggest Three Rhombus Sums in a Grid](./solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js)|Medium| -1879|[Minimum XOR Sum of Two Arrays](./solutions/1879-minimum-xor-sum-of-two-arrays.js)|Hard| -1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| -1881|[Maximum Value after Insertion](./solutions/1881-maximum-value-after-insertion.js)|Medium| -1882|[Process Tasks Using Servers](./solutions/1882-process-tasks-using-servers.js)|Medium| -1883|[Minimum Skips to Arrive at Meeting On Time](./solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js)|Hard| -1884|[Egg Drop With 2 Eggs and N Floors](./solutions/1884-egg-drop-with-2-eggs-and-n-floors.js)|Medium| -1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| -1887|[Reduction Operations to Make the Array Elements Equal](./solutions/1887-reduction-operations-to-make-the-array-elements-equal.js)|Medium| -1888|[Minimum Number of Flips to Make the Binary String Alternating](./solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)|Medium| -1889|[Minimum Space Wasted From Packaging](./solutions/1889-minimum-space-wasted-from-packaging.js)|Hard| -1893|[Check if All the Integers in a Range Are Covered](./solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js)|Easy| -1894|[Find the Student that Will Replace the Chalk](./solutions/1894-find-the-student-that-will-replace-the-chalk.js)|Medium| -1895|[Largest Magic Square](./solutions/1895-largest-magic-square.js)|Medium| -1896|[Minimum Cost to Change the Final Value of Expression](./solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js)|Hard| -1897|[Redistribute Characters to Make All Strings Equal](./solutions/1897-redistribute-characters-to-make-all-strings-equal.js)|Easy| -1898|[Maximum Number of Removable Characters](./solutions/1898-maximum-number-of-removable-characters.js)|Medium| -1899|[Merge Triplets to Form Target Triplet](./solutions/1899-merge-triplets-to-form-target-triplet.js)|Medium| -1900|[The Earliest and Latest Rounds Where Players Compete](./solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js)|Hard| -1901|[Find a Peak Element II](./solutions/1901-find-a-peak-element-ii.js)|Medium| -1903|[Largest Odd Number in String](./solutions/1903-largest-odd-number-in-string.js)|Easy| -1904|[The Number of Full Rounds You Have Played](./solutions/1904-the-number-of-full-rounds-you-have-played.js)|Medium| -1905|[Count Sub Islands](./solutions/1905-count-sub-islands.js)|Medium| -1906|[Minimum Absolute Difference Queries](./solutions/1906-minimum-absolute-difference-queries.js)|Medium| -1909|[Remove One Element to Make the Array Strictly Increasing](./solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js)|Easy| -1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| -1911|[Maximum Alternating Subsequence Sum](./solutions/1911-maximum-alternating-subsequence-sum.js)|Medium| -1912|[Design Movie Rental System](./solutions/1912-design-movie-rental-system.js)|Hard| -1913|[Maximum Product Difference Between Two Pairs](./solutions/1913-maximum-product-difference-between-two-pairs.js)|Easy| -1914|[Cyclically Rotating a Grid](./solutions/1914-cyclically-rotating-a-grid.js)|Medium| -1915|[Number of Wonderful Substrings](./solutions/1915-number-of-wonderful-substrings.js)|Medium| -1916|[Count Ways to Build Rooms in an Ant Colony](./solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js)|Hard| -1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| -1921|[Eliminate Maximum Number of Monsters](./solutions/1921-eliminate-maximum-number-of-monsters.js)|Medium| -1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| -1923|[Longest Common Subpath](./solutions/1923-longest-common-subpath.js)|Hard| -1925|[Count Square Sum Triples](./solutions/1925-count-square-sum-triples.js)|Easy| -1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| -1927|[Sum Game](./solutions/1927-sum-game.js)|Medium| -1928|[Minimum Cost to Reach Destination in Time](./solutions/1928-minimum-cost-to-reach-destination-in-time.js)|Hard| -1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| -1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| -1931|[Painting a Grid With Three Different Colors](./solutions/1931-painting-a-grid-with-three-different-colors.js)|Hard| -1932|[Merge BSTs to Create Single BST](./solutions/1932-merge-bsts-to-create-single-bst.js)|Hard| -1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| -1936|[Add Minimum Number of Rungs](./solutions/1936-add-minimum-number-of-rungs.js)|Medium| -1937|[Maximum Number of Points with Cost](./solutions/1937-maximum-number-of-points-with-cost.js)|Medium| -1938|[Maximum Genetic Difference Query](./solutions/1938-maximum-genetic-difference-query.js)|Hard| -1941|[Check if All Characters Have Equal Number of Occurrences](./solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js)|Easy| -1943|[Describe the Painting](./solutions/1943-describe-the-painting.js)|Medium| -1944|[Number of Visible People in a Queue](./solutions/1944-number-of-visible-people-in-a-queue.js)|Hard| -1945|[Sum of Digits of String After Convert](./solutions/1945-sum-of-digits-of-string-after-convert.js)|Easy| -1946|[Largest Number After Mutating Substring](./solutions/1946-largest-number-after-mutating-substring.js)|Medium| -1947|[Maximum Compatibility Score Sum](./solutions/1947-maximum-compatibility-score-sum.js)|Medium| -1948|[Delete Duplicate Folders in System](./solutions/1948-delete-duplicate-folders-in-system.js)|Hard| -1952|[Three Divisors](./solutions/1952-three-divisors.js)|Easy| -1953|[Maximum Number of Weeks for Which You Can Work](./solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js)|Medium| -1954|[Minimum Garden Perimeter to Collect Enough Apples](./solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js)|Medium| -1955|[Count Number of Special Subsequences](./solutions/1955-count-number-of-special-subsequences.js)|Hard| -1957|[Delete Characters to Make Fancy String](./solutions/1957-delete-characters-to-make-fancy-string.js)|Easy| -1958|[Check if Move is Legal](./solutions/1958-check-if-move-is-legal.js)|Medium| -1959|[Minimum Total Space Wasted With K Resizing Operations](./solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js)|Medium| -1960|[Maximum Product of the Length of Two Palindromic Substrings](./solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js)|Hard| -1961|[Check If String Is a Prefix of Array](./solutions/1961-check-if-string-is-a-prefix-of-array.js)|Easy| -1963|[Minimum Number of Swaps to Make the String Balanced](./solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js)|Medium| -1964|[Find the Longest Valid Obstacle Course at Each Position](./solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js)|Hard| -1967|[Number of Strings That Appear as Substrings in Word](./solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js)|Easy| -1968|[Array With Elements Not Equal to Average of Neighbors](./solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js)|Medium| -1969|[Minimum Non-Zero Product of the Array Elements](./solutions/1969-minimum-non-zero-product-of-the-array-elements.js)|Medium| -1970|[Last Day Where You Can Still Cross](./solutions/1970-last-day-where-you-can-still-cross.js)|Hard| -1971|[Find if Path Exists in Graph](./solutions/1971-find-if-path-exists-in-graph.js)|Easy| -1974|[Minimum Time to Type Word Using Special Typewriter](./solutions/1974-minimum-time-to-type-word-using-special-typewriter.js)|Easy| -1975|[Maximum Matrix Sum](./solutions/1975-maximum-matrix-sum.js)|Medium| -1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| -1977|[Number of Ways to Separate Numbers](./solutions/1977-number-of-ways-to-separate-numbers.js)|Hard| -1979|[Find Greatest Common Divisor of Array](./solutions/1979-find-greatest-common-divisor-of-array.js)|Easy| -1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| -1981|[Minimize the Difference Between Target and Chosen Elements](./solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js)|Medium| -1982|[Find Array Given Subset Sums](./solutions/1982-find-array-given-subset-sums.js)|Hard| -1984|[Minimum Difference Between Highest and Lowest of K Scores](./solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js)|Easy| -1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| -1986|[Minimum Number of Work Sessions to Finish the Tasks](./solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js)|Medium| -1987|[Number of Unique Good Subsequences](./solutions/1987-number-of-unique-good-subsequences.js)|Hard| -1991|[Find the Middle Index in Array](./solutions/1991-find-the-middle-index-in-array.js)|Easy| -1992|[Find All Groups of Farmland](./solutions/1992-find-all-groups-of-farmland.js)|Medium| -1993|[Operations on Tree](./solutions/1993-operations-on-tree.js)|Medium| -1994|[The Number of Good Subsets](./solutions/1994-the-number-of-good-subsets.js)|Hard| -1995|[Count Special Quadruplets](./solutions/1995-count-special-quadruplets.js)|Easy| -1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| -1997|[First Day Where You Have Been in All the Rooms](./solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js)|Medium| -1998|[GCD Sort of an Array](./solutions/1998-gcd-sort-of-an-array.js)|Hard| -2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| -2001|[Number of Pairs of Interchangeable Rectangles](./solutions/2001-number-of-pairs-of-interchangeable-rectangles.js)|Medium| -2002|[Maximum Product of the Length of Two Palindromic Subsequences](./solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)|Medium| -2003|[Smallest Missing Genetic Value in Each Subtree](./solutions/2003-smallest-missing-genetic-value-in-each-subtree.js)|Hard| -2006|[Count Number of Pairs With Absolute Difference K](./solutions/2006-count-number-of-pairs-with-absolute-difference-k.js)|Easy| -2007|[Find Original Array From Doubled Array](./solutions/2007-find-original-array-from-doubled-array.js)|Medium| -2008|[Maximum Earnings From Taxi](./solutions/2008-maximum-earnings-from-taxi.js)|Medium| -2009|[Minimum Number of Operations to Make Array Continuous](./solutions/2009-minimum-number-of-operations-to-make-array-continuous.js)|Hard| -2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| -2012|[Sum of Beauty in the Array](./solutions/2012-sum-of-beauty-in-the-array.js)|Medium| -2013|[Detect Squares](./solutions/2013-detect-squares.js)|Medium| -2014|[Longest Subsequence Repeated k Times](./solutions/2014-longest-subsequence-repeated-k-times.js)|Hard| -2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| -2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| -2018|[Check if Word Can Be Placed In Crossword](./solutions/2018-check-if-word-can-be-placed-in-crossword.js)|Medium| -2019|[The Score of Students Solving Math Expression](./solutions/2019-the-score-of-students-solving-math-expression.js)|Hard| -2022|[Convert 1D Array Into 2D Array](./solutions/2022-convert-1d-array-into-2d-array.js)|Easy| -2023|[Number of Pairs of Strings With Concatenation Equal to Target](./solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js)|Medium| -2024|[Maximize the Confusion of an Exam](./solutions/2024-maximize-the-confusion-of-an-exam.js)|Medium| -2025|[Maximum Number of Ways to Partition an Array](./solutions/2025-maximum-number-of-ways-to-partition-an-array.js)|Hard| -2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| -2028|[Find Missing Observations](./solutions/2028-find-missing-observations.js)|Medium| -2029|[Stone Game IX](./solutions/2029-stone-game-ix.js)|Medium| -2030|[Smallest K-Length Subsequence With Occurrences of a Letter](./solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js)|Hard| -2032|[Two Out of Three](./solutions/2032-two-out-of-three.js)|Easy| -2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| -2035|[Partition Array Into Two Arrays to Minimize Sum Difference](./solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js)|Hard| -2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| -2038|[Remove Colored Pieces if Both Neighbors are the Same Color](./solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js)|Medium| -2039|[The Time When the Network Becomes Idle](./solutions/2039-the-time-when-the-network-becomes-idle.js)|Medium| -2040|[Kth Smallest Product of Two Sorted Arrays](./solutions/2040-kth-smallest-product-of-two-sorted-arrays.js)|Hard| -2042|[Check if Numbers Are Ascending in a Sentence](./solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js)|Easy| -2043|[Simple Bank System](./solutions/2043-simple-bank-system.js)|Medium| -2044|[Count Number of Maximum Bitwise-OR Subsets](./solutions/2044-count-number-of-maximum-bitwise-or-subsets.js)|Medium| -2045|[Second Minimum Time to Reach Destination](./solutions/2045-second-minimum-time-to-reach-destination.js)|Hard| -2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| -2048|[Next Greater Numerically Balanced Number](./solutions/2048-next-greater-numerically-balanced-number.js)|Medium| -2049|[Count Nodes With the Highest Score](./solutions/2049-count-nodes-with-the-highest-score.js)|Medium| -2050|[Parallel Courses III](./solutions/2050-parallel-courses-iii.js)|Hard| -2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| -2055|[Plates Between Candles](./solutions/2055-plates-between-candles.js)|Medium| -2056|[Number of Valid Move Combinations On Chessboard](./solutions/2056-number-of-valid-move-combinations-on-chessboard.js)|Hard| -2057|[Smallest Index With Equal Value](./solutions/2057-smallest-index-with-equal-value.js)|Easy| -2058|[Find the Minimum and Maximum Number of Nodes Between Critical Points](./solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js)|Medium| -2059|[Minimum Operations to Convert Number](./solutions/2059-minimum-operations-to-convert-number.js)|Medium| -2060|[Check if an Original String Exists Given Two Encoded Strings](./solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js)|Hard| -2062|[Count Vowel Substrings of a String](./solutions/2062-count-vowel-substrings-of-a-string.js)|Easy| -2063|[Vowels of All Substrings](./solutions/2063-vowels-of-all-substrings.js)|Medium| -2064|[Minimized Maximum of Products Distributed to Any Store](./solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js)|Medium| -2065|[Maximum Path Quality of a Graph](./solutions/2065-maximum-path-quality-of-a-graph.js)|Hard| -2068|[Check Whether Two Strings are Almost Equivalent](./solutions/2068-check-whether-two-strings-are-almost-equivalent.js)|Easy| -2069|[Walking Robot Simulation II](./solutions/2069-walking-robot-simulation-ii.js)|Medium| -2070|[Most Beautiful Item for Each Query](./solutions/2070-most-beautiful-item-for-each-query.js)|Medium| -2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| -2074|[Reverse Nodes in Even Length Groups](./solutions/2074-reverse-nodes-in-even-length-groups.js)|Medium| -2075|[Decode the Slanted Ciphertext](./solutions/2075-decode-the-slanted-ciphertext.js)|Medium| -2076|[Process Restricted Friend Requests](./solutions/2076-process-restricted-friend-requests.js)|Hard| -2078|[Two Furthest Houses With Different Colors](./solutions/2078-two-furthest-houses-with-different-colors.js)|Easy| -2079|[Watering Plants](./solutions/2079-watering-plants.js)|Medium| -2080|[Range Frequency Queries](./solutions/2080-range-frequency-queries.js)|Medium| -2081|[Sum of k-Mirror Numbers](./solutions/2081-sum-of-k-mirror-numbers.js)|Hard| -2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| -2086|[Minimum Number of Food Buckets to Feed the Hamsters](./solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js)|Medium| -2087|[Minimum Cost Homecoming of a Robot in a Grid](./solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js)|Medium| -2088|[Count Fertile Pyramids in a Land](./solutions/2088-count-fertile-pyramids-in-a-land.js)|Hard| -2089|[Find Target Indices After Sorting Array](./solutions/2089-find-target-indices-after-sorting-array.js)|Easy| -2090|[K Radius Subarray Averages](./solutions/2090-k-radius-subarray-averages.js)|Medium| -2091|[Removing Minimum and Maximum From Array](./solutions/2091-removing-minimum-and-maximum-from-array.js)|Medium| -2092|[Find All People With Secret](./solutions/2092-find-all-people-with-secret.js)|Hard| -2094|[Finding 3-Digit Even Numbers](./solutions/2094-finding-3-digit-even-numbers.js)|Easy| -2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| -2096|[Step-By-Step Directions From a Binary Tree Node to Another](./solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js)|Medium| -2097|[Valid Arrangement of Pairs](./solutions/2097-valid-arrangement-of-pairs.js)|Hard| -2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| -2100|[Find Good Days to Rob the Bank](./solutions/2100-find-good-days-to-rob-the-bank.js)|Medium| -2101|[Detonate the Maximum Bombs](./solutions/2101-detonate-the-maximum-bombs.js)|Medium| -2103|[Rings and Rods](./solutions/2103-rings-and-rods.js)|Easy| -2104|[Sum of Subarray Ranges](./solutions/2104-sum-of-subarray-ranges.js)|Medium| -2105|[Watering Plants II](./solutions/2105-watering-plants-ii.js)|Medium| -2106|[Maximum Fruits Harvested After at Most K Steps](./solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js)|Hard| -2108|[Find First Palindromic String in the Array](./solutions/2108-find-first-palindromic-string-in-the-array.js)|Easy| -2109|[Adding Spaces to a String](./solutions/2109-adding-spaces-to-a-string.js)|Medium| -2110|[Number of Smooth Descent Periods of a Stock](./solutions/2110-number-of-smooth-descent-periods-of-a-stock.js)|Medium| -2111|[Minimum Operations to Make the Array K-Increasing](./solutions/2111-minimum-operations-to-make-the-array-k-increasing.js)|Hard| -2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| -2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| -2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| -2117|[Abbreviating the Product of a Range](./solutions/2117-abbreviating-the-product-of-a-range.js)|Hard| -2119|[A Number After a Double Reversal](./solutions/2119-a-number-after-a-double-reversal.js)|Easy| -2120|[Execution of All Suffix Instructions Staying in a Grid](./solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js)|Medium| -2121|[Intervals Between Identical Elements](./solutions/2121-intervals-between-identical-elements.js)|Medium| -2122|[Recover the Original Array](./solutions/2122-recover-the-original-array.js)|Hard| -2124|[Check if All A's Appears Before All B's](./solutions/2124-check-if-all-as-appears-before-all-bs.js)|Easy| -2125|[Number of Laser Beams in a Bank](./solutions/2125-number-of-laser-beams-in-a-bank.js)|Medium| -2126|[Destroying Asteroids](./solutions/2126-destroying-asteroids.js)|Medium| -2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard| -2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy| -2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium| -2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium| -2132|[Stamping the Grid](./solutions/2132-stamping-the-grid.js)|Hard| -2133|[Check if Every Row and Column Contains All Numbers](./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js)|Easy| -2134|[Minimum Swaps to Group All 1's Together II](./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js)|Medium| -2135|[Count Words Obtained After Adding a Letter](./solutions/2135-count-words-obtained-after-adding-a-letter.js)|Medium| -2136|[Earliest Possible Day of Full Bloom](./solutions/2136-earliest-possible-day-of-full-bloom.js)|Hard| -2138|[Divide a String Into Groups of Size k](./solutions/2138-divide-a-string-into-groups-of-size-k.js)|Easy| -2139|[Minimum Moves to Reach Target Score](./solutions/2139-minimum-moves-to-reach-target-score.js)|Medium| -2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium| -2141|[Maximum Running Time of N Computers](./solutions/2141-maximum-running-time-of-n-computers.js)|Hard| -2144|[Minimum Cost of Buying Candies With Discount](./solutions/2144-minimum-cost-of-buying-candies-with-discount.js)|Easy| -2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium| -2147|[Number of Ways to Divide a Long Corridor](./solutions/2147-number-of-ways-to-divide-a-long-corridor.js)|Hard| -2148|[Count Elements With Strictly Smaller and Greater Elements](./solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js)|Easy| -2149|[Rearrange Array Elements by Sign](./solutions/2149-rearrange-array-elements-by-sign.js)|Medium| -2150|[Find All Lonely Numbers in the Array](./solutions/2150-find-all-lonely-numbers-in-the-array.js)|Medium| -2151|[Maximum Good People Based on Statements](./solutions/2151-maximum-good-people-based-on-statements.js)|Hard| -2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy| -2155|[All Divisions With the Highest Score of a Binary Array](./solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js)|Medium| -2156|[Find Substring With Given Hash Value](./solutions/2156-find-substring-with-given-hash-value.js)|Hard| -2157|[Groups of Strings](./solutions/2157-groups-of-strings.js)|Hard| -2160|[Minimum Sum of Four Digit Number After Splitting Digits](./solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js)|Easy| -2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium| -2162|[Minimum Cost to Set Cooking Time](./solutions/2162-minimum-cost-to-set-cooking-time.js)|Medium| -2164|[Sort Even and Odd Indices Independently](./solutions/2164-sort-even-and-odd-indices-independently.js)|Easy| -2165|[Smallest Value of the Rearranged Number](./solutions/2165-smallest-value-of-the-rearranged-number.js)|Medium| -2166|[Design Bitset](./solutions/2166-design-bitset.js)|Medium| -2167|[Minimum Time to Remove All Cars Containing Illegal Goods](./solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js)|Hard| -2169|[Count Operations to Obtain Zero](./solutions/2169-count-operations-to-obtain-zero.js)|Easy| -2170|[Minimum Operations to Make the Array Alternating](./solutions/2170-minimum-operations-to-make-the-array-alternating.js)|Medium| -2171|[Removing Minimum Number of Magic Beans](./solutions/2171-removing-minimum-number-of-magic-beans.js)|Medium| -2172|[Maximum AND Sum of Array](./solutions/2172-maximum-and-sum-of-array.js)|Hard| -2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy| -2177|[Find Three Consecutive Integers That Sum to a Given Number](./solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js)|Medium| -2178|[Maximum Split of Positive Even Integers](./solutions/2178-maximum-split-of-positive-even-integers.js)|Medium| -2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard| -2180|[Count Integers With Even Digit Sum](./solutions/2180-count-integers-with-even-digit-sum.js)|Easy| -2181|[Merge Nodes in Between Zeros](./solutions/2181-merge-nodes-in-between-zeros.js)|Medium| -2183|[Count Array Pairs Divisible by K](./solutions/2183-count-array-pairs-divisible-by-k.js)|Hard| -2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy| -2186|[Minimum Number of Steps to Make Two Strings Anagram II](./solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js)|Medium| -2187|[Minimum Time to Complete Trips](./solutions/2187-minimum-time-to-complete-trips.js)|Medium| -2188|[Minimum Time to Finish the Race](./solutions/2188-minimum-time-to-finish-the-race.js)|Hard| -2190|[Most Frequent Number Following Key In an Array](./solutions/2190-most-frequent-number-following-key-in-an-array.js)|Easy| -2191|[Sort the Jumbled Numbers](./solutions/2191-sort-the-jumbled-numbers.js)|Medium| -2192|[All Ancestors of a Node in a Directed Acyclic Graph](./solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js)|Medium| -2193|[Minimum Number of Moves to Make Palindrome](./solutions/2193-minimum-number-of-moves-to-make-palindrome.js)|Hard| -2194|[Cells in a Range on an Excel Sheet](./solutions/2194-cells-in-a-range-on-an-excel-sheet.js)|Easy| -2195|[Append K Integers With Minimal Sum](./solutions/2195-append-k-integers-with-minimal-sum.js)|Medium| -2196|[Create Binary Tree From Descriptions](./solutions/2196-create-binary-tree-from-descriptions.js)|Medium| -2197|[Replace Non-Coprime Numbers in Array](./solutions/2197-replace-non-coprime-numbers-in-array.js)|Hard| -2200|[Find All K-Distant Indices in an Array](./solutions/2200-find-all-k-distant-indices-in-an-array.js)|Easy| -2201|[Count Artifacts That Can Be Extracted](./solutions/2201-count-artifacts-that-can-be-extracted.js)|Medium| -2202|[Maximize the Topmost Element After K Moves](./solutions/2202-maximize-the-topmost-element-after-k-moves.js)|Medium| -2203|[Minimum Weighted Subgraph With the Required Paths](./solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js)|Hard| -2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy| -2207|[Maximize Number of Subsequences in a String](./solutions/2207-maximize-number-of-subsequences-in-a-string.js)|Medium| -2209|[Minimum White Tiles After Covering With Carpets](./solutions/2209-minimum-white-tiles-after-covering-with-carpets.js)|Hard| -2210|[Count Hills and Valleys in an Array](./solutions/2210-count-hills-and-valleys-in-an-array.js)|Easy| -2211|[Count Collisions on a Road](./solutions/2211-count-collisions-on-a-road.js)|Medium| -2212|[Maximum Points in an Archery Competition](./solutions/2212-maximum-points-in-an-archery-competition.js)|Medium| -2213|[Longest Substring of One Repeating Character](./solutions/2213-longest-substring-of-one-repeating-character.js)|Hard| -2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy| -2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium| -2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium| -2218|[Maximum Value of K Coins From Piles](./solutions/2218-maximum-value-of-k-coins-from-piles.js)|Hard| -2220|[Minimum Bit Flips to Convert Number](./solutions/2220-minimum-bit-flips-to-convert-number.js)|Easy| -2221|[Find Triangular Sum of an Array](./solutions/2221-find-triangular-sum-of-an-array.js)|Medium| -2222|[Number of Ways to Select Buildings](./solutions/2222-number-of-ways-to-select-buildings.js)|Medium| -2223|[Sum of Scores of Built Strings](./solutions/2223-sum-of-scores-of-built-strings.js)|Hard| -2224|[Minimum Number of Operations to Convert Time](./solutions/2224-minimum-number-of-operations-to-convert-time.js)|Easy| -2225|[Find Players With Zero or One Losses](./solutions/2225-find-players-with-zero-or-one-losses.js)|Medium| -2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium| -2227|[Encrypt and Decrypt Strings](./solutions/2227-encrypt-and-decrypt-strings.js)|Hard| -2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium| -2234|[Maximum Total Beauty of the Gardens](./solutions/2234-maximum-total-beauty-of-the-gardens.js)|Hard| -2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy| -2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy| -2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy| -2240|[Number of Ways to Buy Pens and Pencils](./solutions/2240-number-of-ways-to-buy-pens-and-pencils.js)|Medium| -2241|[Design an ATM Machine](./solutions/2241-design-an-atm-machine.js)|Medium| -2242|[Maximum Score of a Node Sequence](./solutions/2242-maximum-score-of-a-node-sequence.js)|Hard| -2243|[Calculate Digit Sum of a String](./solutions/2243-calculate-digit-sum-of-a-string.js)|Easy| -2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium| -2245|[Maximum Trailing Zeros in a Cornered Path](./solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js)|Medium| -2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard| -2248|[Intersection of Multiple Arrays](./solutions/2248-intersection-of-multiple-arrays.js)|Easy| -2249|[Count Lattice Points Inside a Circle](./solutions/2249-count-lattice-points-inside-a-circle.js)|Medium| -2250|[Count Number of Rectangles Containing Each Point](./solutions/2250-count-number-of-rectangles-containing-each-point.js)|Medium| -2251|[Number of Flowers in Full Bloom](./solutions/2251-number-of-flowers-in-full-bloom.js)|Hard| -2255|[Count Prefixes of a Given String](./solutions/2255-count-prefixes-of-a-given-string.js)|Easy| -2256|[Minimum Average Difference](./solutions/2256-minimum-average-difference.js)|Medium| -2257|[Count Unguarded Cells in the Grid](./solutions/2257-count-unguarded-cells-in-the-grid.js)|Medium| -2258|[Escape the Spreading Fire](./solutions/2258-escape-the-spreading-fire.js)|Hard| -2259|[Remove Digit From Number to Maximize Result](./solutions/2259-remove-digit-from-number-to-maximize-result.js)|Easy| -2260|[Minimum Consecutive Cards to Pick Up](./solutions/2260-minimum-consecutive-cards-to-pick-up.js)|Medium| -2261|[K Divisible Elements Subarrays](./solutions/2261-k-divisible-elements-subarrays.js)|Medium| -2262|[Total Appeal of A String](./solutions/2262-total-appeal-of-a-string.js)|Hard| -2264|[Largest 3-Same-Digit Number in String](./solutions/2264-largest-3-same-digit-number-in-string.js)|Easy| -2265|[Count Nodes Equal to Average of Subtree](./solutions/2265-count-nodes-equal-to-average-of-subtree.js)|Medium| -2266|[Count Number of Texts](./solutions/2266-count-number-of-texts.js)|Medium| -2267|[Check if There Is a Valid Parentheses String Path](./solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js)|Hard| -2269|[Find the K-Beauty of a Number](./solutions/2269-find-the-k-beauty-of-a-number.js)|Easy| -2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium| -2271|[Maximum White Tiles Covered by a Carpet](./solutions/2271-maximum-white-tiles-covered-by-a-carpet.js)|Medium| -2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard| -2273|[Find Resultant Array After Removing Anagrams](./solutions/2273-find-resultant-array-after-removing-anagrams.js)|Easy| -2274|[Maximum Consecutive Floors Without Special Floors](./solutions/2274-maximum-consecutive-floors-without-special-floors.js)|Medium| -2275|[Largest Combination With Bitwise AND Greater Than Zero](./solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js)|Medium| -2278|[Percentage of Letter in String](./solutions/2278-percentage-of-letter-in-string.js)|Easy| -2279|[Maximum Bags With Full Capacity of Rocks](./solutions/2279-maximum-bags-with-full-capacity-of-rocks.js)|Medium| -2280|[Minimum Lines to Represent a Line Chart](./solutions/2280-minimum-lines-to-represent-a-line-chart.js)|Medium| -2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy| -2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium| -2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy| -2288|[Apply Discount to Prices](./solutions/2288-apply-discount-to-prices.js)|Medium| -2293|[Min Max Game](./solutions/2293-min-max-game.js)|Easy| -2294|[Partition Array Such That Maximum Difference Is K](./solutions/2294-partition-array-such-that-maximum-difference-is-k.js)|Medium| -2295|[Replace Elements in an Array](./solutions/2295-replace-elements-in-an-array.js)|Medium| -2296|[Design a Text Editor](./solutions/2296-design-a-text-editor.js)|Hard| -2299|[Strong Password Checker II](./solutions/2299-strong-password-checker-ii.js)|Easy| -2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium| -2301|[Match Substring After Replacement](./solutions/2301-match-substring-after-replacement.js)|Hard| -2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard| -2303|[Calculate Amount Paid in Taxes](./solutions/2303-calculate-amount-paid-in-taxes.js)|Easy| -2304|[Minimum Path Cost in a Grid](./solutions/2304-minimum-path-cost-in-a-grid.js)|Medium| -2305|[Fair Distribution of Cookies](./solutions/2305-fair-distribution-of-cookies.js)|Medium| -2306|[Naming a Company](./solutions/2306-naming-a-company.js)|Hard| -2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy| -2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard| -2315|[Count Asterisks](./solutions/2315-count-asterisks.js)|Easy| -2316|[Count Unreachable Pairs of Nodes in an Undirected Graph](./solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js)|Medium| -2317|[Maximum XOR After Operations](./solutions/2317-maximum-xor-after-operations.js)|Medium| -2318|[Number of Distinct Roll Sequences](./solutions/2318-number-of-distinct-roll-sequences.js)|Hard| -2319|[Check if Matrix Is X-Matrix](./solutions/2319-check-if-matrix-is-x-matrix.js)|Easy| -2320|[Count Number of Ways to Place Houses](./solutions/2320-count-number-of-ways-to-place-houses.js)|Medium| -2321|[Maximum Score Of Spliced Array](./solutions/2321-maximum-score-of-spliced-array.js)|Hard| -2322|[Minimum Score After Removals on a Tree](./solutions/2322-minimum-score-after-removals-on-a-tree.js)|Hard| -2325|[Decode the Message](./solutions/2325-decode-the-message.js)|Easy| -2326|[Spiral Matrix IV](./solutions/2326-spiral-matrix-iv.js)|Medium| -2328|[Number of Increasing Paths in a Grid](./solutions/2328-number-of-increasing-paths-in-a-grid.js)|Hard| -2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy| -2334|[Subarray With Elements Greater Than Varying Threshold](./solutions/2334-subarray-with-elements-greater-than-varying-threshold.js)|Hard| -2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium| -2337|[Move Pieces to Obtain a String](./solutions/2337-move-pieces-to-obtain-a-string.js)|Medium| -2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard| -2341|[Maximum Number of Pairs in Array](./solutions/2341-maximum-number-of-pairs-in-array.js)|Easy| -2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium| -2347|[Best Poker Hand](./solutions/2347-best-poker-hand.js)|Easy| -2348|[Number of Zero-Filled Subarrays](./solutions/2348-number-of-zero-filled-subarrays.js)|Medium| -2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium| -2350|[Shortest Impossible Sequence of Rolls](./solutions/2350-shortest-impossible-sequence-of-rolls.js)|Hard| -2351|[First Letter to Appear Twice](./solutions/2351-first-letter-to-appear-twice.js)|Easy| -2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium| -2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard| -2358|[Maximum Number of Groups Entering a Competition](./solutions/2358-maximum-number-of-groups-entering-a-competition.js)|Medium| -2359|[Find Closest Node to Given Two Nodes](./solutions/2359-find-closest-node-to-given-two-nodes.js)|Medium| -2360|[Longest Cycle in a Graph](./solutions/2360-longest-cycle-in-a-graph.js)|Hard| -2363|[Merge Similar Items](./solutions/2363-merge-similar-items.js)|Easy| -2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium| -2365|[Task Scheduler II](./solutions/2365-task-scheduler-ii.js)|Medium| -2366|[Minimum Replacements to Sort the Array](./solutions/2366-minimum-replacements-to-sort-the-array.js)|Hard| -2367|[Number of Arithmetic Triplets](./solutions/2367-number-of-arithmetic-triplets.js)|Easy| -2368|[Reachable Nodes With Restrictions](./solutions/2368-reachable-nodes-with-restrictions.js)|Medium| -2369|[Check if There is a Valid Partition For The Array](./solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js)|Medium| -2370|[Longest Ideal Subsequence](./solutions/2370-longest-ideal-subsequence.js)|Medium| -2373|[Largest Local Values in a Matrix](./solutions/2373-largest-local-values-in-a-matrix.js)|Easy| -2374|[Node With Highest Edge Score](./solutions/2374-node-with-highest-edge-score.js)|Medium| -2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium| -2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy| -2380|[Time Needed to Rearrange a Binary String](./solutions/2380-time-needed-to-rearrange-a-binary-string.js)|Medium| -2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium| -2382|[Maximum Segment Sum After Removals](./solutions/2382-maximum-segment-sum-after-removals.js)|Hard| -2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy| -2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium| -2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy| -2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium| -2391|[Minimum Amount of Time to Collect Garbage](./solutions/2391-minimum-amount-of-time-to-collect-garbage.js)|Medium| -2392|[Build a Matrix With Conditions](./solutions/2392-build-a-matrix-with-conditions.js)|Hard| -2395|[Find Subarrays With Equal Sum](./solutions/2395-find-subarrays-with-equal-sum.js)|Easy| -2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium| -2397|[Maximum Rows Covered by Columns](./solutions/2397-maximum-rows-covered-by-columns.js)|Medium| -2399|[Check Distances Between Same Letters](./solutions/2399-check-distances-between-same-letters.js)|Easy| -2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium| -2404|[Most Frequent Even Element](./solutions/2404-most-frequent-even-element.js)|Easy| -2405|[Optimal Partition of String](./solutions/2405-optimal-partition-of-string.js)|Medium| -2409|[Count Days Spent Together](./solutions/2409-count-days-spent-together.js)|Easy| -2410|[Maximum Matching of Players With Trainers](./solutions/2410-maximum-matching-of-players-with-trainers.js)|Medium| -2411|[Smallest Subarrays With Maximum Bitwise OR](./solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js)|Medium| -2412|[Minimum Money Required Before Transactions](./solutions/2412-minimum-money-required-before-transactions.js)|Hard| -2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy| -2414|[Length of the Longest Alphabetical Continuous Substring](./solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js)|Medium| -2415|[Reverse Odd Levels of Binary Tree](./solutions/2415-reverse-odd-levels-of-binary-tree.js)|Medium| -2416|[Sum of Prefix Scores of Strings](./solutions/2416-sum-of-prefix-scores-of-strings.js)|Hard| -2418|[Sort the People](./solutions/2418-sort-the-people.js)|Easy| -2419|[Longest Subarray With Maximum Bitwise AND](./solutions/2419-longest-subarray-with-maximum-bitwise-and.js)|Medium| -2421|[Number of Good Paths](./solutions/2421-number-of-good-paths.js)|Hard| -2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium| -2426|[Number of Pairs Satisfying Inequality](./solutions/2426-number-of-pairs-satisfying-inequality.js)|Hard| -2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy| -2428|[Maximum Sum of an Hourglass](./solutions/2428-maximum-sum-of-an-hourglass.js)|Medium| -2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium| -2432|[The Employee That Worked on the Longest Task](./solutions/2432-the-employee-that-worked-on-the-longest-task.js)|Easy| -2433|[Find The Original Array of Prefix Xor](./solutions/2433-find-the-original-array-of-prefix-xor.js)|Medium| -2434|[Using a Robot to Print the Lexicographically Smallest String](./solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js)|Medium| -2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard| -2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy| -2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium| -2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium| -2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy| -2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| -2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy| -2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard| -2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard| -2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium| -2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| -2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| -2537|[Count the Number of Good Subarrays](./solutions/2537-count-the-number-of-good-subarrays.js)|Medium| -2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium| -2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard| -2559|[Count Vowel Strings in Ranges](./solutions/2559-count-vowel-strings-in-ranges.js)|Medium| -2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium| -2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium| -2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy| -2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium| -2594|[Minimum Time to Repair Cars](./solutions/2594-minimum-time-to-repair-cars.js)|Medium| -2615|[Sum of Distances](./solutions/2615-sum-of-distances.js)|Medium| -2618|[Check if Object Instance of Class](./solutions/2618-check-if-object-instance-of-class.js)|Medium| -2619|[Array Prototype Last](./solutions/2619-array-prototype-last.js)|Easy| -2620|[Counter](./solutions/2620-counter.js)|Easy| -2621|[Sleep](./solutions/2621-sleep.js)|Easy| -2622|[Cache With Time Limit](./solutions/2622-cache-with-time-limit.js)|Medium| -2623|[Memoize](./solutions/2623-memoize.js)|Medium| -2624|[Snail Traversal](./solutions/2624-snail-traversal.js)|Medium| -2625|[Flatten Deeply Nested Array](./solutions/2625-flatten-deeply-nested-array.js)|Medium| -2626|[Array Reduce Transformation](./solutions/2626-array-reduce-transformation.js)|Easy| -2627|[Debounce](./solutions/2627-debounce.js)|Medium| -2629|[Function Composition](./solutions/2629-function-composition.js)|Easy| -2630|[Memoize II](./solutions/2630-memoize-ii.js)|Hard| -2631|[Group By](./solutions/2631-group-by.js)|Medium| -2634|[Filter Elements from Array](./solutions/2634-filter-elements-from-array.js)|Easy| -2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy| -2637|[Promise Time Limit](./solutions/2637-promise-time-limit.js)|Medium| -2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy| -2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium| -2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard| -2657|[Find the Prefix Common Array of Two Arrays](./solutions/2657-find-the-prefix-common-array-of-two-arrays.js)|Medium| -2658|[Maximum Number of Fish in a Grid](./solutions/2658-maximum-number-of-fish-in-a-grid.js)|Medium| -2661|[First Completely Painted Row or Column](./solutions/2661-first-completely-painted-row-or-column.js)|Medium| -2665|[Counter II](./solutions/2665-counter-ii.js)|Easy| -2666|[Allow One Function Call](./solutions/2666-allow-one-function-call.js)|Easy| -2667|[Create Hello World Function](./solutions/2667-create-hello-world-function.js)|Easy| -2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy| -2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium| -2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium| -2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium| -2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium| -2695|[Array Wrapper](./solutions/2695-array-wrapper.js)|Easy| -2698|[Find the Punishment Number of an Integer](./solutions/2698-find-the-punishment-number-of-an-integer.js)|Medium| -2703|[Return Length of Arguments Passed](./solutions/2703-return-length-of-arguments-passed.js)|Easy| -2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy| -2705|[Compact Object](./solutions/2705-compact-object.js)|Medium| -2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy| -2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium| -2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium| -2723|[Add Two Promises](./solutions/2723-add-two-promises.js)|Easy| -2724|[Sort By](./solutions/2724-sort-by.js)|Easy| -2725|[Interval Cancellation](./solutions/2725-interval-cancellation.js)|Easy| -2726|[Calculator with Method Chaining](./solutions/2726-calculator-with-method-chaining.js)|Easy| -2727|[Is Object Empty](./solutions/2727-is-object-empty.js)|Easy| -2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium| -2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium| -2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard| -2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy| -2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium| -2873|[Maximum Value of an Ordered Triplet I](./solutions/2873-maximum-value-of-an-ordered-triplet-i.js)|Easy| -2874|[Maximum Value of an Ordered Triplet II](./solutions/2874-maximum-value-of-an-ordered-triplet-ii.js)|Medium| -2900|[Longest Unequal Adjacent Groups Subsequence I](./solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js)|Easy| -2901|[Longest Unequal Adjacent Groups Subsequence II](./solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js)|Medium| -2918|[Minimum Equal Sum of Two Arrays After Replacing Zeros](./solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js)|Medium| -2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| -2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium| -2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy| -2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard| -3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy| -3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy| -3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium| -3068|[Find the Maximum Sum of Node Values](./solutions/3068-find-the-maximum-sum-of-node-values.js)|Hard| -3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy| -3108|[Minimum Cost Walk in Weighted Graph](./solutions/3108-minimum-cost-walk-in-weighted-graph.js)|Hard| -3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy| -3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy| -3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium| -3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium| -3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy| -3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium| -3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium| -3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium| -3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard| -3306|[Count of Substrings Containing Every Vowel and K Consonants II](./solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| -3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium| -3337|[Total Characters in String After Transformations II](./solutions/3337-total-characters-in-string-after-transformations-ii.js)|Hard| -3341|[Find Minimum Time to Reach Last Room I](./solutions/3341-find-minimum-time-to-reach-last-room-i.js)|Medium| -3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium| -3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard| -3355|[Zero Array Transformation I](./solutions/3355-zero-array-transformation-i.js)|Medium| -3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium| -3362|[Zero Array Transformation III](./solutions/3362-zero-array-transformation-iii.js)|Medium| -3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy| -3392|[Count Subarrays of Length Three With a Condition](./solutions/3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| -3394|[Check if Grid can be Cut into Sections](./solutions/3394-check-if-grid-can-be-cut-into-sections.js)|Medium| -3396|[Minimum Number of Operations to Make Elements in Array Distinct](./solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| -3397|[Maximum Number of Distinct Elements After Operations](./solutions/3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| -3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| -3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy| -3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy| -3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium| -3463|[Check If Digits Are Equal in String After Operations II](./solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js)|Hard| -3464|[Maximize the Distance Between Points on a Square](./solutions/3464-maximize-the-distance-between-points-on-a-square.js)|Hard| +``` +/** + * 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. + */ -## License +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + +}; -[MIT License](https://opensource.org/licenses/MIT) +const example1 = twoSum([2, 7, 11, 15], 9); // [0,1] +const example2 = twoSum([3, 2, 4], 6); // [1,2] +const example3 = twoSum([3, 3], 6); // [0,1] -Copyright (c) 2019-2025 [Josh Crozier](https://joshcrozier.com) +console.log(example1); +console.log(example2); +console.log(example3); +``` + +## Test cases + +Test cases is groupped inderections for learning in propper order how it recommended in [neetcode](https://neetcode.io/roadmap) + +``` +example + 0.ArraysHash + 1.TwoPointers + ... + 18.MathGeometry +``` + +## Links + +[List of solutions](https://github.com/Barklim/leetcode-javascript/blob/master/README1.md) + +This repo is Copy of [leetcode-javascript](https://github.com/JoshCrozier/leetcode-javascript) diff --git a/README1.md b/README1.md new file mode 100644 index 00000000..9fb5d6c0 --- /dev/null +++ b/README1.md @@ -0,0 +1,769 @@ +# LeetCode solutions in JavaScript + +[https://leetcode.com/](https://leetcode.com/) + +## Table of Contents: + +|#|Title|Difficulty| +|:---|:---|:---| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +76|[Minimum Window Substring](./0076-minimum-window-substring.js)|Hard| +77|[Combinations](./0077-combinations.js)|Medium| +78|[Subsets](./0078-subsets.js)|Medium| +79|[Word Search](./0079-word-search.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| +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| +87|[Scramble String](./0087-scramble-string.js)|Hard| +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| +91|[Decode Ways](./0091-decode-ways.js)|Medium| +92|[Reverse Linked List II](./0092-reverse-linked-list-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| +96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium| +97|[Interleaving String](./0097-interleaving-string.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| +103|[Binary Tree Zigzag Level Order Traversal](./0103-binary-tree-zigzag-level-order-traversal.js)|Medium| +104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| +105|[Construct Binary Tree from Preorder and Inorder Traversal](./0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)|Medium| +106|[Construct Binary Tree from Inorder and Postorder Traversal](./0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium| +107|[Binary Tree Level Order Traversal II](./0107-binary-tree-level-order-traversal-ii.js)|Medium| +108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| +109|[Convert Sorted List to Binary Search Tree](./0109-convert-sorted-list-to-binary-search-tree.js)|Medium| +110|[Balanced Binary Tree](./0110-balanced-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| +113|[Path Sum II](./0113-path-sum-ii.js)|Medium| +114|[Flatten Binary Tree to Linked List](./0114-flatten-binary-tree-to-linked-list.js)|Medium| +115|[Distinct Subsequences](./0115-distinct-subsequences.js)|Hard| +116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| +117|[Populating Next Right Pointers in Each Node II](./0117-populating-next-right-pointers-in-each-node-ii.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| +122|[Best Time to Buy and Sell Stock II](./0122-best-time-to-buy-and-sell-stock-ii.js)|Medium| +123|[Best Time to Buy and Sell Stock III](./0123-best-time-to-buy-and-sell-stock-iii.js)|Hard| +124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard| +125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| +126|[Word Ladder II](./0126-word-ladder-ii.js)|Hard| +127|[Word Ladder](./0127-word-ladder.js)|Hard| +128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| +129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium| +130|[Surrounded Regions](./0130-surrounded-regions.js)|Medium| +131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| +132|[Palindrome Partitioning II](./0132-palindrome-partitioning-ii.js)|Hard| +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| +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| +144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| +145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| +146|[LRU Cache](./0146-lru-cache.js)|Medium| +147|[Insertion Sort List](./0147-insertion-sort-list.js)|Medium| +148|[Sort List](./0148-sort-list.js)|Medium| +149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| +150|[Evaluate Reverse Polish Notation](./0150-evaluate-reverse-polish-notation.js)|Medium| +151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| +152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +153|[Find Minimum in Rotated Sorted Array](./0153-find-minimum-in-rotated-sorted-array.js)|Medium| +154|[Find Minimum in Rotated Sorted Array II](./0154-find-minimum-in-rotated-sorted-array-ii.js)|Hard| +155|[Min Stack](./0155-min-stack.js)|Medium| +160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| +162|[Find Peak Element](./0162-find-peak-element.js)|Medium| +164|[Maximum Gap](./0164-maximum-gap.js)|Medium| +165|[Compare Version Numbers](./0165-compare-version-numbers.js)|Medium| +166|[Fraction to Recurring Decimal](./0166-fraction-to-recurring-decimal.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| +171|[Excel Sheet Column Number](./0171-excel-sheet-column-number.js)|Easy| +172|[Factorial Trailing Zeroes](./0172-factorial-trailing-zeroes.js)|Medium| +173|[Binary Search Tree Iterator](./0173-binary-search-tree-iterator.js)|Medium| +174|[Dungeon Game](./0174-dungeon-game.js)|Hard| +179|[Largest Number](./0179-largest-number.js)|Medium| +187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| +188|[Best Time to Buy and Sell Stock IV](./0188-best-time-to-buy-and-sell-stock-iv.js)|Hard| +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| +199|[Binary Tree Right Side View](./0199-binary-tree-right-side-view.js)|Medium| +200|[Number of Islands](./0200-number-of-islands.js)|Medium| +201|[Bitwise AND of Numbers Range](./0201-bitwise-and-of-numbers-range.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| +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| +208|[Implement Trie (Prefix Tree)](./0208-implement-trie-prefix-tree.js)|Medium| +209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium| +210|[Course Schedule II](./0210-course-schedule-ii.js)|Medium| +211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium| +212|[Word Search II](./0212-word-search-ii.js)|Hard| +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| +216|[Combination Sum III](./0216-combination-sum-iii.js)|Medium| +217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| +218|[The Skyline Problem](./0218-the-skyline-problem.js)|Hard| +219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| +220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| +221|[Maximal Square](./0221-maximal-square.js)|Medium| +222|[Count Complete Tree Nodes](./0222-count-complete-tree-nodes.js)|Easy| +223|[Rectangle Area](./0223-rectangle-area.js)|Medium| +224|[Basic Calculator](./0224-basic-calculator.js)|Hard| +225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| +226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +227|[Basic Calculator II](./0227-basic-calculator-ii.js)|Medium| +228|[Summary Ranges](./0228-summary-ranges.js)|Easy| +229|[Majority Element II](./0229-majority-element-ii.js)|Medium| +230|[Kth Smallest Element in a BST](./0230-kth-smallest-element-in-a-bst.js)|Medium| +231|[Power of Two](./0231-power-of-two.js)|Easy| +232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| +233|[Number of Digit One](./0233-number-of-digit-one.js)|Hard| +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| +236|[Lowest Common Ancestor of a Binary Tree](./0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium| +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| +239|[Sliding Window Maximum](./0239-sliding-window-maximum.js)|Hard| +240|[Search a 2D Matrix II](./0240-search-a-2d-matrix-ii.js)|Medium| +241|[Different Ways to Add Parentheses](./0241-different-ways-to-add-parentheses.js)|Medium| +242|[Valid Anagram](./0242-valid-anagram.js)|Easy| +257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy| +258|[Add Digits](./0258-add-digits.js)|Easy| +260|[Single Number III](./0260-single-number-iii.js)|Medium| +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| +274|[H-Index](./0274-h-index.js)|Medium| +275|[H-Index II](./0275-h-index-ii.js)|Medium| +278|[First Bad Version](./0278-first-bad-version.js)|Medium| +279|[Perfect Squares](./0279-perfect-squares.js)|Medium| +282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| +283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +284|[Peeking Iterator](./0284-peeking-iterator.js)|Medium| +287|[Find the Duplicate Number](./0287-find-the-duplicate-number.js)|Medium| +289|[Game of Life](./0289-game-of-life.js)|Medium| +290|[Word Pattern](./0290-word-pattern.js)|Easy| +292|[Nim Game](./0292-nim-game.js)|Easy| +295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| +297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard| +299|[Bulls and Cows](./0299-bulls-and-cows.js)|Medium| +300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium| +301|[Remove Invalid Parentheses](./0301-remove-invalid-parentheses.js)|Hard| +303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| +304|[Range Sum Query 2D - Immutable](./0304-range-sum-query-2d-immutable.js)|Medium| +306|[Additive Number](./0306-additive-number.js)|Medium| +307|[Range Sum Query - Mutable](./0307-range-sum-query-mutable.js)|Medium| +309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| +310|[Minimum Height Trees](./0310-minimum-height-trees.js)|Medium| +312|[Burst Balloons](./0312-burst-balloons.js)|Hard| +313|[Super Ugly Number](./0313-super-ugly-number.js)|Medium| +315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| +316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| +318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| +319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium| +321|[Create Maximum Number](./0321-create-maximum-number.js)|Hard| +322|[Coin Change](./0322-coin-change.js)|Medium| +324|[Wiggle Sort II](./0324-wiggle-sort-ii.js)|Medium| +326|[Power of Three](./0326-power-of-three.js)|Easy| +327|[Count of Range Sum](./0327-count-of-range-sum.js)|Hard| +328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| +329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard| +330|[Patching Array](./0330-patching-array.js)|Hard| +331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| +332|[Reconstruct Itinerary](./0332-reconstruct-itinerary.js)|Hard| +334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| +335|[Self Crossing](./0335-self-crossing.js)|Hard| +336|[Palindrome Pairs](./0336-palindrome-pairs.js)|Hard| +337|[House Robber III](./0337-house-robber-iii.js)|Medium| +338|[Counting Bits](./0338-counting-bits.js)|Easy| +341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium| +342|[Power of Four](./0342-power-of-four.js)|Easy| +343|[Integer Break](./0343-integer-break.js)|Medium| +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| +350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +352|[Data Stream as Disjoint Intervals](./0352-data-stream-as-disjoint-intervals.js)|Hard| +354|[Russian Doll Envelopes](./0354-russian-doll-envelopes.js)|Hard| +355|[Design Twitter](./0355-design-twitter.js)|Medium| +357|[Count Numbers with Unique Digits](./0357-count-numbers-with-unique-digits.js)|Medium| +363|[Max Sum of Rectangle No Larger Than K](./0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard| +365|[Water and Jug Problem](./0365-water-and-jug-problem.js)|Medium| +367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| +368|[Largest Divisible Subset](./0368-largest-divisible-subset.js)|Medium| +371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| +372|[Super Pow](./0372-super-pow.js)|Medium| +373|[Find K Pairs with Smallest Sums](./0373-find-k-pairs-with-smallest-sums.js)|Medium| +374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| +375|[Guess Number Higher or Lower II](./0375-guess-number-higher-or-lower-ii.js)|Medium| +376|[Wiggle Subsequence](./0376-wiggle-subsequence.js)|Medium| +377|[Combination Sum IV](./0377-combination-sum-iv.js)|Medium| +378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| +380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| +381|[Insert Delete GetRandom O(1) - Duplicates allowed](./0381-insert-delete-getrandom-o1-duplicates-allowed.js)|Hard| +382|[Linked List Random Node](./0382-linked-list-random-node.js)|Medium| +383|[Ransom Note](./0383-ransom-note.js)|Easy| +384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium| +385|[Mini Parser](./0385-mini-parser.js)|Medium| +386|[Lexicographical Numbers](./0386-lexicographical-numbers.js)|Medium| +387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +388|[Longest Absolute File Path](./0388-longest-absolute-file-path.js)|Medium| +389|[Find the Difference](./0389-find-the-difference.js)|Easy| +390|[Elimination Game](./0390-elimination-game.js)|Medium| +391|[Perfect Rectangle](./0391-perfect-rectangle.js)|Hard| +392|[Is Subsequence](./0392-is-subsequence.js)|Easy| +393|[UTF-8 Validation](./0393-utf-8-validation.js)|Medium| +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| +396|[Rotate Function](./0396-rotate-function.js)|Medium| +397|[Integer Replacement](./0397-integer-replacement.js)|Medium| +398|[Random Pick Index](./0398-random-pick-index.js)|Medium| +399|[Evaluate Division](./0399-evaluate-division.js)|Medium| +400|[Nth Digit](./0400-nth-digit.js)|Medium| +401|[Binary Watch](./0401-binary-watch.js)|Easy| +402|[Remove K Digits](./0402-remove-k-digits.js)|Medium| +403|[Frog Jump](./0403-frog-jump.js)|Hard| +404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| +405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| +406|[Queue Reconstruction by Height](./0406-queue-reconstruction-by-height.js)|Medium| +407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| +409|[Longest Palindrome](./0409-longest-palindrome.js)|Easy| +410|[Split Array Largest Sum](./0410-split-array-largest-sum.js)|Hard| +412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| +413|[Arithmetic Slices](./0413-arithmetic-slices.js)|Medium| +414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| +415|[Add Strings](./0415-add-strings.js)|Easy| +416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium| +417|[Pacific Atlantic Water Flow](./0417-pacific-atlantic-water-flow.js)|Medium| +419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| +420|[Strong Password Checker](./0420-strong-password-checker.js)|Hard| +421|[Maximum XOR of Two Numbers in an Array](./0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium| +423|[Reconstruct Original Digits from English](./0423-reconstruct-original-digits-from-english.js)|Medium| +424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium| +427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium| +429|[N-ary Tree Level Order Traversal](./0429-n-ary-tree-level-order-traversal.js)|Medium| +430|[Flatten a Multilevel Doubly Linked List](./0430-flatten-a-multilevel-doubly-linked-list.js)|Medium| +432|[All O`one Data Structure](./0432-all-oone-data-structure.js)|Hard| +433|[Minimum Genetic Mutation](./0433-minimum-genetic-mutation.js)|Medium| +434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| +435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| +436|[Find Right Interval](./0436-find-right-interval.js)|Medium| +437|[Path Sum III](./0437-path-sum-iii.js)|Medium| +438|[Find All Anagrams in a String](./0438-find-all-anagrams-in-a-string.js)|Medium| +440|[K-th Smallest in Lexicographical Order](./0440-k-th-smallest-in-lexicographical-order.js)|Hard| +441|[Arranging Coins](./0441-arranging-coins.js)|Easy| +442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| +443|[String Compression](./0443-string-compression.js)|Medium| +445|[Add Two Numbers II](./0445-add-two-numbers-ii.js)|Medium| +446|[Arithmetic Slices II - Subsequence](./0446-arithmetic-slices-ii-subsequence.js)|Hard| +447|[Number of Boomerangs](./0447-number-of-boomerangs.js)|Medium| +448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| +449|[Serialize and Deserialize BST](./0449-serialize-and-deserialize-bst.js)|Medium| +450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| +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| +453|[Minimum Moves to Equal Array Elements](./0453-minimum-moves-to-equal-array-elements.js)|Medium| +454|[4Sum II](./0454-4sum-ii.js)|Medium| +455|[Assign Cookies](./0455-assign-cookies.js)|Easy| +456|[132 Pattern](./0456-132-pattern.js)|Medium| +457|[Circular Array Loop](./0457-circular-array-loop.js)|Medium| +458|[Poor Pigs](./0458-poor-pigs.js)|Hard| +459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +460|[LFU Cache](./0460-lfu-cache.js)|Hard| +461|[Hamming Distance](./0461-hamming-distance.js)|Easy| +462|[Minimum Moves to Equal Array Elements II](./0462-minimum-moves-to-equal-array-elements-ii.js)|Medium| +463|[Island Perimeter](./0463-island-perimeter.js)|Medium| +464|[Can I Win](./0464-can-i-win.js)|Medium| +466|[Count The Repetitions](./0466-count-the-repetitions.js)|Hard| +467|[Unique Substrings in Wraparound String](./0467-unique-substrings-in-wraparound-string.js)|Medium| +468|[Validate IP Address](./0468-validate-ip-address.js)|Medium| +470|[Implement Rand10() Using Rand7()](./0470-implement-rand10-using-rand7.js)|Medium| +472|[Concatenated Words](./0472-concatenated-words.js)|Hard| +473|[Matchsticks to Square](./0473-matchsticks-to-square.js)|Medium| +474|[Ones and Zeroes](./0474-ones-and-zeroes.js)|Medium| +475|[Heaters](./0475-heaters.js)|Medium| +476|[Number Complement](./0476-number-complement.js)|Easy| +477|[Total Hamming Distance](./0477-total-hamming-distance.js)|Medium| +478|[Generate Random Point in a Circle](./0478-generate-random-point-in-a-circle.js)|Medium| +479|[Largest Palindrome Product](./0479-largest-palindrome-product.js)|Hard| +480|[Sliding Window Median](./0480-sliding-window-median.js)|Hard| +481|[Magical String](./0481-magical-string.js)|Medium| +482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| +483|[Smallest Good Base](./0483-smallest-good-base.js)|Hard| +485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| +486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| +488|[Zuma Game](./0488-zuma-game.js)|Hard| +491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| +492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| +493|[Reverse Pairs](./0493-reverse-pairs.js)|Hard| +494|[Target Sum](./0494-target-sum.js)|Medium| +495|[Teemo Attacking](./0495-teemo-attacking.js)|Easy| +496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| +497|[Random Point in Non-overlapping Rectangles](./0497-random-point-in-non-overlapping-rectangles.js)|Medium| +498|[Diagonal Traverse](./0498-diagonal-traverse.js)|Medium| +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| +504|[Base 7](./0504-base-7.js)|Easy| +506|[Relative Ranks](./0506-relative-ranks.js)|Easy| +507|[Perfect Number](./0507-perfect-number.js)|Easy| +508|[Most Frequent Subtree Sum](./0508-most-frequent-subtree-sum.js)|Medium| +509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| +513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium| +514|[Freedom Trail](./0514-freedom-trail.js)|Hard| +520|[Detect Capital](./0520-detect-capital.js)|Easy| +521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| +530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| +541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +542|[01 Matrix](./0542-01-matrix.js)|Medium| +543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| +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| +560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| +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| +575|[Distribute Candies](./0575-distribute-candies.js)|Easy| +589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| +594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.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| +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| +637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.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| +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| +654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| +680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| +684|[Redundant Connection](./0684-redundant-connection.js)|Medium| +686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| +695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| +696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| +697|[Degree of an Array](./0697-degree-of-an-array.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| +703|[Kth Largest Element in a Stream](./0703-kth-largest-element-in-a-stream.js)|Easy| +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| +714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| +717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| +720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.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| +735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| +739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +743|[Network Delay Time](./0743-network-delay-time.js)|Medium| +744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| +745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard| +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| +748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| +762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| +763|[Partition Labels](./0763-partition-labels.js)|Medium| +783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| +784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| +790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| +791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| +796|[Rotate String](./0796-rotate-string.js)|Easy| +802|[Find Eventual Safe States](./0802-find-eventual-safe-states.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| +827|[Making A Large Island](./0827-making-a-large-island.js)|Hard| +830|[Positions of Large Groups](./0830-positions-of-large-groups.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| +868|[Binary Gap](./0868-binary-gap.js)|Easy| +872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy| +873|[Length of Longest Fibonacci Subsequence](./0873-length-of-longest-fibonacci-subsequence.js)|Medium| +875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium| +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| +889|[Construct Binary Tree from Preorder and Postorder Traversal](./0889-construct-binary-tree-from-preorder-and-postorder-traversal.js)|Medium| +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| +909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium| +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| +918|[Maximum Sum Circular Subarray](./0918-maximum-sum-circular-subarray.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| +933|[Number of Recent Calls](./0933-number-of-recent-calls.js)|Easy| +937|[Reorder Data in Log Files](./0937-reorder-data-in-log-files.js)|Medium| +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| +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| +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| +1023|[Camelcase Matching](./1023-camelcase-matching.js)|Medium| +1028|[Recover a Tree From Preorder Traversal](./1028-recover-a-tree-from-preorder-traversal.js)|Hard| +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| +1079|[Letter Tile Possibilities](./1079-letter-tile-possibilities.js)|Medium| +1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| +1092|[Shortest Common Supersequence](./1092-shortest-common-supersequence.js)|Hard| +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| +1137|[N-th Tribonacci Number](./1137-n-th-tribonacci-number.js)|Easy| +1143|[Longest Common Subsequence](./1143-longest-common-subsequence.js)|Medium| +1161|[Maximum Level Sum of a Binary Tree](./1161-maximum-level-sum-of-a-binary-tree.js)|Medium| +1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| +1200|[Minimum Absolute Difference](./1200-minimum-absolute-difference.js)|Easy| +1206|[Design Skiplist](./1206-design-skiplist.js)|Hard| +1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| +1208|[Get Equal Substrings Within Budget](./1208-get-equal-substrings-within-budget.js)|Medium| +1217|[Minimum Cost to Move Chips to The Same Position](./1217-minimum-cost-to-move-chips-to-the-same-position.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| +1261|[Find Elements in a Contaminated Binary Tree](./1261-find-elements-in-a-contaminated-binary-tree.js)|Medium| +1267|[Count Servers that Communicate](./1267-count-servers-that-communicate.js)|Medium| +1268|[Search Suggestions System](./1268-search-suggestions-system.js)|Medium| +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| +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| +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| +1319|[Number of Operations to Make Network Connected](./1319-number-of-operations-to-make-network-connected.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| +1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| +1352|[Product of the Last K Numbers](./1352-product-of-the-last-k-numbers.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| +1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| +1366|[Rank Teams by Votes](./1366-rank-teams-by-votes.js)|Medium| +1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard| +1372|[Longest ZigZag Path in a Binary Tree](./1372-longest-zigzag-path-in-a-binary-tree.js)|Medium| +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| +1415|[The k-th Lexicographical String of All Happy Strings of Length n](./1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.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| +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| +1448|[Count Good Nodes in Binary Tree](./1448-count-good-nodes-in-binary-tree.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| +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| +1462|[Course Schedule IV](./1462-course-schedule-iv.js)|Medium| +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| +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| +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| +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| +1524|[Number of Sub-arrays With Odd Sum](./1524-number-of-sub-arrays-with-odd-sum.js)|Medium| +1528|[Shuffle String](./1528-shuffle-string.js)|Easy| +1535|[Find the Winner of an Array Game](./1535-find-the-winner-of-an-array-game.js)|Medium| +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| +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| +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| +1718|[Construct the Lexicographically Largest Valid Sequence](./1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium| +1726|[Tuple with Same Product](./1726-tuple-with-same-product.js)|Medium| +1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| +1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1749|[Maximum Absolute Sum of Any Subarray](./1749-maximum-absolute-sum-of-any-subarray.js)|Medium| +1752|[Check if Array Is Sorted and Rotated](./1752-check-if-array-is-sorted-and-rotated.js)|Easy| +1764|[Form Array by Concatenating Subarrays of Another Array](./1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| +1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| +1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| +1769|[Minimum Number of Operations to Move All Balls to Each Box](./1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js)|Medium| +1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1790|[Check if One String Swap Can Make Strings Equal](./1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| +1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| +1800|[Maximum Ascending Subarray Sum](./1800-maximum-ascending-subarray-sum.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| +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| +1910|[Remove All Occurrences of a Substring](./1910-remove-all-occurrences-of-a-substring.js)|Medium| +1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| +1926|[Nearest Exit from Entrance in Maze](./1926-nearest-exit-from-entrance-in-maze.js)|Medium| +1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| +1930|[Unique Length-3 Palindromic Subsequences](./1930-unique-length-3-palindromic-subsequences.js)|Medium| +1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| +1980|[Find Unique Binary String](./1980-find-unique-binary-string.js)|Medium| +1985|[Find the Kth Largest Integer in the Array](./1985-find-the-kth-largest-integer-in-the-array.js)|Medium| +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| +2017|[Grid Game](./2017-grid-game.js)|Medium| +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| +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| +2127|[Maximum Employees to Be Invited to a Meeting](./2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard| +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| +2161|[Partition Array According to Given Pivot](./2161-partition-array-according-to-given-pivot.js)|Medium| +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| +2300|[Successful Pairs of Spells and Potions](./2300-successful-pairs-of-spells-and-potions.js)|Medium| +2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| +2342|[Max Sum of a Pair With Equal Sum of Digits](./2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium| +2349|[Design a Number Container System](./2349-design-a-number-container-system.js)|Medium| +2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| +2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium| +2375|[Construct Smallest Number From DI String](./2375-construct-smallest-number-from-di-string.js)|Medium| +2381|[Shifting Letters II](./2381-shifting-letters-ii.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| +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| +2460|[Apply Operations to an Array](./2460-apply-operations-to-an-array.js)|Easy| +2462|[Total Cost to Hire K Workers](./2462-total-cost-to-hire-k-workers.js)|Medium| +2467|[Most Profitable Path in a Tree](./2467-most-profitable-path-in-a-tree.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| +2493|[Divide Nodes Into the Maximum Number of Groups](./2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard| +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| +2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium| +2570|[Merge Two 2D Arrays by Summing Values](./2570-merge-two-2d-arrays-by-summing-values.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| +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| +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| +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| +2658|[Maximum Number of Fish in a Grid](./2658-maximum-number-of-fish-in-a-grid.js)|Medium| +2661|[First Completely Painted Row or Column](./2661-first-completely-painted-row-or-column.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| +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| +2694|[Event Emitter](./2694-event-emitter.js)|Medium| +2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| +2698|[Find the Punishment Number of an Integer](./2698-find-the-punishment-number-of-an-integer.js)|Medium| +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| +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| +2725|[Interval Cancellation](./2725-interval-cancellation.js)|Easy| +2726|[Calculator with Method Chaining](./2726-calculator-with-method-chaining.js)|Easy| +2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| +2948|[Make Lexicographically Smallest Array by Swapping Elements](./2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| +3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| +3066|[Minimum Operations to Exceed Threshold Value II](./3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium| +3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy| +3110|[Score of a String](./3110-score-of-a-string.js)|Easy| +3151|[Special Array I](./3151-special-array-i.js)|Easy| +3160|[Find the Number of Distinct Colors Among the Balls](./3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium| +3174|[Clear Digits](./3174-clear-digits.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| +3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| +3452|[Sum of Good Numbers](./3452-sum-of-good-numbers.js)|Easy| + +## License + +[MIT License](https://opensource.org/licenses/MIT) + +Copyright (c) 2019-2025 [Josh Crozier](https://joshcrozier.com) diff --git a/dStructure/MaxHeapAdhoc.js b/dStructure/MaxHeapAdhoc.js new file mode 100644 index 00000000..7028c31d --- /dev/null +++ b/dStructure/MaxHeapAdhoc.js @@ -0,0 +1,114 @@ +/** + * The minimalistic (ad hoc) version of a MaxHeap data structure that doesn't have + * external dependencies and that is easy to copy-paste and use during the + * coding interview if allowed by the interviewer (since many data + * structures in JS are missing). + */ +class MaxHeapAdhoc { + constructor(heap = []) { + this.heap = []; + heap.forEach(this.add); + } + + add(num) { + this.heap.push(num); + this.heapifyUp(); + } + + peek() { + return this.heap[0]; + } + + poll() { + if (this.heap.length === 0) return undefined; + const top = this.heap[0]; + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.heapifyDown(); + return top; + } + + isEmpty() { + return this.heap.length === 0; + } + + toString() { + return this.heap.join(','); + } + + heapifyUp() { + let nodeIndex = this.heap.length - 1; + while (nodeIndex > 0) { + const parentIndex = this.getParentIndex(nodeIndex); + if (this.heap[parentIndex] >= this.heap[nodeIndex]) break; + this.swap(parentIndex, nodeIndex); + nodeIndex = parentIndex; + } + } + + heapifyDown() { + let nodeIndex = 0; + + while ( + ( + this.hasLeftChild(nodeIndex) && this.heap[nodeIndex] < this.leftChild(nodeIndex) + ) + || ( + this.hasRightChild(nodeIndex) && this.heap[nodeIndex] < this.rightChild(nodeIndex) + ) + ) { + const leftIndex = this.getLeftChildIndex(nodeIndex); + const rightIndex = this.getRightChildIndex(nodeIndex); + const left = this.leftChild(nodeIndex); + const right = this.rightChild(nodeIndex); + + if (this.hasLeftChild(nodeIndex) && this.hasRightChild(nodeIndex)) { + if (left >= right) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } else { + this.swap(rightIndex, nodeIndex); + nodeIndex = rightIndex; + } + } else if (this.hasLeftChild(nodeIndex)) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } + } + } + + getLeftChildIndex(parentIndex) { + return (2 * parentIndex) + 1; + } + + getRightChildIndex(parentIndex) { + return (2 * parentIndex) + 2; + } + + getParentIndex(childIndex) { + return Math.floor((childIndex - 1) / 2); + } + + hasLeftChild(parentIndex) { + return this.getLeftChildIndex(parentIndex) < this.heap.length; + } + + hasRightChild(parentIndex) { + return this.getRightChildIndex(parentIndex) < this.heap.length; + } + + leftChild(parentIndex) { + return this.heap[this.getLeftChildIndex(parentIndex)]; + } + + rightChild(parentIndex) { + return this.heap[this.getRightChildIndex(parentIndex)]; + } + + swap(indexOne, indexTwo) { + const tmp = this.heap[indexTwo]; + this.heap[indexTwo] = this.heap[indexOne]; + this.heap[indexOne] = tmp; + } + } + \ No newline at end of file diff --git a/dStructure/MinHeapAdhoc.js b/dStructure/MinHeapAdhoc.js new file mode 100644 index 00000000..35a64545 --- /dev/null +++ b/dStructure/MinHeapAdhoc.js @@ -0,0 +1,115 @@ +/** + * The minimalistic (ad hoc) version of a MinHeap data structure that doesn't have + * external dependencies and that is easy to copy-paste and use during the + * coding interview if allowed by the interviewer (since many data + * structures in JS are missing). + */ +class MinHeapAdhoc { + constructor(heap = []) { + this.heap = []; + heap.forEach(this.add); + } + + add(num) { + this.heap.push(num); + this.heapifyUp(); + } + + peek() { + return this.heap[0]; + } + + poll() { + if (this.heap.length === 0) return undefined; + const top = this.heap[0]; + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.heapifyDown(); + return top; + } + + isEmpty() { + return this.heap.length === 0; + } + + toString() { + return this.heap.join(','); + } + + heapifyUp() { + let nodeIndex = this.heap.length - 1; + while (nodeIndex > 0) { + const parentIndex = this.getParentIndex(nodeIndex); + if (this.heap[parentIndex] <= this.heap[nodeIndex]) break; + this.swap(parentIndex, nodeIndex); + nodeIndex = parentIndex; + } + } + + heapifyDown() { + let nodeIndex = 0; + + while ( + ( + this.hasLeftChild(nodeIndex) + && this.heap[nodeIndex] > this.leftChild(nodeIndex) + ) + || ( + this.hasRightChild(nodeIndex) + && this.heap[nodeIndex] > this.rightChild(nodeIndex) + ) + ) { + const leftIndex = this.getLeftChildIndex(nodeIndex); + const rightIndex = this.getRightChildIndex(nodeIndex); + const left = this.leftChild(nodeIndex); + const right = this.rightChild(nodeIndex); + + if (this.hasLeftChild(nodeIndex) && this.hasRightChild(nodeIndex)) { + if (left <= right) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } else { + this.swap(rightIndex, nodeIndex); + nodeIndex = rightIndex; + } + } else if (this.hasLeftChild(nodeIndex)) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } + } + } + + getLeftChildIndex(parentIndex) { + return 2 * parentIndex + 1; + } + + getRightChildIndex(parentIndex) { + return 2 * parentIndex + 2; + } + + getParentIndex(childIndex) { + return Math.floor((childIndex - 1) / 2); + } + + hasLeftChild(parentIndex) { + return this.getLeftChildIndex(parentIndex) < this.heap.length; + } + + hasRightChild(parentIndex) { + return this.getRightChildIndex(parentIndex) < this.heap.length; + } + + leftChild(parentIndex) { + return this.heap[this.getLeftChildIndex(parentIndex)]; + } + + rightChild(parentIndex) { + return this.heap[this.getRightChildIndex(parentIndex)]; + } + + swap(indexOne, indexTwo) { + const tmp = this.heap[indexTwo]; + this.heap[indexTwo] = this.heap[indexOne]; + this.heap[indexOne] = tmp; + } +} \ No newline at end of file diff --git a/dStructure/binTree.js b/dStructure/binTree.js new file mode 100644 index 00000000..94398268 --- /dev/null +++ b/dStructure/binTree.js @@ -0,0 +1,128 @@ +class TreeNode { + constructor(val) { + this.val = val; + this.left = null; + this.right = null + } +} + +class BinaryTree { + constructor() { + this.root = null; + } + + add(val) { + const newNode = new TreeNode(val) + if (!this.root) { + this.root = newNode; + return; + } + + let currentNode = this.root; + + while(currentNode) { + if (newNode.val < currentNode.val) { + if (!currentNode.left) { + currentNode.left = newNode; + return; + } + + currentNode = currentNode.left + } else { + if (!currentNode.right) { + currentNode.right = newNode; + return; + } + + currentNode = currentNode.right + } + + } + } + + search(val) { + let currentNode = this.root; + while (currentNode) { + if (val === currentNode.val) { + return currentNode; + } + if (val < currentNode.val) { + currentNode = currentNode.left; + } else { + currentNode = currentNode.right; + } + } + return null; + } + + print(root = this.root) { + if (!root) return true + console.log(root.val) + this.print(root.left) + this.print(root.right) + } +} + +function createTreeFromArray(arr) { + if (!arr.length || arr[0] === null) return null; + + let root = new TreeNode(arr[0]); + let queue = [root]; + let i = 1; + + while (i < arr.length) { + let current = queue.shift(); + + if (arr[i] !== null) { + current.left = new TreeNode(arr[i]); + queue.push(current.left); + } + i++; + + if (i < arr.length && arr[i] !== null) { + current.right = new TreeNode(arr[i]); + queue.push(current.right); + } + i++; + } + + return root; +} + +var levelOrder = function(root) { + if (!root) return []; + + let result = []; + let queue = [root]; + + while (queue.length) { + let levelSize = queue.length; + let currentLevel = []; + + for (let i = 0; i < levelSize; i++) { + let node = queue.shift(); + currentLevel.push(node.val); + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + result.push(currentLevel); + } + + return result; +}; + +// const myTree = new BinaryTree(); +// const treeFromArray = createTreeFromArray([3,9,20,null,null,15,7]); +// var myTreeStringify = JSON.stringify(treeFromArray, null, 2); + +// const foundNode = myTree.search(10); + +// console.log('!!! myTree'); +// // console.log(myTree); +// // console.log(myTree.print()); +// console.log(myTreeStringify); +// // console.log(foundNode); +// // levelOrder(createTreeFromArray([3,9,20,null,null,15,7])) +// console.log('!!!'); diff --git a/dStructure/binTree2.js b/dStructure/binTree2.js new file mode 100644 index 00000000..562d8c3c --- /dev/null +++ b/dStructure/binTree2.js @@ -0,0 +1,218 @@ +class TreeNode { + constructor(value) { + this.value = value; + this.left = null; + this.right = null + } +} + +class BinaryTree { + constructor() { + this.root = null; + } + + add(value) { + const newNode = new TreeNode(value) + if (!this.root) { + this.root = newNode; + return; + } + + let currentNode = this.root; + + while(currentNode) { + if (newNode.value < currentNode.value) { + if (!currentNode.left) { + currentNode.left = newNode; + return; + } + + currentNode = currentNode.left + } else { + if (!currentNode.right) { + currentNode.right = newNode; + return; + } + + currentNode = currentNode.right + } + + } + } + + preOrder(node, callback) { + if (!node) { + return; + } + + if (callback) { + callback(node) + } + + this.preOrder(node.left, callback); + this.preOrder(node.right, callback); + } + + inOrder(node, callback) { + if (!node) { + return; + } + + this.inOrder(node.left, callback); + if (callback) { + callback(node) + } + this.inOrder(node.right, callback); + } + + postOrder(node, callback) { + if (!node) { + return; + } + + this.postOrder(node.left, callback); + this.postOrder(node.right, callback); + if (callback) { + callback(node) + } + } + + traverseDFS(callback, method) { + if (method === 'preOrder') { + return this.preOrder(this.root, callback); + } + + if (method === 'inOrder') { + return this.inOrder(this.root, callback); + } + + if (method === 'postOrder') { + return this.postOrder(this.root, callback); + } + + } + + traverseBFS(callback) { + const queue = [this.root]; + + while(queue.length) { + const node = queue.shift(); + callback(node); + + if (node.left) { + queue.push(node.left); + } + + if (node.right) { + queue.push(node.right); + } + } + } + + search(value) { + let currentNode = this.root; + while (currentNode) { + if (value === currentNode.value) { + return currentNode; + } + if (value < currentNode.value) { + currentNode = currentNode.left; + } else { + currentNode = currentNode.right; + } + } + return null; + } + + print(root = this.root) { + if (!root) return true + console.log(root.value) + this.print(root.left) + this.print(root.right) + } +} + +function createTreeFromArray(arr) { + if (!arr.length || arr[0] === null) return null; + + let root = new TreeNode(arr[0]); + let queue = [root]; + let i = 1; + + while (i < arr.length) { + let current = queue.shift(); // Берем текущий узел + + if (arr[i] !== null) { + current.left = new TreeNode(arr[i]); + queue.push(current.left); + } + i++; + + if (i < arr.length && arr[i] !== null) { + current.right = new TreeNode(arr[i]); + queue.push(current.right); + } + i++; + } + + return root; +} + +const myTree = new BinaryTree() +myTree.add(8); +myTree.add(7); +myTree.add(9); +myTree.add(5); +myTree.add(10); +myTree.add(20); +myTree.add(6); +myTree.add(2); +myTree.add(11); + +/* + 8 + 7 9 + 5 10 +2 6 20 + 11 +*/ +var myTreeStringify = JSON.stringify(myTree, null, 2); + +// myTree.traverseDFS((node) => { +// console.log(node.value) +// }, 'preOrder') +// 8 7 5 2 6 9 10 20 11 + +// myTree.traverseDFS((node) => { +// console.log(node.value) +// }, 'inOrder') +// 2 5 6 7 8 9 10 11 20 + +// myTree.traverseDFS((node) => { +// console.log(node.value) +// }, 'postOrder') +// 2 6 5 7 11 20 10 9 8 + +// myTree.traverseBFS((node) => { +// console.log(node.value) +// }) +// 8 7 9 5 10 2 6 20 11 + +const foundNode = myTree.search(10); + +const myTree2 = new BinaryTree(); +const treeFromArray = createTreeFromArray([3,9,20,null,null,15,7]); +var myTreeStringify2 = JSON.stringify(treeFromArray, null, 2); + +// const myTree3 = new BinaryTree(); +// [3,9,20,null,null,15,7].forEach(value => myTree3.add(value)) +// var myTreeStringify3 = JSON.stringify(myTree3, null, 2); + +console.log('!!! myTree'); +// console.log(myTree); +// console.log(myTree.print()); +// console.log(myTreeStringify); +// console.log(foundNode); +console.log(myTreeStringify2); +// console.log(myTreeStringify3); +console.log('!!!'); diff --git a/dStructure/linkedList.js b/dStructure/linkedList.js new file mode 100644 index 00000000..3d2ffecd --- /dev/null +++ b/dStructure/linkedList.js @@ -0,0 +1,375 @@ +class LinkedListNode { + constructor(val, next = null) { + this.val = val; + this.next = next; + } + + toString(callback) { + return callback ? callback(this.val) : `${this.val}`; + } +} + +class LinkedList { + /** + * @param {Function} [comparatorFunction] + */ + constructor(comparatorFunction) { + /** @var LinkedListNode */ + this.head = null; + + /** @var LinkedListNode */ + this.tail = null; + + this.compare = new Comparator(comparatorFunction); + } + + /** + * @param {*} val + * @return {LinkedList} + */ + prepend(val) { + // Make new node to be a head. + const newNode = new LinkedListNode(val, this.head); + this.head = newNode; + + // If there is no tail yet let's make new node a tail. + if (!this.tail) { + this.tail = newNode; + } + + return this; + } + + /** + * @param {*} val + * @return {LinkedList} + */ + append(val) { + const newNode = new LinkedListNode(val); + + // If there is no head yet let's make new node a head. + if (!this.head) { + this.head = newNode; + this.tail = newNode; + + return this; + } + + // Attach new node to the end of linked list. + this.tail.next = newNode; + this.tail = newNode; + + return this; + } + + /** + * @param {*} val + * @param {number} index + * @return {LinkedList} + */ + insert(val, rawIndex) { + const index = rawIndex < 0 ? 0 : rawIndex; + if (index === 0) { + this.prepend(val); + } else { + let count = 1; + let currentNode = this.head; + const newNode = new LinkedListNode(val); + while (currentNode) { + if (count === index) break; + currentNode = currentNode.next; + count += 1; + } + if (currentNode) { + newNode.next = currentNode.next; + currentNode.next = newNode; + } else { + if (this.tail) { + this.tail.next = newNode; + this.tail = newNode; + } else { + this.head = newNode; + this.tail = newNode; + } + } + } + return this; + } + + /** + * @param {*} val + * @return {LinkedListNode} + */ + delete(val) { + if (!this.head) { + return null; + } + + let deletedNode = null; + + // If the head must be deleted then make next node that is different + // from the head to be a new head. + while (this.head && this.compare.equal(this.head.val, val)) { + deletedNode = this.head; + this.head = this.head.next; + } + + let currentNode = this.head; + + if (currentNode !== null) { + // If next node must be deleted then make next node to be a next next one. + while (currentNode.next) { + if (this.compare.equal(currentNode.next.val, val)) { + deletedNode = currentNode.next; + currentNode.next = currentNode.next.next; + } else { + currentNode = currentNode.next; + } + } + } + + // Check if tail must be deleted. + if (this.compare.equal(this.tail.val, val)) { + this.tail = currentNode; + } + + return deletedNode; + } + + /** + * @param {Object} findParams + * @param {*} findParams.val + * @param {function} [findParams.callback] + * @return {LinkedListNode} + */ + find({ val = undefined, callback = undefined }) { + if (!this.head) { + return null; + } + + let currentNode = this.head; + + while (currentNode) { + // If callback is specified then try to find node by callback. + if (callback && callback(currentNode.val)) { + return currentNode; + } + + // If val is specified then try to compare by val.. + if (val !== undefined && this.compare.equal(currentNode.val, val)) { + return currentNode; + } + + currentNode = currentNode.next; + } + + return null; + } + + /** + * @return {LinkedListNode} + */ + deleteTail() { + const deletedTail = this.tail; + + if (this.head === this.tail) { + // There is only one node in linked list. + this.head = null; + this.tail = null; + + return deletedTail; + } + + // If there are many nodes in linked list... + + // Rewind to the last node and delete "next" link for the node before the last one. + let currentNode = this.head; + while (currentNode.next) { + if (!currentNode.next.next) { + currentNode.next = null; + } else { + currentNode = currentNode.next; + } + } + + this.tail = currentNode; + + return deletedTail; + } + + /** + * @return {LinkedListNode} + */ + deleteHead() { + if (!this.head) { + return null; + } + + const deletedHead = this.head; + + if (this.head.next) { + this.head = this.head.next; + } else { + this.head = null; + this.tail = null; + } + + return deletedHead; + } + + /** + * @param {*[]} values - Array of values that need to be converted to linked list. + * @return {LinkedList} + */ + fromArray(values) { + values.forEach((val) => this.append(val)); + + return this; + } + + /** + * @return {LinkedListNode[]} + */ + toArray() { + const nodes = []; + + let currentNode = this.head; + while (currentNode) { + nodes.push(currentNode); + currentNode = currentNode.next; + } + + return nodes; + } + + /** + * @param {function} [callback] + * @return {string} + */ + toString(callback) { + return this.toArray().map((node) => node.toString(callback)).toString(); + } + + /** + * Reverse a linked list. + * @returns {LinkedList} + */ + reverse() { + let currNode = this.head; + let prevNode = null; + let nextNode = null; + + while (currNode) { + // Store next node. + nextNode = currNode.next; + + // Change next node of the current node so it would link to previous node. + currNode.next = prevNode; + + // Move prevNode and currNode nodes one step forward. + prevNode = currNode; + currNode = nextNode; + } + + // Reset head and tail. + this.tail = this.head; + this.head = prevNode; + + return this; + } +} + +class Comparator { + /** + * Constructor. + * @param {function(a: *, b: *)} [compareFunction] - It may be custom compare function that, let's + * say may compare custom objects together. + */ + constructor(compareFunction) { + this.compare = compareFunction || Comparator.defaultCompareFunction; + } + + /** + * Default comparison function. It just assumes that "a" and "b" are strings or numbers. + * @param {(string|number)} a + * @param {(string|number)} b + * @returns {number} + */ + static defaultCompareFunction(a, b) { + if (a === b) { + return 0; + } + + return a < b ? -1 : 1; + } + + /** + * Checks if two variables are equal. + * @param {*} a + * @param {*} b + * @return {boolean} + */ + equal(a, b) { + return this.compare(a, b) === 0; + } + + /** + * Checks if variable "a" is less than "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + lessThan(a, b) { + return this.compare(a, b) < 0; + } + + /** + * Checks if variable "a" is greater than "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + greaterThan(a, b) { + return this.compare(a, b) > 0; + } + + /** + * Checks if variable "a" is less than or equal to "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + lessThanOrEqual(a, b) { + return this.lessThan(a, b) || this.equal(a, b); + } + + /** + * Checks if variable "a" is greater than or equal to "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + greaterThanOrEqual(a, b) { + return this.greaterThan(a, b) || this.equal(a, b); + } + + /** + * Reverses the comparison order. + */ + reverse() { + const compareOriginal = this.compare; + this.compare = (a, b) => compareOriginal(b, a); + } +} + +const traversList = (linkedList) => { + let currentNode = linkedList; + let res = [] + + while (currentNode) { + res.push(currentNode.val) + currentNode = currentNode.next; + } + + return res.join(',') +} \ No newline at end of file diff --git a/dStructure/linkedList2.js b/dStructure/linkedList2.js new file mode 100644 index 00000000..c075ddbb --- /dev/null +++ b/dStructure/linkedList2.js @@ -0,0 +1,119 @@ +class Node { + constructor(val = null, prev = null, next = null) { + this.val = val + this.prev = prev + this.next = next + } +} + +var MyLinkedList = function() { + this.head = new Node() + this.tail = new Node() + this.length = 0 + this.head.next = this.tail + this.tail.prev = this.head +}; + +/** + * @param {number} index + * @return {number} + */ +MyLinkedList.prototype.get = function(idx) { + if (idx < 0 || idx >= this.length) return -1 + + let curNode = this.head.next + + while (idx--) curNode = curNode.next + + return curNode.val +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtHead = function(val) { + let prev = this.head + let next = this.head.next + + let node = new Node(val, prev, next) + + prev.next = node + next.prev = node + + this.length++ +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtTail = function(val) { + let prev = this.tail.prev + let next = this.tail + + let node = new Node(val, prev, next) + + prev.next = node + next.prev = node + + this.length++ +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtIndex = function(idx, val) { + if (idx < 0 || idx > this.length) return null + + if (idx === this.length) { + this.addAtTail(val) + return + } + + let prev = this.head + + while (idx--) prev = prev.next + + let next = prev.next + + let node = new Node(val, prev, next) + + prev.next = node + next.prev = node + + this.length++ +}; + +/** + * @param {number} index + * @return {void} + */ +MyLinkedList.prototype.deleteAtIndex = function(idx) { + if (idx < 0 || idx >= this.length) return null + + let prev = this.head + + while (idx--) prev = prev.next + + let next = prev.next.next + + prev.next = next + next.prev = prev + + this.length-- +}; + +MyLinkedList.prototype.toArray = function() { + const nodes = []; + + let currentNode = this.head; + while (currentNode) { + nodes.push(currentNode.val); + currentNode = currentNode.next; + } + + return nodes; +}; \ No newline at end of file diff --git a/example/0.ArraysHash/0001.js b/example/0.ArraysHash/0001.js new file mode 100644 index 00000000..832be269 --- /dev/null +++ b/example/0.ArraysHash/0001.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = twoSum([2, 7, 11, 15], 9); // [0,1] +const example2 = twoSum([3, 2, 4], 6); // [1,2] +const example3 = twoSum([3, 3], 6); // [0,1] +const example4 = twoSum([4 ,5, 6], 10); // [0,2] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/0.ArraysHash/0036.js b/example/0.ArraysHash/0036.js new file mode 100644 index 00000000..fbde1c73 --- /dev/null +++ b/example/0.ArraysHash/0036.js @@ -0,0 +1,48 @@ +/** + * 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 example1 = isValidSudoku([ + ["5", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"], +]); // true +const example2 = isValidSudoku([ + ["8", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"], +]); // false + +console.log(example1); +console.log(example2); diff --git a/example/0.ArraysHash/0049.js b/example/0.ArraysHash/0049.js new file mode 100644 index 00000000..a91467a9 --- /dev/null +++ b/example/0.ArraysHash/0049.js @@ -0,0 +1,30 @@ +/** + * 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 example1 = groupAnagrams(["eat","tea","tan","ate","nat","bat"]); // [["bat"],["nat","tan"],["ate","eat","tea"]] +const example2 = groupAnagrams([""]); // [[""]] +const example3 = groupAnagrams(["a"]); // [["a"]] +const example4 = groupAnagrams(["act","pots","tops","cat","stop","hat"]); // [["hat"],["act", "cat"],["stop", "pots", "tops"]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file diff --git a/example/0.ArraysHash/0128.js b/example/0.ArraysHash/0128.js new file mode 100644 index 00000000..a7630df0 --- /dev/null +++ b/example/0.ArraysHash/0128.js @@ -0,0 +1,36 @@ +/** + * 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 example1 = longestConsecutive([100,4,200,1,3,2]); // 4 +const example2 = longestConsecutive([0,3,7,2,5,8,4,6,0,1]); // 9 +const example3 = longestConsecutive([1,0,1,2]); // 3 +const example4 = longestConsecutive([2,20,4,10,3,4,5]); // 4 +const example5 = longestConsecutive([0,3,2,5,4,6,1,1]); // 7 +const example6 = longestConsecutive([1,3,5,7]); // 1 +const example7 = longestConsecutive([]); // 0 + + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); diff --git a/example/0.ArraysHash/0167.js b/example/0.ArraysHash/0167.js new file mode 100644 index 00000000..028d9258 --- /dev/null +++ b/example/0.ArraysHash/0167.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = twoSum([2,7,11,15], 9); // [1,2] +const example2 = twoSum([2, 3, 4], 6); // [1,3] +const example3 = twoSum([-1,0], -1); // [1,2] + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/0.ArraysHash/0217.js b/example/0.ArraysHash/0217.js new file mode 100644 index 00000000..4c43c373 --- /dev/null +++ b/example/0.ArraysHash/0217.js @@ -0,0 +1,23 @@ +/** + * 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) { + +}; + +const example1 = containsDuplicate([1,2,3,3]); // true +const example2 = containsDuplicate([1,2,3,4]); // false + +console.log(example1); +console.log(example2); + \ No newline at end of file diff --git a/example/0.ArraysHash/0238.js b/example/0.ArraysHash/0238.js new file mode 100644 index 00000000..160bbaf3 --- /dev/null +++ b/example/0.ArraysHash/0238.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 example1 = productExceptSelf([1,2,3,4]); // [24,12,8,6] +const example2 = productExceptSelf([-1,1,0,-3,3]); // [0,0,9,0,0] +const example3 = productExceptSelf([1,2,4,6]); // [48,24,12,8] +const example4 = productExceptSelf([-1,0,1,2,3]); // [0,-6,0,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/0.ArraysHash/0242.js b/example/0.ArraysHash/0242.js new file mode 100644 index 00000000..4c8769b5 --- /dev/null +++ b/example/0.ArraysHash/0242.js @@ -0,0 +1,26 @@ +/** + * 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 example1 = isAnagram('anagram', "nagaram"); // true +const example2 = isAnagram("rat", 'car'); // false +const example3 = isAnagram('racecar', 'carrace'); // true +const example4 = isAnagram('jar', 'jam'); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/0.ArraysHash/0271.js b/example/0.ArraysHash/0271.js new file mode 100644 index 00000000..0ac480fc --- /dev/null +++ b/example/0.ArraysHash/0271.js @@ -0,0 +1,50 @@ +/** + * @param {string[]} strs + * @returns {string} + */ +var encode = function (strs) {}; + +/** + * @param {string} str + * @returns {string[]} + */ +var decode = function (str) {}; + +const example1 = encode(["neet", "code", "love", "you"]); // 4#neet4#code4#love3#you +const example2 = decode(example1); // ["neet","code","love","you"] +const example3 = encode(["we", "say", ":", "yes"]); // 2#we3#say1#:3#yes +const example4 = decode(example3); // ["we","say",":","yes"] +const example5 = encode(["ne#et", "co#de", "lo#ve", "you"]); // 5#ne#et5#co#de5#lo#ve3#you +const example6 = decode(example1); // ["ne#et", "co#de", "lo#ve", "you"] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + +// var encode = function (strs) { +// let res = ""; +// for (let s of strs) { +// res += s.length + "#" + s; +// } +// return res; +// }; + +// var decode = function (str) { +// let res = []; +// let i = 0; +// while (i < str.length) { +// let j = i; +// while (str[j] !== "#") { +// j++; +// } +// let length = parseInt(str.substring(i, j)); +// i = j + 1; +// j = i + length; +// res.push(str.substring(i, j)); +// i = j; +// } +// return res; +// }; diff --git a/example/0.ArraysHash/0347.js b/example/0.ArraysHash/0347.js new file mode 100644 index 00000000..2285fb6d --- /dev/null +++ b/example/0.ArraysHash/0347.js @@ -0,0 +1,25 @@ +/** + * 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 example1 = topKFrequent([1, 1, 1, 2, 2, 3], 2); // [1,2] +const example2 = topKFrequent([1], 1); // [1] +const example3 = topKFrequent([3, 3, 5, 5, 5, 6], 2); // [3, 5] + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/1.TwoPointers/0011.js b/example/1.TwoPointers/0011.js new file mode 100644 index 00000000..23dcde07 --- /dev/null +++ b/example/1.TwoPointers/0011.js @@ -0,0 +1,37 @@ +/** + * 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) { + +}; + + +const example1 = maxArea([1,8,6,2,5,4,8,3,7]); // 49 +const example2 = maxArea([1,1]); // 1 +const example3 = maxArea([9,0,8]); // 16 +const example4 = maxArea([9,0,8,4,0,0,0,0,0,0,4]); // 40 +const example5 = maxArea([9,8,4,0,0,0,0,0,0,4]); // 36 +const example6 = maxArea([4,0,0,0,0,0,0,4]); // 28 +const example7 = maxArea([1,0,4,0,0,0,0,0,0,4]); // 28 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); \ No newline at end of file diff --git a/example/1.TwoPointers/0015.js b/example/1.TwoPointers/0015.js new file mode 100644 index 00000000..1ad1b7bf --- /dev/null +++ b/example/1.TwoPointers/0015.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = threeSum([-1,0,1,2,-1,-4]); // [[-1,-1,2],[-1,0,1]] +const example2 = threeSum([0,1,1]); // [] +const example3 = threeSum([0,0,0]); // [[0,0,0]] +const example4 = threeSum([-4, -1, -1,0,1,2]); // [[-1,-1,2],[-1,0,1]] +const example5 = threeSum([-3, -2, 1, 2]); // [[ -3, 1, 2 ]] +const example6 = threeSum([-2, -1, 3]); // [[ -2, -1, 3 ]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); diff --git a/example/1.TwoPointers/0026.js b/example/1.TwoPointers/0026.js new file mode 100644 index 00000000..c936242b --- /dev/null +++ b/example/1.TwoPointers/0026.js @@ -0,0 +1,41 @@ +/** + * 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) { + +}; + + +const example1 = removeDuplicates([1,1,2]); // 2, nums = [1,2,_] +const example2 = removeDuplicates([0,0,1,1,1,2,2,3,3,4]); // 5, nums = [0,1,2,3,4,_,_,_,_,_] +const example3 = removeDuplicates([2,3,3,3,3]); // 2, nums = [2,3,_,_,_] +const example4 = removeDuplicates([1]); // 1, nums = [1] +const example5 = removeDuplicates([0,1,1,1,2,2,3,3,4]); // 5, nums = [0,1,2,3,4,_,_,_,_,_] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/1.TwoPointers/0042.js b/example/1.TwoPointers/0042.js new file mode 100644 index 00000000..28fac23c --- /dev/null +++ b/example/1.TwoPointers/0042.js @@ -0,0 +1,28 @@ +/** + * 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 example1 = trap([0,1,0,2,1,0,1,3,2,1,2,1]); // 6 +const example2 = trap([4,2,0,3,2,5]); // 9 +const example3 = trap([0,2,0,3,1,0,1,3,2,1]); // 9 +const example4 = trap([1,0,2]); // 1 +const example5 = trap([2,0,1,3]); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/1.TwoPointers/0088.js b/example/1.TwoPointers/0088.js new file mode 100644 index 00000000..271e5d29 --- /dev/null +++ b/example/1.TwoPointers/0088.js @@ -0,0 +1,47 @@ +/** + * 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) { + +}; + + +const example1 = merge([1,2,3,0,0,0], 3, [2,5,6], 3); // [1,2,2,3,5,6] +const example2 = merge([1], 1 , [], 0); // [1] +const example3 = merge([0], 0, [1], 1); // [1] +const example4 = merge([1,2,0,0], 2, [5,6], 2); // [1,2,5,6] +const example5 = merge([1,2,3,0,0,0], 4, [2,5,6], 2); // [1, 2, 2, 3, 0, 5] +const example6 = merge([1,2,3,4], 4, [5,6], 2); // [1,2,3,4,5,6] +const example7 = merge([1,2,3,4], 2, [5,6], 2); // [1,2,5,6] +const example8 = merge([1,2], 2, [3,4,5,6], 3); // [1,2,3,4,5] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); +console.log(example8); + \ No newline at end of file diff --git a/example/1.TwoPointers/0125.js b/example/1.TwoPointers/0125.js new file mode 100644 index 00000000..4cbbe881 --- /dev/null +++ b/example/1.TwoPointers/0125.js @@ -0,0 +1,27 @@ +/** + * 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 example1 = isPalindrome("A man, a plan, a canal: Panama" ); // true +const example2 = isPalindrome("race a car"); // false +const example3 = isPalindrome(" "); // true + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/1.TwoPointers/0283.js b/example/1.TwoPointers/0283.js new file mode 100644 index 00000000..2e40bc67 --- /dev/null +++ b/example/1.TwoPointers/0283.js @@ -0,0 +1,33 @@ +/** + * 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) { + +}; + +const example1 = moveZeroes([0,1,0,3,12]); // [1,3,12,0,0] +const example2 = moveZeroes([0]); // [0] +const example3 = moveZeroes([0,1,3,12]); // [1,3,12,0] +const example4 = moveZeroes([0,1,0,3,12]); // [1,3,12,0,0] +const example5 = moveZeroes([1,2,0,3,12]); // [1,2,3,12,0] +const example6 = moveZeroes([0,0,0,1]); // [1,0,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + \ No newline at end of file diff --git a/example/1.TwoPointers/0344.js b/example/1.TwoPointers/0344.js new file mode 100644 index 00000000..33d5bb5e --- /dev/null +++ b/example/1.TwoPointers/0344.js @@ -0,0 +1,24 @@ +/** + * 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) { + +}; + +const example1 = reverseString(["h","e","l","l","o"]); // ["o","l","l","e","h"] +const example2 = reverseString(["H","a","n","n","a","h"]); // ["h","a","n","n","a","H"] + +console.log(example1); +console.log(example2); diff --git a/example/1.TwoPointers/0392.js b/example/1.TwoPointers/0392.js new file mode 100644 index 00000000..550f9a9b --- /dev/null +++ b/example/1.TwoPointers/0392.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +const example1 = isSubsequence('abc', 'ahbgdc'); // true +const example2 = isSubsequence('axc', 'ahbgdc'); // false +const example3 = isSubsequence('abc', 'ab1c'); // true +const example4 = isSubsequence('abc', 'abb1abc'); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file diff --git a/example/1.TwoPointers/0844.js b/example/1.TwoPointers/0844.js new file mode 100644 index 00000000..40fa4ad7 --- /dev/null +++ b/example/1.TwoPointers/0844.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) { + +}; + +const example1 = backspaceCompare('ab#c', 'ad#c'); // true 'ac' +const example2 = backspaceCompare('ab##', 'c#d#'); // true '' +const example3 = backspaceCompare('a#c', 'b'); // false +const example4 = backspaceCompare('a#b', 'a#bb'); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file diff --git a/example/1.TwoPointers/0977.js b/example/1.TwoPointers/0977.js new file mode 100644 index 00000000..fade9f82 --- /dev/null +++ b/example/1.TwoPointers/0977.js @@ -0,0 +1,23 @@ +/** + * 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(nums) { + +}; + +const example1 = sortedSquares([-4,-1,0,3,10]); // [0,1,9,16,100] +const example2 = sortedSquares([-7,-3,2,3,11]); // [4,9,9,49,121] + +console.log(example1); +console.log(example2); diff --git a/example/2.SlidingWindow/0003.js b/example/2.SlidingWindow/0003.js new file mode 100644 index 00000000..6d941715 --- /dev/null +++ b/example/2.SlidingWindow/0003.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = lengthOfLongestSubstring("abcabcbb"); // 3 +const example2 = lengthOfLongestSubstring("bbbbb"); // 1 +const example3 = lengthOfLongestSubstring("pwwkew"); // 3 +const example4 = lengthOfLongestSubstring("zxyzxyz"); // 3 +const example5 = lengthOfLongestSubstring("xxxx"); // 1 +const example6 = lengthOfLongestSubstring("xxxox"); // 2 +const example7 = lengthOfLongestSubstring("xxxoox"); // 2 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); diff --git a/example/2.SlidingWindow/0076.js b/example/2.SlidingWindow/0076.js new file mode 100644 index 00000000..9a6448a9 --- /dev/null +++ b/example/2.SlidingWindow/0076.js @@ -0,0 +1,23 @@ +/** + * @param {string} s + * @param {string} t + * @return {string} + */ +var minWindow = function(s, t) { + +}; + + +const example1 = minWindow("ADOBECODEBANC", "ABC"); // "BANC" +const example2 = minWindow("a", "a"); // "a" +const example3 = minWindow("a", "aa"); // "" +const example4 = minWindow("OUZODYXAZV", "XYZ"); // "YXAZ" +const example5 = minWindow("xyz", "xyz"); // "xyz" +const example6 = minWindow("x", "xy"); // "" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); diff --git a/example/2.SlidingWindow/0121.js b/example/2.SlidingWindow/0121.js new file mode 100644 index 00000000..74fc7cc3 --- /dev/null +++ b/example/2.SlidingWindow/0121.js @@ -0,0 +1,33 @@ +/** + * 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) { + +}; + + +const example1 = maxProfit([7,1,5,3,6,4]); // 5 +const example2 = maxProfit([7,6,4,3,1]); // 0 +const example3 = maxProfit([10,1,5,6,7,1]); // 6 +const example4 = maxProfit([10,8,7,5,2]); // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/2.SlidingWindow/0209.js b/example/2.SlidingWindow/0209.js new file mode 100644 index 00000000..ba00d1ca --- /dev/null +++ b/example/2.SlidingWindow/0209.js @@ -0,0 +1,29 @@ +/** + * 209. Minimum Size Subarray Sum + * https://leetcode.com/problems/minimum-size-subarray-sum/ + * Difficulty: Medium + * + * Given an array of positive integers nums and a positive integer target, return the + * minimal length of a subarray whose sum is greater than or equal to target. If there + * is no such subarray, return 0 instead. + */ + +/** + * @param {number} target + * @param {number[]} nums + * @return {number} + */ +var minSubArrayLen = function(target, nums) { + +}; + + +const example1 = minSubArrayLen(7, [2,3,1,2,4,3]); // 2 +const example2 = minSubArrayLen(4, [1,4,4]); // 1 +const example3 = minSubArrayLen(11, [1,1,1,1,1,1,1,1]); // 0 +const example4 = minSubArrayLen(3, [1,1,2,1,3,1,1,1]); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/2.SlidingWindow/0239.js b/example/2.SlidingWindow/0239.js new file mode 100644 index 00000000..700d131c --- /dev/null +++ b/example/2.SlidingWindow/0239.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function(nums, k) { + +}; + + +const example1 = maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3); // [3,3,5,5,6,7] +const example2 = maxSlidingWindow([1], 1); // [1] +const example3 = maxSlidingWindow([1,2,1,0,4,2,6], 3); // [2,2,4,4,6] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/2.SlidingWindow/0424.js b/example/2.SlidingWindow/0424.js new file mode 100644 index 00000000..aeb9b6a1 --- /dev/null +++ b/example/2.SlidingWindow/0424.js @@ -0,0 +1,39 @@ +/** + * 424. Longest Repeating Character Replacement + * https://leetcode.com/problems/longest-repeating-character-replacement/ + * Difficulty: Medium + * + * You are given a string s and an integer k. You can choose any character of the string + * and change it to any other uppercase English character. You can perform this operation + * at most k times. + * + * Return the length of the longest substring containing the same letter you can get after + * performing the above operations. + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var characterReplacement = function(s, k) { + +}; + +const example1 = characterReplacement("ABAB", 2); // 4 +const example2 = characterReplacement("AABABBA", 1); // 4 +const example3 = characterReplacement("XYYX", 2); // 4 +const example4 = characterReplacement("AAABABB", 1); // 5 +const example5 = characterReplacement("", 1); // 0 +const example6 = characterReplacement("AAABBBXXXAABBXX", 1); // 4 +const example7 = characterReplacement("AAABBBXXXAABBXX", 2); // 5 +const example8 = characterReplacement("AAABBBXXXAABBXX", 3); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); +console.log(example8); diff --git a/example/2.SlidingWindow/0567.js b/example/2.SlidingWindow/0567.js new file mode 100644 index 00000000..eaf0b130 --- /dev/null +++ b/example/2.SlidingWindow/0567.js @@ -0,0 +1,19 @@ +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var checkInclusion = function(s1, s2) { + +}; + + +const example1 = checkInclusion("ab", "eidbaooo"); // true +const example2 = checkInclusion("ab", "eidboaoo"); // false +const example3 = checkInclusion("abc", "lecabee"); // true +const example4 = checkInclusion("abc", "lecaabee"); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/2.SlidingWindow/0643.js b/example/2.SlidingWindow/0643.js new file mode 100644 index 00000000..46906cee --- /dev/null +++ b/example/2.SlidingWindow/0643.js @@ -0,0 +1,33 @@ +/** + * 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) { + +}; + + +const example1 = findMaxAverage([1,12,-5,-6,50,3], 4); // 12.75 +const example2 = findMaxAverage([5], 1); // 5 +const example3 = findMaxAverage([3, 3], 2); // 3 +const example4 = findMaxAverage([4 ,5, 6], 2); // 5.5 +const example5 = findMaxAverage([4 ,5, 6], 1); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/2.SlidingWindow/0904.js b/example/2.SlidingWindow/0904.js new file mode 100644 index 00000000..3adab2d7 --- /dev/null +++ b/example/2.SlidingWindow/0904.js @@ -0,0 +1,41 @@ +/** + * @param {number[]} fruits + * @return {number} + */ +var totalFruit = function(fruits) { + +}; + +const example1 = totalFruit([1,2,1]); // 3 +const example2 = totalFruit([0,1,2,2]); // 3 +const example3 = totalFruit([1,2,3,2,2]); // 4 +const example4 = totalFruit([4,5,6]); // 2 +const example5 = totalFruit([4,5,5,5,1,6,6]); // no 5 -> 4 [4,5,5,5] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + +// var totalFruit = function(fruits) { +// let begin = 0; +// let window_state = new Map(); +// let result = 0; + +// for (let end = 0; end < fruits.length; end++) { +// window_state.set(fruits[end], (window_state.get(fruits[end]) || 0) + 1); + +// while (window_state.size > 2) { +// window_state.set(fruits[begin], window_state.get(fruits[begin]) - 1); +// if (window_state.get(fruits[begin]) === 0) { +// window_state.delete(fruits[begin]); +// } +// begin++; +// } + +// result = Math.max(result, end - begin + 1); +// } + +// return result; +// }; \ No newline at end of file diff --git a/example/2.SlidingWindow/1004.js b/example/2.SlidingWindow/1004.js new file mode 100644 index 00000000..78ff5242 --- /dev/null +++ b/example/2.SlidingWindow/1004.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +const example1 = longestOnes([1,1,1,0,0,0,1,1,1,1,0], 2); // 6 [1,1,1,0,0,1!,1,1,1,1,1!] +const example2 = longestOnes([0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], 3); // 10 [0,0,1,1,1!,1!,1,1,1,1!,1,1,0,0,0,1,1,1,1] +const example3 = longestOnes([1,0,1,0,0,1], 1); // 3 +const example4 = longestOnes([1,0,0,1,0,0,0,1], 2); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/2.SlidingWindow/1493.js b/example/2.SlidingWindow/1493.js new file mode 100644 index 00000000..76777bc8 --- /dev/null +++ b/example/2.SlidingWindow/1493.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +// 1004. +const example1 = longestSubarray([1,1,0,1]); // 3 [1,1,1] +const example2 = longestSubarray([0,1,1,1,0,1,1,0,1]); // 5 [1,1,1,1,1] +const example3 = longestSubarray([1,1,1]); // 2 +const example4 = longestSubarray([0,1,0,1,0,1,1,0]); // 3 +const example5 = longestSubarray([0,0]); // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/20.0ther/0009.js b/example/20.0ther/0009.js new file mode 100644 index 00000000..032ee5bf --- /dev/null +++ b/example/20.0ther/0009.js @@ -0,0 +1,28 @@ +/** + * 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 (nums) { + +}; + +const example1 = isPalindrome(121); // true +const example2 = isPalindrome(-121); // false +const example3 = isPalindrome(10); // false +const example4 = isPalindrome(3003); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/20.0ther/0412.js b/example/20.0ther/0412.js new file mode 100644 index 00000000..27328c9c --- /dev/null +++ b/example/20.0ther/0412.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +const example1 = fizzBuzz(3); // ["1","2","Fizz"] +const example2 = fizzBuzz(5); // ["1","2","Fizz","4","Buzz"] +const example3 = fizzBuzz(15); // ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/3.Linkedlist/0002.js b/example/3.Linkedlist/0002.js new file mode 100644 index 00000000..b648c09f --- /dev/null +++ b/example/3.Linkedlist/0002.js @@ -0,0 +1,79 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(2); +myLinkedList.append(4); +myLinkedList.append(3); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(5); +myLinkedList2.append(6); +myLinkedList2.append(4); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(0); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(0); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); + +const myLinkedList6 = new LinkedList(); +myLinkedList6.prepend(9); +myLinkedList6.append(9); +myLinkedList6.append(9); +myLinkedList6.append(9); + +const myLinkedList7 = new LinkedList(); +myLinkedList7.prepend(1); +myLinkedList7.append(2); +myLinkedList7.append(3); + +const myLinkedList8 = new LinkedList(); +myLinkedList8.prepend(4); +myLinkedList8.append(5); +myLinkedList8.append(6); + +const myLinkedList9 = new LinkedList(); +myLinkedList3.prepend(9); + +const myLinkedList10 = new LinkedList(); +myLinkedList4.prepend(9); + + +const executeList = (l1, l2) => addTwoNumbers(l1.head, l2.head) + +const execute = (l1, l2) => { + console.log('travers') + console.log(l1.toString()); + console.log(l2.toString()); + const list1 = executeList(l1, l2) + console.log(traversList(list1)) +} + +execute(myLinkedList, myLinkedList2) // [2,4,3] [5,6,4] // [7,0,8] +execute(myLinkedList3, myLinkedList4) // [0] [0] // [0] ??? +execute(myLinkedList5, myLinkedList6) // [9,9,9,9,9,9,9] [9,9,9,9] // [8,9,9,9,0,0,0,1] +execute(myLinkedList7, myLinkedList8) // [1,2,3] [4,5,6] // [5,7,9] +execute(myLinkedList9, myLinkedList10) // [9] [9] // [8,1] diff --git a/example/3.Linkedlist/0019.js b/example/3.Linkedlist/0019.js new file mode 100644 index 00000000..42f67694 --- /dev/null +++ b/example/3.Linkedlist/0019.js @@ -0,0 +1,55 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); +myLinkedList.append(5); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); +myLinkedList3.append(2); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(3); +myLinkedList4.append(4); +myLinkedList4.append(5); +myLinkedList4.append(6); +myLinkedList4.append(7); + +const executeList = (list, n) => removeNthFromEnd(list.head, n) + +const execute = (list, n) => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list, n) + console.log(traversList(list1)) +} + +execute(myLinkedList, 2) // 1,2,3,4,5 // 1,2,3,5 +execute(myLinkedList2, 1) // 1 // [] +execute(myLinkedList3, 1) // 1,2 // 1 +execute(myLinkedList4, 4) // 1,2,3,4,5,6,7 // 1,2,3,5,6,7 +execute(myLinkedList4, 2) // 1,2,3,5,6,7 // 1,2,3,5,7 + + \ No newline at end of file diff --git a/example/3.Linkedlist/0021.js b/example/3.Linkedlist/0021.js new file mode 100644 index 00000000..daa79431 --- /dev/null +++ b/example/3.Linkedlist/0021.js @@ -0,0 +1,50 @@ +/** + * 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 {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function(list1, list2) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(3); +myLinkedList2.append(4); + +const myLinkedList3 = new LinkedList(); + +const myLinkedList4 = new LinkedList(); + +const myLinkedList5 = new LinkedList(); + +const myLinkedList6 = new LinkedList(); +myLinkedList6.prepend(0); + +const executeList = (list, list2) => mergeTwoLists(list.head, list2.head) + +const execute = (list, list2) => { + console.log('travers') + console.log(list.toString()); + console.log(list2.toString()); + const list1 = executeList(list, list2) + console.log(traversList(list1)) +} + +execute(myLinkedList, myLinkedList2) // 1,2,4 1,3,4 // 1,1,2,3,4,4 +execute(myLinkedList3, myLinkedList4) // [] [] // [] +execute(myLinkedList5, myLinkedList6) // [] [0] // [0] + + \ No newline at end of file diff --git a/example/3.Linkedlist/0024.js b/example/3.Linkedlist/0024.js new file mode 100644 index 00000000..2e46b4bf --- /dev/null +++ b/example/3.Linkedlist/0024.js @@ -0,0 +1,55 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(3); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); +myLinkedList5.append(3); +myLinkedList5.append(4); +myLinkedList5.append(5); +myLinkedList5.append(6); + +const executeList = (list, n) => swapPairs(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // 1,2,3,4, // 1,2,3,5 +execute(myLinkedList2) // [] // [] +execute(myLinkedList3) // [1] // [1] +execute(myLinkedList4) // 1,2,3 // 2,1,3 +execute(myLinkedList5) // 1,2,3,4,5,6 // 2,1,4,3,6,5 + + \ No newline at end of file diff --git a/example/3.Linkedlist/0083.js b/example/3.Linkedlist/0083.js new file mode 100644 index 00000000..81eccb80 --- /dev/null +++ b/example/3.Linkedlist/0083.js @@ -0,0 +1,62 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(1); +myLinkedList.append(2); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(1); +myLinkedList2.append(2); +myLinkedList2.append(3); +myLinkedList2.append(3); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); +myLinkedList3.append(2); +myLinkedList3.append(4); +myLinkedList3.append(4); +myLinkedList3.append(4); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(4); +myLinkedList4.append(4); +myLinkedList4.append(5); +myLinkedList4.append(6); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); + +const executeList = list => deleteDuplicates(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // 1 1 2 // 1 2 +execute(myLinkedList2) // 1 1 2 3 3 // 1 2 3 +execute(myLinkedList3) // 1 2 4 4 4 // 1 2 4 +execute(myLinkedList4) // 1 2 4 4 5 6 // 1 2 4 5 6 +execute(myLinkedList5) // 1 2 // 1 2 + + \ No newline at end of file diff --git a/example/3.Linkedlist/0138.js b/example/3.Linkedlist/0138.js new file mode 100644 index 00000000..331aa89d --- /dev/null +++ b/example/3.Linkedlist/0138.js @@ -0,0 +1,66 @@ +/** + * // 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) { + map = new Map(); + + if (head === null) return null; + if (map.has(head)) return map.get(head); + + const copy = new LinkedListNode(head.val); + map.set(head, copy); + copy.next = copyRandomList(head.next); + copy.random = map.get(head.random) || null; + return copy; +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(2); +myLinkedList2.append(3); +myLinkedList2.append(4); +myLinkedList2.append(5); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(2); +myLinkedList3.append(4); +myLinkedList3.append(6); +myLinkedList3.append(8); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(2); +myLinkedList4.append(4); +myLinkedList4.append(6); +myLinkedList4.append(8); +myLinkedList4.append(10); + + +const executeList = list => copyRandomList(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // [1,2,3,4] // [1,4,2,3] +execute(myLinkedList2) // [1,2,3,4,5] // [1,5,2,4,3] +execute(myLinkedList3) // [2,4,6,8] // [2,8,4,6] +execute(myLinkedList4) // [2,4,6,8,10] // [2,10,4,8,6] diff --git a/example/3.Linkedlist/0141.js b/example/3.Linkedlist/0141.js new file mode 100644 index 00000000..fc032cc7 --- /dev/null +++ b/example/3.Linkedlist/0141.js @@ -0,0 +1,15 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + +}; \ No newline at end of file diff --git a/example/3.Linkedlist/0143.js b/example/3.Linkedlist/0143.js new file mode 100644 index 00000000..3cfdadf9 --- /dev/null +++ b/example/3.Linkedlist/0143.js @@ -0,0 +1,55 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(2); +myLinkedList2.append(3); +myLinkedList2.append(4); +myLinkedList2.append(5); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(2); +myLinkedList3.append(4); +myLinkedList3.append(6); +myLinkedList3.append(8); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(2); +myLinkedList4.append(4); +myLinkedList4.append(6); +myLinkedList4.append(8); +myLinkedList4.append(10); + + +const executeList = list => reorderList(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // [1,2,3,4] // [1,4,2,3] +execute(myLinkedList2) // [1,2,3,4,5] // [1,5,2,4,3] +execute(myLinkedList3) // [2,4,6,8] // [2,8,4,6] +execute(myLinkedList4) // [2,4,6,8,10] // [2,10,4,8,6] diff --git a/example/3.Linkedlist/0206.js b/example/3.Linkedlist/0206.js new file mode 100644 index 00000000..78770076 --- /dev/null +++ b/example/3.Linkedlist/0206.js @@ -0,0 +1,29 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.append(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +console.log('reverseList'); +console.log(myLinkedList.toString()); +console.log('reverseList reversed'); +const list = reverseList(myLinkedList.head) +console.log(list.value); +console.log(list.next.value); +console.log(list.next.next.value); +console.log(list.next.next.next.value); \ No newline at end of file diff --git a/example/3.Linkedlist/0234.js b/example/3.Linkedlist/0234.js new file mode 100644 index 00000000..943eb40f --- /dev/null +++ b/example/3.Linkedlist/0234.js @@ -0,0 +1,62 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(2); +myLinkedList.append(1); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(2); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); +myLinkedList3.append(2); +myLinkedList3.append(4); +myLinkedList3.append(2); +myLinkedList3.append(1); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(4); +myLinkedList4.append(4); +myLinkedList4.append(2); +myLinkedList4.append(1); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); +myLinkedList5.append(4); +myLinkedList5.append(5); +myLinkedList5.append(2); +myLinkedList5.append(1); + +const executeList = list => isPalindrome(list.head) + +const execute = list => { + console.log(list.toString()); + console.log(executeList(list)); +} + +console.log('middleNode'); + +execute(myLinkedList) // 1 2 2 1 // true +execute(myLinkedList2) // 1 2 // false +execute(myLinkedList3) // 1 2 4 2 1 // true +execute(myLinkedList4) // 1 2 4 4 2 1 // true +execute(myLinkedList5) // 1 2 4 5 2 1 // false \ No newline at end of file diff --git a/example/3.Linkedlist/0287.js b/example/3.Linkedlist/0287.js new file mode 100644 index 00000000..ef4f444b --- /dev/null +++ b/example/3.Linkedlist/0287.js @@ -0,0 +1,57 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + +}; + +// const myLinkedList = new LinkedList(); +// myLinkedList.prepend(1); +// myLinkedList.append(3); +// myLinkedList.append(4); +// myLinkedList.append(2); +// myLinkedList.append(2); + +// const myLinkedList2 = new LinkedList(); +// myLinkedList2.prepend(3); +// myLinkedList2.append(1); +// myLinkedList2.append(3); +// myLinkedList2.append(4); +// myLinkedList2.append(2); + +// const myLinkedList3 = new LinkedList(); +// myLinkedList3.prepend(3); +// myLinkedList3.append(3); +// myLinkedList3.append(3); +// myLinkedList3.append(3); +// myLinkedList3.append(3); + +// const myLinkedList4 = new LinkedList(); +// myLinkedList4.prepend(1); +// myLinkedList4.append(2); +// myLinkedList4.append(3); +// myLinkedList4.append(2); +// myLinkedList4.append(2); + +// const myLinkedList5 = new LinkedList(); +// myLinkedList5.prepend(1); +// myLinkedList5.append(2); +// myLinkedList5.append(3); +// myLinkedList5.append(4); +// myLinkedList5.append(4); + +// const executeList = list => reorderList(list.head) + +// const execute = list => { +// console.log('travers') +// console.log(list.toString()); +// const list1 = executeList(list) +// console.log(traversList(list1)) +// } + +// execute(myLinkedList) // [1,3,4,2,2] // 2 +// execute(myLinkedList2) // [3,1,3,4,2] // 3 +// execute(myLinkedList3) // [3,3,3,3,3] // 3 +// execute(myLinkedList4) // [1,2,3,2,2] // 2 +// execute(myLinkedList5) // [1,2,3,4,4] // 4 diff --git a/example/3.Linkedlist/0445.js b/example/3.Linkedlist/0445.js new file mode 100644 index 00000000..097daa83 --- /dev/null +++ b/example/3.Linkedlist/0445.js @@ -0,0 +1,56 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(7); +myLinkedList.append(2); +myLinkedList.append(4); +myLinkedList.append(3); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(5); +myLinkedList2.append(6); +myLinkedList2.append(4); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(0); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(0); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); +myLinkedList5.append(3); + +const myLinkedList6 = new LinkedList(); +myLinkedList6.prepend(4); +myLinkedList6.append(5); +myLinkedList6.append(6); + +const executeList = (l1, l2) => addTwoNumbers(l1.head, l2.head) + +const execute = (l1, l2) => { + console.log('travers') + console.log(l1.toString()); + console.log(l2.toString()); + const list1 = executeList(l1, l2) + console.log(traversList(list1)) +} + +execute(myLinkedList, myLinkedList2) // [7,2,4,3] [5,6,4] // [7,8,0,7] +execute(myLinkedList3, myLinkedList4) // [0] [0] // [0] ??? +execute(myLinkedList5, myLinkedList6) // [1,2,3] [4,5,6] // [5,7,9] \ No newline at end of file diff --git a/example/3.Linkedlist/0707.js b/example/3.Linkedlist/0707.js new file mode 100644 index 00000000..268ee42f --- /dev/null +++ b/example/3.Linkedlist/0707.js @@ -0,0 +1,202 @@ + +var MyLinkedList = function() { + +}; + +/** + * @param {number} index + * @return {number} + */ +MyLinkedList.prototype.get = function(index) { + +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtHead = function(val) { + +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtTail = function(val) { + +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtIndex = function(index, val) { + +}; + +/** + * @param {number} index + * @return {void} + */ +MyLinkedList.prototype.deleteAtIndex = function(index) { + +}; + +/** + * Your MyLinkedList object will be instantiated and called as such: + * var obj = new MyLinkedList() + * var param_1 = obj.get(index) + * obj.addAtHead(val) + * obj.addAtTail(val) + * obj.addAtIndex(index,val) + * obj.deleteAtIndex(index) + */ + + +// var obj = new MyLinkedList() +// var param_1 = obj.get(index) +// obj.addAtHead(val) +// obj.addAtTail(val) +// obj.addAtIndex(index,val) +// obj.deleteAtIndex(index) + +const myLinkedList = new MyLinkedList(); +myLinkedList.addAtHead(1); +myLinkedList.addAtTail(3); +myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3 +myLinkedList.get(1); // return 2 +myLinkedList.deleteAtIndex(1); // now the linked list is 1->3 +myLinkedList.get(1); // return 3 + +console.log(myLinkedList); +console.log(myLinkedList.get(1)); // 3 +console.log(myLinkedList.get(2)); // -1 +console.log(myLinkedList.get(3)); // -1 +myLinkedList.addAtTail(4); +console.log(myLinkedList.get(2)); // 2 +console.log(myLinkedList); + + +// class Node { +// constructor(val = null, prev = null, next = null) { +// this.val = val +// this.prev = prev +// this.next = next +// } +// } + +// var MyLinkedList = function() { +// this.head = new Node() +// this.tail = new Node() +// this.length = 0 +// this.head.next = this.tail +// this.tail.prev = this.head +// }; + +// /** +// * @param {number} index +// * @return {number} +// */ +// MyLinkedList.prototype.get = function(idx) { +// if (idx < 0 || idx >= this.length) return -1 + +// let curNode = this.head.next + +// while (idx--) curNode = curNode.next + +// return curNode.val +// }; + +// /** +// * @param {number} val +// * @return {void} +// */ +// MyLinkedList.prototype.addAtHead = function(val) { +// let prev = this.head +// let next = this.head.next + +// let node = new Node(val, prev, next) + +// prev.next = node +// next.prev = node + +// this.length++ +// }; + +// /** +// * @param {number} val +// * @return {void} +// */ +// MyLinkedList.prototype.addAtTail = function(val) { +// let prev = this.tail.prev +// let next = this.tail + +// let node = new Node(val, prev, next) + +// prev.next = node +// next.prev = node + +// this.length++ +// }; + +// /** +// * @param {number} index +// * @param {number} val +// * @return {void} +// */ +// MyLinkedList.prototype.addAtIndex = function(idx, val) { +// if (idx < 0 || idx > this.length) return null + +// if (idx === this.length) { +// this.addAtTail(val) +// return +// } + +// let prev = this.head + +// while (idx--) prev = prev.next + +// let next = prev.next + +// let node = new Node(val, prev, next) + +// prev.next = node +// next.prev = node + +// this.length++ +// }; + +// /** +// * @param {number} index +// * @return {void} +// */ +// MyLinkedList.prototype.deleteAtIndex = function(idx) { +// if (idx < 0 || idx >= this.length) return null + +// let prev = this.head + +// while (idx--) prev = prev.next + +// let next = prev.next.next + +// prev.next = next +// next.prev = prev + +// this.length-- +// }; + +// MyLinkedList.prototype.toArray = function() { +// const nodes = []; + +// let currentNode = this.head; +// while (currentNode) { +// nodes.push(currentNode.val); +// currentNode = currentNode.next; +// } + +// return nodes; +// }; + + diff --git a/example/3.Linkedlist/0876.js b/example/3.Linkedlist/0876.js new file mode 100644 index 00000000..1526a0d2 --- /dev/null +++ b/example/3.Linkedlist/0876.js @@ -0,0 +1,71 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +let head = myLinkedList.head; +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); + +const runMiddleNode = () => middleNode(myLinkedList.head).value + +console.log('middleNode'); +console.log(myLinkedList.toString()); // 123 +console.log(runMiddleNode()); // 1 2 3 // 2 +myLinkedList.append(4); +console.log(runMiddleNode()); // 1 2 3 4 // 3 +myLinkedList.append(5); +console.log(runMiddleNode()); // 12 3 45 // 3 +myLinkedList.append(6); +console.log(runMiddleNode()); // 12 3 4 56 // 4 +myLinkedList.append(7); +myLinkedList.append(8); +console.log(runMiddleNode()); // 123 4 5 678 // 5 +myLinkedList.append(9); +console.log(runMiddleNode()); // 1234 5 6789 // 5 + +// const myLinkedList = new MyLinkedList(); +// let head = myLinkedList.head; +// myLinkedList.addAtHead(1); +// myLinkedList.addAtTail(2); +// myLinkedList.addAtTail(3); + +// console.log('middleNode'); +// console.log(middleNode(head).val); // 1 2 3 // 2 +// myLinkedList.addAtTail(4); +// console.log(middleNode(head).val); // 1 2 3 4 // 3 +// myLinkedList.addAtTail(5); +// console.log(middleNode(head).val); // 12 3 45 // 3 +// myLinkedList.addAtTail(6); +// console.log(middleNode(head).val); // 12 3 4 56 // 4 +// myLinkedList.addAtTail(7); +// myLinkedList.addAtTail(8); +// console.log(middleNode(head).val); // 123 4 5 678 // 5 +// myLinkedList.addAtTail(9); +// console.log(middleNode(head).val); // 1234 5 6789 // 5 + + + \ No newline at end of file diff --git a/example/3.Linkedlist/2095.js b/example/3.Linkedlist/2095.js new file mode 100644 index 00000000..d4a2f38a --- /dev/null +++ b/example/3.Linkedlist/2095.js @@ -0,0 +1,81 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +let head = myLinkedList.head; +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); +myLinkedList.append(5); +myLinkedList.append(6); +myLinkedList.append(7); + +console.log('deleteNode'); +console.log(myLinkedList.toArray().join(',')); + +console.log('deleteNode 4'); +deleteMiddle(myLinkedList.head) // 123 4 567 // 123 567 +console.log(myLinkedList.toArray().join(',')); + +console.log('deleteNode 35'); // 12 3 5 67 // 12 3 67 +deleteMiddle(myLinkedList.head) +console.log(myLinkedList.toArray().join(',')); + +console.log('deleteNode 3'); // 12 3 67 // 12 67 +deleteMiddle(myLinkedList.head) +console.log(myLinkedList.toArray().join(',')); + +// const myLinkedList = new MyLinkedList(); +// let head = myLinkedList.head; +// myLinkedList.addAtHead(1); +// myLinkedList.addAtTail(2); +// myLinkedList.addAtTail(3); +// myLinkedList.addAtTail(4); +// myLinkedList.addAtTail(5); +// myLinkedList.addAtTail(6); +// myLinkedList.addAtTail(7); + +// console.log('deleteNode'); +// console.log(myLinkedList.toArray().join(',')); + +// console.log('deleteNode 4'); +// deleteMiddle(head) // 123 4 567 // 123 567 +// console.log(myLinkedList.toArray().join(',')); + +// console.log('deleteNode 35'); // 12 3 5 67 // 12 3 67 +// deleteMiddle(head) +// console.log(myLinkedList.toArray().join(',')); + +// console.log('deleteNode 3'); // 12 3 67 // 12 67 +// deleteMiddle(head) +// console.log(myLinkedList.toArray().join(',')); + + + diff --git a/example/4.BinarySearch/0004.js b/example/4.BinarySearch/0004.js new file mode 100644 index 00000000..457b00d2 --- /dev/null +++ b/example/4.BinarySearch/0004.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + +}; + +const example1 = search([1,3], [2]); // 2 +const example2 = search([1,2], [3,4]); // 2.5 +const example3 = search([1,2], [3]); // 2 +const example4 = search([1,3], [2,4]); // 2.5 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); \ No newline at end of file diff --git a/example/4.BinarySearch/0033.js b/example/4.BinarySearch/0033.js new file mode 100644 index 00000000..83d9a250 --- /dev/null +++ b/example/4.BinarySearch/0033.js @@ -0,0 +1,26 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + +}; + +const example1 = search([4,5,6,7,0,1,2], 0); // 4 +const example2 = search([4,5,6,7,0,1,2], 3); // -1 +const example3 = search([1], 0); // -1 +const example4 = search([3,4,5,1,2], 1); // 3 +const example5 = search([4,5,6,7,0,1,2], 2); // 6 +const example6 = search([11,13,15,17], 13); // 1 +const example7 = search([4,5,0,1,2,3], 0); // 2 +const example8 = search([4,5,6,7], 5); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); +console.log(example8); diff --git a/example/4.BinarySearch/0074.js b/example/4.BinarySearch/0074.js new file mode 100644 index 00000000..056c21a1 --- /dev/null +++ b/example/4.BinarySearch/0074.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + +}; + +const example1 = searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3); // true +const example2 = searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13); // false +const example3 = searchMatrix([[1,2,4,8],[10,11,12,13],[14,20,30,40]], 10); // true +const example4 = searchMatrix([[1,2,4,8],[10,11,12,13],[14,20,30,40]], 15); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/4.BinarySearch/0153.js b/example/4.BinarySearch/0153.js new file mode 100644 index 00000000..4ab6b9c8 --- /dev/null +++ b/example/4.BinarySearch/0153.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function(nums) { + +}; + +const example1 = findMin([3,4,5,1,2]); // 1 +const example2 = findMin([4,5,6,7,0,1,2]); // 0 +const example3 = findMin([11,13,15,17]); // 11 +const example4 = findMin([4,5,0,1,2,3]); // 0 +const example5 = findMin([4,5,6,7]); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/4.BinarySearch/0704.js b/example/4.BinarySearch/0704.js new file mode 100644 index 00000000..b7b1ae47 --- /dev/null +++ b/example/4.BinarySearch/0704.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + +}; + +const example1 = search([-1,0,3,5,9,12], 9); // 4 +const example2 = search([-1,0,3,5,9,12], 2); // -1 +const example3 = search([-1,0,2,4,6,8], 4); // 3 +const example4 = search([-1,0,2,4,6,8], 3); // -1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/4.BinarySearch/0875.js b/example/4.BinarySearch/0875.js new file mode 100644 index 00000000..1208f7e4 --- /dev/null +++ b/example/4.BinarySearch/0875.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} piles + * @param {number} h + * @return {number} + */ +var minEatingSpeed = function(piles, h) { + +}; + +const example1 = minEatingSpeed([3,6,7,11], 8); // 4 +const example2 = minEatingSpeed([30,11,23,4,20], 5); // 30 +const example3 = minEatingSpeed([30,11,23,4,20], 6); // 23 +const example4 = minEatingSpeed([1,4,3,2], 9); // 2 +const example5 = minEatingSpeed([25,10,23,4], 4); // 25 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/4.BinarySearch/0981.js b/example/4.BinarySearch/0981.js new file mode 100644 index 00000000..9b36ac85 --- /dev/null +++ b/example/4.BinarySearch/0981.js @@ -0,0 +1,85 @@ +var TimeMap = function() { + +}; + +/** + * @param {string} key + * @param {string} value + * @param {number} timestamp + * @return {void} + */ +TimeMap.prototype.set = function(key, value, timestamp) { + +}; + +/** + * @param {string} key + * @param {number} timestamp + * @return {string} + */ +TimeMap.prototype.get = function(key, timestamp) { + +}; + +/** + * Your TimeMap object will be instantiated and called as such: + * var obj = new TimeMap() + * obj.set(key,value,timestamp) + * var param_2 = obj.get(key,timestamp) + */ + +// Input +// ["TimeMap", "set", "get", "get", "set", "get", "get"] +// [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] +// Output +// [null, null, "bar", "bar", null, "bar2", "bar2"] + + +const timeMap = new TimeMap(); +timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. +timeMap.get("foo", 1); // return "bar" +timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar". +timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. +timeMap.get("foo", 4); // return "bar2" +timeMap.get("foo", 5); // return "bar2" + +// var TimeMap = function() { +// this.keyStore = new Map(); +// }; + +// /** +// * @param {string} key +// * @param {string} value +// * @param {number} timestamp +// * @return {void} +// */ +// TimeMap.prototype.set = function(key, value, timestamp) { +// if (!this.keyStore.has(key)) { +// this.keyStore.set(key, []); +// } +// this.keyStore.get(key).push([timestamp, value]); +// }; + +// /** +// * @param {string} key +// * @param {number} timestamp +// * @return {string} +// */ +// TimeMap.prototype.get = function(key, timestamp) { +// const values = this.keyStore.get(key) || []; +// let left = 0; +// let right = values.length - 1; +// let result = ''; + +// while (left <= right) { +// const mid = Math.floor((left + right) / 2); +// if (values[mid][0] <= timestamp) { +// result = values[mid][1]; +// left = mid + 1; +// } else { +// right = mid - 1; +// } +// } + +// return result; +// }; diff --git a/example/5.Stack/0020.js b/example/5.Stack/0020.js new file mode 100644 index 00000000..8484efe6 --- /dev/null +++ b/example/5.Stack/0020.js @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function(s) { + +}; + +const example1 = isValid('()'); // true +const example2 = isValid('()[]{}'); // true +const example3 = isValid('(]'); // false +const example4 = isValid('([])'); // true + +const example5 = isValid('[]'); // true +const example6 = isValid('([{}])'); // true +const example7 = isValid('[(])'); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); diff --git a/example/5.Stack/0022.js b/example/5.Stack/0022.js new file mode 100644 index 00000000..c3bae815 --- /dev/null +++ b/example/5.Stack/0022.js @@ -0,0 +1,10 @@ +/** + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function(n) { + +}; + +const example1 = generateParenthesis(3); // ["((()))","(()())","(())()","()(())","()()()"] +const example2 = generateParenthesis(1); // ["()"] \ No newline at end of file diff --git a/example/5.Stack/0071.js b/example/5.Stack/0071.js new file mode 100644 index 00000000..1b683439 --- /dev/null +++ b/example/5.Stack/0071.js @@ -0,0 +1,19 @@ +/** + * @param {string} path + * @return {string} + */ +var simplifyPath = function(path) { + +}; + +const example1 = simplifyPath("/home/"); // "/home" +const example2 = simplifyPath("/home//foo/"); // "/home/foo" +const example3 = simplifyPath("/home/user/Documents/../Pictures"); // "/home/user/Pictures" +const example4 = simplifyPath("/../"); // "/" +const example5 = simplifyPath("/.../a/../b/c/../d/./"); // "/.../b/d" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/5.Stack/0084.js b/example/5.Stack/0084.js new file mode 100644 index 00000000..1efaa070 --- /dev/null +++ b/example/5.Stack/0084.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights) { + +}; + +const example1 = isValid([2,1,5,6,2,3]); // 10 +const example2 = isValid([2,4]); // 4 +const example3 = isValid([7,1,7,2,2,4]); // 8 +const example4 = isValid([1,3,7]); // 7 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/5.Stack/0150.js b/example/5.Stack/0150.js new file mode 100644 index 00000000..970d0d18 --- /dev/null +++ b/example/5.Stack/0150.js @@ -0,0 +1,15 @@ +/** + * @param {string[]} tokens + * @return {number} + */ +var evalRPN = function(tokens) { + +}; + +const example1 = evalRPN(["2","1","+","3","*"]); // 9 +const example2 = evalRPN(["4","13","5","/","+"]); // 6 +const example3 = evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]); // 22 + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/5.Stack/0739.js b/example/5.Stack/0739.js new file mode 100644 index 00000000..4557cdfb --- /dev/null +++ b/example/5.Stack/0739.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function(temperatures) { + +}; + +const example1 = dailyTemperatures([73,74,75,71,69,72,76,73]); // [1,1,4,2,1,1,0,0] +const example2 = dailyTemperatures([30,40,50,60]); // [1,1,1,0] +const example3 = dailyTemperatures([30,60,90]); // [1,1,0] +const example4 = dailyTemperatures([30,38,30,36,35,40,28]); // [1,4,1,2,1,0,0] +const example5 = dailyTemperatures([22,21,20]); // [0,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/5.Stack/0853.js b/example/5.Stack/0853.js new file mode 100644 index 00000000..767f2653 --- /dev/null +++ b/example/5.Stack/0853.js @@ -0,0 +1,21 @@ +/** + * @param {number} target + * @param {number[]} position + * @param {number[]} speed + * @return {number} + */ +var carFleet = function(target, position, speed) { + +}; + +const example1 = carFleet(12, [10,8,0,5,3], [2,4,1,1,3]); // 3 +const example2 = carFleet(10, [3], [3]); // 1 +const example3 = carFleet(100, [0,2,4], [4,2,1]); // 1 +const example4 = carFleet(10, [1,4], [3,2]); // 1 +const example5 = carFleet(10, [4,1,0,7], [2,2,1,1]); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/5.Stack/0933.js b/example/5.Stack/0933.js new file mode 100644 index 00000000..4e32a4b8 --- /dev/null +++ b/example/5.Stack/0933.js @@ -0,0 +1,33 @@ +var RecentCounter = function() { + +}; + +/** + * @param {number} t + * @return {number} + */ +RecentCounter.prototype.ping = function(t) { + +}; + +var obj = new RecentCounter() +var param_1 = obj.ping(1) + +console.log(param_1); // 1 +console.log(obj.ping(3001)); // 2 +console.log(obj.ping()); // 3 + +function callPingMultipleTimes(obj, times, start = 1, step = 1) { + let results = []; + let t = start; + + for (let i = 0; i < times; i++) { + results.push(obj.ping(t)); + t += step; + } + + return results; +} + +var obj = new RecentCounter(); +console.log(callPingMultipleTimes(obj, 500, 1, 1000)); diff --git a/example/5.Stack/1047.js b/example/5.Stack/1047.js new file mode 100644 index 00000000..ac769944 --- /dev/null +++ b/example/5.Stack/1047.js @@ -0,0 +1,13 @@ +/** + * @param {string} s + * @return {string} + */ +var removeDuplicates = function(s) { + +}; + +const example1 = removeDuplicates('abbaca'); // "ca" +const example2 = removeDuplicates('azxxzy'); // "ay" + +console.log(example1); +console.log(example2); diff --git a/example/5.Stack/2390.js b/example/5.Stack/2390.js new file mode 100644 index 00000000..865937cf --- /dev/null +++ b/example/5.Stack/2390.js @@ -0,0 +1,13 @@ +/** + * @param {string} s + * @return {string} + */ +var removeStars = function(s) { + +}; + +const example1 = removeStars('leet**cod*e'); // 'lecoe' +const example2 = removeStars('erase*****'); // '' + +console.log(example1); +console.log(example2); diff --git a/example/6.Tree/0098.js b/example/6.Tree/0098.js new file mode 100644 index 00000000..ffb0b17c --- /dev/null +++ b/example/6.Tree/0098.js @@ -0,0 +1,25 @@ +/** + * 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) { + +}; + +const testCases = [ + { input: [2,1,3], expected: true }, + { input: [5,1,4,null,null,3,6], expected: false }, + { input: [1,2,3], expected: false }, + { input: [] , expected: true }, +]; + +const results = testCases.map(({ input }) => isValidBST(createTreeFromArray(input))); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0100.js b/example/6.Tree/0100.js new file mode 100644 index 00000000..87956500 --- /dev/null +++ b/example/6.Tree/0100.js @@ -0,0 +1,24 @@ +/** + * 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 example1 = isSameTree(); // p = [1,2,3], q = [1,2,3] // true +const example2 = isSameTree(); // p = [1,2], q = [1,null,2] // false +const example3 = isSameTree(); // p = [1,2,1], q = [1,1,2] // false + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/0101.js b/example/6.Tree/0101.js new file mode 100644 index 00000000..a9e46c46 --- /dev/null +++ b/example/6.Tree/0101.js @@ -0,0 +1,25 @@ +/** + * 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) { + +}; + +const testCases = [ + { input: [1,2,2,3,4,4,3], expected: true }, + { input: [1,2,2,null,3,null,3], expected: false }, + { input: [1,2,3,null,null,4], expected: false }, + { input: [] , expected: true }, +]; + +const results = testCases.map(({ input }) => isSymmetric(createTreeFromArray(input))); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0102.js b/example/6.Tree/0102.js new file mode 100644 index 00000000..ab001e76 --- /dev/null +++ b/example/6.Tree/0102.js @@ -0,0 +1,25 @@ +/** + * 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 testCases = [ + { input: [3,9,20,null,null,15,7], expected: [[3],[9,20],[15,7]] }, + { input: [1], expected: [[1]] }, + { input: [] , expected: [] }, + { input: [1,2,3,4,5,6,7], expected: [[1],[2,3],[4,5,6,7]] } +]; + +const results = testCases.map(({ input }) => levelOrder(createTreeFromArray(input))); +console.log(results); diff --git a/example/6.Tree/0103.js b/example/6.Tree/0103.js new file mode 100644 index 00000000..fb419726 --- /dev/null +++ b/example/6.Tree/0103.js @@ -0,0 +1,23 @@ +/** + * 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 zigzagLevelOrder = function(root) { + +}; + +const example1 = zigzagLevelOrder(); // root = [3,9,20,null,null,15,7] // [[3],[20,9],[15,7]] +const example2 = zigzagLevelOrder(); // root = [[1] // [[1]] +const example3 = zigzagLevelOrder(); // root = [] // [] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/0104.js b/example/6.Tree/0104.js new file mode 100644 index 00000000..604c41a5 --- /dev/null +++ b/example/6.Tree/0104.js @@ -0,0 +1,26 @@ +/** + * 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) { + +}; + +const testCases = [ + { input: [3,9,20,null,null,15,7], expected: 3 }, + { input: [1,null,2], expected: 2 }, + { input: [1,2,3,null,null,4], expected: 3 }, + { input: [], expected: 0 } +]; + +const results = testCases.map(({ input }) => maxDepth(createTreeFromArray(input))); + +console.log(results); diff --git a/example/6.Tree/0110.js b/example/6.Tree/0110.js new file mode 100644 index 00000000..6d8ca09f --- /dev/null +++ b/example/6.Tree/0110.js @@ -0,0 +1,26 @@ +/** + * 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 isBalanced = function(root) { + +}; + +const testCases = [ + { input: [3,9,20,null,null,15,7], expected: true }, + { input: [1,2,2,3,3,null,null,4,4], expected: false }, + { input: [] , expected: true }, + { input: [1,2,3,null,null,4], expected: true }, + { input: [1,2,3,null,null,4,null,5], expected: false } +]; + +const results = testCases.map(({ input }) => isBalanced(createTreeFromArray(input))); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0112.js b/example/6.Tree/0112.js new file mode 100644 index 00000000..5b2ea437 --- /dev/null +++ b/example/6.Tree/0112.js @@ -0,0 +1,25 @@ +/** + * 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) { + +}; + +const testCases = [ + { input: [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum: 22, expected: true }, + { input: [1,2,3], targetSum: 5, expected: false }, + { input: [] , targetSum: 0, expected: false }, +]; + +const results = testCases.map(({ input, targetSum }) => hasPathSum(createTreeFromArray(input), targetSum)); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0117.js b/example/6.Tree/0117.js new file mode 100644 index 00000000..cdc5c394 --- /dev/null +++ b/example/6.Tree/0117.js @@ -0,0 +1,23 @@ +/** + * // 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 example1 = connect(); // root = [1,2,3,4,5,null,7] // [1,#,2,3,#,4,5,7,#] +const example2 = connect(); // root = [] // [] + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0199.js b/example/6.Tree/0199.js new file mode 100644 index 00000000..d76de689 --- /dev/null +++ b/example/6.Tree/0199.js @@ -0,0 +1,29 @@ +/** + * 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 rightSideView = function(root) { + +}; + +const example1 = rightSideView(); // [1,2,3,null,5,null,4] // [1,3,4] +const example2 = rightSideView(); // root = [1,2,3,4,null,null,null,5] // [1,3,4,5] +const example3 = rightSideView(); // root = [1,null,3] // [1,3] +const example4 = rightSideView(); // root = [] // [] +const example5 = rightSideView(); // root = [1,2,3] // [1,3] +const example6 = rightSideView(); // root = [1,2,3,4,5,6,7] // [1,3,7] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); \ No newline at end of file diff --git a/example/6.Tree/0226.js b/example/6.Tree/0226.js new file mode 100644 index 00000000..2fbcba37 --- /dev/null +++ b/example/6.Tree/0226.js @@ -0,0 +1,27 @@ +/** + * 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 {TreeNode} + */ +var invertTree = function(root) { + +}; + +const testCases = [ + { input: [4,2,7,1,3,6,9], expected: [ 4,7,2,9,6,3,1] }, + { input: [2,1,3], expected: [2,3,1] }, + { input: [], expected: [] }, + { input: [1,2,3,4,5,6,7], expected: [1,3,2,7,6,5,4] }, + { input: [3,2,1], expected: [3,1,2] } +]; + +const results = testCases.map(({ input }) => invertTree(createTreeFromArray(input))); +var myTreeStringify = JSON.stringify(results, null, 2); +console.log(myTreeStringify); diff --git a/example/6.Tree/0236.js b/example/6.Tree/0236.js new file mode 100644 index 00000000..168f7bc1 --- /dev/null +++ b/example/6.Tree/0236.js @@ -0,0 +1,28 @@ +/** + * 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) { + +}; + +const example1 = lowestCommonAncestor(); // root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 // 3 +const example2 = lowestCommonAncestor(); // root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 // 5 +const example3 = lowestCommonAncestor(); // root = [1,2], p = 1, q = 2 // 1 +const example4 = lowestCommonAncestor(); // root = [5,3,8,1,4,7,9,null,2], p = 3, q = 8 // 5 +const example5 = lowestCommonAncestor(); // root = [5,3,8,1,4,7,9,null,2], p = 3, q = 4 // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/6.Tree/0515.js b/example/6.Tree/0515.js new file mode 100644 index 00000000..5dc6eec4 --- /dev/null +++ b/example/6.Tree/0515.js @@ -0,0 +1,48 @@ +/** + * 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 largestValues = function(root) { + +}; + +const testCases = [ + { input: [1,3,2,5,3,null,9], expected: [1,3,9] }, + { input: [1,2,3], expected: [1,3] }, + { input: [] , expected: [] }, +]; + +const results = testCases.map(({ input }) => largestValues(createTreeFromArray(input))); +console.log(results); + +// function largestValues(root) { +// if (!root) return []; + +// let result = []; +// let queue = [root]; + +// while (queue.length) { +// let levelSize = queue.length; +// let levelMax = -Infinity; + +// for (let i = 0; i < levelSize; i++) { +// let node = queue.shift(); +// levelMax = Math.max(levelMax, node.val); + +// if (node.left) queue.push(node.left); +// if (node.right) queue.push(node.right); +// } + +// result.push(levelMax); +// } + +// return result; +// } \ No newline at end of file diff --git a/example/6.Tree/0543.js b/example/6.Tree/0543.js new file mode 100644 index 00000000..4c1ebd85 --- /dev/null +++ b/example/6.Tree/0543.js @@ -0,0 +1,21 @@ +/** + * 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 diameterOfBinaryTree = function(root) { + +}; + +const example1 = diameterOfBinaryTree(); // root = [1,2,3,4,5] // 3 +const example2 = diameterOfBinaryTree(); // root = [1,2] // 1 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0700.js b/example/6.Tree/0700.js new file mode 100644 index 00000000..17fefb57 --- /dev/null +++ b/example/6.Tree/0700.js @@ -0,0 +1,22 @@ +/** + * 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) { + +}; + +const example1 = searchBST(); // root = [4,2,7,1,3], val = 2 // [2,1,3] +const example2 = searchBST(); // root = [4,2,7,1,3], val = 5 // [] + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0701.js b/example/6.Tree/0701.js new file mode 100644 index 00000000..cea39be5 --- /dev/null +++ b/example/6.Tree/0701.js @@ -0,0 +1,24 @@ +/** + * 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) { + +}; + +const example1 = insertIntoBST(); // root = [4,2,7,1,3], val = 5 // [4,2,7,1,3,5] +const example2 = insertIntoBST(); // root = [40,20,60,10,30,50,70], val = 25 // [40,20,60,10,30,50,70,null,null,25] +const example3 = insertIntoBST(); //root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 // [4,2,7,1,3,5] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/1302.js b/example/6.Tree/1302.js new file mode 100644 index 00000000..d41df5f8 --- /dev/null +++ b/example/6.Tree/1302.js @@ -0,0 +1,21 @@ +/** + * 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 deepestLeavesSum = function(root) { + +}; + +const example1 = isValidBST(); // root = [1,2,3,4,5,null,6,7,null,null,null,null,8] // 15 +const example2 = isValidBST(); // root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] // 19 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/1325.js b/example/6.Tree/1325.js new file mode 100644 index 00000000..828853f1 --- /dev/null +++ b/example/6.Tree/1325.js @@ -0,0 +1,43 @@ +/** + * 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} target + * @return {TreeNode} + */ +var removeLeafNodes = function(root, target) { + +}; + +const testCases = [ + { input: [1,2,3,2,null,2,4], target: 2, expected: [1,null,3,null,4] }, + { input: [1,3,3,3,2], target: 3, expected: [1,3,null,null,2] }, + { input: [1,2,null,2,null,2], target: 2, expected: [1] }, + { input: [] , expected: [] }, +]; + +const results = testCases.map(({ input }) => removeLeafNodes(createTreeFromArray(input))); +const print = results.map(res => levelOrder(res)) + +console.log(results); +console.log(print); + +// Not working +// function removeLeafNodes(root, target) { +// if (!root) return null; + +// root.left = removeLeafNodes(root.left, target); +// root.right = removeLeafNodes(root.right, target); + +// if (!root.left && !root.right && root.val === target) { +// return null; +// } + +// return root; +// } \ No newline at end of file diff --git a/example/7.Tries/0208.js b/example/7.Tries/0208.js new file mode 100644 index 00000000..51364c3f --- /dev/null +++ b/example/7.Tries/0208.js @@ -0,0 +1,44 @@ + +var Trie = function() { + +}; + +/** + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function(word) { + +}; + +/** + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function(word) { + +}; + +/** + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function(prefix) { + +}; + +/** + * Your Trie object will be instantiated and called as such: + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) + */ + +const trie = new Trie(); +trie.insert("apple"); +trie.search("apple"); // return True +trie.search("app"); // return False +trie.startsWith("app"); // return True +trie.insert("app"); +trie.search("app"); \ No newline at end of file diff --git a/example/7.Tries/0211.js b/example/7.Tries/0211.js new file mode 100644 index 00000000..b0f4036b --- /dev/null +++ b/example/7.Tries/0211.js @@ -0,0 +1,27 @@ + +var WordDictionary = function() { + +}; + +/** + * @param {string} word + * @return {void} + */ +WordDictionary.prototype.addWord = function(word) { + +}; + +/** + * @param {string} word + * @return {boolean} + */ +WordDictionary.prototype.search = function(word) { + +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * var obj = new WordDictionary() + * obj.addWord(word) + * var param_2 = obj.search(word) + */ \ No newline at end of file diff --git a/example/7.Tries/0212.js b/example/7.Tries/0212.js new file mode 100644 index 00000000..e4ec0175 --- /dev/null +++ b/example/7.Tries/0212.js @@ -0,0 +1,15 @@ +/** + * @param {character[][]} board + * @param {string[]} words + * @return {string[]} + */ +var findWords = function(board, words) { + +}; + +const example1 = suggestedProducts([["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], ["oath","pea","eat","rain"]); // ["eat","oath"] +const example2 = suggestedProducts([["a","b"],["c","d"]], ["abcb"]); // [] + +console.log(example1); +console.log(example2); + diff --git a/example/7.Tries/1268.js b/example/7.Tries/1268.js new file mode 100644 index 00000000..cb3066a0 --- /dev/null +++ b/example/7.Tries/1268.js @@ -0,0 +1,15 @@ +/** + * @param {string[]} products + * @param {string} searchWord + * @return {string[][]} + */ +var suggestedProducts = function(products, searchWord) { + +}; + +const example1 = suggestedProducts(["mobile","mouse","moneypot","monitor","mousepad"], "mouse"); // [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]] +const example2 = suggestedProducts(["havana"], "havana"); // [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] + +console.log(example1); +console.log(example2); + diff --git a/example/8.Heap/0023.js b/example/8.Heap/0023.js new file mode 100644 index 00000000..c057f5f6 --- /dev/null +++ b/example/8.Heap/0023.js @@ -0,0 +1,23 @@ +/** + * 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 example1 = mergeKLists([[1,4,5],[1,3,4],[2,6]]); // 1,1,2,3,4,4,5,6] +const example2 = mergeKLists([]); // [] +const example3 = mergeKLists([[]]); // [] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/0215.js b/example/8.Heap/0215.js new file mode 100644 index 00000000..971883b6 --- /dev/null +++ b/example/8.Heap/0215.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findKthLargest = function(nums, k) { + +}; + +const example1 = findKthLargest([3,2,1,5,6,4], 2); // 5 +const example2 = findKthLargest([3,2,3,1,2,4,5,5,6], 4); // 4 +const example3 = findKthLargest([2,3,1,5,4], 2); // 4 +const example4 = findKthLargest([2,3,1,1,5,5,4], 3); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/0295.js b/example/8.Heap/0295.js new file mode 100644 index 00000000..a9a5394f --- /dev/null +++ b/example/8.Heap/0295.js @@ -0,0 +1,34 @@ + +var MedianFinder = function() { + +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function(num) { + +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function() { + +}; + +const medianFinder = new MedianFinder(); +medianFinder.addNum(1); // arr = [1] +medianFinder.addNum(2); // arr = [1, 2] +medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) +medianFinder.addNum(3); // arr[1, 2, 3] +medianFinder.findMedian(); // return 2.0 + +const medianFinder2 = new MedianFinder(); +medianFinder2.addNum(1); // arr = [1] +medianFinder2.findMedian(); // return 1.0 +medianFinder2.addNum(3); // arr = [1, 3] +medianFinder2.findMedian(); // return 2.0 +medianFinder2.addNum(2); // arr[1, 2, 3] +medianFinder2.findMedian(); // return 2.0 diff --git a/example/8.Heap/0347.js b/example/8.Heap/0347.js new file mode 100644 index 00000000..20d78459 --- /dev/null +++ b/example/8.Heap/0347.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + +}; + + +const example1 = topKFrequent([1, 1, 1, 2, 2, 3], 2); // [1,2] +const example2 = topKFrequent([1], 1); // [1] +const example3 = topKFrequent([3, 3, 5, 5, 5, 6], 2); // [3, 5] + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/8.Heap/0355.js b/example/8.Heap/0355.js new file mode 100644 index 00000000..61215a67 --- /dev/null +++ b/example/8.Heap/0355.js @@ -0,0 +1,67 @@ +var Twitter = function() { + +}; + +/** + * @param {number} userId + * @param {number} tweetId + * @return {void} + */ +Twitter.prototype.postTweet = function(userId, tweetId) { + +}; + +/** + * @param {number} userId + * @return {number[]} + */ +Twitter.prototype.getNewsFeed = function(userId) { + +}; + +/** + * @param {number} followerId + * @param {number} followeeId + * @return {void} + */ +Twitter.prototype.follow = function(followerId, followeeId) { + +}; + +/** + * @param {number} followerId + * @param {number} followeeId + * @return {void} + */ +Twitter.prototype.unfollow = function(followerId, followeeId) { + +}; + +/** + * Your Twitter object will be instantiated and called as such: + * var obj = new Twitter() + * obj.postTweet(userId,tweetId) + * var param_2 = obj.getNewsFeed(userId) + * obj.follow(followerId,followeeId) + * obj.unfollow(followerId,followeeId) + */ + +const twitter = new Twitter(); +twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] +twitter.follow(1, 2); // User 1 follows user 2. +twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. +twitter.unfollow(1, 2); // User 1 unfollows user 2. +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. + +const twitter2 = new Twitter(); +twitter2.postTweet(1, 10); // User 1 posts a new tweet with id = 10. +twitter2.postTweet(2, 20); // User 2 posts a new tweet with id = 20. +twitter2.getNewsFeed(1); // User 1's news feed should only contain their own tweets -> [10]. +twitter2.getNewsFeed(2); // User 2's news feed should only contain their own tweets -> [20]. +twitter2.follow(1, 2); // User 1 follows user 2. +twitter2.getNewsFeed(1); // User 1's news feed should contain both tweets from user 1 and user 2 -> [20, 10]. +twitter2.getNewsFeed(2); // User 2's news feed should still only contain their own tweets -> [20]. +twitter2.unfollow(1, 2); // User 1 follows user 2. +twitter2.getNewsFeed(1); // User 1's news feed should only contain their own tweets -> [10]. \ No newline at end of file diff --git a/example/8.Heap/0451.js b/example/8.Heap/0451.js new file mode 100644 index 00000000..781b9cf7 --- /dev/null +++ b/example/8.Heap/0451.js @@ -0,0 +1,22 @@ +/** + * @param {string} s + * @return {string} + */ +var frequencySort = function(s) { + +}; + +const example1 = frequencySort("tree"); // "eert" +const example2 = frequencySort("cccaaa"); // "aaaccc" +const example3 = frequencySort("Aabb"); // "bbAa" +const example4 = frequencySort("BbAaCc"); // "ccbaCBA" +const example5 = frequencySort("BbAAAaaCc"); // "AAAaacbCB" +const example6 = frequencySort("BabBbBbBbbABBABBbAabbbABBaBbBabaabBbbBAAaaAbbAABaAbBBaAaaaaBABbaBbAAbBBbbABBaaBBbabAbBBAAbAbaaaBrBBaAaabAbbBbABabABaBabBBBBBaAbAaABaaaAAaAgAaAaBAbaBaBaBbbbBbABBBBaaaBbbbAbbbBaBBaAbBBbbaaaaaBbbaaAAbAABBABBaAAABBbbBbBbbBbaABBAAbBAbabbbabwBbbBArABaBBbabBaBabABABaabBBABBAabBAAaabbbbBAababAaBaaAaBbBbBAAbaBabBbabaBaaBbaabABAbbBbaBAbabABbbaAaBbAAAbBbaabBBAbbbABbaabAAAaaaBaBaaaBBABbBAbAAbaABaabbbbBBAabbbBABBbaABBAAAabaAbaBAbbaBaBbAbaAAbBaBAbAabBBbBsBabbbAaBbabAAaABAaBAAAbbaBaAbABABBBAbABABbbbBaaBaBAbABAbaaAbBbAABBbAbbAaBbabaBbABAAbAABbbAabAaAaBbBBbAAbBbaaaBAbABBbBBaCabBBabBAaBbBaAbbBAbbBaBAabBAababAaAbaAaabBBBABabaabBAAAabBAAAbBAbAaaaAbAaBaAbbAaABABBbBBAABAabaAAbBaBbAAaabbABBBABaBAabAbAAbBbAabAbaBbAbBAABAABAAAbBaaaaBabbaBABBaABbAabBaBAbAbbABAbaAAbaAAaBaabaBbBBbBABAABBABBaabBBbBBABAAaAAbbBbABBBbAabAbABbAAAbbAbABbbAbBAbabbbBBBBbAAabaabBABABaaAbaBBBBbbABbBbBABBaAbAaBBABBBabAABBBBBbBBabBaaBbaaBaBbaBbbAABbbAaaBBBbabaabBABABBBGabbBAbaBabAaAAabbbBaabBBbABBabBabbBbAbbAaBbAaAabBabBBbaBLaAbbAaaBaabAAab"); // "AAAaacbCB" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + diff --git a/example/8.Heap/0502.js b/example/8.Heap/0502.js new file mode 100644 index 00000000..06d45854 --- /dev/null +++ b/example/8.Heap/0502.js @@ -0,0 +1,16 @@ +/** + * @param {number} k + * @param {number} w + * @param {number[]} profits + * @param {number[]} capital + * @return {number} + */ +var findMaximizedCapital = function(k, w, profits, capital) { + +}; + +const example1 = findMaximizedCapital(2, 0, [1,2,3], [0,1,1]); // 4 +const example2 = findMaximizedCapital(3, 0, [1,2,3], [0,1,2]); // 6 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/8.Heap/0621.js b/example/8.Heap/0621.js new file mode 100644 index 00000000..e47ca682 --- /dev/null +++ b/example/8.Heap/0621.js @@ -0,0 +1,20 @@ +/** + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function(tasks, n) { + +}; + +const example1 = leastInterval(["A","A","A","B","B","B"], 2); // 8 +const example2 = leastInterval(["A","C","A","B","D","B"], 1); // 6 +const example3 = leastInterval(["A","A","A", "B","B","B"], 3); // 10 +const example4 = leastInterval(["X","X","Y","Y"], 2); // 5 +const example5 = leastInterval(["A","A","A","B","C"], 3); // 9 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/8.Heap/0642.js b/example/8.Heap/0642.js new file mode 100644 index 00000000..4da6a8e2 --- /dev/null +++ b/example/8.Heap/0642.js @@ -0,0 +1 @@ +console.log(example1); \ No newline at end of file diff --git a/example/8.Heap/0703.js b/example/8.Heap/0703.js new file mode 100644 index 00000000..dd70f97d --- /dev/null +++ b/example/8.Heap/0703.js @@ -0,0 +1,33 @@ +/** + * @param {number} k + * @param {number[]} nums + */ +var KthLargest = function(k, nums) { + +}; + +/** + * @param {number} val + * @return {number} + */ +KthLargest.prototype.add = function(val) { + +}; + +const kthLargest = new KthLargest(3, [4, 5, 8, 2]); +kthLargest.add(3); // return 4 +kthLargest.add(5); // return 5 +kthLargest.add(10); // return 5 +kthLargest.add(9); // return 8 +kthLargest.add(4); // return 8 + +console.log(kthLargest); + +const kthLargest2 = new KthLargest(4, [7, 7, 7, 7, 8, 3]); +kthLargest2.add(2); // return 7 +kthLargest2.add(10); // return 7 +kthLargest2.add(9); // return 7 +kthLargest2.add(9); // return 8 + +console.log(kthLargest2); + diff --git a/example/8.Heap/0973.js b/example/8.Heap/0973.js new file mode 100644 index 00000000..20818eb3 --- /dev/null +++ b/example/8.Heap/0973.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function(points, k) { + +}; + +const example1 = kClosest([[1,3],[-2,2]], 1); // [[-2,2]] +const example2 = kClosest([[3,3],[5,-1],[-2,4]], 2); // [[3,3],[-2,4]] +const example3 = kClosest([[0,2],[2,2]], 1); // [[0,2]] +const example4 = kClosest([[0,2],[2,0],[2,2]], 2); // [[[0,2],[2,0]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/1046.js b/example/8.Heap/1046.js new file mode 100644 index 00000000..7477352a --- /dev/null +++ b/example/8.Heap/1046.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} stones + * @return {number} + */ +var lastStoneWeight = function(stones) { + +}; + +const example1 = lastStoneWeight([2,7,4,1,8,1]); // 1 +const example2 = lastStoneWeight([1]); // 1 +const example3 = lastStoneWeight([2,3,6,2,4]); // 1 +const example4 = lastStoneWeight([1,2]); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/1962.js b/example/8.Heap/1962.js new file mode 100644 index 00000000..a11e39ae --- /dev/null +++ b/example/8.Heap/1962.js @@ -0,0 +1,14 @@ +/** + * @param {number[]} piles + * @param {number} k + * @return {number} + */ +var minStoneSum = function(piles, k) { + +}; + +const example1 = minStoneSum([5,4,9], 2); // 12 +const example2 = minStoneSum([4,3,6,7], 3); // 12 + +console.log(example1); +console.log(example2); diff --git a/example/9.Intervals/0056.js b/example/9.Intervals/0056.js new file mode 100644 index 00000000..a9845157 --- /dev/null +++ b/example/9.Intervals/0056.js @@ -0,0 +1,17 @@ +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var merge = function(intervals) { + +}; + +const example1 = merge([[1,3],[2,6],[8,10],[15,18]]); // [[1,6],[8,10],[15,18]] +const example2 = merge([[1,4],[4,5]]); // [[1,5]] +const example3 = merge([[1,3],[1,5],[6,7]]); // [[1,5],[6,7]] +const example4 = merge([[1,2],[2,3]]); // [[1,3]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0057.js b/example/9.Intervals/0057.js new file mode 100644 index 00000000..1918c08b --- /dev/null +++ b/example/9.Intervals/0057.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} intervals + * @param {number[]} newInterval + * @return {number[][]} + */ +var insert = function(intervals, newInterval) { + +}; + +const example1 = insert([[1,3],[6,9]], [2,5]); // [[1,5],[6,9]] +const example2 = insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]); // [[1,2],[3,10],[12,16]] +const example3 = insert([[1,3],[4,6]], [2,5]); // [[1,6]] +const example4 = insert([[1,2],[3,5],[9,10]], [6,7]); // [[1,2],[3,5],[6,7],[9,10]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0252.js b/example/9.Intervals/0252.js new file mode 100644 index 00000000..e8cc38f2 --- /dev/null +++ b/example/9.Intervals/0252.js @@ -0,0 +1,17 @@ +/** + * @param {Interval[]} intervals + * @returns {boolean} + */ +var canAttendMeetings = function (intervals) { + +}; + +const example1 = canAttendMeetings(); // +const example2 = canAttendMeetings(); // +const example3 = canAttendMeetings([(0,30),(5,10),(15,20)]); // false +const example4 = canAttendMeetings([(5,8),(9,15)]); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0253.js b/example/9.Intervals/0253.js new file mode 100644 index 00000000..78493361 --- /dev/null +++ b/example/9.Intervals/0253.js @@ -0,0 +1,17 @@ +/** + * @param {Interval[]} intervals + * @returns {number} + */ +var minMeetingRooms = function(intervals) { + +}; + +const example1 = merge(); // [[1,6],[8,10],[15,18]] +const example2 = merge(); // [[1,5]] +const example3 = merge([(0,40),(5,10),(15,20)]); // 2 +const example4 = merge([(4,9)]); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0435.js b/example/9.Intervals/0435.js new file mode 100644 index 00000000..688fb4c1 --- /dev/null +++ b/example/9.Intervals/0435.js @@ -0,0 +1,19 @@ +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var eraseOverlapIntervals = function(intervals) { + +}; + +const example1 = eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]]); // 1 +const example2 = eraseOverlapIntervals([[1,2],[1,2],[1,2]]); // 2 +const example3 = eraseOverlapIntervals([[1,2],[2,3]]); // 0 +const example4 = eraseOverlapIntervals([[1,2],[2,4],[1,4]]); // 1 +const example5 = eraseOverlapIntervals([[1,2],[2,4]]); // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/9.Intervals/1851.js b/example/9.Intervals/1851.js new file mode 100644 index 00000000..5ca4c146 --- /dev/null +++ b/example/9.Intervals/1851.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} intervals + * @param {number[]} queries + * @return {number[]} + */ +var minInterval = function(intervals, queries) { + +}; + +const example1 = minInterval([[1,4],[2,4],[3,6],[4,4]], [2,3,4,5]); // [3,3,1,4] +const example2 = minInterval([[2,3],[2,5],[1,8],[20,25]], [2,19,5,22]); // [2,-1,4,6] +const example3 = minInterval([[1,3],[2,3],[3,7],[6,6]], [2,3,1,7,6,8]); // [2,2,3,5,1,-1] +const example4 = minInterval([[1,2],[2,3]]); // [[1,3]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/Dayly/1358.js b/example/Dayly/1358.js new file mode 100644 index 00000000..46552125 --- /dev/null +++ b/example/Dayly/1358.js @@ -0,0 +1,47 @@ +/** + * @param {string} s + * @return {number} + */ +var numberOfSubstrings = function(s) { + +}; + +const example1 = numberOfSubstrings('abcabc'); // 10 +const example2 = numberOfSubstrings('aaacb'); // 3 +const example3 = numberOfSubstrings('abc'); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var numberOfSubstrings = function(s) { +// return solve(s, 3) - solve(s, 2) +// }; + +// var solve = function(word, n) { +// const vowels = new Set(['a', 'b', 'c']) +// const freqMap = new Map() +// let l = 0, r = 0, result = 0 + +// while (r < word.length) { +// if (vowels.has(word[r])) { +// freqMap.set(word[r], (freqMap.get(word[r]) || 0) + 1) +// } else { +// freqMap.clear() +// l = r + 1 +// } + +// while (freqMap.size > n) { +// freqMap.set(word[l], freqMap.get(word[l]) - 1) +// if (freqMap.get(word[l]) === 0) { +// freqMap.delete(word[l]) +// } +// l++ +// } + +// result += r - l + 1 +// r++ +// } + +// return result +// } \ No newline at end of file diff --git a/example/Dayly/2062.js b/example/Dayly/2062.js new file mode 100644 index 00000000..ad0246f2 --- /dev/null +++ b/example/Dayly/2062.js @@ -0,0 +1,47 @@ +/** + * @param {string} word + * @return {number} + */ +var countVowelSubstrings = function(word) { + +}; + +const example1 = countVowelSubstrings('aeiouu'); // 2 +const example2 = countVowelSubstrings('unicornarihan'); // 0 +const example3 = countVowelSubstrings('cuaieuouac'); // 7 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var countVowelSubstrings = function(word) { +// return solve(word, 5) - solve(word, 4) +// }; + +// var solve = function(word, n) { +// const vowels = new Set(['a', 'e', 'i', 'o', 'u']) +// const freqMap = new Map() +// let l = 0, r = 0, result = 0 + +// while (r < word.length) { +// if (vowels.has(word[r])) { +// freqMap.set(word[r], (freqMap.get(word[r]) || 0) + 1) +// } else { +// freqMap.clear() +// l = r + 1 +// } + +// while (freqMap.size > n) { +// freqMap.set(word[l], freqMap.get(word[l]) - 1) +// if (freqMap.get(word[l]) === 0) { +// freqMap.delete(word[l]) +// } +// l++ +// } + +// result += r - l + 1 +// r++ +// } + +// return result +// } \ No newline at end of file diff --git a/example/Dayly/2226.js b/example/Dayly/2226.js new file mode 100644 index 00000000..8cfcbc54 --- /dev/null +++ b/example/Dayly/2226.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} candies + * @param {number} k + * @return {number} + */ +var maximumCandies = function(candies, k) { + l = 1 + r = Math.max(...candies) + result = 0 + + while (l <= r) { + mid = Math.floor((l+r)/2) + childredCount = candies.reduce((sum, pile) => sum + Math.floor(pile/mid), 0) + + if (childredCount >= k) { + result = mid + l = mid + 1 + } else { + r = mid - 1 + } + } + + return result +}; + +const example1 = maximumCandies([5,8,6], 3); // 5 +const example2 = maximumCandies([2,5], 11); // 0 + +console.log(example1); +console.log(example2); diff --git a/example/Dayly/2379.js b/example/Dayly/2379.js new file mode 100644 index 00000000..1f9faa5f --- /dev/null +++ b/example/Dayly/2379.js @@ -0,0 +1,40 @@ +/** + * @param {string} blocks + * @param {number} k + * @return {number} + */ +var minimumRecolors = function(blocks, k) { + +}; + +const example1 = minimumRecolors('WBBWWBBWBW', 7); // 3 +const example2 = minimumRecolors('WBWBBBW', 2); // 0 +const example3 = minimumRecolors('WWBWBB', 4); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var minimumRecolors = function(blocks, k) { +// let begin = 0 +// let window_state = 0 +// let result = Infinity; + +// for (let end = 0; end < blocks.length; end++) { +// if (blocks[end] === 'W') { +// window_state += 1 +// } + +// while (end - begin + 1 === k) { +// result = Math.min(result, window_state) +// if (blocks[begin] === 'W') { +// window_state -= 1 +// } +// begin++ +// } +// } + +// if (result === Infinity) return 0 +// return result +// }; + diff --git a/example/Dayly/2523.js b/example/Dayly/2523.js new file mode 100644 index 00000000..ec807b5e --- /dev/null +++ b/example/Dayly/2523.js @@ -0,0 +1,45 @@ +/** + * @param {number} left + * @param {number} right + * @return {number[]} + */ +var closestPrimes = function(left, right) { + +}; + +const example1 = closestPrimes(10, 19); // [11,13] +const example2 = closestPrimes(4, 6); //[-1,-1] +const example3 = closestPrimes(0 ,0); // [-1,-1] +const example4 = closestPrimes(16, 20); // [17,19] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + +// var closestPrimes = function(left, right) { +// function isPrime(n) { +// if (n < 2) return false; +// if (n === 2 || n === 3) return true; +// if (n % 2 === 0 || n % 3 === 0) return false; +// for (let i = 5; i * i <= n; i += 6) { +// if (n % i === 0 || n % (i + 2) === 0) return false; +// } +// return true; +// } + +// let prevPrime = -1, minDiff = Infinity; +// let result = [-1, -1]; + +// for (let i = left; i <= right; i++) { +// if (isPrime(i)) { +// if (prevPrime !== -1 && i - prevPrime < minDiff) { +// minDiff = i - prevPrime; +// result = [prevPrime, i]; +// } +// prevPrime = i; +// } +// } + +// return result; +// }; \ No newline at end of file diff --git a/example/Dayly/2529.js b/example/Dayly/2529.js new file mode 100644 index 00000000..a044f0d4 --- /dev/null +++ b/example/Dayly/2529.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var maximumCount = function(nums) { + +}; + +const example1 = maximumCount([-2,-1,-1,1,2,3]); // 3 +const example2 = maximumCount([-3,-2,-1,0,0,1,2]); // 3 +const example3 = maximumCount([5,20,66,1314]); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/Dayly/2560.js b/example/Dayly/2560.js new file mode 100644 index 00000000..94485b76 --- /dev/null +++ b/example/Dayly/2560.js @@ -0,0 +1,40 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +const minCapability = (nums, k) => { + const canStealKHouses = (capability) => { + let count = 0; + let i = 0; + while (i < nums.length) { + if (nums[i] <= capability) { + count++; + i += 2; + } else { + i++; + } + } + return count >= k; + }; + + let left = Math.min(...nums); + let right = Math.max(...nums); + + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (canStealKHouses(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +}; + +const example1 = minCapability([2,3,5,9], 2); // 5 +const example2 = minCapability([2,7,9,3,1], 2); // 2 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/Dayly/2594.js b/example/Dayly/2594.js new file mode 100644 index 00000000..4a052a91 --- /dev/null +++ b/example/Dayly/2594.js @@ -0,0 +1,40 @@ +/** + * @param {number[]} ranks + * @param {number} cars + * @return {number} + */ +var repairCars = function(ranks, cars) { + +}; + +const example1 = repairCars([4,2,3,1], 10); // 16 +const example2 = repairCars([5,1,8], 6); // 16 + +console.log(example1); +console.log(example2); + +// var repairCars = function(ranks, cars) { +// let left = 1 +// let right = Math.max(...ranks)*cars*cars + +// var canRepairAll = function(time) { +// let totalCarsRepaired = 0 +// for (let rank of ranks) { +// totalCarsRepaired += Math.floor(Math.sqrt(time/rank)) +// if (totalCarsRepaired >= cars) return true +// } +// return false +// } + +// while (left < right) { +// let mid = Math.floor((left + right)/2) + +// if (canRepairAll(mid)) { +// right = mid +// } else { +// left = mid + 1 +// } +// } + +// return left +// }; \ No newline at end of file diff --git a/example/Dayly/3208.js b/example/Dayly/3208.js new file mode 100644 index 00000000..d7197573 --- /dev/null +++ b/example/Dayly/3208.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} colors + * @param {number} k + * @return {number} + */ +var numberOfAlternatingGroups = function(colors, k) { + +}; + +const example1 = numberOfAlternatingGroups([0,1,0,1,0], 3); // 3 +const example2 = numberOfAlternatingGroups([0,1,0,0,1,0,1], 6); // 2 +const example3 = numberOfAlternatingGroups([1,1,0,1], 4); // 0 +const example4 = numberOfAlternatingGroups([1,1,1,1,1,1,0,1], 2); // 2 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + +// var numberOfAlternatingGroups = function(colors, k) { +// colors.push(...colors.slice(0, k - 1)); +// let begin = 0; +// let result = 0; + +// for (let end = 0; end < colors.length; end++) { +// if (colors[end] === colors[end - 1]) { +// begin = end +// } + +// if (end - begin + 1 >= k) { +// result++ +// } +// } + +// return result +// }; \ No newline at end of file diff --git a/example/Dayly/3306.js b/example/Dayly/3306.js new file mode 100644 index 00000000..7e3ec0d4 --- /dev/null +++ b/example/Dayly/3306.js @@ -0,0 +1,61 @@ +/** + * @param {string} word + * @param {number} k + * @return {number} + */ +var countVowelSubstrings = function(word, k) { + +}; + +const example1 = countVowelSubstrings('aeiouu', 0); // 2 +const example2 = countVowelSubstrings('unicornarihan', 0); // 0 +const example3 = countVowelSubstrings('cuaieuouac', 0); // 7 +const example4 = countVowelSubstrings('aeioqq', 1); // 0 +const example5 = countVowelSubstrings('aeiou', 0); // 1 +const example6 = countVowelSubstrings('ieaouqqieaouqq', 1); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + +// var countVowelSubstrings = function(word, k) { +// return solve(word, k) - solve(word, k + 1); +// }; + +// var solve = function(word, k) { +// const vowels = new Set(['a', 'e', 'i', 'o', 'u']); +// let vowelMap = new Map(); +// let result = 0; +// let consonants = 0; +// let left = 0; + +// for (let right = 0; right < word.length; right++) { +// let char = word[right]; + +// if (vowels.has(char)) { +// vowelMap.set(char, (vowelMap.get(char) || 0) + 1); +// } else { +// consonants++; +// } + +// while (vowelMap.size === 5 && consonants >= k) { +// result += word.length - right; +// let leftChar = word[left]; + +// if (vowels.has(leftChar)) { +// vowelMap.set(leftChar, vowelMap.get(leftChar) - 1); +// if (vowelMap.get(leftChar) === 0) { +// vowelMap.delete(leftChar); +// } +// } else { +// consonants--; +// } +// left++; +// } +// } + +// return result; +// } \ No newline at end of file diff --git a/example/Dayly/3356.js b/example/Dayly/3356.js new file mode 100644 index 00000000..a54f5205 --- /dev/null +++ b/example/Dayly/3356.js @@ -0,0 +1,55 @@ +/** + * @param {number[]} nums + * @param {number[][]} queries + * @return {number} + */ +var minZeroArray = function(nums, queries) { + +}; + + +const example1 = minZeroArray([2,0,2], [[0,2,1],[0,2,1],[1,1,3]]); // 2 +const example2 = minZeroArray([4,3,2,1], [[1,3,2],[0,2,1]]); // -1 + +console.log(example1); +console.log(example2); + +// var minZeroArray = function(nums, queries) { +// const n = nums.length; +// let left = 0; +// let right = queries.length; +// let result = -1; + +// const canZeroArray = function(nums, queries, k) { +// const n = nums.length; +// const diff = new Array(n + 1).fill(0); + +// for (let i = 0; i < k; i++) { +// let [l, r, val] = queries[i]; +// diff[l] -= val; +// if (r + 1 < n) { +// diff[r + 1] += val; +// } +// } + +// let currentDecrement = 0; +// for (let i = 0; i < n; i++) { +// currentDecrement += diff[i]; +// if (nums[i] + currentDecrement > 0) { +// return false; +// } +// } +// return true; +// } + +// while (left <= right) { +// const mid = Math.trunc((left + right) / 2); + +// if (canZeroArray(nums.slice(), queries, mid)) { +// result = mid; +// right = mid - 1; +// } +// else { left = mid + 1; } +// } +// return result; +// }; \ No newline at end of file diff --git a/example/ProgrammingSkills/0.Basic/0028.js b/example/ProgrammingSkills/0.Basic/0028.js new file mode 100644 index 00000000..10d81267 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0028.js @@ -0,0 +1,18 @@ +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function(haystack, needle) { + +}; + +const example1 = strStr("sadbutsad", "sad"); // 0 +const example2 = strStr("leetcode","leeto"); // -1 +const example3 = strStr("bro", "rosb"); // -1 +const example4 = strStr("asasadbutsad", "sad"); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/ProgrammingSkills/0.Basic/0066.js b/example/ProgrammingSkills/0.Basic/0066.js new file mode 100644 index 00000000..26647893 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0066.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + +}; + +const example1 = plusOne([1,2,3]); // [1,2,4] +const example2 = plusOne([4,3,2,1]); // [4,3,2,2] +const example3 = plusOne([9]); // [1,0] +const example4 = plusOne([1,9,9]); // [2,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + diff --git a/example/ProgrammingSkills/0.Basic/0389.js b/example/ProgrammingSkills/0.Basic/0389.js new file mode 100644 index 00000000..f5ccad70 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0389.js @@ -0,0 +1,16 @@ +/** + * @param {string} s + * @param {string} t + * @return {character} + */ +var findTheDifference = function(s, t) { + +}; + +const example1 = findTheDifference("abcd", "abcde"); // "e" +const example2 = findTheDifference("","y"); // "y" +const example3 = findTheDifference("bro", "rosb"); // "s" + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/ProgrammingSkills/0.Basic/0459.js b/example/ProgrammingSkills/0.Basic/0459.js new file mode 100644 index 00000000..347e67fc --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0459.js @@ -0,0 +1,35 @@ +/** + * @param {string} s + * @return {boolean} + */ +var repeatedSubstringPattern = function(s) { + +}; + +const example1 = repeatedSubstringPattern("abab"); // true +const example2 = repeatedSubstringPattern("aba"); // false +const example3 = repeatedSubstringPattern("abcabcabcabc"); // true +const example4 = repeatedSubstringPattern("121"); // false +const example5 = repeatedSubstringPattern("123123"); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + +// var repeatedSubstringPattern = function(s) { +// return (s + s).slice(1, s.length * 2 - 1).indexOf(s) !== -1 +// }; + +// var repeatedSubstringPattern = function(s) { +// const n = s.length; + +// for (let i = 1; i <= Math.floor(n / 2); i++) { +// if (n % i === 0 && s.slice(0, i).repeat(n / i) === s) { +// return true; +// } +// } + +// return false; +// }; \ No newline at end of file diff --git a/example/ProgrammingSkills/0.Basic/0896.js b/example/ProgrammingSkills/0.Basic/0896.js new file mode 100644 index 00000000..c63d96c0 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0896.js @@ -0,0 +1,38 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var isMonotonic = function(nums) { + +}; + +const example1 = isMonotonic([1,2,2,3]); // true +const example2 = isMonotonic([6,5,4,4]); // true +const example3 = isMonotonic([1,3,2]); // false + +console.log(example1); +console.log(example2); +console.log(example3); + +var isMonotonic = function(nums) { + let n = nums.length + if (n === 1) return true + + let isInc = true + let isDec = true + + for (let i = 1; i < n; i++) { + if (!isInc && !isDec) { + return false + } + + if (nums[i - 1] > nums[i]) { + isInc = false + } + + if (nums[i - 1] < nums[i]) { + isDec = false + } + } + return isInc || isDec +}; diff --git a/example/ProgrammingSkills/0.Basic/1502.js b/example/ProgrammingSkills/0.Basic/1502.js new file mode 100644 index 00000000..a52f9bce --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/1502.js @@ -0,0 +1,19 @@ +/** + * 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) { + +} \ No newline at end of file diff --git a/example/ProgrammingSkills/0.Basic/1768.js b/example/ProgrammingSkills/0.Basic/1768.js new file mode 100644 index 00000000..f38b0260 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/1768.js @@ -0,0 +1,42 @@ +/** + * 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) { + +}; + +const example1 = mergeAlternately("abc", "pqr"); // "apbqcr" +const example2 = mergeAlternately("ab","pqrs"); // "apbqrs" +const example3 = mergeAlternately("abcd", "pq"); // "apbqcd" +const example4 = mergeAlternately("12", "some"); // "1s2ome" +const example5 = mergeAlternately("1234", "so"); // "1s2o34" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + +// 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/example/ProgrammingSkills/0.Basic/1822.js b/example/ProgrammingSkills/0.Basic/1822.js new file mode 100644 index 00000000..a081caa1 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/1822.js @@ -0,0 +1,29 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var arraySign = function(nums) { + +}; + +const example1 = arraySign([-1,-2,-3,-4,3,2,1]); // 1 +const example2 = arraySign([1,5,0,2,-3]); // 0 +const example3 = arraySign([-1,1,-1,1,-1]); // -1 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var arraySign = function(nums) { +// let minusCount = 0; +// for (const number of nums) { +// if (number === 0) { +// return 0 +// } + +// if (number < 0) { +// minusCount += 1 +// } +// } +// return minusCount % 2 === 0 ? 1 : -1 +// }; \ No newline at end of file diff --git a/example/ProgrammingSkills/1.Simulation/0058.js b/example/ProgrammingSkills/1.Simulation/0058.js new file mode 100644 index 00000000..c340ada6 --- /dev/null +++ b/example/ProgrammingSkills/1.Simulation/0058.js @@ -0,0 +1,15 @@ +/** + * @param {string} s + * @return {number} + */ +var lengthOfLastWord = function(s) { + +}; + +const example1 = lengthOfLastWord("Hello World"); // 5 +const example2 = lengthOfLastWord(" fly me to the moon "); // 4 +const example3 = lengthOfLastWord("luffy is still joyboy"); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/ProgrammingSkills/1.Simulation/0709.js b/example/ProgrammingSkills/1.Simulation/0709.js new file mode 100644 index 00000000..421e25f2 --- /dev/null +++ b/example/ProgrammingSkills/1.Simulation/0709.js @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @return {string} + */ +var toLowerCase = function(s) { + let result = ''; + for (let i = 0; i < s.length; i++) { + const ascii = s.charCodeAt(i); + if (ascii >= 65 && ascii <= 90) { + result += String.fromCharCode(ascii + 32); + } else { + result += s.charAt(i); + } + } + return result; +}; + +const example1 = lengthOfLastWord("Hello World"); // 5 +const example2 = lengthOfLastWord(" fly me to the moon "); // 4 +const example3 = lengthOfLastWord("luffy is still joyboy"); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/ProgrammingSkills/1.Simulation/1572.js b/example/ProgrammingSkills/1.Simulation/1572.js new file mode 100644 index 00000000..dd72e23d --- /dev/null +++ b/example/ProgrammingSkills/1.Simulation/1572.js @@ -0,0 +1,27 @@ +/** + * @param {string} s + * @return {number} + */ +var diagonalSum = function(mat) { + +}; + +const example1 = diagonalSum([[1,2,3],[4,5,6],[7,8,9]]); // 25 +const example2 = diagonalSum([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]); // 8 + +console.log(example1); +console.log(example2); + +// var diagonalSum = function(mat) { +// let n = mat.length; +// let row = 0; + +// const lambda = (sum, vec) => { +// sum += vec[row]; +// if (row !== n - row - 1) sum += vec[n - row - 1]; +// row++; +// return sum; +// }; + +// return mat.reduce(lambda, 0); +// }; \ No newline at end of file diff --git a/example/README.md b/example/README.md new file mode 100644 index 00000000..b2389a66 --- /dev/null +++ b/example/README.md @@ -0,0 +1,560 @@ +# Order + +Better order to solve problems + +## Lists + +### [0.ArraaysHash](https://github.com/Barklim/leetcode-javascript/tree/master/example/0.ArraysHash) + +1. Two sum +167. Two Integer Sum II +0. +217. Contains Duplicate +242. Valid Anagram +49. Group Anagrams +347. Top K Frequent Elements +271. Encode Decode +238. Product of Array Except Self +36. Valid Sudoku +128. Longest Consecutive Sequence + +### [1.TwoPointers](https://github.com/Barklim/leetcode-javascript/tree/master/example/1.TwoPointers) + +344. Reverse string leetcode +125. Valid Palendrom +15. 3sum +977. Squares of a sorted Array +11. Container With Most Water +26. Remove duplicates +283. Move Zeroes +392. Ls Subseq +844. Backspace String compare +88. Merge sorted Array +0. +42. Trapping Rain Water + +### [2.SlidingWindow](https://github.com/Barklim/leetcode-javascript/tree/master/example/2.SlidingWindow) + +643. Maximum Average Subarray +209. Minimum size Subarray Sum +1004. Max Consecutive One iii +1493. Longest Subarray of 1s After Deleting One Element +904. Fruit Into Baskets +0. +121. Best Time to Buy and Sell Stock +424. Longest Repeating Character Replacement +567. Permutation in String +- 76. Minimum Window Substring +- 239. Sliding Window Maximum + +### [3.Linked list](https://github.com/Barklim/leetcode-javascript/tree/master/example/3.Linkedlist) + +707. Design Linked List +876. Middle of the Linked List +2095. Delete the Middle Node of a Linked List +206. Reverse Linked List +234. Palindrome Linked List +83. Remove Duplicates from Sorted List +19. Remove Nth Node from End of List +24. Swap Nodes in Pairs +21. Merge Two sorted Lists +141. Linked List Cycle +0. +143. Reorder List +- 138. Copy List with Random Pointer +2. Add Two Numbers +287. Find the Duplicate Number +- 23. Merge k Sorted Lists +- 25. Reverse Nodes in k-Group +1. +445. Add Two Numbers II + +### [4.Binary Search](https://github.com/Barklim/leetcode-javascript/tree/master/example/4.BinarySearch) + +704. Binary Search +- 74. Search a 2D Matrix +- 875. Koko Eating Bananas +- 153. Find Minimum in Rotated Sorted Array +- 33. Search in Rotated Sorted Array +- 981. Time Based Key-Value Store +- 4. Median of Two Sorted Arrays + +### HashMap + +706. Design Hash map + +### LRU Cache + +146. LRU Cache + +### [Stack, Queue](https://github.com/Barklim/leetcode-javascript/tree/master/example/5.Stack) + +20. Valid Parentheses +1047. Remove All Adjacent duplicates in String +2390. Removing Stars From a string +71. Simplify Path +- 933. Number of Recent Calls +0. +- 155. Min Stack +- 150. Evaluate Reverse Polish Notation +22. Generate Parentheses +- 739. Daily Temperatures +- 853. Car Fleet +- 84. Largest Rectangle in Histogram + +### [Binare Tree, DFS](https://github.com/Barklim/leetcode-javascript/tree/master/example/6.Tree) + +104. Maximum Depth of Binary Tree +226. Invert Binary Tree +101. Symmetric Tree +100. Same Tree +112. Path sum + +### Binary Search Tree + +700. Search in a Binary search tree +701. Insert into a Binary search tree +98. Validate Binary Search tree (нужно следить за диапозоном хранимых/возможным значений) +110. Balanced Binary tree + +### Binary Tree, BFS + +102. Binary Tree Level Order Traversal +515. Find Largest Value in Each Tree Row +199. Binary Tree Right Side View +117. Populating Next Right Pointers in Each Node ii +1325. Delete Leaves With a Given Value +1302. Deepest Leaves Sum +543. Diameter of Binary Tree (104 task) +103. Binary Tree Zigzag level Order Traversal +236. Lowest Common Ancestor of a Binary tree +0. +572. Subtree of Another Tree +1448. Count Good Nodes in Binary Tree +230. Kth Smallest Element in a BST +105. Construct Binary Tree from Preorder and Inorder Traversal +124. Binary Tree Maximum Path Sum +297. Serialize and Deserialize Binary Tree + +### [Trie, Autocomplete](https://github.com/Barklim/leetcode-javascript/tree/master/example/7.Tries) + +208. Implement trie +1268. Search suggestion system +0. +211. Design Add and Search Words Data Structure +212. Word Search II + +### [Heap Pt.1](https://github.com/Barklim/leetcode-javascript/tree/master/example/8.Heap) + +215. Kth Largest Element in an Array (минхипа максхипа) +703. Kth Largest Element in a Stream +347. Top K Frequent Elements +451. Sort Characters By Frequency + +### Heap Pt.2 + +1046. Last stone Weight +502. IPO +295. Find Median from Data Stream +1962. Remove stones to minimize the total +23. Merge k sorted Lists +642. Design Search Autocomplete System +0. +999. K Closest Points to Origin +999. Task Scheduler +999. Design Twitter + +### [Intervals](https://github.com/Barklim/leetcode-javascript/tree/master/example/9.Intervals) + +252. Meeting Rooms (сортировать по дате начала митинга) +56. Merge Intervals +57. Insert Intervals +253. Meeting Rooms ii +0. +435. Non-overlapping Intervals +1851. Minimum Interval to Include Each Query + +### Graphs Workshop + +752. Open the lock +433. Minimum Genetic Mutation +2101. Detonation the Maximum Bombs +841. Keys and rooms +1971. Find if path Exists in Graph +133. clone graph +1557. Minimum number of Vertices to Reach All Nodes + +### Graphs Workshop 2 + +323. Number of Connected components in an Undirected Graph (547. none premium) +200. Number of Islands +1466. Reorder Routes to Make All Paths Lead to the City Zero +695. Max Area of island +2368. Reachable Nodes with restrictions +542. 01 Matrix +994. Rotting oranges +1129. Shortest Path with Alternating Colors +1926. Nearest Exit from Entrance in Maze +1091. Shortest path in Binary Matrix +433. Minimum Genetic mutation (752.) + +### Dijkstra + +743. Network delay time +1514. Path with maximum Probability +787. Cheapest Flights Within K Stops + +### Topological sort Pt.1 + +2115. Find all possible Recipes from given Supplies + +### Topological sort Pt.2 + +207. Course Schedule +210. Course Schedule ii +1136. Parallel Courses + +### Backtracking Pt.1 + +46. Permutations +77. Combinations +78. Subsets +22. Generate Paretheses + +### Backtracking Pt.2 + +216. Combination Sum iii +17. letter combinations of a phone number +51. N-Queens +489. Robot room cleaner + +### Dynamic Programming Pt.1 + +509. Fibonacci Number +70. Climbing Stairs +746. Min Cost Climbing Stairs +322. Coin Change +198. House Robber + +### Dynamic Programming Pt.2 + +91. Decode ways +62. Unique paths +64. Minimum path sum +72. Edit Distance + +### Greedy +### Advanced Graphs +### Bit Manipulation +### Math & Geometry + +## [Blind 75 by BFE](https://www.greatfrontend.com/interviews/blind75) + +442. Find All Duplicates in an Array +9999. End of Array Reachable +9999. Maximum Sum in Contiguous Array + +## Programming skills + +### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/0.Basic) + +1768. Merge Strings Alternately +389. Find the Difference +28. Find the Index of the First Occurrence in a String +459. Repeated Substring Pattern +66. Plus One + +### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/1.Simulation) + +58. Length of Last Word +1041. Robot Bounded In Circle +1572. Matrix Diagonal Sum + +## 30 Days of JavaScript + +2667. Create Hello World Function +2620. Counter +2704. To Be Or Not To Be +2665. Counter II +2635. Apply Transform Over Each Element in Array +2634. Filter Elements from Array +2626. Array Reduce Transformation +2629. Function Composition +2666. Allow One Function Call +2623. Memoize + +2677. Chunk Array +2631. Group By +2724. Sort By +2722. Join Two Arrays by ID +2625. Flatten Deeply Nested Array +2705. Compact Object + +### [Strong List](structy.net) + +1. Depth-First Search (DFS) +1. 79 - Word Search +2. 200 - Number of Islands +3. 695 - Max Area of Island +4. 463 - Island Perimeter +5. 733 - Flood Fill +6. 130 - Surrounded Regions +7. 417 - Pacific Atlantic Water Flow +8. 261 - Graph Valid Tree +9. 329 - Longest Increasing Path in a Matrix +10. 688 - Knight Probability in Chessboard +11. 332 - Reconstruct Itinerary +12. 1306 - Jump Game III +2. Breadth-First Search (BFS) +1. 286 - Walls and Gates +2. 542 - 01 Matrix +3. 994 - Rotting Oranges +4. 752 - Open the Lock +5. 127 - Word Ladder +6. 934 - Shortest Bridge +7. 1466 - Reorder Routes to Make All Paths Lead to the City Zero +8. 1162 - As Far from Land as Possible +9. 815 - Bus Routes +10. 1197 - Minimum Knight Moves +11. 1091 - Shortest Path in Binary Matrix +12. 1293 - Shortest Path in a Grid with Obstacles Elimination +3. Topological Sort +1. 207 (Course Schedule) +2. 210 (Course Schedule II) +3. 1136 (Parallel Courses) +4. 310 (Minimum Height Trees) +5. 444 (Sequence Reconstruction) +6. 269 (Alien Dictionary) +7. 802 Find Eventual Safe States +8. 1203 Sort Items by Groups Respecting Dependencies +9. 1192 Critical Connections in a Network (Tarjan's Algorithm) + +4. Dijkstra's Algorithm +1. 743 - Network Delay Time +2. 1334 - Find the City With the Smallest Number of Neighbors at a Threshold Distance +3. 1514 - Path with Maximum Probability +4. 1631 - Path With Minimum Effort +5. 778 - Swim in Rising Water +6. 1786 - Number of Restricted Paths From First to Last Node +7. 787 - Cheapest Flights Within K Stops +8 882 - Reachable Nodes In Subdivided Graph +9. 1368 - Minimum Cost to Make at Least One Valid Path in a Grid +10. 1791 - Minimum Number of Refueling Stops + +5. Union-Find (Disjoint Set Union) +1. 547 - Number of Provinces +2. 684 - Redundant Connection +3. 721 - Accounts Merge +4. 1584 - Min Cost to Connect All Points +5. 990 - Satisfiability of Equality Equations +6. 1319 - Number of Operations to Make Network Connected +7. 1202 - Smallest String With Swaps +8. 1632 - Rank Transform of a Matrix + +6. Floyd-Warshall / All-Pairs Shortest Path +1. 1462 - Course Schedule IV +2. 785 (Is Graph Bipartite?) +3. 886 (Possible Bipartition) +4. 1617 (Count Subtrees With Max Distance Between Cities) +5. 1125 (Smallest Sufficient Team) + + +### Ru companies + +##### Anagramms, Math, Simple nums + +242. Valid Anagram +49. Group Angagrams +204. Count Primes +7. Reverse Integer +136. Single Number +137. Single Number ii + +##### ArraaysHash (Prefix sum) + +### Uni +303. 724. 304. 1314. 268. 287. 189. 674. +### Jandex +560. +### Oz +896. + +##### ArraaysHash + +1. Sum +36. Valid Sudoku +205. Isomorphic Strings +356. Line reflection +146. Lru Cache +2657. Find the Prefix Common + +##### TwoPointers + +977. Squares of a sorted Array +283. Move Zeroes +125. Valid Palendrom +167. Two Integer Sum II +161. One Edit Distance + +##### SlidingWindow + +228. Summary Ranges +485. Max Consecutive Ones +3. Longest... +849. Maximize Distance to closest person +443. String Compression + +##### Linked list + +### Сбебс +19. Remove Nth Node from End of List +143. Reorder List +23. Merge k Sorted Lists +### Jandex +206. Reverse Linked List +234. Palindrome Linked List +### Uni +876. Middle of the Linked List +143. Reorder List + +##### Binary Search + +704. Binary Search +852. Peak Index in a Mountain Array +33. Search in Rotated Sorted Array +34. Find First and Last Position of Element in Sorted Array +74. Search a 2D Matrix +69. Sqrt(x) +658. Find K Closesest Elements + +##### Stack, Queue + +20. Valid Parentheses +1249. Minimum Remove to Make Valid Parentheses +739. Daily Temperatures +912. Sort an Array + +##### Binare Tree + +### Uni +144. +199. Binary Tree Right Side View +### Jandex +102. Binary Tree Level Order Traversal +* 101. Symmetric Tree +100. Same Tree +112. Path sum + +##### Heap + +215. Kth Largest Element in an Array +347. Top K Frequent Elements (не отсортирован) +912. Sort an Array + +##### Intervals + +### Uni +56. Merge Intervals +252. Meeting Rooms +1094. Car pooling +452. Minimum Number of Arrows to Burst Balloons +347. Top K Frequent Elements (не отсортирован) +### Avi +2. Add Two Numbers + +##### Graphs + +62. Unique paths +63. Unique paths ii +64. Minimum Path Sum +200. Number of Islands +207. Course Schedule +210. Course Schedule ii +130. Surronded Regions +695. Max Area of Island +1091. Shortest path in Binary Matrix + +##### Backtracking + +17. letter combinations of a phone number +46. Permatations +51. N-Queens +22. Generate Parentheses + + +### [classic](https://leetcode.com/explore/interview/card/top-interview-questions-easy) + +##### Array + +26. Remove Duplicates from Sorted Array +122. Best Time to Buy and Sell Stock II +189. Rotate Array +217. Contains Duplicate +136. Single Number +350. Intersection of Two Arrays II +66. Plus One +283. Move Zeroes +1. Two Sum +36. Valid Sudoku +48. Rotate Image + +##### String + +344. Reverse String +7. Reverse Integer +387. First Unique Character in a String +242. Valid Anagram +125. Valid Palindrome +8. String to Integer (atoi) +28. Implement strStr() +14. Longest Common Prefix + +##### Linked list + +237. Delete Node in a Linked List +19. Remove Nth Node From End of List +206. Reverse Linked List +21. Merge Two Sorted Lists +234. Palindrome Linked List +141. Linked List Cycle + +##### Trees + +104. Maximum Depth of Binary Tree +98. Validate Binary Search Tree +101. Symmetric Tree +102. Binary Tree Level Order Traversal +108. Convert Sorted Array to Binary Search Tree + +##### Sorting and Searching + +88. Merge Sorted Array +278. First Bad Version + +##### Dynamic Programming + +70. Climbing Stairs +121. Best Time to Buy and Sell Stock +53. Maximum Subarray +198. House Robber + +##### Design + +384. Shuffle an Array +155. Min Stack + +##### Math + +412. Fizz Buzz +204. Count Primes +326. Power of Three +13. Roman to Integer + +##### Other + +191. Number of 1 Bits +461. Hamming Distance +190. Reverse Bits +118. Pascal's Triangle +20. Valid Parentheses +268. Missing Number \ No newline at end of file diff --git a/example/js/2620.js b/example/js/2620.js new file mode 100644 index 00000000..807259a4 --- /dev/null +++ b/example/js/2620.js @@ -0,0 +1,27 @@ +/** + * 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) { + + return function() { + + }; +}; + +const counter = createCounter(10) +counter() +counter() +counter() +console.log(counter()) // 13 +console.log(counter()) // 14 \ No newline at end of file diff --git a/example/js/2623.js b/example/js/2623.js new file mode 100644 index 00000000..7d8965ee --- /dev/null +++ b/example/js/2623.js @@ -0,0 +1,43 @@ +/** + * 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) { + + return function(...args) { + + } +} + +let callCount = 0; +const memoizedFn = memoize(function (a, b) { + callCount += 1; + return a + b; +}); +memoizedFn(2, 3); // 5 +memoizedFn(2, 3); // 5 +console.log(callCount); // 1 diff --git a/example/js/2625.js b/example/js/2625.js new file mode 100644 index 00000000..79f0d023 --- /dev/null +++ b/example/js/2625.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + \ No newline at end of file diff --git a/example/js/2626.js b/example/js/2626.js new file mode 100644 index 00000000..a111181b --- /dev/null +++ b/example/js/2626.js @@ -0,0 +1,42 @@ +/** + * 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) { + +}; + + +function sum1(accum, curr) { return accum + curr; } +ex1 = reduce([1,2,3,4], sum1, 0) + +function sum2(accum, curr) { return accum + curr * curr; } +ex2 = reduce([1,2,3,4], sum2, 100) + +function sum3(accum, curr) { return 0; } +ex3 = reduce([], sum3, 25) + +console.log(ex1) // 10 +console.log(ex2) // 130 +console.log(ex3) // 25 + \ No newline at end of file diff --git a/example/js/2629.js b/example/js/2629.js new file mode 100644 index 00000000..01bd9a5c --- /dev/null +++ b/example/js/2629.js @@ -0,0 +1,40 @@ +/** + * 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 function(x) { + + } +}; + + +functions1 = [x => x + 1, x => x * x, x => 2 * x] +ex1 = compose(functions1)(4) + +functions2 = [x => 10 * x, x => 10 * x, x => 10 * x] +ex2 = compose(functions2)(1) + +functions3 = [] +ex3 = compose(functions3)(42) + +console.log(ex1) // 65 +console.log(ex2) // 1000 +console.log(ex3) // 42 \ No newline at end of file diff --git a/example/js/2631.js b/example/js/2631.js new file mode 100644 index 00000000..36ed11fb --- /dev/null +++ b/example/js/2631.js @@ -0,0 +1,56 @@ +/** + * 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) { + +}; + +const array1 = [ + {id: 1}, + {id: 1}, + {id: 2} +] + +const fn = (item) => item.id + +console.log(array1.groupBy(fn)) +// { +// 1: [{id: 1}, {id: 1}], +// 2: [{id: 2}] +// } + +// Ex2 +const array2 = [1, 2, 3] +console.log(array2.groupBy(String)) +// { +// "1": [1], +// "2": [2], +// "3": [3], +// } + +// Ex3 +const array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +const fn3 = function (n) { + return String(n > 5); +} +console.log(array3.groupBy(fn3)) \ No newline at end of file diff --git a/example/js/2634.js b/example/js/2634.js new file mode 100644 index 00000000..e77df729 --- /dev/null +++ b/example/js/2634.js @@ -0,0 +1,41 @@ +/** + * 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) { + +}; + + +fn1 = function greaterThan10(n) { return n > 10; } +ex1 = filter([0,10,20,30], fn1) + +fn2 = function firstIndex(n, i) { return i === 0; } +ex2 = filter([1,2,3], fn2) + +fn3 = function plusOne(n) { return n + 1 } +ex3 = filter([-2,-1,0,1,2], fn3) + +console.log(ex1) // [20, 30] +console.log(ex2) // [1] +console.log(ex3) // [-2,0,1,2] + \ No newline at end of file diff --git a/example/js/2635.js b/example/js/2635.js new file mode 100644 index 00000000..74ff0a4f --- /dev/null +++ b/example/js/2635.js @@ -0,0 +1,37 @@ +/** + * 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 arr = [1,2,3] + +fn1 = function plusone(n) { return n + 1; } +ex1 = map(arr, fn1) + +fn2 = function plusI(n, i) { return n + i; } +ex2 = map(arr, fn2) + +fn3 = function constant() { return 42; } +ex3 = map(arr, fn3) + +console.log(ex1) +console.log(ex2) +console.log(ex3) + \ No newline at end of file diff --git a/example/js/2655.js b/example/js/2655.js new file mode 100644 index 00000000..a6452395 --- /dev/null +++ b/example/js/2655.js @@ -0,0 +1,32 @@ +/** + * 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) { + +}; + +const counter = createCounter(5) +// counter.increment(); // 6 +// counter.reset(); // 5 +// counter.decrement(); // 4 + +console.log(counter.increment()) // 6 +console.log(counter.increment()) // 7 +console.log(counter.reset()) // 5 +console.log(counter.decrement()) // 4 + \ No newline at end of file diff --git a/example/js/2666.js b/example/js/2666.js new file mode 100644 index 00000000..14019d9a --- /dev/null +++ b/example/js/2666.js @@ -0,0 +1,27 @@ +/** + * 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. + */ +var once = function(fn) { + + return function(...args){ + + } +}; + +let fn = (a,b,c) => (a + b + c) +let onceFn = once(fn) + +ex1 = onceFn(1,2,3); // 6 +ex2 = onceFn(2,3,6); // returns undefined without calling fn + +console.log(ex1) +console.log(ex2) + diff --git a/example/js/2667.js b/example/js/2667.js new file mode 100644 index 00000000..5c11e53c --- /dev/null +++ b/example/js/2667.js @@ -0,0 +1,23 @@ +/** + * 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 function(...args) { + + } +}; + +const f = createHelloWorld(); +f(); + +console.log(f()) // "Hello World" \ No newline at end of file diff --git a/example/js/2677.js b/example/js/2677.js new file mode 100644 index 00000000..4336c420 --- /dev/null +++ b/example/js/2677.js @@ -0,0 +1,37 @@ +/** + * 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) { + +}; + +ex1 = chunk([1,2,3,4,5], 1) +console.log(ex1) // [[1],[2],[3],[4],[5]] + +ex2 = chunk([1,9,6,3,2], 3) +console.log(ex2) // [[1,9,6],[3,2]] + +ex3 = chunk([8,5,3,2,6], 6) +console.log(ex3) // [[8,5,3,2,6]] + +ex4 = chunk([], 1) +console.log(ex4) // [] + \ No newline at end of file diff --git a/example/js/2704.js b/example/js/2704.js new file mode 100644 index 00000000..84350183 --- /dev/null +++ b/example/js/2704.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +// expect(5).toBe(5); // true +// expect(5).notToBe(5); // throws "Equal" + +console.log(expect(5).toBe(5)) +console.log(expect(5).notToBe(5)) \ No newline at end of file diff --git a/example/js/2705.js b/example/js/2705.js new file mode 100644 index 00000000..9ce6a147 --- /dev/null +++ b/example/js/2705.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +ex1 = compactObject([null, 0, false, 1]) +console.log(ex1) // [1] + +ex2 = compactObject({"a": null, "b": [false, 1]}) +console.log(ex2) // {"b": [1]} + +ex3 = compactObject([null, 0, 5, [0], [false, 16]]) +console.log(ex3) // [5, [], [16]] \ No newline at end of file diff --git a/example/js/2722.js b/example/js/2722.js new file mode 100644 index 00000000..8956df7d --- /dev/null +++ b/example/js/2722.js @@ -0,0 +1,78 @@ +/** + * 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) { + +}; + + +arr1 = [ + {"id": 1, "x": 1}, + {"id": 2, "x": 9} +], +arr2 = [ + {"id": 3, "x": 5} +] + +ex1 = join(arr1, arr2) +console.log(ex1) +// [ +// {"id": 1, "x": 1}, +// {"id": 2, "x": 9}, +// {"id": 3, "x": 5} +// ] + + +arr1 = [ + {"id": 1, "x": 2, "y": 3}, + {"id": 2, "x": 3, "y": 6} +], +arr2 = [ + {"id": 2, "x": 10, "y": 20}, + {"id": 3, "x": 0, "y": 0} +] + +ex2 = join(arr1, arr2) +console.log(ex2) +// [ +// {"id": 1, "x": 2, "y": 3}, +// {"id": 2, "x": 10, "y": 20}, +// {"id": 3, "x": 0, "y": 0} +// ] + +arr1 = [ + {"id": 1, "b": {"b": 94}, "v": [4, 3], "y": 48} +], +arr2 = [ + {"id": 1, "b": {"c": 84}, "v": [1, 3]} +] + +ex3 = join(arr1, arr2) +console.log(ex3) +// [ +// {"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48} +// ] \ No newline at end of file diff --git a/example/js/2724.js b/example/js/2724.js new file mode 100644 index 00000000..6436853d --- /dev/null +++ b/example/js/2724.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +ex1 = sortBy([5, 4, 1, 2, 3], fn = (x) => x) +console.log(ex1) // [1, 2, 3, 4, 5] + +ex2 = sortBy([{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x) +console.log(ex2) // [{"x": -1}, {"x": 0}, {"x": 1}] + +ex3 = sortBy([[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]) +console.log(ex3) // [[10, 1], [5, 2], [3, 4]] + \ No newline at end of file diff --git a/solutions/0002-add-two-numbers.js b/solutions/0002-add-two-numbers.js deleted file mode 100644 index 81b72151..00000000 --- a/solutions/0002-add-two-numbers.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 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(); - - for (let tail = result, carry = 0; l1 || l2 || carry;) { - const value = (l1?.val ?? 0) + (l2?.val ?? 0) + carry; - tail.next = new ListNode(value % 10); - tail = tail.next; - carry = value >= 10 ? 1 : 0; - [l1, l2] = [l1 && l1.next, l2 && l2.next]; - } - - return result.next; -}; diff --git a/solutions/0003-longest-substring-without-repeating-characters.js b/solutions/0003-longest-substring-without-repeating-characters.js deleted file mode 100644 index 2bdecb15..00000000 --- a/solutions/0003-longest-substring-without-repeating-characters.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 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/solutions/0009-palindrome-number.js b/solutions/0009-palindrome-number.js deleted file mode 100644 index a4691dc2..00000000 --- a/solutions/0009-palindrome-number.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 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/solutions/0015-3sum.js b/solutions/0015-3sum.js deleted file mode 100644 index 35d01c95..00000000 --- a/solutions/0015-3sum.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 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 = []; - nums.sort((a, b) => a - b); - - for (let i = 0; i < nums.length - 2; i++) { - if (i > 0 && nums[i] === nums[i - 1]) continue; - let j = i + 1; - let k = nums.length - 1; - while (j < k) { - const sum = nums[i] + nums[j] + nums[k]; - if (!sum) { - result.push([nums[i], nums[j], nums[k]]); - j++; - k--; - while (j < k && nums[j] === nums[j - 1]) { - j++; - } - while (j < k && nums[k] === nums[k + 1]) { - k--; - } - } else { - sum < 0 ? j++ : k--; - } - } - } - - return result; -}; diff --git a/solutions/0019-remove-nth-node-from-end-of-list.js b/solutions/0019-remove-nth-node-from-end-of-list.js deleted file mode 100644 index 1e133150..00000000 --- a/solutions/0019-remove-nth-node-from-end-of-list.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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/solutions/0021-merge-two-sorted-lists.js b/solutions/0021-merge-two-sorted-lists.js deleted file mode 100644 index f5c16393..00000000 --- a/solutions/0021-merge-two-sorted-lists.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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/solutions/0024-swap-nodes-in-pairs.js b/solutions/0024-swap-nodes-in-pairs.js deleted file mode 100644 index 39a27600..00000000 --- a/solutions/0024-swap-nodes-in-pairs.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 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/solutions/0033-search-in-rotated-sorted-array.js b/solutions/0033-search-in-rotated-sorted-array.js deleted file mode 100644 index 632b7e3c..00000000 --- a/solutions/0033-search-in-rotated-sorted-array.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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/solutions/0042-trapping-rain-water.js b/solutions/0042-trapping-rain-water.js deleted file mode 100644 index 15766764..00000000 --- a/solutions/0042-trapping-rain-water.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 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) { - let result = 0; - - for (let left = 0, right = height.length - 1, maxL = 0, maxR = 0; left < right;) { - maxL = Math.max(maxL, height[left]); - maxR = Math.max(maxR, height[right]); - result += maxL < maxR ? maxL - height[left++] : maxR - height[right--]; - } - - return result; -}; diff --git a/solutions/0049-group-anagrams.js b/solutions/0049-group-anagrams.js deleted file mode 100644 index 3f48828b..00000000 --- a/solutions/0049-group-anagrams.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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/solutions/0058-length-of-last-word.js b/solutions/0058-length-of-last-word.js deleted file mode 100644 index db2632c8..00000000 --- a/solutions/0058-length-of-last-word.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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; -}; diff --git a/solutions/0074-search-a-2d-matrix.js b/solutions/0074-search-a-2d-matrix.js deleted file mode 100644 index 8cb17adb..00000000 --- a/solutions/0074-search-a-2d-matrix.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 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/solutions/0076-minimum-window-substring.js b/solutions/0076-minimum-window-substring.js deleted file mode 100644 index 7879c4ac..00000000 --- a/solutions/0076-minimum-window-substring.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 76. Minimum Window Substring - * https://leetcode.com/problems/minimum-window-substring/ - * Difficulty: Hard - * - * Given two strings s and t of lengths m and n respectively, return the minimum window substring - * of s such that every character in t (including duplicates) is included in the window. If there - * is no such substring, return the empty string "". - * - * The testcases will be generated such that the answer is unique. - */ - -/** - * @param {string} s - * @param {string} t - * @return {string} - */ -var minWindow = function(s, t) { - const values = new Array(128).fill(0); - let [start, end] = [-Infinity, Infinity]; - - for (let i = 0; i < t.length; i++) { - values[t.charCodeAt(i)]++; - } - - for (let i = 0, j = 0, total = t.length; i < s.length; i++) { - if (values[s.charCodeAt(i)] > 0) { - total--; - } - values[s.charCodeAt(i)]--; - while (!total) { - if (end - start > i - j) { - [start, end] = [j, i]; - } - values[s.charCodeAt(j)]++; - if (values[s.charCodeAt(j)] > 0) { - total++; - } - j++; - } - } - - return end !== Infinity ? s.slice(start, end + 1) : ''; -}; diff --git a/solutions/0083-remove-duplicates-from-sorted-list.js b/solutions/0083-remove-duplicates-from-sorted-list.js deleted file mode 100644 index b1e7de59..00000000 --- a/solutions/0083-remove-duplicates-from-sorted-list.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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(); - let tail = result; - - while (head) { - if (head.val !== head.next?.val) { - tail.next = new ListNode(head.val); - tail = tail.next; - } - previous = head.val; - head = head.next; - } - - return result.next; -}; diff --git a/solutions/0088-merge-sorted-array.js b/solutions/0088-merge-sorted-array.js deleted file mode 100644 index c94a4117..00000000 --- a/solutions/0088-merge-sorted-array.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 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/solutions/0098-validate-binary-search-tree.js b/solutions/0098-validate-binary-search-tree.js deleted file mode 100644 index 73c8d164..00000000 --- a/solutions/0098-validate-binary-search-tree.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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/solutions/0101-symmetric-tree.js b/solutions/0101-symmetric-tree.js deleted file mode 100644 index 548cfb75..00000000 --- a/solutions/0101-symmetric-tree.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 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/solutions/0102-binary-tree-level-order-traversal.js b/solutions/0102-binary-tree-level-order-traversal.js deleted file mode 100644 index eb34e09b..00000000 --- a/solutions/0102-binary-tree-level-order-traversal.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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/solutions/0110-balanced-binary-tree.js b/solutions/0110-balanced-binary-tree.js deleted file mode 100644 index 2f4e7213..00000000 --- a/solutions/0110-balanced-binary-tree.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 110. Balanced Binary Tree - * https://leetcode.com/problems/balanced-binary-tree/ - * Difficulty: Easy - * - * Given a binary tree, determine if it is height-balanced. - */ - -/** - * 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 isBalanced = function(root) { - if (!root) return true; - return isBalanced(root.right) && isBalanced(root.left) - && Math.abs(traverse(root.right) - traverse(root.left)) < 2; -}; - -function traverse(node, depth = 0) { - if (!node) return depth; - return Math.max(traverse(node.right, depth + 1), traverse(node.left, depth + 1)); -} diff --git a/solutions/0112-path-sum.js b/solutions/0112-path-sum.js deleted file mode 100644 index c4f37a2f..00000000 --- a/solutions/0112-path-sum.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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/solutions/0121-best-time-to-buy-and-sell-stock.js b/solutions/0121-best-time-to-buy-and-sell-stock.js deleted file mode 100644 index 20d2557f..00000000 --- a/solutions/0121-best-time-to-buy-and-sell-stock.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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/solutions/0125-valid-palindrome.js b/solutions/0125-valid-palindrome.js deleted file mode 100644 index 74ad00f1..00000000 --- a/solutions/0125-valid-palindrome.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * 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/solutions/0153-find-minimum-in-rotated-sorted-array.js b/solutions/0153-find-minimum-in-rotated-sorted-array.js deleted file mode 100644 index 4146f626..00000000 --- a/solutions/0153-find-minimum-in-rotated-sorted-array.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 153. Find Minimum in Rotated Sorted Array - * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ - * Difficulty: Medium - * - * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. - * For example, the array nums = [0,1,2,4,5,6,7] might become: - * - [4,5,6,7,0,1,2] if it was rotated 4 times. - * - [0,1,2,4,5,6,7] if it was rotated 7 times. - * - * Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array - * [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. - * - * Given the sorted rotated array nums of unique elements, return the minimum element of this - * array. - * - * You must write an algorithm that runs in O(log n) time. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findMin = function(nums) { - let left = 0; - let right = nums.length - 1; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - - if (nums[mid] <= nums[right]) { - right = mid; - } else { - left = mid + 1; - } - } - - return nums[left]; -}; diff --git a/solutions/0189-rotate-array.js b/solutions/0189-rotate-array.js deleted file mode 100644 index b6bcc49a..00000000 --- a/solutions/0189-rotate-array.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 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/solutions/0209-minimum-size-subarray-sum.js b/solutions/0209-minimum-size-subarray-sum.js deleted file mode 100644 index ee8208ed..00000000 --- a/solutions/0209-minimum-size-subarray-sum.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 209. Minimum Size Subarray Sum - * https://leetcode.com/problems/minimum-size-subarray-sum/ - * Difficulty: Medium - * - * Given an array of positive integers nums and a positive integer target, return the - * minimal length of a subarray whose sum is greater than or equal to target. If there - * is no such subarray, return 0 instead. - */ - -/** - * @param {number} target - * @param {number[]} nums - * @return {number} - */ -var minSubArrayLen = function(target, nums) { - let result = Infinity; - - for (let right = 0, sum = 0, left = 0; right < nums.length; right++) { - sum += nums[right]; - while (sum >= target) { - result = Math.min(result, right - left + 1); - sum -= nums[left]; - left++; - } - } - - return result === Infinity ? 0 : result; -}; diff --git a/solutions/0215-kth-largest-element-in-an-array.js b/solutions/0215-kth-largest-element-in-an-array.js deleted file mode 100644 index a41a489b..00000000 --- a/solutions/0215-kth-largest-element-in-an-array.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * 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/solutions/0217-contains-duplicate.js b/solutions/0217-contains-duplicate.js deleted file mode 100644 index 951c214f..00000000 --- a/solutions/0217-contains-duplicate.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 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/solutions/0226-invert-binary-tree.js b/solutions/0226-invert-binary-tree.js deleted file mode 100644 index 8ca433ef..00000000 --- a/solutions/0226-invert-binary-tree.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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; -}; diff --git a/solutions/0234-palindrome-linked-list.js b/solutions/0234-palindrome-linked-list.js deleted file mode 100644 index 37b4a5e6..00000000 --- a/solutions/0234-palindrome-linked-list.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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/solutions/0238-product-of-array-except-self.js b/solutions/0238-product-of-array-except-self.js deleted file mode 100644 index f297cd25..00000000 --- a/solutions/0238-product-of-array-except-self.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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/solutions/0239-sliding-window-maximum.js b/solutions/0239-sliding-window-maximum.js deleted file mode 100644 index b4845467..00000000 --- a/solutions/0239-sliding-window-maximum.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 239. Sliding Window Maximum - * https://leetcode.com/problems/sliding-window-maximum/ - * Difficulty: Hard - * - * You are given an array of integers nums, there is a sliding window of size k which is moving - * from the very left of the array to the very right. You can only see the k numbers in the - * window. Each time the sliding window moves right by one position. - * - * Return the max sliding window. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var maxSlidingWindow = function(nums, k) { - const result = []; - const queue = []; - - for (let i = 0; i < nums.length; i++) { - while (queue.length && queue[0] < i - k + 1) { - queue.shift(); - } - while (queue.length && nums[queue[queue.length - 1]] < nums[i]) { - queue.pop(); - } - queue.push(i); - if (i >= k - 1) { - result.push(nums[queue[0]]); - } - } - - return result; -}; diff --git a/solutions/0242-valid-anagram.js b/solutions/0242-valid-anagram.js deleted file mode 100644 index e922f3d0..00000000 --- a/solutions/0242-valid-anagram.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 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/solutions/0283-move-zeroes.js b/solutions/0283-move-zeroes.js deleted file mode 100644 index d3008579..00000000 --- a/solutions/0283-move-zeroes.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 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) { - [nums[i], nums[j++]] = [nums[j], nums[i]]; - } - } -}; diff --git a/solutions/0347-top-k-frequent-elements.js b/solutions/0347-top-k-frequent-elements.js deleted file mode 100644 index 87b6b3e5..00000000 --- a/solutions/0347-top-k-frequent-elements.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 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/solutions/0389-find-the-difference.js b/solutions/0389-find-the-difference.js deleted file mode 100644 index d789a16e..00000000 --- a/solutions/0389-find-the-difference.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 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/solutions/0412-fizz-buzz.js b/solutions/0412-fizz-buzz.js deleted file mode 100644 index ed737dd8..00000000 --- a/solutions/0412-fizz-buzz.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 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/solutions/0424-longest-repeating-character-replacement.js b/solutions/0424-longest-repeating-character-replacement.js deleted file mode 100644 index 2db1471e..00000000 --- a/solutions/0424-longest-repeating-character-replacement.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 424. Longest Repeating Character Replacement - * https://leetcode.com/problems/longest-repeating-character-replacement/ - * Difficulty: Medium - * - * You are given a string s and an integer k. You can choose any character of the string - * and change it to any other uppercase English character. You can perform this operation - * at most k times. - * - * Return the length of the longest substring containing the same letter you can get after - * performing the above operations. - */ - -/** - * @param {string} s - * @param {number} k - * @return {number} - */ -var characterReplacement = function(s, k) { - const count = new Map(); - let max = 0; - let left = 0; - - return s.split('').reduce((maxLength, char, right) => { - count.set(char, (count.get(char) || 0) + 1); - max = Math.max(max, count.get(char)); - if (right - left + 1 - max > k) { - count.set(s[left], count.get(s[left++]) - 1); - } - return Math.max(maxLength, right - left + 1); - }, 0); -}; diff --git a/solutions/0451-sort-characters-by-frequency.js b/solutions/0451-sort-characters-by-frequency.js deleted file mode 100644 index 4c29eed3..00000000 --- a/solutions/0451-sort-characters-by-frequency.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 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(''); -}; diff --git a/solutions/0515-find-largest-value-in-each-tree-row.js b/solutions/0515-find-largest-value-in-each-tree-row.js deleted file mode 100644 index 7c20a6e7..00000000 --- a/solutions/0515-find-largest-value-in-each-tree-row.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 515. Find Largest Value in Each Tree Row - * https://leetcode.com/problems/find-largest-value-in-each-tree-row/ - * Difficulty: Medium - * - * Given the root of a binary tree, return an array of the largest value in each row - * of the tree (0-indexed). - */ - -/** - * 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 largestValues = function(root) { - if (!root) return []; - const result = []; - const queue = [root]; - - while (queue.length) { - const level = queue.length; - let max = -Infinity; - for (let i = 0; i < level; i++) { - const node = queue.shift(); - max = Math.max(max, node.val); - if (node.left) queue.push(node.left); - if (node.right) queue.push(node.right); - } - result.push(max); - } - - return result; -}; diff --git a/solutions/0516-longest-palindromic-subsequence.js b/solutions/0516-longest-palindromic-subsequence.js deleted file mode 100644 index 5541b2ec..00000000 --- a/solutions/0516-longest-palindromic-subsequence.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 516. Longest Palindromic Subsequence - * https://leetcode.com/problems/longest-palindromic-subsequence/ - * Difficulty: Medium - * - * Given a string s, find the longest palindromic subsequence's length in s. - * - * A subsequence is a sequence that can be derived from another sequence by deleting some - * or no elements without changing the order of the remaining elements. - */ - -/** - * @param {string} s - * @return {number} - */ -/** - * @param {string} s - * @return {number} - */ -var longestPalindromeSubseq = function(s) { - const dp = new Array(s.length).fill(0); - - for (let i = s.length - 1, previous; i >= 0; i--) { - previous = dp.slice(); - dp[i] = 1; - for (let j = i + 1; j < s.length; j++) { - if (s[i] === s[j]) { - dp[j] = (previous[j - 1] || 0) + 2; - } else { - dp[j] = Math.max(dp[j - 1], previous[j]); - } - } - } - - return dp[s.length - 1]; -}; diff --git a/solutions/0517-super-washing-machines.js b/solutions/0517-super-washing-machines.js deleted file mode 100644 index 399565ba..00000000 --- a/solutions/0517-super-washing-machines.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 517. Super Washing Machines - * https://leetcode.com/problems/super-washing-machines/ - * Difficulty: Hard - * - * You have n super washing machines on a line. Initially, each washing machine has some - * dresses or is empty. - * - * For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress - * of each washing machine to one of its adjacent washing machines at the same time. - * - * Given an integer array machines representing the number of dresses in each washing machine - * from left to right on the line, return the minimum number of moves to make all the washing - * machines have the same number of dresses. If it is not possible to do it, return -1. - */ - -/** - * @param {number[]} machines - * @return {number} - */ -var findMinMoves = function(machines) { - const total = machines.reduce((sum, num) => sum + num, 0); - const target = total / machines.length; - if (total % machines.length !== 0) return -1; - - let result = 0; - for (let i = 0, balance = 0; i < machines.length; i++) { - balance += machines[i] - target; - result = Math.max(result, Math.abs(balance), machines[i] - target); - } - return result; -}; diff --git a/solutions/0518-coin-change-ii.js b/solutions/0518-coin-change-ii.js deleted file mode 100644 index 4b93fd9f..00000000 --- a/solutions/0518-coin-change-ii.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 518. Coin Change II - * https://leetcode.com/problems/coin-change-ii/ - * Difficulty: Medium - * - * You are given an integer array coins representing coins of different denominations and - * an integer amount representing a total amount of money. - * - * Return the number of combinations that make up that amount. If that amount of money - * cannot be made up by any combination of the coins, return 0. - * - * You may assume that you have an infinite number of each kind of coin. - * - * The answer is guaranteed to fit into a signed 32-bit integer. - */ - -/** - * @param {number} amount - * @param {number[]} coins - * @return {number} - */ -var change = function(amount, coins) { - const dp = new Array(amount + 1).fill(0); - dp[0] = 1; - - for (const coin of coins) { - for (let i = coin; i <= amount; i++) { - dp[i] += dp[i - coin]; - } - } - - return dp[amount]; -}; diff --git a/solutions/0519-random-flip-matrix.js b/solutions/0519-random-flip-matrix.js deleted file mode 100644 index 03edb7e7..00000000 --- a/solutions/0519-random-flip-matrix.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 519. Random Flip Matrix - * https://leetcode.com/problems/random-flip-matrix/ - * Difficulty: Medium - * - * There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm - * to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices - * (i, j) where matrix[i][j] == 0 should be equally likely to be returned. - * - * Optimize your algorithm to minimize the number of calls made to the built-in random function - * of your language and optimize the time and space complexity. - * - * Implement the Solution class: - * - Solution(int m, int n) Initializes the object with the size of the binary matrix m and n. - * - int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips - * it to 1. - * - void reset() Resets all the values of the matrix to be 0. - */ - -/** - * @param {number} m - * @param {number} n - */ -var Solution = function(m, n) { - this.m = m; - this.n = n; - this.total = m * n; - this.flipped = new Map(); -}; - -/** - * @return {number[]} - */ -Solution.prototype.flip = function() { - const index = Math.floor(Math.random() * this.total--); - const result = this.flipped.get(index) ?? index; - this.flipped.set(index, this.flipped.get(this.total) ?? this.total); - return [Math.floor(result / this.n), result % this.n]; -}; - -/** - * @return {void} - */ -Solution.prototype.reset = function() { - this.total = this.m * this.n; - this.flipped.clear(); -}; diff --git a/solutions/0522-longest-uncommon-subsequence-ii.js b/solutions/0522-longest-uncommon-subsequence-ii.js deleted file mode 100644 index 0dd63297..00000000 --- a/solutions/0522-longest-uncommon-subsequence-ii.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 522. Longest Uncommon Subsequence II - * https://leetcode.com/problems/longest-uncommon-subsequence-ii/ - * Difficulty: Medium - * - * Given an array of strings strs, return the length of the longest uncommon subsequence - * between them. If the longest uncommon subsequence does not exist, return -1. - * - * An uncommon subsequence between an array of strings is a string that is a subsequence - * of one string but not the others. - * - * A subsequence of a string s is a string that can be obtained after deleting any number - * of characters from s. - * - * For example, "abc" is a subsequence of "aebdc" because you can delete the underlined - * characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", - * "aeb", and "" (empty string). - */ - -/** - * @param {string[]} strs - * @return {number} - */ -var findLUSlength = function(strs) { - strs.sort((a, b) => b.length - a.length); - - for (let i = 0; i < strs.length; i++) { - let isUnique = true; - for (let j = 0; j < strs.length; j++) { - if (i !== j && isSubsequence(strs[i], strs[j])) { - isUnique = false; - break; - } - } - if (isUnique) { - return strs[i].length; - } - } - - return -1; - - function isSubsequence(s1, s2) { - let index = 0; - for (const char of s2) { - if (char === s1[index]) index++; - if (index === s1.length) return true; - } - return false; - } -}; diff --git a/solutions/0523-continuous-subarray-sum.js b/solutions/0523-continuous-subarray-sum.js deleted file mode 100644 index 21b57dc2..00000000 --- a/solutions/0523-continuous-subarray-sum.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 523. Continuous Subarray Sum - * https://leetcode.com/problems/continuous-subarray-sum/ - * Difficulty: Medium - * - * Given an integer array nums and an integer k, return true if nums has a good subarray - * or false otherwise. - * - * A good subarray is a subarray where: - * - its length is at least two, and - * - the sum of the elements of the subarray is a multiple of k. - * - * Note that: - * - A subarray is a contiguous part of the array. - * - An integer x is a multiple of k if there exists an integer n such that x = n * k. - * 0 is always a multiple of k. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {boolean} - */ -var checkSubarraySum = function(nums, k) { - const map = new Map([[0, -1]]); - - for (let i = 0, sum = 0; i < nums.length; i++) { - sum += nums[i]; - if (k !== 0) { - sum = sum % k; - } - - if (map.has(sum)) { - if (i - map.get(sum) >= 2) { - return true; - } - } else { - map.set(sum, i); - } - } - - return false; -}; diff --git a/solutions/0524-longest-word-in-dictionary-through-deleting.js b/solutions/0524-longest-word-in-dictionary-through-deleting.js deleted file mode 100644 index ee0dee1e..00000000 --- a/solutions/0524-longest-word-in-dictionary-through-deleting.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 524. Longest Word in Dictionary through Deleting - * https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ - * Difficulty: Medium - * - * Given a string s and a string array dictionary, return the longest string in the dictionary - * that can be formed by deleting some of the given string characters. If there is more than - * one possible result, return the longest word with the smallest lexicographical order. - * If there is no possible result, return the empty string. - */ - -/** - * @param {string} s - * @param {string[]} dictionary - * @return {string} - */ -var findLongestWord = function(s, dictionary) { - return dictionary - .sort((a, b) => a.length === b.length ? a.localeCompare(b) : b.length - a.length) - .find(word => { - let i = 0; - for (const character of s) { - if (character === word[i]) i++; - if (i === word.length) return true; - } - return false; - }) || ''; -}; diff --git a/solutions/0525-contiguous-array.js b/solutions/0525-contiguous-array.js deleted file mode 100644 index eef44899..00000000 --- a/solutions/0525-contiguous-array.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 525. Contiguous Array - * https://leetcode.com/problems/contiguous-array/ - * Difficulty: Medium - * - * Given a binary array nums, return the maximum length of a contiguous subarray - * with an equal number of 0 and 1. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findMaxLength = function(nums) { - const map = new Map([[0, -1]]); - let result = 0; - - for (let i = 0, count = 0; i < nums.length; i++) { - count += nums[i] === 1 ? 1 : -1; - if (map.has(count)) { - result = Math.max(result, i - map.get(count)); - } else { - map.set(count, i); - } - } - - return result; -}; diff --git a/solutions/0526-beautiful-arrangement.js b/solutions/0526-beautiful-arrangement.js deleted file mode 100644 index 0fd536f7..00000000 --- a/solutions/0526-beautiful-arrangement.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 526. Beautiful Arrangement - * https://leetcode.com/problems/beautiful-arrangement/ - * Difficulty: Medium - * - * Suppose you have n integers labeled 1 through n. A permutation of those n integers perm - * (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either - * of the following is true: - * - perm[i] is divisible by i. - * - i is divisible by perm[i]. - * - * Given an integer n, return the number of the beautiful arrangements that you can construct. - */ - -/** - * @param {number} n - * @return {number} - */ -var countArrangement = function(n) { - let count = 0; - backtrack(1, 0); - return count; - - function backtrack(offset, used) { - if (offset > n) { - count++; - return; - } - for (let i = 1; i <= n; i++) { - if (!(used & (1 << i)) && (i % offset === 0 || offset % i === 0)) { - backtrack(offset + 1, used | (1 << i)); - } - } - } -}; diff --git a/solutions/0528-random-pick-with-weight.js b/solutions/0528-random-pick-with-weight.js deleted file mode 100644 index 26555599..00000000 --- a/solutions/0528-random-pick-with-weight.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 528. Random Pick with Weight - * https://leetcode.com/problems/random-pick-with-weight/ - * Difficulty: Medium - * - * You are given a 0-indexed array of positive integers w where w[i] describes the - * weight of the ith index. - * - * You need to implement the function pickIndex(), which randomly picks an index in - * the range [0, w.length - 1] (inclusive) and returns it. The probability of picking - * an index i is w[i] / sum(w). - * - * For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 - * (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%). - */ - -/** - * @param {number[]} w - */ -var Solution = function(w) { - this.sums = []; - let sum = 0; - for (const weight of w) { - sum += weight; - this.sums.push(sum); - } - this.total = sum; -}; - -/** - * @return {number} - */ -Solution.prototype.pickIndex = function() { - const target = Math.random() * this.total; - let left = 0; - let right = this.sums.length - 1; - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (this.sums[mid] <= target) { - left = mid + 1; - } else { - right = mid; - } - } - return left; -}; diff --git a/solutions/0529-minesweeper.js b/solutions/0529-minesweeper.js deleted file mode 100644 index 15d5e851..00000000 --- a/solutions/0529-minesweeper.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * 529. Minesweeper - * https://leetcode.com/problems/minesweeper/ - * Difficulty: Medium - * - * Let's play the minesweeper game (Wikipedia, online game)! - * - * You are given an m x n char matrix board representing the game board where: - * - 'M' represents an unrevealed mine, - * - 'E' represents an unrevealed empty square, - * - 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, - * left, right, and all 4 diagonals), - * - digit ('1' to '8') represents how many mines are adjacent to this revealed square, and - * - 'X' represents a revealed mine. - * - * You are also given an integer array click where click = [clickr, clickc] represents the - * next click position among all the unrevealed squares ('M' or 'E'). - * - * Return the board after revealing this position according to the following rules: - * 1. If a mine 'M' is revealed, then the game is over. You should change it to 'X'. - * 2. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed - * blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. - * 3. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a - * digit ('1' to '8') representing the number of adjacent mines. - * 4. Return the board when no more squares will be revealed. - */ - -/** - * @param {character[][]} board - * @param {number[]} click - * @return {character[][]} - */ -var updateBoard = function(board, click) { - const [row, col] = click; - const rows = board.length; - const cols = board[0].length; - const directions = [ - [-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1] - ]; - - if (board[row][col] === 'M') { - board[row][col] = 'X'; - return board; - } - - dfs(row, col); - return board; - - function dfs(r, c) { - if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== 'E') return; - - let mines = 0; - for (const [dr, dc] of directions) { - const nr = r + dr; - const nc = c + dc; - if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] === 'M') { - mines++; - } - } - - board[r][c] = mines > 0 ? mines.toString() : 'B'; - if (mines === 0) { - for (const [dr, dc] of directions) { - dfs(r + dr, c + dc); - } - } - } -}; diff --git a/solutions/0532-k-diff-pairs-in-an-array.js b/solutions/0532-k-diff-pairs-in-an-array.js deleted file mode 100644 index 769ca6f8..00000000 --- a/solutions/0532-k-diff-pairs-in-an-array.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 532. K-diff Pairs in an Array - * https://leetcode.com/problems/k-diff-pairs-in-an-array/ - * Difficulty: Medium - * - * Given an array of integers nums and an integer k, return the number of unique k-diff - * pairs in the array. - * - * A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: - * - 0 <= i, j < nums.length - * - i != j - * - |nums[i] - nums[j]| == k - * - * Notice that |val| denotes the absolute value of val. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var findPairs = function(nums, k) { - const map = new Map(); - let result = 0; - - for (const num of nums) { - if (!map.has(num)) { - if (!k) { - map.set(num, 1); - } else { - if (map.has(num - k)) result++; - if (map.has(num + k)) result++; - map.set(num, 1); - } - } else if (!k && map.get(num) === 1) { - result++; - map.set(num, 2); - } - } - - return result; -}; diff --git a/solutions/0535-encode-and-decode-tinyurl.js b/solutions/0535-encode-and-decode-tinyurl.js deleted file mode 100644 index 4875c4bb..00000000 --- a/solutions/0535-encode-and-decode-tinyurl.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 535. Encode and Decode TinyURL - * https://leetcode.com/problems/encode-and-decode-tinyurl/ - * Difficulty: Medium - * - * TinyURL is a URL shortening service where you enter a URL such as - * https://leetcode.com/problems/design-tinyurl and it returns a short URL such as - * http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. - * - * There is no restriction on how your encode/decode algorithm should work. You just - * need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be - * decoded to the original URL. - * - * Implement the Solution class: - * - Solution() Initializes the object of the system. - * - String encode(String longUrl) Returns a tiny URL for the given longUrl. - * - String decode(String shortUrl) Returns the original long URL for the given shortUrl. - * It is guaranteed that the given shortUrl was encoded by the same object. - */ - -const map = new Map(); -let counter = 1; - -/** - * Encodes a URL to a shortened URL. - * - * @param {string} longUrl - * @return {string} - */ -var encode = function(longUrl) { - const shortUrl = 'https://tinyurl.com/' + counter.toString(); - map.set(shortUrl, longUrl); - counter++; - return shortUrl; -}; - -/** - * Decodes a shortened URL to its original URL. - * - * @param {string} shortUrl - * @return {string} - */ -var decode = function(shortUrl) { - return map.get(shortUrl) || null; -}; diff --git a/solutions/0537-complex-number-multiplication.js b/solutions/0537-complex-number-multiplication.js deleted file mode 100644 index ad2697f6..00000000 --- a/solutions/0537-complex-number-multiplication.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 537. Complex Number Multiplication - * https://leetcode.com/problems/complex-number-multiplication/ - * Difficulty: Medium - * - * A complex number can be represented as a string on the form "real+imaginaryi" where: - * - real is the real part and is an integer in the range [-100, 100]. - * - imaginary is the imaginary part and is an integer in the range [-100, 100]. - * - i2 == -1. - * - * Given two complex numbers num1 and num2 as strings, return a string of the complex number - * that represents their multiplications. - */ - -/** - * @param {string} num1 - * @param {string} num2 - * @return {string} - */ -var complexNumberMultiply = function(num1, num2) { - const [r1, i1] = num1.split('+').map(n => parseInt(n.replace('i', ''))); - const [r2, i2] = num2.split('+').map(n => parseInt(n.replace('i', ''))); - return `${r1 * r2 - i1 * i2}+${r1 * i2 + r2 * i1}i`; -}; diff --git a/solutions/0538-convert-bst-to-greater-tree.js b/solutions/0538-convert-bst-to-greater-tree.js deleted file mode 100644 index ce8499f8..00000000 --- a/solutions/0538-convert-bst-to-greater-tree.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 538. Convert BST to Greater Tree - * https://leetcode.com/problems/convert-bst-to-greater-tree/ - * Difficulty: Medium - * - * Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every - * key of the original BST is changed to the original key plus the sum of all keys greater - * than the original key in BST. - * - * As a reminder, a binary search tree is a tree that satisfies these constraints: - * - 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 {TreeNode} - */ -var convertBST = function(root) { - let sum = 0; - traverse(root); - return root; - - function traverse(node) { - if (!node) return; - traverse(node.right); - sum += node.val; - node.val = sum; - traverse(node.left); - } -}; diff --git a/solutions/0539-minimum-time-difference.js b/solutions/0539-minimum-time-difference.js deleted file mode 100644 index 717c9a73..00000000 --- a/solutions/0539-minimum-time-difference.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 539. Minimum Time Difference - * https://leetcode.com/problems/minimum-time-difference/ - * Difficulty: Medium - * - * Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes - * difference between any two time-points in the list. - */ - -/** - * @param {string[]} timePoints - * @return {number} - */ -var findMinDifference = function(timePoints) { - const minutes = timePoints.map(time => { - const [h, m] = time.split(':').map(Number); - return h * 60 + m; - }).sort((a, b) => a - b); - let diff = Infinity; - - for (let i = 1; i < minutes.length; i++) { - diff = Math.min(diff, minutes[i] - minutes[i - 1]); - } - - return Math.min(diff, 1440 - minutes[minutes.length - 1] + minutes[0]); -}; diff --git a/solutions/0540-single-element-in-a-sorted-array.js b/solutions/0540-single-element-in-a-sorted-array.js deleted file mode 100644 index f3996dca..00000000 --- a/solutions/0540-single-element-in-a-sorted-array.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 540. Single Element in a Sorted Array - * https://leetcode.com/problems/single-element-in-a-sorted-array/ - * Difficulty: Medium - * - * You are given a sorted array consisting of only integers where every element appears - * exactly twice, except for one element which appears exactly once. - * - * Return the single element that appears only once. - * - * Your solution must run in O(log n) time and O(1) space. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var singleNonDuplicate = function(nums) { - let left = 0; - let right = nums.length - 1; - - while (left < right) { - let middle = left + Math.floor((right - left) / 2); - middle = middle - (middle % 2); - if (nums[middle] === nums[middle + 1]) { - left = middle + 2; - } else { - right = middle; - } - } - - return nums[left]; -}; diff --git a/solutions/0546-remove-boxes.js b/solutions/0546-remove-boxes.js deleted file mode 100644 index c13f21eb..00000000 --- a/solutions/0546-remove-boxes.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 546. Remove Boxes - * https://leetcode.com/problems/remove-boxes/ - * Difficulty: Hard - * - * You are given several boxes with different colors represented by different positive numbers. - * - * You may experience several rounds to remove boxes until there is no box left. Each time you - * can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), - * remove them and get k * k points. - * - * Return the maximum points you can get. - */ - -/** - * @param {number[]} boxes - * @return {number} - */ -var removeBoxes = function(boxes) { - const dp = new Array(boxes.length).fill().map(() => { - return new Array(boxes.length).fill().map(() => new Array(boxes.length + 1).fill(0)); - }); - return dfs(0, boxes.length - 1, 0); - - function dfs(l, r, k) { - if (l > r) return 0; - if (dp[l][r][k]) return dp[l][r][k]; - let i = l; - let count = k + 1; - while (i < r && boxes[i] === boxes[i + 1]) { - i++; - count++; - } - let max = count * count + dfs(i + 1, r, 0); - for (let m = i + 1; m <= r; m++) { - if (boxes[l] === boxes[m]) { - max = Math.max(max, dfs(i + 1, m - 1, 0) + dfs(m, r, count)); - } - } - return dp[l][r][k] = max; - } -}; diff --git a/solutions/0552-student-attendance-record-ii.js b/solutions/0552-student-attendance-record-ii.js deleted file mode 100644 index 49e65abe..00000000 --- a/solutions/0552-student-attendance-record-ii.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 552. Student Attendance Record II - * https://leetcode.com/problems/student-attendance-record-ii/ - * Difficulty: Hard - * - * An attendance record for a student can be represented as a string 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. - * - * Any 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. - * - * Given an integer n, return the number of possible attendance records of length n that make - * a student eligible for an attendance award. The answer may be very large, so return it - * modulo 109 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -var checkRecord = function(n) { - const MOD = 1e9 + 7; - const dp = [[1, 0, 0], [0, 0, 0]]; - - for (let i = 0; i < n; i++) { - const m = dp.map(row => [...row]); - dp[0][0] = (m[0][0] + m[0][1] + m[0][2]) % MOD; - dp[0][1] = m[0][0]; - dp[0][2] = m[0][1]; - dp[1][0] = (m[0][0] + m[0][1] + m[0][2] + m[1][0] + m[1][1] + m[1][2]) % MOD; - dp[1][1] = m[1][0]; - dp[1][2] = m[1][1]; - } - - return (dp[0][0] + dp[0][1] + dp[0][2] + dp[1][0] + dp[1][1] + dp[1][2]) % MOD; -}; diff --git a/solutions/0553-optimal-division.js b/solutions/0553-optimal-division.js deleted file mode 100644 index 50c89bb9..00000000 --- a/solutions/0553-optimal-division.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 553. Optimal Division - * https://leetcode.com/problems/optimal-division/ - * Difficulty: Medium - * - * You are given an integer array nums. The adjacent integers in nums will perform - * the float division. - * - For example, for nums = [2,3,4], we will evaluate the expression "2/3/4". - * - * However, you can add any number of parenthesis at any position to change the priority - * of operations. You want to add these parentheses such the value of the expression after - * the evaluation is maximum. - * - * Return the corresponding expression that has the maximum value in string format. - * - * Note: your expression should not contain redundant parenthesis. - */ - -/** - * @param {number[]} nums - * @return {string} - */ -var optimalDivision = function(nums) { - if (nums.length === 1) return nums[0].toString(); - if (nums.length === 2) return `${nums[0]}/${nums[1]}`; - return `${nums[0]}/(${nums.slice(1).join('/')})`; -}; diff --git a/solutions/0554-brick-wall.js b/solutions/0554-brick-wall.js deleted file mode 100644 index 114c386e..00000000 --- a/solutions/0554-brick-wall.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 554. Brick Wall - * https://leetcode.com/problems/brick-wall/ - * Difficulty: Medium - * - * There is a rectangular brick wall in front of you with n rows of bricks. The ith row has - * some number of bricks each of the same height (i.e., one unit) but they can be of different - * widths. The total width of each row is the same. - * - * Draw a vertical line from the top to the bottom and cross the least bricks. If your line - * goes through the edge of a brick, then the brick is not considered as crossed. You cannot - * draw a line just along one of the two vertical edges of the wall, in which case the line - * will obviously cross no bricks. - * - * Given the 2D array wall that contains the information about the wall, return the minimum - * number of crossed bricks after drawing such a vertical line. - */ - -/** - * @param {number[][]} wall - * @return {number} - */ -var leastBricks = function(wall) { - const map = new Map(); - let max = 0; - - for (const row of wall) { - for (let i = 0, sum = 0; i < row.length - 1; i++) { - sum += row[i]; - map.set(sum, (map.get(sum) || 0) + 1); - max = Math.max(max, map.get(sum)); - } - } - - return wall.length - max; -}; diff --git a/solutions/0556-next-greater-element-iii.js b/solutions/0556-next-greater-element-iii.js deleted file mode 100644 index f8ee8bc7..00000000 --- a/solutions/0556-next-greater-element-iii.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 556. Next Greater Element III - * https://leetcode.com/problems/next-greater-element-iii/ - * Difficulty: Medium - * - * Given a positive integer n, find the smallest integer which has exactly the same digits existing - * in the integer n and is greater in value than n. If no such positive integer exists, return -1. - * - * Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it - * does not fit in 32-bit integer, return -1. - */ - -/** - * @param {number} n - * @return {number} - */ -var nextGreaterElement = function(n) { - const digits = [...String(n)]; - let i = digits.length - 2; - - while (i >= 0 && digits[i] >= digits[i + 1]) i--; - if (i < 0) return -1; - - let j = digits.length - 1; - while (j >= 0 && digits[j] <= digits[i]) j--; - - [digits[i], digits[j]] = [digits[j], digits[i]]; - let left = i + 1; - let right = digits.length - 1; - while (left < right) { - [digits[left], digits[right]] = [digits[right], digits[left]]; - left++; - right--; - } - - const result = +digits.join(''); - return result > n && result <= 2**31 - 1 ? result : -1; -}; diff --git a/solutions/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js b/solutions/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js deleted file mode 100644 index 7dc99724..00000000 --- a/solutions/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 558. Logical OR of Two Binary Grids Represented as Quad-Trees - * https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/ - * Difficulty: Medium - * - * A Binary Matrix is a matrix in which all the elements are either 0 or 1. - * - * Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 - * represents another n * n binary matrix. - * - * Return a Quad-Tree representing the n * n binary matrix which is the result of logical - * bitwise OR of the two binary matrixes represented by quadTree1 and quadTree2. - * - * Notice that you can assign the value of a node to True or False when isLeaf is False, and - * both are accepted in the answer. - * - * A Quad-Tree is a tree data structure in which each internal node has exactly four children. - * Besides, each node has two attributes: - * - val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. - * - isLeaf: True if the node is leaf node on the tree or False if the node has the four children. - * class Node { - * public boolean val; - * public boolean isLeaf; - * public Node topLeft; - * public Node topRight; - * public Node bottomLeft; - * public Node bottomRight; - * }. - * - * We can construct a Quad-Tree from a two-dimensional area using the following steps: - * 1. If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to - * the value of the grid and set the four children to Null and stop. - * 2. If the current grid has different values, set isLeaf to False and set val to any value and - * divide the current grid into four sub-grids as shown in the photo. - * 3. Recurse for each of the children with the proper sub-grid. - */ - -/** - * // Definition for a QuadTree node. - * function _Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { - * this.val = val; - * this.isLeaf = isLeaf; - * this.topLeft = topLeft; - * this.topRight = topRight; - * this.bottomLeft = bottomLeft; - * this.bottomRight = bottomRight; - * }; - */ - -/** - * @param {_Node} quadTree1 - * @param {_Node} quadTree2 - * @return {_Node} - */ -var intersect = function(quadTree1, quadTree2) { - if (quadTree1.isLeaf) return quadTree1.val ? quadTree1 : quadTree2; - if (quadTree2.isLeaf) return quadTree2.val ? quadTree2 : quadTree1; - - const topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft); - const topRight = intersect(quadTree1.topRight, quadTree2.topRight); - const bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft); - const bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight); - - if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf - && topLeft.val === topRight.val && topRight.val === bottomLeft.val - && bottomLeft.val === bottomRight.val) { - return new _Node(topLeft.val, true, null, null, null, null); - } - - return new _Node(false, false, topLeft, topRight, bottomLeft, bottomRight); -}; diff --git a/solutions/0559-maximum-depth-of-n-ary-tree.js b/solutions/0559-maximum-depth-of-n-ary-tree.js deleted file mode 100644 index 0d83dd59..00000000 --- a/solutions/0559-maximum-depth-of-n-ary-tree.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 559. Maximum Depth of N-ary Tree - * https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ - * Difficulty: Easy - * - * Given a n-ary tree, find its maximum depth. - * - * The maximum depth is the number of nodes along the longest path from the root node down to - * the farthest leaf node. - * - * Nary-Tree input serialization is represented in their level order traversal, each group of - * children is separated by the null value (See examples). - */ - -/** - * // Definition for a _Node. - * function _Node(val,children) { - * this.val = val === undefined ? null : val; - * this.children = children === undefined ? null : children; - * }; - */ - -/** - * @param {_Node|null} root - * @return {number} - */ -var maxDepth = function(root) { - if (!root) return 0; - if (!root.children || !root.children.length) return 1; - return Math.max(...root.children.map(child => maxDepth(child))) + 1; -}; diff --git a/solutions/0561-array-partition.js b/solutions/0561-array-partition.js deleted file mode 100644 index 17596442..00000000 --- a/solutions/0561-array-partition.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * 561. Array Partition - * https://leetcode.com/problems/array-partition/ - * Difficulty: Easy - * - * Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), - * (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. - * Return the maximized sum. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var arrayPairSum = function(nums) { - return nums.sort((a, b) => a - b).reduce((sum, v, i, a) => - sum + (i % 2 === 0 ? Math.min(v, a[i + 1]) : 0), 0); -}; diff --git a/solutions/0564-find-the-closest-palindrome.js b/solutions/0564-find-the-closest-palindrome.js deleted file mode 100644 index d67ea4fc..00000000 --- a/solutions/0564-find-the-closest-palindrome.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 564. Find the Closest Palindrome - * https://leetcode.com/problems/find-the-closest-palindrome/ - * Difficulty: Hard - * - * Given a string n representing an integer, return the closest integer (not including itself), - * which is a palindrome. If there is a tie, return the smaller one. - * - * The closest is defined as the absolute difference minimized between two integers. - */ - -/** - * @param {string} n - * @return {string} - */ -var nearestPalindromic = function(n) { - const num = BigInt(n); - - if (num <= 10n) return String(num - 1n); - if (num === 11n) return '9'; - if (n === '1' + '0'.repeat(n.length - 1)) return String(num - 1n); - if (n === '9'.repeat(n.length)) return String(num + 2n); - - const leftHalf = n.slice(0, Math.ceil(n.length / 2)); - const leftNum = BigInt(leftHalf); - const candidates = [ - String(10n ** BigInt(n.length - 1) - 1n), - createPalindrome(leftNum - 1n, n.length), - createPalindrome(leftNum, n.length), - createPalindrome(leftNum + 1n, n.length), - String(10n ** BigInt(n.length) + 1n) - ].filter(x => x !== n); - - return candidates.reduce((min, curr) => { - const currDiff = BigInt(curr) > num ? BigInt(curr) - num : num - BigInt(curr); - const minDiff = BigInt(min) > num ? BigInt(min) - num : num - BigInt(min); - return currDiff < minDiff - ? curr - : currDiff === minDiff - ? (curr < min ? curr : min) - : min; - }); - - function createPalindrome(left, length) { - const s = String(left); - return length % 2 === 0 - ? s + s.split('').reverse().join('') - : s + s.slice(0, -1).split('').reverse().join(''); - } -}; diff --git a/solutions/0567-permutation-in-string.js b/solutions/0567-permutation-in-string.js deleted file mode 100644 index 20c61c88..00000000 --- a/solutions/0567-permutation-in-string.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 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/solutions/0572-subtree-of-another-tree.js b/solutions/0572-subtree-of-another-tree.js deleted file mode 100644 index cd204e3f..00000000 --- a/solutions/0572-subtree-of-another-tree.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 572. Subtree of Another Tree - * https://leetcode.com/problems/subtree-of-another-tree/ - * Difficulty: Easy - * - * Given the roots of two binary trees root and subRoot, return true if there is a subtree of - * root with the same structure and node values of subRoot and false otherwise. - * - * A subtree of a binary tree tree is a tree that consists of a node in tree and all of this - * node's descendants. The tree tree could also be considered as a subtree of itself. - */ - -/** - * 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 {TreeNode} subRoot - * @return {boolean} - */ -var isSubtree = function(root, subRoot) { - return traverse(root).includes(traverse(subRoot)); - function traverse(node) { - return !node ? '#' : `,${node.val},${traverse(node.left)},${traverse(node.right)}`; - } -}; diff --git a/solutions/0576-out-of-boundary-paths.js b/solutions/0576-out-of-boundary-paths.js deleted file mode 100644 index ee1c8acc..00000000 --- a/solutions/0576-out-of-boundary-paths.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 576. Out of Boundary Paths - * https://leetcode.com/problems/out-of-boundary-paths/ - * Difficulty: Medium - * - * There is an m x n grid with a ball. The ball is initially at the position [startRow, - * startColumn]. You are allowed to move the ball to one of the four adjacent cells in - * the grid (possibly out of the grid crossing the grid boundary). You can apply at most - * maxMove moves to the ball. - * - * Given the five integers m, n, maxMove, startRow, startColumn, return the number of - * paths to move the ball out of the grid boundary. Since the answer can be very large, - * return it modulo 109 + 7. - */ - -/** - * @param {number} m - * @param {number} n - * @param {number} maxMove - * @param {number} startRow - * @param {number} startColumn - * @return {number} - */ -var findPaths = function(m, n, maxMove, startRow, startColumn) { - const MOD = 1e9 + 7; - const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; - const dp = new Array(maxMove + 1).fill().map(() => { - return new Array(m).fill().map(() => new Array(n).fill(-1)); - }); - - return solve(maxMove, startRow, startColumn); - - function solve(moves, row, col) { - if (row < 0 || row >= m || col < 0 || col >= n) return 1; - if (moves === 0) return 0; - if (dp[moves][row][col] !== -1) return dp[moves][row][col]; - - let paths = 0; - for (const [dr, dc] of directions) { - paths = (paths + solve(moves - 1, row + dr, col + dc)) % MOD; - } - return dp[moves][row][col] = paths; - } -}; diff --git a/solutions/0581-shortest-unsorted-continuous-subarray.js b/solutions/0581-shortest-unsorted-continuous-subarray.js deleted file mode 100644 index ab1dca43..00000000 --- a/solutions/0581-shortest-unsorted-continuous-subarray.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 581. Shortest Unsorted Continuous Subarray - * https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ - * Difficulty: Medium - * - * Given an integer array nums, you need to find one continuous subarray such that if you - * only sort this subarray in non-decreasing order, then the whole array will be sorted - * in non-decreasing order. - * - * Return the shortest such subarray and output its length. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findUnsortedSubarray = function(nums) { - let start = -1; - let end = -2; - - for (let i = 1, min = nums[nums.length - 1], max = nums[0]; i < nums.length; i++) { - max = Math.max(max, nums[i]); - min = Math.min(min, nums[nums.length - 1 - i]); - if (nums[i] < max) { - end = i; - } - if (nums[nums.length - 1 - i] > min) { - start = nums.length - 1 - i; - } - } - - return end - start + 1; -}; diff --git a/solutions/0583-delete-operation-for-two-strings.js b/solutions/0583-delete-operation-for-two-strings.js deleted file mode 100644 index ab547889..00000000 --- a/solutions/0583-delete-operation-for-two-strings.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 583. Delete Operation for Two Strings - * https://leetcode.com/problems/delete-operation-for-two-strings/ - * Difficulty: Medium - * - * Given two strings word1 and word2, return the minimum number of steps required to - * make word1 and word2 the same. - * - * In one step, you can delete exactly one character in either string. - */ - -/** - * @param {string} word1 - * @param {string} word2 - * @return {number} - */ -var minDistance = function(word1, word2) { - const dp = new Array(word1.length + 1).fill().map(() => { - return new Array(word2.length + 1).fill(0); - }); - - for (let i = 1; i <= word1.length; i++) { - dp[i][0] = i; - } - for (let j = 1; j <= word2.length; j++) { - dp[0][j] = j; - } - for (let i = 1; i <= word1.length; i++) { - for (let j = 1; j <= word2.length; j++) { - dp[i][j] = word1[i - 1] === word2[j - 1] - ? dp[i - 1][j - 1] - : Math.min(dp[i - 1][j], dp[i][j - 1]) + 1; - } - } - - return dp[word1.length][word2.length]; -}; diff --git a/solutions/0587-erect-the-fence.js b/solutions/0587-erect-the-fence.js deleted file mode 100644 index 6df622fa..00000000 --- a/solutions/0587-erect-the-fence.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 587. Erect the Fence - * https://leetcode.com/problems/erect-the-fence/ - * Difficulty: Hard - * - * You are given an array trees where trees[i] = [xi, yi] represents the location of - * a tree in the garden. - * - * Fence the entire garden using the minimum length of rope, as it is expensive. The - * garden is well-fenced only if all the trees are enclosed. - * - * Return the coordinates of trees that are exactly located on the fence perimeter. - * You may return the answer in any order. - */ - -/** - * @param {number[][]} trees - * @return {number[][]} - */ -var outerTrees = function(trees) { - const a = []; - const b = []; - - trees.sort(([x1, y1], [x2, y2]) => x1 === x2 ? y1 - y2 : x1 - x2); - for (const point of trees) { - while (a.length >= 2 && cross(a[a.length - 2], a[a.length - 1], point) < 0) { - a.pop(); - } - a.push(point); - while (b.length >= 2 && cross(b[b.length - 2], b[b.length - 1], point) > 0) { - b.pop(); - } - b.push(point); - } - - return [...new Set([...a, ...b].map(p => JSON.stringify(p)))].map(p => JSON.parse(p)); - - function cross(p, q, r) { - return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); - } -}; diff --git a/solutions/0590-n-ary-tree-postorder-traversal.js b/solutions/0590-n-ary-tree-postorder-traversal.js deleted file mode 100644 index 32e39913..00000000 --- a/solutions/0590-n-ary-tree-postorder-traversal.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 590. N-ary Tree Postorder Traversal - * https://leetcode.com/problems/n-ary-tree-postorder-traversal/ - * Difficulty: Easy - * - * Given the root of an n-ary tree, return the postorder traversal of its nodes' values. - * - * Nary-Tree input serialization is represented in their level order traversal. Each group - * of children is separated by the null value (See examples) - */ - -/** - * // Definition for a _Node. - * function _Node(val,children) { - * this.val = val; - * this.children = children; - * }; - */ - -/** - * @param {_Node|null} root - * @return {number[]} - */ -var postorder = function(root) { - const result = []; - traverse(root); - return result; - - function traverse(node) { - if (!node) return; - node.children.forEach(child => traverse(child)); - result.push(node.val); - } -}; diff --git a/solutions/0591-tag-validator.js b/solutions/0591-tag-validator.js deleted file mode 100644 index 2fef8784..00000000 --- a/solutions/0591-tag-validator.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 591. Tag Validator - * https://leetcode.com/problems/tag-validator/ - * Difficulty: Hard - * - * Given a string representing a code snippet, implement a tag validator to parse the code and - * return whether it is valid. - * - * A code snippet is valid if all the following rules hold: - * 1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. - * 2. A closed tag (not necessarily valid) has exactly the following format: - * TAG_CONTENT. Among them, is the start tag, and - * is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid - * if and only if the TAG_NAME and TAG_CONTENT are valid. - * 3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, - * the TAG_NAME is invalid. - * 4. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see - * note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with - * invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. - * 5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. - * However, you also need to consider the issue of unbalanced when tags are nested. - * 6. A < is unmatched if you cannot find a subsequent >. And when you find a < or should be parsed as TAG_NAME (not necessarily - * valid). - * 7. The cdata has the following format : . The range of CDATA_CONTENT - * is defined as the characters between . - * 8. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator - * to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter - * valid or invalid), you should treat it as regular characters. - */ - -/** - * @param {string} code - * @return {boolean} - */ -var isValid = function(code) { - const stack = []; - - for (let i = 0; i < code.length;) { - if (i > 0 && !stack.length) { - return false; - } - if (code.startsWith('', j); - if (i === -1) { - return false; - } - i += 3; - } else if (code.startsWith('', j); - if (i === -1) { - return false; - } - const tag = code.slice(j, i); - if (!stack.length || stack.pop() !== tag || !/^[A-Z]{1,9}$/.test(tag)) { - return false; - } - i++; - } else if (code[i] === '<') { - const j = i + 1; - i = code.indexOf('>', j); - if (i === -1) { - return false; - } - const tag = code.slice(j, i); - if (!/^[A-Z]{1,9}$/.test(tag)) { - return false; - } - stack.push(tag); - i++; - } else { - i++; - } - } - - return !stack.length; -}; diff --git a/solutions/0592-fraction-addition-and-subtraction.js b/solutions/0592-fraction-addition-and-subtraction.js deleted file mode 100644 index 4078b08f..00000000 --- a/solutions/0592-fraction-addition-and-subtraction.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 592. Fraction Addition and Subtraction - * https://leetcode.com/problems/fraction-addition-and-subtraction/ - * Difficulty: Medium - * - * Given a string expression representing an expression of fraction addition and subtraction, - * return the calculation result in string format. - * - * The final result should be an irreducible fraction. If your final result is an integer, - * change it to the format of a fraction that has a denominator 1. So in this case, 2 should - * be converted to 2/1. - */ - -/** - * @param {string} expression - * @return {string} - */ -var fractionAddition = function(expression) { - const gcdCalc = (a, b) => b === 0 ? a : gcdCalc(b, a % b); - const fractions = expression.match(/[+-]?\d+\/\d+/g); - let n = 0; - let d = 1; - - for (const fraction of fractions) { - const [numerator, denominator] = fraction.split('/').map(Number); - n = n * denominator + numerator * d; - d = d * denominator; - const gcd = Math.abs(gcdCalc(n, d)); - n /= gcd; - d /= gcd; - } - - return `${n}/${d}`; -}; diff --git a/solutions/0593-valid-square.js b/solutions/0593-valid-square.js deleted file mode 100644 index df3975d4..00000000 --- a/solutions/0593-valid-square.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 593. Valid Square - * https://leetcode.com/problems/valid-square/ - * Difficulty: Medium - * - * Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the - * four points construct a square. - * - * The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. - * - * A valid square has four equal sides with positive length and four equal angles (90-degree - * angles). - */ - -/** - * @param {number[]} p1 - * @param {number[]} p2 - * @param {number[]} p3 - * @param {number[]} p4 - * @return {boolean} - */ -var validSquare = function(p1, p2, p3, p4) { - const helper = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2; - const points = [p1, p2, p3, p4]; - const set = new Set(); - - for (let i = 0; i < 4; i++) { - for (let j = i + 1; j < 4; j++) { - const d = helper(points[i], points[j]); - if (!d) { - return false; - } - set.add(d); - } - } - - return set.size === 2; -}; diff --git a/solutions/0598-range-addition-ii.js b/solutions/0598-range-addition-ii.js deleted file mode 100644 index 7a013ccd..00000000 --- a/solutions/0598-range-addition-ii.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 598. Range Addition II - * https://leetcode.com/problems/range-addition-ii/ - * Difficulty: Easy - * - * You are given an m x n matrix M initialized with all 0's and an array of operations ops, - * where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai - * and 0 <= y < bi. - * - * Count and return the number of maximum integers in the matrix after performing all the - * operations. - */ - -/** - * @param {number} m - * @param {number} n - * @param {number[][]} ops - * @return {number} - */ -var maxCount = function(m, n, ops) { - let a = m; - let b = n; - - for (const op of ops) { - a = Math.min(a, op[0]); - b = Math.min(b, op[1]); - } - - return a * b; -}; diff --git a/solutions/0600-non-negative-integers-without-consecutive-ones.js b/solutions/0600-non-negative-integers-without-consecutive-ones.js deleted file mode 100644 index c352c96a..00000000 --- a/solutions/0600-non-negative-integers-without-consecutive-ones.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 600. Non-negative Integers without Consecutive Ones - * https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/ - * Difficulty: Hard - * - * Given a positive integer n, return the number of the integers in the range [0, n] whose - * binary representations do not contain consecutive ones. - */ - -/** - * @param {number} n - * @return {number} - */ -var findIntegers = function(n) { - const binary = n.toString(2); - const dp = new Array(binary.length + 1).fill(0); - let result = 0; - - dp[0] = 1; - dp[1] = 2; - - for (let i = 2; i <= binary.length; i++) { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - for (let i = 0, previous = 0; i < binary.length; i++) { - if (binary[i] === '1') { - result += dp[binary.length - i - 1]; - if (previous === 1) { - return result; - } - previous = 1; - } else { - previous = 0; - } - } - - return result + 1; -}; diff --git a/solutions/0609-find-duplicate-file-in-system.js b/solutions/0609-find-duplicate-file-in-system.js deleted file mode 100644 index ce7a151d..00000000 --- a/solutions/0609-find-duplicate-file-in-system.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 609. Find Duplicate File in System - * https://leetcode.com/problems/find-duplicate-file-in-system/ - * Difficulty: Medium - * - * Given a list paths of directory info, including the directory path, and all the files with - * contents in this directory, return all the duplicate files in the file system in terms of - * their paths. You may return the answer in any order. - * - * A group of duplicate files consists of at least two files that have the same content. - * - * A single directory info string in the input list has the following format: - * - "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)" - * - * It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content - * ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and - * m >= 0. If m = 0, it means the directory is just the root directory. - * - * The output is a list of groups of duplicate file paths. For each group, it contains all the - * file paths of the files that have the same content. A file path is a string that has the - * following format: - * - "directory_path/file_name.txt" - */ - -/** - * @param {string[]} paths - * @return {string[][]} - */ -var findDuplicate = function(paths) { - const map = new Map(); - - for (const path of paths) { - const [directory, ...files] = path.split(' '); - for (const file of files) { - const [name, content] = file.split('('); - const fullPath = `${directory}/${name}`; - const fileContent = content.slice(0, -1); - map.set(fileContent, (map.get(fileContent) || []).concat(fullPath)); - } - } - - return Array.from(map.values()).filter(group => group.length > 1); -}; diff --git a/solutions/0611-valid-triangle-number.js b/solutions/0611-valid-triangle-number.js deleted file mode 100644 index 719adc88..00000000 --- a/solutions/0611-valid-triangle-number.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 611. Valid Triangle Number - * https://leetcode.com/problems/valid-triangle-number/ - * Difficulty: Medium - * - * Given an integer array nums, return the number of triplets chosen from the array that - * can make triangles if we take them as side lengths of a triangle. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var triangleNumber = function(nums) { - let count = 0; - - nums.sort((a, b) => a - b); - - for (let k = nums.length - 1; k >= 2; k--) { - for (let i = 0, j = k - 1; i < j;) { - if (nums[i] + nums[j] > nums[k]) { - count += j - i; - j--; - } else { - i++; - } - } - } - - return count; -}; diff --git a/solutions/0622-design-circular-queue.js b/solutions/0622-design-circular-queue.js deleted file mode 100644 index 1f3ab2f6..00000000 --- a/solutions/0622-design-circular-queue.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * 622. Design Circular Queue - * https://leetcode.com/problems/design-circular-queue/ - * Difficulty: Medium - * - * Design your implementation of the circular queue. The circular queue is a linear data structure - * in which the operations are performed based on FIFO (First In First Out) principle, and the - * last position is connected back to the first position to make a circle. It is also called - * "Ring Buffer". - * - * One of the benefits of the circular queue is that we can make use of the spaces in front of - * the queue. In a normal queue, once the queue becomes full, we cannot insert the next element - * even if there is a space in front of the queue. But using the circular queue, we can use the - * space to store new values. - * - * Implement the MyCircularQueue class: - * - MyCircularQueue(k) Initializes the object with the size of the queue to be k. - * - int Front() Gets the front item from the queue. If the queue is empty, return -1. - * - int Rear() Gets the last item from the queue. If the queue is empty, return -1. - * - boolean enQueue(int value) Inserts an element into the circular queue. Return true if the - * operation is successful. - * - boolean deQueue() Deletes an element from the circular queue. Return true if the operation - * is successful. - * - boolean isEmpty() Checks whether the circular queue is empty or not. - * - boolean isFull() Checks whether the circular queue is full or not. - * - * You must solve the problem without using the built-in queue data structure in your programming - * language. - */ - -/** - * @param {number} k - */ -var MyCircularQueue = function(k) { - this.queue = new Array(k); - this.size = k; - this.front = -1; - this.rear = -1; -}; - -/** - * @param {number} value - * @return {boolean} - */ -MyCircularQueue.prototype.enQueue = function(value) { - if (this.isFull()) { - return false; - } - if (this.isEmpty()) { - this.front = 0; - } - this.rear = (this.rear + 1) % this.size; - this.queue[this.rear] = value; - return true; -}; - -/** - * @return {boolean} - */ -MyCircularQueue.prototype.deQueue = function() { - if (this.isEmpty()) { - return false; - } else if (this.front === this.rear) { - this.front = -1; - this.rear = -1; - } else { - this.front = (this.front + 1) % this.size; - } - return true; -}; - -/** - * @return {number} - */ -MyCircularQueue.prototype.Front = function() { - return this.isEmpty() ? -1 : this.queue[this.front]; -}; - -/** - * @return {number} - */ -MyCircularQueue.prototype.Rear = function() { - return this.isEmpty() ? -1 : this.queue[this.rear]; -}; - -/** - * @return {boolean} - */ -MyCircularQueue.prototype.isEmpty = function() { - return this.front === -1; -}; - -/** - * @return {boolean} - */ -MyCircularQueue.prototype.isFull = function() { - return (this.rear + 1) % this.size === this.front; -}; diff --git a/solutions/0623-add-one-row-to-tree.js b/solutions/0623-add-one-row-to-tree.js deleted file mode 100644 index 32ce3c7d..00000000 --- a/solutions/0623-add-one-row-to-tree.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 623. Add One Row to Tree - * https://leetcode.com/problems/add-one-row-to-tree/ - * Difficulty: Medium - * - * Given the root of a binary tree and two integers val and depth, add a row of nodes with value - * val at the given depth depth. - * - * Note that the root node is at depth 1. - * - * The adding rule is: - * - Given the integer depth, for each not null tree node cur at the depth depth - 1, create two - * tree nodes with value val as cur's left subtree root and right subtree root. - * - cur's original left subtree should be the left subtree of the new left subtree root. - * - cur's original right subtree should be the right subtree of the new right subtree root. - * - If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with - * value val as the new root of the whole original tree, and the original tree is the new root's - * left subtree. - */ - -/** - * 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 - * @param {number} depth - * @return {TreeNode} - */ -var addOneRow = function(root, val, depth) { - if (depth === 1) { - return new TreeNode(val, root); - } - dfs(root, 1); - - return root; - - function dfs(node, level) { - if (!node) return; - if (level === depth - 1) { - node.left = new TreeNode(val, node.left); - node.right = new TreeNode(val, null, node.right); - return; - } - dfs(node.left, level + 1); - dfs(node.right, level + 1); - } -}; diff --git a/solutions/0624-maximum-distance-in-arrays.js b/solutions/0624-maximum-distance-in-arrays.js deleted file mode 100644 index a4a79fea..00000000 --- a/solutions/0624-maximum-distance-in-arrays.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 624. Maximum Distance in Arrays - * https://leetcode.com/problems/maximum-distance-in-arrays/ - * Difficulty: Medium - * - * You are given m arrays, where each array is sorted in ascending order. - * - * You can pick up two integers from two different arrays (each array picks one) and calculate - * the distance. We define the distance between two integers a and b to be their absolute - * difference |a - b|. - * - * Return the maximum distance. - */ - -/** - * @param {number[][]} arrays - * @return {number} - */ -var maxDistance = function(arrays) { - let result = 0; - let min = arrays[0][0]; - let max = arrays[0][arrays[0].length - 1]; - - for (let i = 1; i < arrays.length; i++) { - const newMin = arrays[i][0]; - const newMax = arrays[i][arrays[i].length - 1]; - result = Math.max(result, Math.abs(newMax - min), Math.abs(max - newMin)); - min = Math.min(min, newMin); - max = Math.max(max, newMax); - } - - return result; -}; diff --git a/solutions/0629-k-inverse-pairs-array.js b/solutions/0629-k-inverse-pairs-array.js deleted file mode 100644 index 87ad0955..00000000 --- a/solutions/0629-k-inverse-pairs-array.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 629. K Inverse Pairs Array - * https://leetcode.com/problems/k-inverse-pairs-array/ - * Difficulty: Hard - * - * For an integer array nums, an inverse pair is a pair of integers [i, j] where - * 0 <= i < j < nums.length and nums[i] > nums[j]. - * - * Given two integers n and k, return the number of different arrays consisting of numbers from - * 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return - * it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var kInversePairs = function(n, k) { - const MOD = 1e9 + 7; - const dp = new Array(k + 1).fill(0); - - dp[0] = 1; - for (let i = 1; i <= n; i++) { - const previous = dp.slice(); - dp[0] = 1; - for (let j = 1; j <= k; j++) { - dp[j] = (previous[j] + dp[j-1]) % MOD; - if (j >= i) dp[j] = (dp[j] - previous[j-i] + MOD) % MOD; - } - } - - return dp[k]; -}; diff --git a/solutions/0630-course-schedule-iii.js b/solutions/0630-course-schedule-iii.js deleted file mode 100644 index 6fbed1e6..00000000 --- a/solutions/0630-course-schedule-iii.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 630. Course Schedule III - * https://leetcode.com/problems/course-schedule-iii/ - * Difficulty: Hard - * - * There are n different online courses numbered from 1 to n. You are given an array courses - * where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken - * continuously for durationi days and must be finished before or on lastDayi. - * - * You will start on the 1st day and you cannot take two or more courses simultaneously. - * - * Return the maximum number of courses that you can take. - */ - -/** - * @param {number[][]} courses - * @return {number} - */ -var scheduleCourse = function(courses) { - courses.sort((a, b) => a[1] - b[1]); - - const maxHeap = new PriorityQueue({ compare: (a, b) => b - a }); - let value = 0; - - for (const [duration, lastDay] of courses) { - if (value + duration <= lastDay) { - value += duration; - maxHeap.enqueue(duration); - } else { - if (maxHeap.front() > duration) { - var prev = maxHeap.dequeue(); - value -= prev; - value += duration; - maxHeap.enqueue(duration); - } - } - } - - return maxHeap.size(); -}; diff --git a/solutions/0632-smallest-range-covering-elements-from-k-lists.js b/solutions/0632-smallest-range-covering-elements-from-k-lists.js deleted file mode 100644 index 17263a92..00000000 --- a/solutions/0632-smallest-range-covering-elements-from-k-lists.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 632. Smallest Range Covering Elements from K Lists - * https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/ - * Difficulty: Hard - * - * You have k lists of sorted integers in non-decreasing order. Find the smallest range that - * includes at least one number from each of the k lists. - * - * We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c - * if b - a == d - c. - */ - -/** - * @param {number[][]} nums - * @return {number[]} - */ -var smallestRange = function(nums) { - const k = nums.length; - const listCountMap = new Map(); - let coveredLists = 0; - let minDiff = Infinity; - let minStart; - let minEnd; - - const allElements = nums.flatMap((list, listIndex) => - list.map(num => ({ num, index: listIndex })) - ).sort((a, b) => a.num - b.num); - - let windowStart = 0; - for (let windowEnd = 0; windowEnd < allElements.length; windowEnd++) { - const currentElement = allElements[windowEnd]; - const listIndex = currentElement.index; - const count = listCountMap.get(listIndex) ?? 0; - - if (count === 0) coveredLists += 1; - listCountMap.set(listIndex, count + 1); - - while (coveredLists === k) { - const leftElement = allElements[windowStart]; - const range = currentElement.num - leftElement.num; - - if (range < minDiff) { - minDiff = range; - minStart = leftElement.num; - minEnd = currentElement.num; - } - const leftListIndex = leftElement.index; - const leftCount = listCountMap.get(leftListIndex); - listCountMap.set(leftListIndex, leftCount - 1); - if (leftCount - 1 === 0) coveredLists -= 1; - windowStart += 1; - } - } - - return [minStart, minEnd]; -}; diff --git a/solutions/0633-sum-of-square-numbers.js b/solutions/0633-sum-of-square-numbers.js deleted file mode 100644 index 42f3dfa7..00000000 --- a/solutions/0633-sum-of-square-numbers.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 633. Sum of Square Numbers - * https://leetcode.com/problems/sum-of-square-numbers/ - * Difficulty: Medium - * - * Given a non-negative integer c, decide whether there're two integers a and b such - * that a2 + b2 = c. - */ - -/** - * @param {number} c - * @return {boolean} - */ -var judgeSquareSum = function(c) { - for (let left = 0, right = Math.floor(Math.sqrt(c)); left <= right;) { - const sum = left * left + right * right; - if (sum === c) return true; - if (sum < c) left++; - else right--; - } - return false; -}; diff --git a/solutions/0636-exclusive-time-of-functions.js b/solutions/0636-exclusive-time-of-functions.js deleted file mode 100644 index 9c745a51..00000000 --- a/solutions/0636-exclusive-time-of-functions.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 636. Exclusive Time of Functions - * https://leetcode.com/problems/exclusive-time-of-functions/ - * Difficulty: Medium - * - * On a single-threaded CPU, we execute a program containing n functions. Each function has a - * unique ID between 0 and n-1. - * - * Function calls are stored in a call stack: when a function call starts, its ID is pushed - * onto the stack, and when a function call ends, its ID is popped off the stack. The function - * whose ID is at the top of the stack is the current function being executed. Each time a - * function starts or ends, we write a log with the ID, whether it started or ended, and the - * timestamp. - * - * You are given a list logs, where logs[i] represents the ith log message formatted as a string - * "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call - * with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function - * call with function ID 1 ended at the end of timestamp 2. Note that a function can be called - * multiple times, possibly recursively. - * - * A function's exclusive time is the sum of execution times for all function calls in the program. - * For example, if a function is called twice, one call executing for 2 time units and another - * call executing for 1 time unit, the exclusive time is 2 + 1 = 3. - * - * Return the exclusive time of each function in an array, where the value at the ith index - * represents the exclusive time for the function with ID i. - */ - -/** - * @param {number} n - * @param {string[]} logs - * @return {number[]} - */ -var exclusiveTime = function(n, logs) { - const stack = []; - const result = new Array(n).fill(0); - let previousTime = 0; - - for (const log of logs) { - const [id, action, time] = log.split(':'); - const currentTime = +time; - - if (action === 'start') { - if (stack.length) { - result[stack[stack.length - 1]] += currentTime - previousTime; - } - stack.push(+id); - previousTime = currentTime; - } else { - result[stack.pop()] += currentTime - previousTime + 1; - previousTime = currentTime + 1; - } - } - - return result; -}; diff --git a/solutions/0638-shopping-offers.js b/solutions/0638-shopping-offers.js deleted file mode 100644 index 1b512cb0..00000000 --- a/solutions/0638-shopping-offers.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 638. Shopping Offers - * https://leetcode.com/problems/shopping-offers/ - * Difficulty: Medium - * - * In LeetCode Store, there are n items to sell. Each item has a price. However, there are - * some special offers, and a special offer consists of one or more different kinds of items - * with a sale price. - * - * You are given an integer array price where price[i] is the price of the ith item, and an - * integer array needs where needs[i] is the number of pieces of the ith item you want to buy. - * - * You are also given an array special where special[i] is of size n + 1 where special[i][j] - * is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last - * integer in the array) is the price of the ith offer. - * - * Return the lowest price you have to pay for exactly certain items as given, where you could - * make optimal use of the special offers. You are not allowed to buy more items than you want, - * even if that would lower the overall price. You could use any of the special offers as many - * times as you want. - */ - -/** - * @param {number[]} price - * @param {number[][]} special - * @param {number[]} needs - * @return {number} - */ -var shoppingOffers = function(price, special, needs) { - const map = new Map(); - return dp(needs); - - function dp(input) { - const key = input.join(','); - if (map.has(key)) return map.get(key); - let minCost = input.reduce((sum, need, i) => sum + need * price[i], 0); - for (const offer of special) { - const nextNeeds = [...input]; - let valid = true; - for (let i = 0; i < price.length; i++) { - if (nextNeeds[i] < offer[i]) { - valid = false; - break; - } - nextNeeds[i] -= offer[i]; - } - if (valid) { - minCost = Math.min(minCost, offer[price.length] + dp(nextNeeds)); - } - } - map.set(key, minCost); - return minCost; - } -}; diff --git a/solutions/0639-decode-ways-ii.js b/solutions/0639-decode-ways-ii.js deleted file mode 100644 index 0a336425..00000000 --- a/solutions/0639-decode-ways-ii.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 639. Decode Ways II - * https://leetcode.com/problems/decode-ways-ii/ - * Difficulty: Hard - * - * A message containing letters from A-Z can be encoded into numbers using the following mapping: - * - 'A' -> "1" - * - 'B' -> "2" - * - 'Z' -> "26" - * - * To decode an encoded message, all the digits must be grouped then mapped back into letters using - * the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped - * into: - * - "AAJF" with the grouping (1 1 10 6) - * - "KJF" with the grouping (11 10 6) - * - * Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is - * different from "06". - * - * In addition to the mapping above, an encoded message may contain the '*' character, which can - * represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" - * may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or - * "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent. - * - * Given a string s consisting of digits and '*' characters, return the number of ways to decode it. - * - * Since the answer may be very large, return it modulo 109 + 7. - */ - -/** - * @param {string} s - * @return {number} - */ -var numDecodings = function(s) { - const mod = 1e9 + 7; - let [i0, i1, i2, i3] = [1, 0, 0, 0]; - - for (const c of s) { - if (c == '*') { - i3 = 9 * i0 + 9 * i1 + 6 * i2; - i1 = i0; - i2 = i0; - } else { - i3 = (c > '0') * i0 + i1 + (c <= '6') * i2; - i1 = (c == '1') * i0; - i2 = (c == '2') * i0; - } - i0 = i3 % mod; - } - - return i0; -}; diff --git a/solutions/0640-solve-the-equation.js b/solutions/0640-solve-the-equation.js deleted file mode 100644 index b6787554..00000000 --- a/solutions/0640-solve-the-equation.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 640. Solve the Equation - * https://leetcode.com/problems/solve-the-equation/ - * Difficulty: Medium - * - * Solve a given equation and return the value of 'x' in the form of a string "x=#value". - * The equation contains only '+', '-' operation, the variable 'x' and its coefficient. - * You should return "No solution" if there is no solution for the equation, or "Infinite - * solutions" if there are infinite solutions for the equation. - * - * If there is exactly one solution for the equation, we ensure that the value of 'x' is - * an integer. - */ - -/** - * @param {string} equation - * @return {string} - */ -var solveEquation = function(equation) { - const [left, right] = equation.split('='); - const leftSide = parseSide(left); - const rightSide = parseSide(right); - const totalX = leftSide.xCount - rightSide.xCount; - const totalNum = rightSide.numSum - leftSide.numSum; - - if (totalX === 0 && totalNum === 0) return 'Infinite solutions'; - if (totalX === 0) return 'No solution'; - - return `x=${totalNum / totalX}`; - - function parseSide(side) { - let xCount = 0; - let numSum = 0; - let currentNum = 0; - let sign = 1; - - for (let i = 0; i < side.length; i++) { - const char = side[i]; - if (char === 'x') { - const v = i === 0 || side[i-1] === '+' || side[i-1] === '-'; - xCount += sign * (currentNum === 0 && (v) ? 1 : currentNum); - currentNum = 0; - } else if (char === '+' || char === '-') { - numSum += sign * currentNum; - sign = char === '+' ? 1 : -1; - currentNum = 0; - } else { - currentNum = currentNum * 10 + parseInt(char); - } - } - numSum += sign * currentNum; - - return { xCount, numSum }; - } -}; diff --git a/solutions/0641-design-circular-deque.js b/solutions/0641-design-circular-deque.js deleted file mode 100644 index 68deaaf9..00000000 --- a/solutions/0641-design-circular-deque.js +++ /dev/null @@ -1,106 +0,0 @@ -/** - * 641. Design Circular Deque - * https://leetcode.com/problems/design-circular-deque/ - * Difficulty: Medium - * - * Design your implementation of the circular double-ended queue (deque). - * - * Implement the MyCircularDeque class: - * - MyCircularDeque(int k) Initializes the deque with a maximum size of k. - * - boolean insertFront() Adds an item at the front of Deque. Returns true if the operation - * is successful, or false otherwise. - * - boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation - * is successful, or false otherwise. - * - boolean deleteFront() Deletes an item from the front of Deque. Returns true if the - * operation is successful, or false otherwise. - * - boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation - * is successful, or false otherwise. - * - int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty. - * - int getRear() Returns the last item from Deque. Returns -1 if the deque is empty. - * - boolean isEmpty() Returns true if the deque is empty, or false otherwise. - * - boolean isFull() Returns true if the deque is full, or false otherwise. - */ - -/** - * @param {number} k - */ -var MyCircularDeque = function(k) { - this.queue = new Array(k); - this.size = k; - this.front = 0; - this.rear = -1; - this.count = 0; -}; - -/** - * @param {number} value - * @return {boolean} - */ -MyCircularDeque.prototype.insertFront = function(value) { - if (this.isFull()) return false; - this.front = (this.front - 1 + this.size) % this.size; - this.queue[this.front] = value; - this.count++; - if (this.count === 1) this.rear = this.front; - return true; -}; - -/** - * @param {number} value - * @return {boolean} - */ -MyCircularDeque.prototype.insertLast = function(value) { - if (this.isFull()) return false; - this.rear = (this.rear + 1) % this.size; - this.queue[this.rear] = value; - this.count++; - return true; -}; - -/** - * @return {boolean} - */ -MyCircularDeque.prototype.deleteFront = function() { - if (this.isEmpty()) return false; - this.front = (this.front + 1) % this.size; - this.count--; - return true; -}; - -/** - * @return {boolean} - */ -MyCircularDeque.prototype.deleteLast = function() { - if (this.isEmpty()) return false; - this.rear = (this.rear - 1 + this.size) % this.size; - this.count--; - return true; -}; - -/** - * @return {number} - */ -MyCircularDeque.prototype.getFront = function() { - return this.isEmpty() ? -1 : this.queue[this.front]; -}; - -/** - * @return {number} - */ -MyCircularDeque.prototype.getRear = function() { - return this.isEmpty() ? -1 : this.queue[this.rear]; -}; - -/** - * @return {boolean} - */ -MyCircularDeque.prototype.isEmpty = function() { - return this.count === 0; -}; - -/** - * @return {boolean} - */ -MyCircularDeque.prototype.isFull = function() { - return this.count === this.size; -}; diff --git a/solutions/0643-maximum-average-subarray-i.js b/solutions/0643-maximum-average-subarray-i.js deleted file mode 100644 index 413edd4f..00000000 --- a/solutions/0643-maximum-average-subarray-i.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 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/solutions/0646-maximum-length-of-pair-chain.js b/solutions/0646-maximum-length-of-pair-chain.js deleted file mode 100644 index 077b2d91..00000000 --- a/solutions/0646-maximum-length-of-pair-chain.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 646. Maximum Length of Pair Chain - * https://leetcode.com/problems/maximum-length-of-pair-chain/ - * Difficulty: Medium - * - * You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti. - * - * A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in - * this fashion. - * - * Return the length longest chain which can be formed. - * - * You do not need to use up all the given intervals. You can select pairs in any order. - */ - -/** - * @param {number[][]} pairs - * @return {number} - */ -var findLongestChain = function(pairs) { - pairs.sort((a, b) => a[1] - b[1]); - let pointer = -Infinity; - let result = 0; - - for (const [start, end] of pairs) { - if (start > pointer) { - pointer = end; - result++; - } - } - - return result; -}; diff --git a/solutions/0647-palindromic-substrings.js b/solutions/0647-palindromic-substrings.js deleted file mode 100644 index e7465fc7..00000000 --- a/solutions/0647-palindromic-substrings.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 647. Palindromic Substrings - * https://leetcode.com/problems/palindromic-substrings/ - * Difficulty: Medium - * - * Given a string s, return the number of palindromic substrings in it. - * - * A string is a palindrome when it reads the same backward as forward. - * - * A substring is a contiguous sequence of characters within the string. - */ - -/** - * @param {string} s - * @return {number} - */ -var countSubstrings = function(s) { - let result = 0; - - for (let i = 0; i < s.length; i++) { - result += expand(i, i); - result += expand(i, i + 1); - } - - return result; - - function expand(left, right) { - let count = 0; - while (left >= 0 && right < s.length && s[left] === s[right]) { - count++; - left--; - right++; - } - return count; - } -}; diff --git a/solutions/0650-2-keys-keyboard.js b/solutions/0650-2-keys-keyboard.js deleted file mode 100644 index d2169c05..00000000 --- a/solutions/0650-2-keys-keyboard.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 650. 2 Keys Keyboard - * https://leetcode.com/problems/2-keys-keyboard/ - * Difficulty: Medium - * - * There is only one character 'A' on the screen of a notepad. You can perform one of two - * operations on this notepad for each step: - * - Copy All: You can copy all the characters present on the screen (a partial copy is - * not allowed). - * - Paste: You can paste the characters which are copied last time. - * - * Given an integer n, return the minimum number of operations to get the character 'A' - * exactly n times on the screen. - */ - -/** - * @param {number} n - * @return {number} - */ -var minSteps = function(n) { - let result = 0; - - for (let factor = 2; n > 1;) { - while (n % factor === 0) { - result += factor; - n /= factor; - } - factor++; - } - - return result; -}; diff --git a/solutions/0652-find-duplicate-subtrees.js b/solutions/0652-find-duplicate-subtrees.js deleted file mode 100644 index dd8640c1..00000000 --- a/solutions/0652-find-duplicate-subtrees.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 652. Find Duplicate Subtrees - * https://leetcode.com/problems/find-duplicate-subtrees/ - * Difficulty: Medium - * - * Given the root of a binary tree, return all duplicate subtrees. - * - * For each kind of duplicate subtrees, you only need to return the root node of any one of them. - * - * Two trees are duplicate if they have the same structure with the same node 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 {TreeNode[]} - */ -var findDuplicateSubtrees = function(root) { - const map = new Map(); - const result = []; - - serialize(root); - - return result; - - function serialize(node) { - if (!node) return '#'; - const key = `${node.val},${serialize(node.left)},${serialize(node.right)}`; - map.set(key, (map.get(key) || 0) + 1); - if (map.get(key) === 2) { - result.push(node); - } - return key; - } -}; diff --git a/solutions/0655-print-binary-tree.js b/solutions/0655-print-binary-tree.js deleted file mode 100644 index 038e3050..00000000 --- a/solutions/0655-print-binary-tree.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 655. Print Binary Tree - * https://leetcode.com/problems/print-binary-tree/ - * Difficulty: Medium - * - * Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents - * a formatted layout of the tree. The formatted layout matrix should be constructed using the - * following rules: - * - The height of the tree is height and the number of rows m should be equal to height + 1. - * - The number of columns n should be equal to 2height+1 - 1. - * - Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]). - * - For each node that has been placed in the matrix at position res[r][c], place its left child at - * res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1]. - * - Continue this process until all the nodes in the tree have been placed. - * - Any empty cells should contain the empty string "". - * - * Return the constructed matrix res. - */ - -/** - * 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 {string[][]} - */ -var printTree = function(root) { - const height = getHeight(root); - const columns = Math.pow(2, height + 1) - 1; - const result = new Array(height + 1).fill().map(() => { - return new Array(columns).fill(''); - }); - - fill(root, 0, Math.floor((columns - 1) / 2), height); - - return result; - - function fill(node, r, c, h) { - if (!node) return; - result[r][c] = node.val.toString(); - fill(node.left, r + 1, c - Math.pow(2, h - r - 1), h); - fill(node.right, r + 1, c + Math.pow(2, h - r - 1), h); - } - - function getHeight(node) { - if (!node) return -1; - return 1 + Math.max(getHeight(node.left), getHeight(node.right)); - } -}; diff --git a/solutions/0657-robot-return-to-origin.js b/solutions/0657-robot-return-to-origin.js deleted file mode 100644 index 06c01e35..00000000 --- a/solutions/0657-robot-return-to-origin.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 657. Robot Return to Origin - * https://leetcode.com/problems/robot-return-to-origin/ - * Difficulty: Easy - * - * There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence - * of its moves, judge if this robot ends up at (0, 0) after it completes its moves. - * - * You are given a string moves that represents the move sequence of the robot where moves[i] - * represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). - * - * Return true if the robot returns to the origin after it finishes all of its moves, or false - * otherwise. - * - * Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move - * to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude - * of the robot's movement is the same for each move. - */ - -/** - * @param {string} moves - * @return {boolean} - */ -/** - * @param {string} moves - * @return {boolean} - */ -var judgeCircle = function(moves) { - let x = 0; - let y = 0; - - for (const move of moves) { - x += move === 'R' ? 1 : move === 'L' ? -1 : 0; - y += move === 'U' ? 1 : move === 'D' ? -1 : 0; - } - - return x === 0 && y === 0; -}; diff --git a/solutions/0658-find-k-closest-elements.js b/solutions/0658-find-k-closest-elements.js deleted file mode 100644 index 390c7b23..00000000 --- a/solutions/0658-find-k-closest-elements.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 658. Find K Closest Elements - * https://leetcode.com/problems/find-k-closest-elements/ - * Difficulty: Medium - * - * Given a sorted integer array arr, two integers k and x, return the k closest integers to x - * in the array. The result should also be sorted in ascending order. - * - * An integer a is closer to x than an integer b if: - * - |a - x| < |b - x|, or - * - |a - x| == |b - x| and a < b - */ - -/** - * @param {number[]} arr - * @param {number} k - * @param {number} x - * @return {number[]} - */ -var findClosestElements = function(arr, k, x) { - let left = 0; - let right = arr.length - k; - - while (left < right) { - const middle = Math.floor((left + right) / 2); - const x1 = arr[middle]; - const x2 = arr[middle + k]; - - if (x - x1 > x2 - x) { - left = middle + 1; - } else { - right = middle; - } - } - - return arr.slice(left, left + k); -}; diff --git a/solutions/0659-split-array-into-consecutive-subsequences.js b/solutions/0659-split-array-into-consecutive-subsequences.js deleted file mode 100644 index 002105c8..00000000 --- a/solutions/0659-split-array-into-consecutive-subsequences.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 659. Split Array into Consecutive Subsequences - * https://leetcode.com/problems/split-array-into-consecutive-subsequences/ - * Difficulty: Medium - * - * You are given an integer array nums that is sorted in non-decreasing order. - * - * Determine if it is possible to split nums into one or more subsequences such that both of the - * following conditions are true: - * - Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more - * than the previous integer). - * - All subsequences have a length of 3 or more. - * - * Return true if you can split nums according to the above conditions, or false otherwise. - * - * A subsequence of an array is a new array that is formed from the original array by deleting some - * (can be none) of the elements without disturbing the relative positions of the remaining - * elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not). - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var isPossible = function(nums) { - const map = new Map(); - const map2 = new Map(); - - for (const n of nums) { - map.set(n, (map.get(n) || 0) + 1); - } - - for (const n of nums) { - if (map.get(n) === 0) continue; - - if ((map2.get(n) || 0) > 0) { - map2.set(n, map2.get(n) - 1); - map.set(n, map.get(n) - 1); - map2.set(n + 1, (map2.get(n + 1) || 0) + 1); - } else if ((map.get(n) || 0) > 0 && (map.get(n + 1) || 0) > 0 && (map.get(n + 2) || 0) > 0) { - map.set(n, map.get(n) - 1); - map.set(n + 1, map.get(n + 1) - 1); - map.set(n + 2, map.get(n + 2) - 1); - map2.set(n + 3, (map2.get(n + 3) || 0) + 1); - } else { - return false; - } - } - - return true; -}; diff --git a/solutions/0661-image-smoother.js b/solutions/0661-image-smoother.js deleted file mode 100644 index 61921b33..00000000 --- a/solutions/0661-image-smoother.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 661. Image Smoother - * https://leetcode.com/problems/image-smoother/ - * Difficulty: Easy - * - * An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by - * rounding down the average of the cell and the eight surrounding cells (i.e., the average of the - * nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not - * present, we do not consider it in the average (i.e., the average of the four cells in the red - * smoother). - * - * Given an m x n integer matrix img representing the grayscale of an image, return the image after - * applying the smoother on each cell of it. - */ - -/** - * @param {number[][]} img - * @return {number[][]} - */ -var imageSmoother = function(img) { - const result = new Array(img.length).fill().map(() => { - return new Array(img[0].length).fill(0); - }); - - for (let i = 0; i < img.length; i++) { - for (let j = 0; j < img[0].length; j++) { - let sum = 0; - let count = 0; - for (let di = -1; di <= 1; di++) { - for (let dj = -1; dj <= 1; dj++) { - const ni = i + di; - const nj = j + dj; - if (ni >= 0 && ni < img.length && nj >= 0 && nj < img[0].length) { - sum += img[ni][nj]; - count++; - } - } - } - result[i][j] = Math.floor(sum / count); - } - } - - return result; -}; diff --git a/solutions/0662-maximum-width-of-binary-tree.js b/solutions/0662-maximum-width-of-binary-tree.js deleted file mode 100644 index bdc8ccc0..00000000 --- a/solutions/0662-maximum-width-of-binary-tree.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 662. Maximum Width of Binary Tree - * https://leetcode.com/problems/maximum-width-of-binary-tree/ - * Difficulty: Medium - * - * Given the root of a binary tree, return the maximum width of the given tree. - * - * The maximum width of a tree is the maximum width among all levels. - * - * The width of one level is defined as the length between the end-nodes (the leftmost and - * rightmost non-null nodes), where the null nodes between the end-nodes that would be present - * in a complete binary tree extending down to that level are also counted into the length - * calculation. - * - * It is guaranteed that the answer will in the range of a 32-bit signed 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 widthOfBinaryTree = function(root) { - const queue = [[root, 0n]]; - let result = 0n; - - while (queue.length) { - const total = queue.length; - const levelStart = queue[0][1]; - let levelEnd; - - for (let i = 0; i < total; i++) { - const [node, index] = queue.shift(); - levelEnd = index; - if (node.left) queue.push([node.left, index * 2n]); - if (node.right) queue.push([node.right, index * 2n + 1n]); - } - - result = result > (levelEnd - levelStart + 1n) - ? result - : (levelEnd - levelStart + 1n); - } - - return Number(result); -}; diff --git a/solutions/0664-strange-printer.js b/solutions/0664-strange-printer.js deleted file mode 100644 index e1b8af3c..00000000 --- a/solutions/0664-strange-printer.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 664. Strange Printer - * https://leetcode.com/problems/strange-printer/ - * Difficulty: Hard - * - * There is a strange printer with the following two special properties: - * - The printer can only print a sequence of the same character each time. - * - At each turn, the printer can print new characters starting from and ending at any place and - * will cover the original existing characters. - * - * Given a string s, return the minimum number of turns the printer needed to print it. - */ - -/** - * @param {string} s - * @return {number} - */ -var strangePrinter = function(s) { - const n = s.length; - const dp = new Array(n).fill().map(() => new Array(n).fill(0)); - - for (let i = n - 1; i >= 0; i--) { - dp[i][i] = 1; - for (let j = i + 1; j < n; j++) { - dp[i][j] = dp[i][j - 1] + 1; - for (let k = i; k < j; k++) { - if (s[k] === s[j]) { - dp[i][j] = Math.min(dp[i][j], dp[i][k] + (k + 1 <= j - 1 ? dp[k + 1][j - 1] : 0)); - } - } - } - } - - return dp[0][n - 1]; -}; diff --git a/solutions/0665-non-decreasing-array.js b/solutions/0665-non-decreasing-array.js deleted file mode 100644 index bd5df656..00000000 --- a/solutions/0665-non-decreasing-array.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 665. Non-decreasing Array - * https://leetcode.com/problems/non-decreasing-array/ - * Difficulty: Medium - * - * Given an array nums with n integers, your task is to check if it could become non-decreasing - * by modifying at most one element. - * - * We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) - * such that (0 <= i <= n - 2). - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var checkPossibility = function(nums) { - let count = 0; - - for (let i = 0; i < nums.length - 1; i++) { - if (nums[i] > nums[i + 1]) { - count++; - if (count > 1) return false; - if (i > 0 && nums[i - 1] > nums[i + 1]) { - nums[i + 1] = nums[i]; - } else { - nums[i] = nums[i + 1]; - } - } - } - - return true; -}; diff --git a/solutions/0667-beautiful-arrangement-ii.js b/solutions/0667-beautiful-arrangement-ii.js deleted file mode 100644 index 56883ac1..00000000 --- a/solutions/0667-beautiful-arrangement-ii.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 667. Beautiful Arrangement II - * https://leetcode.com/problems/beautiful-arrangement-ii/ - * Difficulty: Medium - * - * Given two integers n and k, construct a list answer that contains n different positive integers - * ranging from 1 to n and obeys the following requirement: - * - Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, - * |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. - * - * Return the list answer. If there multiple valid answers, return any of them. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number[]} - */ -var constructArray = function(n, k) { - const result = []; - - for (let i = 0, left = 1, right = n; i < n; i++) { - if (k > 1) { - result.push(k % 2 === 0 ? right-- : left++); - k--; - } else { - result.push(left++); - } - } - - return result; -}; diff --git a/solutions/0668-kth-smallest-number-in-multiplication-table.js b/solutions/0668-kth-smallest-number-in-multiplication-table.js deleted file mode 100644 index 97313f29..00000000 --- a/solutions/0668-kth-smallest-number-in-multiplication-table.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 668. Kth Smallest Number in Multiplication Table - * https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/ - * Difficulty: Hard - * - * Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is - * an integer matrix mat where mat[i][j] == i * j (1-indexed). - * - * Given three integers m, n, and k, return the kth smallest element in the m x n multiplication - * table. - */ - -/** - * @param {number} m - * @param {number} n - * @param {number} k - * @return {number} - */ -var findKthNumber = function(m, n, k) { - let low = 1; - let high = m * n; - - while (low < high) { - const middle = Math.floor((low + high) / 2); - if (helper(middle) < k) { - low = middle + 1; - } else { - high = middle; - } - } - - return low; - - function helper(x) { - let count = 0; - for (let i = 1; i <= m; i++) { - count += Math.min(Math.floor(x / i), n); - } - return count; - } -}; diff --git a/solutions/0669-trim-a-binary-search-tree.js b/solutions/0669-trim-a-binary-search-tree.js deleted file mode 100644 index 69eb15c7..00000000 --- a/solutions/0669-trim-a-binary-search-tree.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 669. Trim a Binary Search Tree - * https://leetcode.com/problems/trim-a-binary-search-tree/ - * Difficulty: Medium - * - * Given the root of a binary search tree and the lowest and highest boundaries as low and high, - * trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change - * the relative structure of the elements that will remain in the tree (i.e., any node's descendant - * should remain a descendant). It can be proven that there is a unique answer. - * - * Return the root of the trimmed binary search tree. Note that the root may change depending on - * the given bounds. - */ - -/** - * 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} low - * @param {number} high - * @return {TreeNode} - */ -var trimBST = function(root, low, high) { - if (!root) return null; - - if (root.val < low) return trimBST(root.right, low, high); - if (root.val > high) return trimBST(root.left, low, high); - root.left = trimBST(root.left, low, high); - root.right = trimBST(root.right, low, high); - - return root; -}; diff --git a/solutions/0670-maximum-swap.js b/solutions/0670-maximum-swap.js deleted file mode 100644 index d1886730..00000000 --- a/solutions/0670-maximum-swap.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 670. Maximum Swap - * https://leetcode.com/problems/maximum-swap/ - * Difficulty: Medium - * - * You are given an integer num. You can swap two digits at most once to get the maximum - * valued number. - * - * Return the maximum valued number you can get. - */ - -/** - * @param {number} num - * @return {number} - */ -var maximumSwap = function(num) { - const digits = [...(num).toString()]; - const last = new Array(10).fill(-1); - digits.forEach((d, i) => last[d] = i); - - for (let i = 0; i < digits.length; i++) { - for (let d = 9; d > digits[i]; d--) { - if (last[d] > i) { - [digits[i], digits[last[d]]] = [digits[last[d]], digits[i]]; - return +digits.join(''); - } - } - } - - return num; -}; diff --git a/solutions/0671-second-minimum-node-in-a-binary-tree.js b/solutions/0671-second-minimum-node-in-a-binary-tree.js deleted file mode 100644 index 8f8a3d48..00000000 --- a/solutions/0671-second-minimum-node-in-a-binary-tree.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 671. Second Minimum Node In a Binary Tree - * https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/ - * Difficulty: Easy - * - * Given a non-empty special binary tree consisting of nodes with the non-negative value, - * where each node in this tree has exactly two or zero sub-node. If the node has two - * sub-nodes, then this node's value is the smaller value among its two sub-nodes. More - * formally, the property root.val = min(root.left.val, root.right.val) always holds. - * - * Given such a binary tree, you need to output the second minimum value in the set made - * of all the nodes' value in the whole tree. - * - * If no such second minimum value exists, output -1 instead. - */ - -/** - * 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 findSecondMinimumValue = function(root) { - return root ? (n => n === Infinity ? -1 : n)(traverse(root, root.val)) : -1; - function traverse(node, min) { - if (!node) return Infinity; - if (node.val > min) return node.val; - return Math.min(traverse(node.left, min), traverse(node.right, min)); - } -}; diff --git a/solutions/0672-bulb-switcher-ii.js b/solutions/0672-bulb-switcher-ii.js deleted file mode 100644 index 554c9d0a..00000000 --- a/solutions/0672-bulb-switcher-ii.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 672. Bulb Switcher II - * https://leetcode.com/problems/bulb-switcher-ii/ - * Difficulty: Medium - * - * There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four - * buttons on the wall. Each of the four buttons has a different functionality where: - * - Button 1: Flips the status of all the bulbs. - * - Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...). - * - Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...). - * - Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... - * (i.e., 1, 4, 7, 10, ...). - * - You must make exactly presses button presses in total. For each press, you may pick any - * of the four buttons to press. - * - * Given the two integers n and presses, return the number of different possible statuses after - * performing all presses button presses. - */ - -/** - * @param {number} n - * @param {number} presses - * @return {number} - */ -var flipLights = function(n, presses) { - if (presses === 0) return 1; - if (n === 1) return presses >= 1 ? 2 : 1; - if (n === 2) return presses === 1 ? 3 : 4; - if (presses === 1) return 4; - if (presses === 2) return 7; - return 8; -}; diff --git a/solutions/0673-number-of-longest-increasing-subsequence.js b/solutions/0673-number-of-longest-increasing-subsequence.js deleted file mode 100644 index a7c2adcf..00000000 --- a/solutions/0673-number-of-longest-increasing-subsequence.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 673. Number of Longest Increasing Subsequence - * https://leetcode.com/problems/number-of-longest-increasing-subsequence/ - * Difficulty: Medium - * - * Given an integer array nums, return the number of longest increasing subsequences. - * - * Notice that the sequence has to be strictly increasing. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findNumberOfLIS = function(nums) { - const lengths = new Array(nums.length).fill(1); - const counts = new Array(nums.length).fill(1); - - for (let i = 1; i < nums.length; i++) { - for (let j = 0; j < i; j++) { - if (nums[i] > nums[j]) { - if (lengths[j] + 1 > lengths[i]) { - lengths[i] = lengths[j] + 1; - counts[i] = counts[j]; - } else if (lengths[j] + 1 === lengths[i]) { - counts[i] += counts[j]; - } - } - } - } - - const max = Math.max(...lengths); - return lengths.reduce((sum, l, i) => { - return sum + (l === max ? counts[i] : 0); - }, 0); -}; diff --git a/solutions/0674-longest-continuous-increasing-subsequence.js b/solutions/0674-longest-continuous-increasing-subsequence.js deleted file mode 100644 index 09057b94..00000000 --- a/solutions/0674-longest-continuous-increasing-subsequence.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 674. Longest Continuous Increasing Subsequence - * https://leetcode.com/problems/longest-continuous-increasing-subsequence/ - * Difficulty: Easy - * - * Given an unsorted array of integers nums, return the length of the longest continuous increasing - * subsequence (i.e. subarray). The subsequence must be strictly increasing. - * - * A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is - * [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findLengthOfLCIS = function(nums) { - let result = 1; - - for (let i = 1, v = 1; i < nums.length; i++) { - v = nums[i] > nums[i-1] ? v + 1 : 1; - result = Math.max(result, v); - } - - return result; -}; diff --git a/solutions/0675-cut-off-trees-for-golf-event.js b/solutions/0675-cut-off-trees-for-golf-event.js deleted file mode 100644 index fb6b8f1c..00000000 --- a/solutions/0675-cut-off-trees-for-golf-event.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * 675. Cut Off Trees for Golf Event - * https://leetcode.com/problems/cut-off-trees-for-golf-event/ - * Difficulty: Hard - * - * You are asked to cut off all the trees in a forest for a golf event. The forest is represented - * as an m x n matrix. In this matrix: - * - 0 means the cell cannot be walked through. - * - 1 represents an empty cell that can be walked through. - * - A number greater than 1 represents a tree in a cell that can be walked through, and this number - * is the tree's height. - * - * In one step, you can walk in any of the four directions: north, east, south, and west. If you are - * standing in a cell with a tree, you can choose whether to cut it off. - * - * You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value - * at its cell becomes 1 (an empty cell). - * - * Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the - * trees. If you cannot cut off all the trees, return -1. - * - * Note: The input is generated such that no two trees have the same height, and there is at least - * one tree needs to be cut off. - */ - -/** - * @param {number[][]} forest - * @return {number} - */ -const cutOffTree = (forest) => { - const treeHeights = forest.flat().filter((height) => height > 1).sort((a, b) => a - b); - let currentPosition = [0, 0]; - let totalDistance = 0; - - while (treeHeights.length) { - const gridCopy = forest.map((row) => [...row]); - const result = findDistance(currentPosition, treeHeights.shift(), gridCopy); - if (result === null) return -1; - const [nextPosition, distance] = result; - currentPosition = nextPosition; - totalDistance += distance; - } - return totalDistance; - - function findDistance(startPosition, targetHeight, grid) { - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - let queue = [startPosition]; - let distance = 0; - - while (queue.length) { - const nextLevel = []; - - for (const [row, col] of queue) { - if (grid[row][col] === targetHeight) return [[row, col], distance]; - if (!grid[row][col]) continue; - - for (const [deltaRow, deltaCol] of directions) { - const newRow = row + deltaRow; - const newCol = col + deltaCol; - if ( - newRow >= 0 && newRow < grid.length && newCol >= 0 - && newCol < grid[0].length && grid[newRow][newCol] - ) { - nextLevel.push([newRow, newCol]); - } - } - grid[row][col] = 0; - } - distance += 1; - queue = nextLevel; - } - return null; - } -}; diff --git a/solutions/0676-implement-magic-dictionary.js b/solutions/0676-implement-magic-dictionary.js deleted file mode 100644 index d470c460..00000000 --- a/solutions/0676-implement-magic-dictionary.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 676. Implement Magic Dictionary - * https://leetcode.com/problems/implement-magic-dictionary/ - * Difficulty: Medium - * - * Design a data structure that is initialized with a list of different words. Provided a string, - * you should determine if you can change exactly one character in this string to match any word - * in the data structure. - * - * Implement the MagicDictionary class: - * - MagicDictionary() Initializes the object. - * - void buildDict(String[] dictionary) Sets the data structure with an array of distinct - * strings dictionary. - * - bool search(String searchWord) Returns true if you can change exactly one character in - * searchWord to match any string in the data structure, otherwise returns false. - */ - -var MagicDictionary = function() { - this.words = new Set(); -}; - -/** - * @param {string[]} dictionary - * @return {void} - */ -MagicDictionary.prototype.buildDict = function(dictionary) { - this.words = new Set(dictionary); -}; - -/** - * @param {string} searchWord - * @return {boolean} - */ -MagicDictionary.prototype.search = function(searchWord) { - const words = searchWord.split(''); - return Array.from(this.words).some(word => { - if (word.length !== searchWord.length) return false; - let diff = 0; - for (let i = 0; i < word.length; i++) { - if (word[i] !== words[i]) diff++; - if (diff > 1) return false; - } - return diff === 1; - }); -}; diff --git a/solutions/0677-map-sum-pairs.js b/solutions/0677-map-sum-pairs.js deleted file mode 100644 index 4e66ad3f..00000000 --- a/solutions/0677-map-sum-pairs.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 677. Map Sum Pairs - * https://leetcode.com/problems/map-sum-pairs/ - * Difficulty: Medium - * - * Design a map that allows you to do the following: - * - Maps a string key to a given value. - * - Returns the sum of the values that have a key with a prefix equal to a given string. - * - * Implement the MapSum class: - * - MapSum() Initializes the MapSum object. - * - void insert(String key, int val) Inserts the key-val pair into the map. If the key - * already existed, the original key-value pair will be overridden to the new one. - * - int sum(string prefix) Returns the sum of all the pairs' value whose key starts - * with the prefix. - */ - -var MapSum = function() { - this.map = new Map(); -}; - -/** - * @param {string} key - * @param {number} val - * @return {void} - */ -MapSum.prototype.insert = function(key, val) { - this.map.set(key, val); -}; - -/** - * @param {string} prefix - * @return {number} - */ -MapSum.prototype.sum = function(prefix) { - return [...this.map.entries()].reduce((total, [key, val]) => { - return key.startsWith(prefix) ? total + val : total; - }, 0); -}; diff --git a/solutions/0678-valid-parenthesis-string.js b/solutions/0678-valid-parenthesis-string.js deleted file mode 100644 index e148d6db..00000000 --- a/solutions/0678-valid-parenthesis-string.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 678. Valid Parenthesis String - * https://leetcode.com/problems/valid-parenthesis-string/ - * Difficulty: Medium - * - * Given a string s containing only three types of characters: '(', ')' and '*', return - * true if s is valid. - * - * The following rules define a valid string: - * - Any left parenthesis '(' must have a corresponding right parenthesis ')'. - * - Any right parenthesis ')' must have a corresponding left parenthesis '('. - * - Left parenthesis '(' must go before the corresponding right parenthesis ')'. - * - '*' could be treated as a single right parenthesis ')' or a single left parenthesis - * '(' or an empty string "". - */ - -/** - * @param {string} s - * @return {boolean} - */ -var checkValidString = function(s) { - let result = 0; - let offset = 0; - - for (const character of s) { - result += character === '(' ? 1 : -1; - offset += character !== ')' ? 1 : -1; - if (offset < 0) return false; - result = Math.max(0, result); - } - - return !result; -}; diff --git a/solutions/0679-24-game.js b/solutions/0679-24-game.js deleted file mode 100644 index ac6bac86..00000000 --- a/solutions/0679-24-game.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 679. 24 Game - * https://leetcode.com/problems/24-game/ - * Difficulty: Hard - * - * You are given an integer array cards of length 4. You have four cards, each containing a number - * in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression - * using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. - * - * You are restricted with the following rules: - * - The division operator '/' represents real division, not integer division. - * - For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12. - * - Every operation done is between two numbers. In particular, we cannot use '-' as a - * unary operator. - * - For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed. - * - You cannot concatenate numbers together - * - For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid. - * - * Return true if you can get such expression that evaluates to 24, and false otherwise. - */ - -/** - * @param {number[]} cards - * @return {boolean} - */ -const judgePoint24 = function(cards) { - if (cards.length === 1) return Math.abs(cards[0] - 24) < 0.1; - - for (let i = 0; i < cards.length; i++) { - for (let j = i + 1; j < cards.length; j++) { - const remaining = new Array(cards.length - 1); - for (let index = 0, current = 0; current < cards.length; current++) { - if (i === current || j === current) continue; - remaining[index++] = cards[current]; - } - const a = cards[i]; - const b = cards[j]; - const operations = [a + b, a - b, b - a, a * b, a / b, b / a]; - for (const result of operations) { - if (result === 0) continue; - remaining[cards.length - 2] = result; - if (judgePoint24(remaining)) return true; - } - } - } - - return false; -}; diff --git a/solutions/0682-baseball-game.js b/solutions/0682-baseball-game.js deleted file mode 100644 index df460824..00000000 --- a/solutions/0682-baseball-game.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 682. Baseball Game - * https://leetcode.com/problems/baseball-game/ - * Difficulty: Easy - * - * You are keeping the scores for a baseball game with strange rules. At the beginning of the - * game, you start with an empty record. - * - * You are given a list of strings operations, where operations[i] is the ith operation you - * must apply to the record and is one of the following: - * - An integer x. - * - Record a new score of x. - * - '+'. - * - Record a new score that is the sum of the previous two scores. - * - 'D'. - * - Record a new score that is the double of the previous score. - * - 'C'. - * - Invalidate the previous score, removing it from the record. - * - * Return the sum of all the scores on the record after applying all the operations. - * - * The test cases are generated such that the answer and all intermediate calculations fit in a - * 32-bit integer and that all operations are valid. - */ - -/** - * @param {string[]} ops - * @return {number} - */ -var calPoints = function(ops) { - const stack = []; - - for (const op of ops) { - if (op === 'C') stack.pop(); - else if (op === 'D') stack.push(stack.at(-1) * 2); - else if (op === '+') stack.push(stack.at(-1) + stack.at(-2)); - else stack.push(Number(op)); - } - - return stack.reduce((sum, num) => sum + num, 0); -}; diff --git a/solutions/0685-redundant-connection-ii.js b/solutions/0685-redundant-connection-ii.js deleted file mode 100644 index 810daf08..00000000 --- a/solutions/0685-redundant-connection-ii.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 685. Redundant Connection II - * https://leetcode.com/problems/redundant-connection-ii/ - * Difficulty: Hard - * - * In this problem, a rooted tree is a directed graph such that, there is exactly one node - * (the root) for which all other nodes are descendants of this node, plus every node has - * exactly one parent, except for the root node which has no parents. - * - * The given input is a directed graph that started as a rooted tree with n nodes (with - * distinct values from 1 to n), with one additional directed edge added. The added edge - * has two different vertices chosen from 1 to n, and was not an edge that already existed. - * - * The resulting graph is given as a 2D-array of edges. Each element of edges is a pair - * [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent - * of child vi. - * - * Return an edge that can be removed so that the resulting graph is a rooted tree of n - * nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. - */ - -/** - * @param {number[][]} edges - * @return {number[]} - */ -var findRedundantDirectedConnection = function(edges) { - const n = edges.length; - const parent = Array.from({ length: n + 1 }, (_, i) => i); - const rank = new Uint32Array(n + 1); - const parents = new Int32Array(n + 1).fill(-1); - let conflict = -1; - let cycle = -1; - - edges.forEach(([u, v], i) => { - if (parents[v] !== -1) conflict = i; - else { - parents[v] = u; - union(u, v) || (cycle = i); - } - }); - - return conflict === -1 ? edges[cycle] : cycle === -1 - ? edges[conflict] : [parents[edges[conflict][1]], edges[conflict][1]]; - - function find(x) { - return parent[x] === x ? x : (parent[x] = find(parent[x])); - } - function union(x, y) { - const [px, py] = [find(x), find(y)]; - if (px === py) return false; - rank[px] < rank[py] - ? parent[px] = py - : rank[px] > rank[py] ? parent[py] = px : (parent[py] = px, rank[px]++); - return true; - } -}; diff --git a/solutions/0687-longest-univalue-path.js b/solutions/0687-longest-univalue-path.js deleted file mode 100644 index a17e7865..00000000 --- a/solutions/0687-longest-univalue-path.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 687. Longest Univalue Path - * https://leetcode.com/problems/longest-univalue-path/ - * Difficulty: Medium - * - * Given the root of a binary tree, return the length of the longest path, where each node - * in the path has the same value. This path may or may not pass through the root. - * - * The length of the path between two nodes is represented by the number of edges between 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 - * @return {number} - */ -var longestUnivaluePath = function(root) { - let max = 0; - dfs(root); - return max; - - function dfs(node) { - if (!node) return 0; - - const left = dfs(node.left); - const right = dfs(node.right); - const leftPath = node.left?.val === node.val ? left + 1 : 0; - const rightPath = node.right?.val === node.val ? right + 1 : 0; - - max = Math.max(max, leftPath + rightPath); - return Math.max(leftPath, rightPath); - } -}; diff --git a/solutions/0688-knight-probability-in-chessboard.js b/solutions/0688-knight-probability-in-chessboard.js deleted file mode 100644 index 122adba0..00000000 --- a/solutions/0688-knight-probability-in-chessboard.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 688. Knight Probability in Chessboard - * https://leetcode.com/problems/knight-probability-in-chessboard/ - * Difficulty: Medium - * - * On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly - * k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right - * cell is (n - 1, n - 1). - * - * A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells - * in a cardinal direction, then one cell in an orthogonal direction. - * - * Each time the knight is to move, it chooses one of eight possible moves uniformly at random - * (even if the piece would go off the chessboard) and moves there. - * - * The knight continues moving until it has made exactly k moves or has moved off the chessboard. - * - * Return the probability that the knight remains on the board after it has stopped moving. - */ - -/** - * @param {number} n - * @param {number} k - * @param {number} row - * @param {number} column - * @return {number} - */ -var knightProbability = function(n, k, row, column) { - const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]; - const dp = new Map(); - - return calc(k, row, column); - - function calc(movesLeft, r, c) { - if (r < 0 || r >= n || c < 0 || c >= n) return 0; - if (movesLeft === 0) return 1; - - const key = `${movesLeft},${r},${c}`; - if (dp.has(key)) return dp.get(key); - - let prob = 0; - for (const [dr, dc] of moves) { - prob += calc(movesLeft - 1, r + dr, c + dc) / 8; - } - - dp.set(key, prob); - return prob; - } -}; diff --git a/solutions/0689-maximum-sum-of-3-non-overlapping-subarrays.js b/solutions/0689-maximum-sum-of-3-non-overlapping-subarrays.js deleted file mode 100644 index c76d8060..00000000 --- a/solutions/0689-maximum-sum-of-3-non-overlapping-subarrays.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 689. Maximum Sum of 3 Non-Overlapping Subarrays - * https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/ - * Difficulty: Hard - * - * Given an integer array nums and an integer k, find three non-overlapping subarrays of - * length k with maximum sum and return them. - * - * Return the result as a list of indices representing the starting position of each - * interval (0-indexed). If there are multiple answers, return the lexicographically - * smallest one. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var maxSumOfThreeSubarrays = function(nums, k) { - const n = nums.length; - let [sumFirst, sumSecond, sumThird] = [0, 0, 0]; - let [maxFirst, maxFirstSecond, maxTotal] = [0, 0, 0]; - let [startFirst, startFirstBest, startSecondBest] = [0, 0, k]; - let result = [0, k, 2 * k]; - - for (let i = 0; i < k; i++) { - sumFirst += nums[i]; - sumSecond += nums[i + k]; - sumThird += nums[i + 2 * k]; - } - [maxFirst, maxFirstSecond, maxTotal] = [ - sumFirst, sumFirst + sumSecond, - sumFirst + sumSecond + sumThird - ]; - - for (let i = 1; i <= n - 3 * k; i++) { - sumFirst += nums[i + k - 1] - nums[i - 1]; - sumSecond += nums[i + 2 * k - 1] - nums[i + k - 1]; - sumThird += nums[i + 3 * k - 1] - nums[i + 2 * k - 1]; - - if (sumFirst > maxFirst) [maxFirst, startFirst] = [sumFirst, i]; - if (maxFirst + sumSecond > maxFirstSecond) { - [maxFirstSecond, startFirstBest, startSecondBest] = [maxFirst + sumSecond, startFirst, i + k]; - } - if (maxFirstSecond + sumThird > maxTotal) { - [maxTotal, ...result] = [ - maxFirstSecond + sumThird, - startFirstBest, - startSecondBest, i + 2 * k - ]; - } - } - - return result; -}; diff --git a/solutions/0690-employee-importance.js b/solutions/0690-employee-importance.js deleted file mode 100644 index 47633b40..00000000 --- a/solutions/0690-employee-importance.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 690. Employee Importance - * https://leetcode.com/problems/employee-importance/ - * Difficulty: Medium - * - * You have a data structure of employee information, including the employee's unique ID, - * importance value, and direct subordinates' IDs. - * - * You are given an array of employees employees where: - * - employees[i].id is the ID of the ith employee. - * - employees[i].importance is the importance value of the ith employee. - * - employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee. - * - * Given an integer id that represents an employee's ID, return the total importance value of this - * employee and all their direct and indirect subordinates. - */ - -/** - * Definition for Employee. - * function Employee(id, importance, subordinates) { - * this.id = id; - * this.importance = importance; - * this.subordinates = subordinates; - * } - */ - -/** - * @param {Employee[]} employees - * @param {number} id - * @return {number} - */ -var GetImportance = function(employees, id) { - const map = new Map(employees.map(e => [e.id, e])); - return dfs(id); - - function dfs(id) { - if (!map.has(id)) return 0; - const e = map.get(id); - return e.importance + e.subordinates.reduce((sum, id) => sum + dfs(id), 0); - } -}; diff --git a/solutions/0691-stickers-to-spell-word.js b/solutions/0691-stickers-to-spell-word.js deleted file mode 100644 index a3bf884c..00000000 --- a/solutions/0691-stickers-to-spell-word.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 691. Stickers to Spell Word - * https://leetcode.com/problems/stickers-to-spell-word/ - * Difficulty: Hard - * - * We are given n different types of stickers. Each sticker has a lowercase English word on it. - * - * You would like to spell out the given string target by cutting individual letters from your - * collection of stickers and rearranging them. You can use each sticker more than once if you - * want, and you have infinite quantities of each sticker. - * - * Return the minimum number of stickers that you need to spell out target. If the task is - * impossible, return -1. - * - * Note: In all test cases, all words were chosen randomly from the 1000 most common US English - * words, and target was chosen as a concatenation of two random words. - */ - -/** - * @param {string[]} stickers - * @param {string} target - * @return {number} - */ -var minStickers = function(stickers, target) { - const dp = new Map([['', 0]]); - return helper(target); - - function helper(str) { - if (dp.has(str)) return dp.get(str); - let result = Infinity; - - for (const s of stickers.filter(s => s.includes(str[0]))) { - result = Math.min(result, 1 + helper(calcDiff(str, s))); - } - - dp.set(str, result === Infinity || result === 0 ? -1 : result); - return dp.get(str); - } - - function calcDiff(str1, str2) { - for (const c of str2) { - if (str1.includes(c)) str1 = str1.replace(c, ''); - } - return str1; - } -}; diff --git a/solutions/0692-top-k-frequent-words.js b/solutions/0692-top-k-frequent-words.js deleted file mode 100644 index 8ac88865..00000000 --- a/solutions/0692-top-k-frequent-words.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 692. Top K Frequent Words - * https://leetcode.com/problems/top-k-frequent-words/ - * Difficulty: Medium - * - * Given an array of strings words and an integer k, return the k most frequent strings. - * - * Return the answer sorted by the frequency from highest to lowest. Sort the words with - * the same frequency by their lexicographical order. - */ - -/** - * @param {string[]} words - * @param {number} k - * @return {string[]} - */ -var topKFrequent = function(words, k) { - const map = new Map(); - words.forEach(word => map.set(word, (map.get(word) || 0) + 1)); - return [...map.entries()] - .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) - .slice(0, k) - .map(([word]) => word); -}; diff --git a/solutions/0698-partition-to-k-equal-sum-subsets.js b/solutions/0698-partition-to-k-equal-sum-subsets.js deleted file mode 100644 index 34020cc0..00000000 --- a/solutions/0698-partition-to-k-equal-sum-subsets.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 698. Partition to K Equal Sum Subsets - * https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ - * Difficulty: Medium - * - * Given an integer array nums and an integer k, return true if it is possible to divide this - * array into k non-empty subsets whose sums are all equal. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {boolean} - */ -var canPartitionKSubsets = function(nums, k) { - const sum = nums.reduce((a, b) => a + b); - if (sum % k !== 0) { - return false; - } - - const target = sum / k; - nums.sort((a, b) => b - a); - if (nums[0] > target) { - return false; - } - - const used = new Array(nums.length).fill(false); - return backtrack(0, 0, 0); - - function backtrack(index, count, updatedSum) { - if (count === k) return true; - if (updatedSum === target) return backtrack(0, count + 1, 0); - if (updatedSum > target) return false; - - for (let i = index; i < nums.length; i++) { - if (!used[i]) { - used[i] = true; - if (backtrack(i + 1, count, updatedSum + nums[i])) return true; - used[i] = false; - if (updatedSum === 0) break; - } - } - return false; - } -}; diff --git a/solutions/0699-falling-squares.js b/solutions/0699-falling-squares.js deleted file mode 100644 index b0192a62..00000000 --- a/solutions/0699-falling-squares.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 699. Falling Squares - * https://leetcode.com/problems/falling-squares/ - * Difficulty: Hard - * - * There are several squares being dropped onto the X-axis of a 2D plane. - * - * You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] - * represents the ith square with a side length of sideLengthi that is dropped with its - * left edge aligned with X-coordinate lefti. - * - * Each square is dropped one at a time from a height above any landed squares. It then - * falls downward (negative Y direction) until it either lands on the top side of another - * square or on the X-axis. A square brushing the left/right side of another square does - * not count as landing on it. Once it lands, it freezes in place and cannot be moved. - * - * After each square is dropped, you must record the height of the current tallest stack - * of squares. - * - * Return an integer array ans where ans[i] represents the height described above after - * dropping the ith square. - */ - -/** - * @param {number[][]} positions - * @return {number[]} - */ -var fallingSquares = function(positions) { - const map = new Map(); - const result = []; - let max = 0; - - for (const [left, side] of positions) { - const right = left + side; - let height = 0; - - for (const [start, [i, n]] of map) { - const end = start + i; - if (right > start && left < end) { - height = Math.max(height, n); - } - } - - height += side; - map.set(left, [side, height]); - max = Math.max(max, height); - result.push(max); - } - - return result; -}; diff --git a/solutions/0703-kth-largest-element-in-a-stream.js b/solutions/0703-kth-largest-element-in-a-stream.js deleted file mode 100644 index d0b45129..00000000 --- a/solutions/0703-kth-largest-element-in-a-stream.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 703. Kth Largest Element in a Stream - * https://leetcode.com/problems/kth-largest-element-in-a-stream/ - * Difficulty: Easy - * - * You are part of a university admissions office and need to keep track of the kth highest test - * score from applicants in real-time. This helps to determine cut-off marks for interviews and - * admissions dynamically as new applicants submit their scores. - * - * You are tasked to implement a class which, for a given integer k, maintains a stream of test - * scores and continuously returns the kth highest test score after a new score has been submitted. - * More specifically, we are looking for the kth highest score in the sorted list of all scores. - * - * Implement the KthLargest class: - * - KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of - * test scores nums. - * - int add(int val) Adds a new test score val to the stream and returns the element representing - * the kth largest element in the pool of test scores so far. - */ - -/** - * @param {number} k - * @param {number[]} nums - */ -var KthLargest = function(k, nums) { - this.main = new MinPriorityQueue(); - this.k = k; - - nums.forEach(n => this.main.enqueue(n)); - - while (this.main.size() > k) { - this.main.dequeue().element; - } -}; - -/** - * @param {number} val - * @return {number} - */ -KthLargest.prototype.add = function(val) { - this.main.enqueue(val); - - if (this.main.size() > this.k) { - this.main.dequeue().element; - } - - return this.main.front().element; -}; diff --git a/solutions/0704-binary-search.js b/solutions/0704-binary-search.js deleted file mode 100644 index a8cf2011..00000000 --- a/solutions/0704-binary-search.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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/solutions/0707-design-linked-list.js b/solutions/0707-design-linked-list.js deleted file mode 100644 index d0f67519..00000000 --- a/solutions/0707-design-linked-list.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * 707. Design Linked List - * https://leetcode.com/problems/design-linked-list/ - * Difficulty: Medium - * - * Design your implementation of the linked list. You can choose to use a singly or - * doubly linked list. - * - * A node in a singly linked list should have two attributes: val and next. val is the value - * of the current node, and next is a pointer/reference to the next node. - * - * If you want to use the doubly linked list, you will need one more attribute prev to indicate - * the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. - * - * Implement the MyLinkedList class: - * - MyLinkedList() Initializes the MyLinkedList object. - * - int get(int index) Get the value of the indexth node in the linked list. If the - * index is invalid, return -1. - * - void addAtHead(int val) Add a node of value val before the first element of the - * linked list. After the insertion, the new node will be the first node of the linked list. - * - void addAtTail(int val) Append a node of value val as the last element of the linked list. - * - void addAtIndex(int index, int val) Add a node of value val before the indexth node - * in the linked list. If index equals the length of the linked list, the node will be - * appended to the end of the linked list. If index is greater than the length, the node - * will not be inserted. - * - void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index - * is valid. - */ - -var MyLinkedList = function() { - this.head = null; - this.size = 0; -}; - -/** - * @param {number} index - * @return {number} - */ -MyLinkedList.prototype.get = function(index) { - if (index < 0 || index >= this.size) return -1; - let current = this.head; - while (index--) current = current.next; - return current.val; -}; - -/** - * @param {number} val - * @return {void} - */ -MyLinkedList.prototype.addAtHead = function(val) { - const node = new Node(val); - node.next = this.head; - this.head = node; - this.size++; -}; - -/** - * @param {number} val - * @return {void} - */ -MyLinkedList.prototype.addAtTail = function(val) { - const node = new Node(val); - if (!this.head) { - this.head = node; - } else { - let current = this.head; - while (current.next) current = current.next; - current.next = node; - } - this.size++; -}; - -/** - * @param {number} index - * @param {number} val - * @return {void} - */ -MyLinkedList.prototype.addAtIndex = function(index, val) { - if (index < 0 || index > this.size) return; - if (index === 0) return this.addAtHead(val); - const node = new Node(val); - let current = this.head; - while (--index) current = current.next; - node.next = current.next; - current.next = node; - this.size++; -}; - -/** - * @param {number} index - * @return {void} - */ -MyLinkedList.prototype.deleteAtIndex = function(index) { - if (index < 0 || index >= this.size) return; - this.size--; - if (index === 0) { - this.head = this.head.next; - return; - } - let current = this.head; - while (--index) current = current.next; - current.next = current.next.next; -}; - -class Node { - constructor(val) { - this.val = val; - this.next = null; - } -} diff --git a/solutions/0709-to-lower-case.js b/solutions/0709-to-lower-case.js deleted file mode 100644 index 49ef785a..00000000 --- a/solutions/0709-to-lower-case.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 709. To Lower Case - * https://leetcode.com/problems/to-lower-case/ - * Difficulty: Easy - * - * Given a string s, return the string after replacing every uppercase letter with the same - * lowercase letter. - */ - -/** - * @param {string} s - * @return {string} - */ -var toLowerCase = function(s) { - return s.toLowerCase(); -}; diff --git a/solutions/0710-random-pick-with-blacklist.js b/solutions/0710-random-pick-with-blacklist.js deleted file mode 100644 index 2715bb35..00000000 --- a/solutions/0710-random-pick-with-blacklist.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 710. Random Pick with Blacklist - * https://leetcode.com/problems/random-pick-with-blacklist/ - * Difficulty: Hard - * - * You are given an integer n and an array of unique integers blacklist. Design an algorithm to - * pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is - * in the mentioned range and not in blacklist should be equally likely to be returned. - * - * Optimize your algorithm such that it minimizes the number of calls to the built-in random - * function of your language. - * - * Implement the Solution class: - * - Solution(int n, int[] blacklist) Initializes the object with the integer n and the - * blacklisted integers blacklist. - * - int pick() Returns a random integer in the range [0, n - 1] and not in blacklist. - */ - -/** - * @param {number} n - * @param {number[]} blacklist - */ -var Solution = function(n, blacklist) { - this.size = n - blacklist.length; - this.mapping = new Map(); - blacklist = new Set(blacklist); - - let last = n - 1; - for (const b of blacklist) { - if (b < this.size) { - while (blacklist.has(last)) last--; - this.mapping.set(b, last--); - } - } -}; - -/** - * @return {number} - */ -Solution.prototype.pick = function() { - const index = Math.floor(Math.random() * this.size); - return this.mapping.get(index) ?? index; -}; diff --git a/solutions/0712-minimum-ascii-delete-sum-for-two-strings.js b/solutions/0712-minimum-ascii-delete-sum-for-two-strings.js deleted file mode 100644 index 65eb0438..00000000 --- a/solutions/0712-minimum-ascii-delete-sum-for-two-strings.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 712. Minimum ASCII Delete Sum for Two Strings - * https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ - * Difficulty: Medium - * - * Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to - * make two strings equal. - */ - -/** - * @param {string} s1 - * @param {string} s2 - * @return {number} - */ -var minimumDeleteSum = function(s1, s2) { - const dp = new Array(s1.length + 1).fill().map(() => { - return new Array(s2.length + 1).fill(0); - }); - - for (let i = 1; i <= s1.length; i++) { - dp[i][0] = dp[i - 1][0] + s1.charCodeAt(i - 1); - } - for (let j = 1; j <= s2.length; j++) { - dp[0][j] = dp[0][j - 1] + s2.charCodeAt(j - 1); - } - - for (let i = 1; i <= s1.length; i++) { - for (let j = 1; j <= s2.length; j++) { - if (s1[i - 1] === s2[j - 1]) { - dp[i][j] = dp[i - 1][j - 1]; - } else { - dp[i][j] = Math.min( - dp[i - 1][j] + s1.charCodeAt(i - 1), - dp[i][j - 1] + s2.charCodeAt(j - 1) - ); - } - } - } - - return dp[s1.length][s2.length]; -}; diff --git a/solutions/0715-range-module.js b/solutions/0715-range-module.js deleted file mode 100644 index dd76c8c8..00000000 --- a/solutions/0715-range-module.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 715. Range Module - * https://leetcode.com/problems/range-module/ - * Difficulty: Hard - * - * A Range Module is a module that tracks ranges of numbers. Design a data structure to track the - * ranges represented as half-open intervals and query about them. - * - * A half-open interval [left, right) denotes all the real numbers x where left <= x < right. - * - * Implement the RangeModule class: - * - RangeModule() Initializes the object of the data structure. - * - void addRange(int left, int right) Adds the half-open interval [left, right), tracking every - * real number in that interval. Adding an interval that partially overlaps with currently tracked - * numbers should add any numbers in the interval [left, right) that are not already tracked. - * - boolean queryRange(int left, int right) Returns true if every real number in the interval - * [left, right) is currently being tracked, and false otherwise. - * - void removeRange(int left, int right) Stops tracking every real number currently being tracked - * in the half-open interval [left, right). - */ - -var RangeModule = function() { - this.ranges = []; -}; - -/** - * @param {number} left - * @param {number} right - * @return {void} - */ -RangeModule.prototype.addRange = function(left, right) { - const intervals = []; - let placed = false; - for (const [start, end] of this.ranges) { - if (start > right && !placed) { - intervals.push([left, right]); - placed = true; - } - if (end < left || start > right) { - intervals.push([start, end]); - } else { - left = Math.min(left, start); - right = Math.max(right, end); - } - } - if (!placed) intervals.push([left, right]); - this.ranges = intervals; -}; - -/** - * @param {number} left - * @param {number} right - * @return {boolean} - */ -RangeModule.prototype.queryRange = function(left, right) { - for (const [start, end] of this.ranges) { - if (start <= left && end >= right) return true; - if (start > left) break; - } - return false; -}; - -/** - * @param {number} left - * @param {number} right - * @return {void} - */ -RangeModule.prototype.removeRange = function(left, right) { - const intervals = []; - for (const [start, end] of this.ranges) { - if (end <= left || start >= right) { - intervals.push([start, end]); - } else { - if (start < left) intervals.push([start, left]); - if (end > right) intervals.push([right, end]); - } - } - this.ranges = intervals; -}; diff --git a/solutions/0718-maximum-length-of-repeated-subarray.js b/solutions/0718-maximum-length-of-repeated-subarray.js deleted file mode 100644 index 97a29b28..00000000 --- a/solutions/0718-maximum-length-of-repeated-subarray.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 718. Maximum Length of Repeated Subarray - * https://leetcode.com/problems/maximum-length-of-repeated-subarray/ - * Difficulty: Medium - * - * Given two integer arrays nums1 and nums2, return the maximum length of a subarray - * that appears in both arrays. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var findLength = function(nums1, nums2) { - const dp = new Array(nums1.length + 1).fill().map(() => { - return new Array(nums2.length + 1).fill(0); - }); - let result = 0; - - for (let i = 1; i <= nums1.length; i++) { - for (let j = 1; j <= nums2.length; j++) { - if (nums1[i - 1] === nums2[j - 1]) { - dp[i][j] = dp[i - 1][j - 1] + 1; - result = Math.max(result, dp[i][j]); - } - } - } - - return result; -}; diff --git a/solutions/0719-find-k-th-smallest-pair-distance.js b/solutions/0719-find-k-th-smallest-pair-distance.js deleted file mode 100644 index fd442d98..00000000 --- a/solutions/0719-find-k-th-smallest-pair-distance.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 719. Find K-th Smallest Pair Distance - * https://leetcode.com/problems/find-k-th-smallest-pair-distance/ - * Difficulty: Hard - * - * The distance of a pair of integers a and b is defined as the absolute difference between a and b. - * - * Given an integer array nums and an integer k, return the kth smallest distance among all the - * pairs nums[i] and nums[j] where 0 <= i < j < nums.length. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var smallestDistancePair = function(nums, k) { - nums.sort((a, b) => a - b); - let left = 0; - let right = nums[nums.length - 1] - nums[0]; - - while (left < right) { - const middle = Math.floor((left + right) / 2); - let count = 0; - let j = 0; - - for (let i = 0; i < nums.length; i++) { - while (j < nums.length && nums[j] - nums[i] <= middle) j++; - count += j - i - 1; - } - - if (count < k) { - left = middle + 1; - } else { - right = middle; - } - } - - return left; -}; diff --git a/solutions/0721-accounts-merge.js b/solutions/0721-accounts-merge.js deleted file mode 100644 index 69b6c7cf..00000000 --- a/solutions/0721-accounts-merge.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 721. Accounts Merge - * https://leetcode.com/problems/accounts-merge/ - * Difficulty: Medium - * - * Given a list of accounts where each element accounts[i] is a list of strings, where the first - * element accounts[i][0] is a name, and the rest of the elements are emails representing emails - * of the account. - * - * Now, we would like to merge these accounts. Two accounts definitely belong to the same person - * if there is some common email to both accounts. Note that even if two accounts have the same - * name, they may belong to different people as people could have the same name. A person can - * have any number of accounts initially, but all of their accounts definitely have the same name. - * - * After merging the accounts, return the accounts in the following format: the first element of - * each account is the name, and the rest of the elements are emails in sorted order. The accounts - * themselves can be returned in any order. - */ - -/** - * @param {string[][]} accounts - * @return {string[][]} - */ -var accountsMerge = function(accounts) { - const parent = new Map(); - const names = new Map(); - const groups = new Map(); - - const find = node => { - if (!parent.has(node)) parent.set(node, node); - return parent.get(node) === node ? node : parent.set(node, find(parent.get(node))).get(node); - }; - - for (const [name, ...emails] of accounts) { - for (const email of emails) { - names.set(email, name); - find(email); - parent.set(find(email), find(emails[0])); - } - } - - for (const email of parent.keys()) { - const root = find(email); - if (!groups.has(root)) groups.set(root, new Set()); - groups.get(root).add(email); - } - - return Array.from(groups, ([root, emails]) => [names.get(root), ...[...emails].sort()]); -}; diff --git a/solutions/0725-split-linked-list-in-parts.js b/solutions/0725-split-linked-list-in-parts.js deleted file mode 100644 index 0659048d..00000000 --- a/solutions/0725-split-linked-list-in-parts.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 725. Split Linked List in Parts - * https://leetcode.com/problems/split-linked-list-in-parts/ - * Difficulty: Medium - * - * Given the head of a singly linked list and an integer k, split the linked list into k - * consecutive linked list parts. - * - * The length of each part should be as equal as possible: no two parts should have a size - * differing by more than one. This may lead to some parts being null. - * - * The parts should be in the order of occurrence in the input list, and parts occurring - * earlier should always have a size greater than or equal to parts occurring later. - * - * Return an array of the k parts. - */ - -/** - * 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 splitListToParts = function(head, k) { - let count = 0; - let current = head; - - while (current) { - count++; - current = current.next; - } - - const base = Math.floor(count / k); - const extra = count % k; - const result = new Array(k).fill(null); - - current = head; - for (let i = 0; i < k && current; i++) { - result[i] = current; - const partSize = base + (i < extra ? 1 : 0); - for (let j = 1; j < partSize; j++) { - current = current.next; - } - const next = current.next; - current.next = null; - current = next; - } - - return result; -}; diff --git a/solutions/0726-number-of-atoms.js b/solutions/0726-number-of-atoms.js deleted file mode 100644 index e1e0496b..00000000 --- a/solutions/0726-number-of-atoms.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * 726. Number of Atoms - * https://leetcode.com/problems/number-of-atoms/ - * Difficulty: Hard - * - * Given a string formula representing a chemical formula, return the count of each atom. - * - * The atomic element always starts with an uppercase character, then zero or more lowercase - * letters, representing the name. - * - * One or more digits representing that element's count may follow if the count is greater - * than 1. If the count is 1, no digits will follow. - * - For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible. - * - * Two formulas are concatenated together to produce another formula. - * - For example, "H2O2He3Mg4" is also a formula. - * - * A formula placed in parentheses, and a count (optionally added) is also a formula. - * - For example, "(H2O2)" and "(H2O2)3" are formulas. - * - * Return the count of all elements as a string in the following form: the first name (in sorted - * order), followed by its count (if that count is more than 1), followed by the second name - * (in sorted order), followed by its count (if that count is more than 1), and so on. - * - * The test cases are generated so that all the values in the output fit in a 32-bit integer. - */ - -/** - * @param {string} formula - * @return {string} - */ -var countOfAtoms = function(formula) { - const [counts] = parseFormula(formula, 0); - return [...counts].sort().map(([atom, count]) => atom + (count > 1 ? count : '')).join(''); - - function parseFormula(str, index) { - const atomCounts = new Map(); - while (index < str.length && str[index] !== ')') { - if (str[index] === '(') { - const [subCounts, nextIndex] = parseFormula(str, index + 1); - const [multiplier, updatedIndex] = extractNumber(str, nextIndex + 1); - for (const [atom, count] of subCounts) { - atomCounts.set(atom, (atomCounts.get(atom) || 0) + count * (multiplier || 1)); - } - index = updatedIndex; - } else { - const [atom, nextIndex] = extractAtom(str, index); - const [count, updatedIndex] = extractNumber(str, nextIndex); - atomCounts.set(atom, (atomCounts.get(atom) || 0) + (count || 1)); - index = updatedIndex; - } - } - return [atomCounts, index]; - } - - function extractAtom(str, index) { - let atom = str[index]; - while (++index < str.length && /[a-z]/.test(str[index])) atom += str[index]; - return [atom, index]; - } - - function extractNumber(str, index) { - let number = 0; - while (index < str.length && /[0-9]/.test(str[index])) { - number = number * 10 + Number(str[index++]); - } - return [number || null, index]; - } -}; diff --git a/solutions/0728-self-dividing-numbers.js b/solutions/0728-self-dividing-numbers.js deleted file mode 100644 index d54a8628..00000000 --- a/solutions/0728-self-dividing-numbers.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 728. Self Dividing Numbers - * https://leetcode.com/problems/self-dividing-numbers/ - * Difficulty: Easy - * - * A self-dividing number is a number that is divisible by every digit it contains. - * - For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, - * and 128 % 8 == 0. - * - * A self-dividing number is not allowed to contain the digit zero. - * - * Given two integers left and right, return a list of all the self-dividing numbers - * in the range [left, right] (both inclusive). - */ - -/** - * @param {number} left - * @param {number} right - * @return {number[]} - */ -var selfDividingNumbers = function(left, right) { - return Array.from({ length: right - left + 1 }, (_, i) => left + i) - .filter(n => String(n).split('').every(d => d !== '0' && n % d === 0)); -}; diff --git a/solutions/0729-my-calendar-i.js b/solutions/0729-my-calendar-i.js deleted file mode 100644 index 51f6cc21..00000000 --- a/solutions/0729-my-calendar-i.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * 729. My Calendar I - * https://leetcode.com/problems/my-calendar-i/ - * Difficulty: Medium - * - * You are implementing a program to use as your calendar. We can add a new event if adding the - * event will not cause a double booking. - * - * A double booking happens when two events have some non-empty intersection (i.e., some moment - * is common to both events.). - * - * The event can be represented as a pair of integers startTime and endTime that represents a - * booking on the half-open interval [startTime, endTime), the range of real numbers x such - * that startTime <= x < endTime. - * - * Implement the MyCalendar class: - * - MyCalendar() Initializes the calendar object. - * - boolean book(int startTime, int endTime) Returns true if the event can be added to the - * calendar successfully without causing a double booking. Otherwise, return false and do - * not add the event to the calendar. - */ - -class MyCalendar { - constructor() { - this.events = []; - } - - /** - * @param {number} startTime - * @param {number} endTime - * @returns {boolean} - */ - book(startTime, endTime) { - const event = [startTime, endTime]; - const index = this.findInsertIndex(startTime); - - if (this.overlapsPrevious(index - 1, startTime) || this.overlapsNext(index, endTime)) { - return false; - } - - this.events.splice(index, 0, event); - return true; - } - - /** - * @param {number} startTime - * @returns {number} - */ - findInsertIndex(startTime) { - let left = 0; - let right = this.events.length; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (this.events[mid][0] > startTime) { - right = mid; - } else { - left = mid + 1; - } - } - - return left; - } - - /** - * @param {number} prevIndex - * @param {number} startTime - * @returns {boolean} - */ - overlapsPrevious(prevIndex, startTime) { - return prevIndex >= 0 && this.events[prevIndex][1] > startTime; - } - - /** - * @param {number} nextIndex - * @param {number} endTime - * @returns {boolean} - */ - overlapsNext(nextIndex, endTime) { - return nextIndex < this.events.length && this.events[nextIndex][0] < endTime; - } -} diff --git a/solutions/0730-count-different-palindromic-subsequences.js b/solutions/0730-count-different-palindromic-subsequences.js deleted file mode 100644 index e06f3329..00000000 --- a/solutions/0730-count-different-palindromic-subsequences.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 730. Count Different Palindromic Subsequences - * https://leetcode.com/problems/count-different-palindromic-subsequences/ - * Difficulty: Hard - * - * Given a string s, return the number of different non-empty palindromic subsequences in s. - * Since the answer may be very large, return it modulo 109 + 7. - * - * A subsequence of a string is obtained by deleting zero or more characters from the string. - * - * A sequence is palindromic if it is equal to the sequence reversed. - * - * Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi. - */ - -/** - * @param {string} s - * @return {number} - */ -var countPalindromicSubsequences = function(s) { - const MOD = 1e9 + 7; - const dp = new Array(s.length).fill().map(() => { - return new Array(s.length).fill(0); - }); - - for (let i = 0; i < s.length; i++) { - dp[i][i] = 1; - } - - for (let len = 2; len <= s.length; len++) { - for (let start = 0; start + len <= s.length; start++) { - const end = start + len - 1; - const charStart = s[start]; - const charEnd = s[end]; - - if (charStart !== charEnd) { - dp[start][end] = (dp[start + 1][end] + dp[start][end - 1] - dp[start + 1][end - 1]) % MOD; - } else { - let left = start + 1; - let right = end - 1; - - while (left <= right && s[left] !== charStart) left++; - while (left <= right && s[right] !== charStart) right--; - - if (left > right) { - dp[start][end] = (2 * dp[start + 1][end - 1] + 2) % MOD; - } else if (left === right) { - dp[start][end] = (2 * dp[start + 1][end - 1] + 1) % MOD; - } else { - dp[start][end] = (2 * dp[start + 1][end - 1] - dp[left + 1][right - 1]) % MOD; - } - } - - if (dp[start][end] < 0) dp[start][end] += MOD; - } - } - - return dp[0][s.length - 1]; -}; diff --git a/solutions/0731-my-calendar-ii.js b/solutions/0731-my-calendar-ii.js deleted file mode 100644 index b2e05575..00000000 --- a/solutions/0731-my-calendar-ii.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 731. My Calendar II - * https://leetcode.com/problems/my-calendar-ii/ - * Difficulty: Medium - * - * You are implementing a program to use as your calendar. We can add a new event if adding the - * event will not cause a triple booking. - * - * A triple booking happens when three events have some non-empty intersection (i.e., some moment - * is common to all the three events.). - * - * The event can be represented as a pair of integers startTime and endTime that represents a - * booking on the half-open interval [startTime, endTime), the range of real numbers x such that - * startTime <= x < endTime. - * - * Implement the MyCalendarTwo class: - * - MyCalendarTwo() Initializes the calendar object. - * - boolean book(int startTime, int endTime) Returns true if the event can be added to the calendar - * successfully without causing a triple booking. Otherwise, return false and do not add the event - * to the calendar. - */ - -var MyCalendarTwo = function() { - this.bookings = []; - this.overlaps = []; -}; - -/** - * @param {number} startTime - * @param {number} endTime - * @return {boolean} - */ -MyCalendarTwo.prototype.book = function(startTime, endTime) { - for (const [start, end] of this.overlaps) { - if (startTime < end && endTime > start) return false; - } - - for (const [start, end] of this.bookings) { - if (startTime < end && endTime > start) { - this.overlaps.push([Math.max(start, startTime), Math.min(end, endTime)]); - } - } - - this.bookings.push([startTime, endTime]); - return true; -}; diff --git a/solutions/0732-my-calendar-iii.js b/solutions/0732-my-calendar-iii.js deleted file mode 100644 index 38b438a1..00000000 --- a/solutions/0732-my-calendar-iii.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 732. My Calendar III - * https://leetcode.com/problems/my-calendar-iii/ - * Difficulty: Hard - * - * A k-booking happens when k events have some non-empty intersection (i.e., there is some time - * that is common to all k events.) - * - * You are given some events [startTime, endTime), after each given event, return an integer k - * representing the maximum k-booking between all the previous events. - * - * Implement the MyCalendarThree class: - * - MyCalendarThree() Initializes the object. - * - int book(int startTime, int endTime) Returns an integer k representing the largest integer - * such that there exists a k-booking in the calendar. - */ - -class MyCalendarThree { - constructor() { - this.events = []; - } - - /** - * @param {number} startTime - * @param {number} endTime - * @returns {number} - */ - book(startTime, endTime) { - this.insertTime(startTime, 1); - this.insertTime(endTime, -1); - let maxBookings = 1; - let currentBookings = 0; - this.events.forEach(event => maxBookings = Math.max(currentBookings += event[1], maxBookings)); - return maxBookings; - } - - /** - * @param {number} targetTime - * @param {number} value - */ - insertTime(targetTime, value) { - const events = this.events; - let left = 0; - let right = events.length - 1; - while (left <= right) { - const mid = left + right >> 1; - if (events[mid][0] < targetTime) left = mid + 1; - else if (events[mid][0] > targetTime) right = mid - 1; - else return events[mid][1] += value; - } - events.splice(left, 0, [targetTime, value]); - } -} diff --git a/solutions/0736-parse-lisp-expression.js b/solutions/0736-parse-lisp-expression.js deleted file mode 100644 index e465f85e..00000000 --- a/solutions/0736-parse-lisp-expression.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 736. Parse Lisp Expression - * https://leetcode.com/problems/parse-lisp-expression/ - * Difficulty: Hard - * - * You are given a string expression representing a Lisp-like expression to return the integer - * value of. - * - * The syntax for these expressions is given as follows. - * - An expression is either an integer, let expression, add expression, mult expression, or an - * assigned variable. Expressions always evaluate to a single integer. - * - (An integer could be positive or negative.) - * - A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the - * string "let", then there are one or more pairs of alternating variables and expressions, - * meaning that the first variable v1 is assigned the value of the expression e1, the second - * variable v2 is assigned the value of the expression e2, and so on sequentially; and then the - * value of this let expression is the value of the expression expr. - * - An add expression takes the form "(add e1 e2)" where add is always the string "add", there are - * always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the - * evaluation of e2. - * - A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there - * are always two expressions e1, e2 and the result is the multiplication of the evaluation of - * e1 and the evaluation of e2. - * - For this question, we will use a smaller subset of variable names. A variable starts with a - * lowercase letter, then zero or more lowercase letters or digits. Additionally, for your - * convenience, the names "add", "let", and "mult" are protected and will never be used as - * variable names. - * - Finally, there is the concept of scope. When an expression of a variable name is evaluated, - * within the context of that evaluation, the innermost scope (in terms of parentheses) is - * checked first for the value of that variable, and then outer scopes are checked sequentially. - * It is guaranteed that every expression is legal. Please see the examples for more details - * on the scope. - */ - -/** - * @param {string} expression - * @return {number} - */ -var evaluate = function(expression) { - return parse(expression, new Map()); - - function parse(exp, scope) { - if (!isNaN(exp)) return parseInt(exp); - if (!exp.startsWith('(')) return scope.get(exp) || 0; - - const tokens = tokenize(exp.slice(1, -1)); - if (tokens[0] === 'add') return parse(tokens[1], scope) + parse(tokens[2], scope); - if (tokens[0] === 'mult') return parse(tokens[1], scope) * parse(tokens[2], scope); - - const newScope = new Map(scope); - for (let i = 1; i < tokens.length - 1; i += 2) { - newScope.set(tokens[i], parse(tokens[i + 1], newScope)); - } - return parse(tokens[tokens.length - 1], newScope); - } - - function tokenize(exp) { - const result = []; - let current = ''; - let depth = 0; - - for (const char of exp) { - if (char === ' ' && depth === 0) { - result.push(current); - current = ''; - } else { - current += char; - if (char === '(') depth++; - if (char === ')') depth--; - } - } - result.push(current); - return result; - } -}; diff --git a/solutions/0738-monotone-increasing-digits.js b/solutions/0738-monotone-increasing-digits.js deleted file mode 100644 index 0505a5c3..00000000 --- a/solutions/0738-monotone-increasing-digits.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 738. Monotone Increasing Digits - * https://leetcode.com/problems/monotone-increasing-digits/ - * Difficulty: Medium - * - * An integer has monotone increasing digits if and only if each pair of adjacent digits - * x and y satisfy x <= y. - * - * Given an integer n, return the largest number that is less than or equal to n with - * monotone increasing digits. - */ - -/** - * @param {number} n - * @return {number} - */ -var monotoneIncreasingDigits = function(n) { - const digits = String(n).split('').map(Number); - let offset = digits.length; - - for (let i = digits.length - 1; i > 0; i--) { - if (digits[i - 1] > digits[i]) { - offset = i; - digits[i - 1]--; - } - } - - for (let i = offset; i < digits.length; i++) { - digits[i] = 9; - } - - return +digits.join(''); -}; diff --git a/solutions/0740-delete-and-earn.js b/solutions/0740-delete-and-earn.js deleted file mode 100644 index 57295b2d..00000000 --- a/solutions/0740-delete-and-earn.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 740. Delete and Earn - * https://leetcode.com/problems/delete-and-earn/ - * Difficulty: Medium - * - * You are given an integer array nums. You want to maximize the number of points you get by - * performing the following operation any number of times: - * - Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every - * element equal to nums[i] - 1 and every element equal to nums[i] + 1. - * - * Return the maximum number of points you can earn by applying the above operation some number - * of times. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var deleteAndEarn = function(nums) { - const points = new Array(10001).fill(0); - let previous = 0; - let result = 0; - - for (const num of nums) { - points[num] += num; - } - - for (const value of points) { - const temp = result; - result = Math.max(result, previous + value); - previous = temp; - } - - return result; -}; diff --git a/solutions/0741-cherry-pickup.js b/solutions/0741-cherry-pickup.js deleted file mode 100644 index b9d347ed..00000000 --- a/solutions/0741-cherry-pickup.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 741. Cherry Pickup - * https://leetcode.com/problems/cherry-pickup/ - * Difficulty: Hard - * - * You are given an n x n grid representing a field of cherries, each cell is one of three - * possible integers. - * - 0 means the cell is empty, so you can pass through, - * - 1 means the cell contains a cherry that you can pick up and pass through, or - * - -1 means the cell contains a thorn that blocks your way. - * - * Return the maximum number of cherries you can collect by following the rules below: - * - Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through - * valid path cells (cells with value 0 or 1). - * - After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path - * cells. - * - When passing through a path cell containing a cherry, you pick it up, and the cell becomes - * an empty cell 0. - * - If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var cherryPickup = function(grid) { - const n = grid.length; - const dp = Array.from({ length: n }, () => - Array.from({ length: n }, () => - new Array(2 * n - 1).fill(-1)) - ); - - if (grid[0][0] === -1) return 0; - dp[0][0][0] = grid[0][0]; - - for (let t = 1; t <= 2 * n - 2; t++) { - for (let x1 = Math.max(0, t - n + 1); x1 <= Math.min(n - 1, t); x1++) { - for (let x2 = Math.max(0, t - n + 1); x2 <= Math.min(n - 1, t); x2++) { - const y1 = t - x1; - const y2 = t - x2; - - if (grid[x1][y1] === -1 || grid[x2][y2] === -1) continue; - - const cherries = grid[x1][y1] + (x1 === x2 ? 0 : grid[x2][y2]); - let maxPrev = -1; - - for (const px1 of [x1 - 1, x1]) { - for (const px2 of [x2 - 1, x2]) { - if (px1 >= 0 && px2 >= 0 && dp[px1][px2][t - 1] >= 0) { - maxPrev = Math.max(maxPrev, dp[px1][px2][t - 1]); - } - } - } - - if (maxPrev >= 0) { - dp[x1][x2][t] = maxPrev + cherries; - } - } - } - } - - return dp[n - 1][n - 1][2 * n - 2] < 0 ? 0 : dp[n - 1][n - 1][2 * n - 2]; -}; diff --git a/solutions/0749-contain-virus.js b/solutions/0749-contain-virus.js deleted file mode 100644 index a9fca54d..00000000 --- a/solutions/0749-contain-virus.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * 749. Contain Virus - * https://leetcode.com/problems/contain-virus/ - * Difficulty: Hard - * - * A virus is spreading rapidly, and your task is to quarantine the infected area by - * installing walls. - * - * The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 - * represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated - * with the virus. A wall (and only one wall) can be installed between any two 4-directionally - * adjacent cells, on the shared boundary. - * - * Every night, the virus spreads to all neighboring cells in all four directions unless - * blocked by a wall. Resources are limited. Each day, you can install walls around only one - * region (i.e., the affected area (continuous block of infected cells) that threatens the - * most uninfected cells the following night). There will never be a tie. - * - * Return the number of walls used to quarantine all the infected regions. If the world will - * become fully infected, return the number of walls used. - */ - -/** - * @param {number[][]} isInfected - * @return {number} - */ -var containVirus = function(isInfected) { - const verticalBarriers = new Set(); - const horizontalBarriers = new Set(); - const grid = isInfected; - const rows = grid.length; - const cols = grid[0].length; - const directions = [[-1, 0, -cols, -cols], [1, 0, cols, 0], [0, -1, -1, -1], [0, 1, 1, 0]]; - let target; - let nextState; - let maxThreat; - let threatenedCells; - let nextVertical; - let nextHorizontal; - let verticalWalls; - let horizontalWalls; - let startRow; - let startCol; - - while (true) { - target = 1; - nextState = 2; - maxThreat = 0; - grid.forEach((row, r) => row.forEach((cell, c) => cell && exploreRegion(r, c))); - if (maxThreat === 0) return verticalBarriers.size + horizontalBarriers.size; - target = 2; - nextState = 0; - traverseRegion(startRow, startCol); - verticalWalls.forEach(pos => verticalBarriers.add(pos)); - horizontalWalls.forEach(pos => horizontalBarriers.add(pos)); - nextState = 1; - threatenedCells = new Set(); - grid.forEach((row, r) => row.forEach((cell, c) => cell && traverseRegion(r, c))); - threatenedCells.forEach(pos => grid[Math.floor(pos / cols)][pos % cols] = 1); - } - - function exploreRegion(row, col) { - threatenedCells = new Set(); - nextVertical = new Set(); - nextHorizontal = new Set(); - traverseRegion(row, col); - if (threatenedCells.size < maxThreat) return; - maxThreat = threatenedCells.size; - verticalWalls = nextVertical; - horizontalWalls = nextHorizontal; - startRow = row; - startCol = col; - } - - function traverseRegion(row, col) { - if (grid[row][col] !== target) return; - grid[row][col] = nextState; - const position = cols * row + col; - for (let i = 0; i < 4; i++) { - const [deltaRow, deltaCol, threatOffset, wallOffset] = directions[i]; - const newRow = row + deltaRow; - const newCol = col + deltaCol; - if (newRow < 0 || newRow === rows || newCol < 0 || newCol === cols) continue; - traverseRegion(newRow, newCol); - if (grid[newRow][newCol] - || (deltaRow ? verticalBarriers : horizontalBarriers).has(position + wallOffset)) continue; - if (nextState) threatenedCells.add(position + threatOffset); - if (nextState > 1) (deltaRow ? nextVertical : nextHorizontal).add(position + wallOffset); - } - } -}; diff --git a/solutions/0752-open-the-lock.js b/solutions/0752-open-the-lock.js deleted file mode 100644 index 873036ab..00000000 --- a/solutions/0752-open-the-lock.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 752. Open the Lock - * https://leetcode.com/problems/open-the-lock/ - * Difficulty: Medium - * - * You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', - * '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example - * we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. - * - * The lock initially starts at '0000', a string representing the state of the 4 wheels. - * - * You are given a list of deadends dead ends, meaning if the lock displays any of these codes, - * the wheels of the lock will stop turning and you will be unable to open it. - * - * Given a target representing the value of the wheels that will unlock the lock, return the - * minimum total number of turns required to open the lock, or -1 if it is impossible. - */ - -/** - * @param {string[]} deadends - * @param {string} target - * @return {number} - */ -var openLock = function(deadends, target) { - const dead = new Set(deadends); - const queue = [['0000', 0]]; - const seen = new Set(['0000']); - - if (dead.has('0000')) return -1; - while (queue.length) { - const [combo, turns] = queue.shift(); - if (combo === target) return turns; - - for (let i = 0; i < 4; i++) { - const current = combo[i]; - const up = (parseInt(current) + 1) % 10; - const down = (parseInt(current) + 9) % 10; - - const nextUp = combo.slice(0, i) + up + combo.slice(i + 1); - if (!seen.has(nextUp) && !dead.has(nextUp)) { - queue.push([nextUp, turns + 1]); - seen.add(nextUp); - } - - const nextDown = combo.slice(0, i) + down + combo.slice(i + 1); - if (!seen.has(nextDown) && !dead.has(nextDown)) { - queue.push([nextDown, turns + 1]); - seen.add(nextDown); - } - } - } - - return -1; -}; diff --git a/solutions/0753-cracking-the-safe.js b/solutions/0753-cracking-the-safe.js deleted file mode 100644 index 52ff0014..00000000 --- a/solutions/0753-cracking-the-safe.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 753. Cracking the Safe - * https://leetcode.com/problems/cracking-the-safe/ - * Difficulty: Hard - * - * There is a safe protected by a password. The password is a sequence of n digits where each - * digit can be in the range [0, k - 1]. - * - * The safe has a peculiar way of checking the password. When you enter in a sequence, it checks - * the most recent n digits that were entered each time you type a digit. - * - * For example, the correct password is "345" and you enter in "012345": - * - After typing 0, the most recent 3 digits is "0", which is incorrect. - * - After typing 1, the most recent 3 digits is "01", which is incorrect. - * - After typing 2, the most recent 3 digits is "012", which is incorrect. - * - After typing 3, the most recent 3 digits is "123", which is incorrect. - * - After typing 4, the most recent 3 digits is "234", which is incorrect. - * - After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks. - * - * Return any string of minimum length that will unlock the safe at some point of entering it. - */ - -/** - * @param {number} n - * @param {number} k - * @return {string} - */ -var crackSafe = function(n, k) { - if (n === 1) return Array.from({ length: k }, (_, i) => i).join(''); - const seen = new Set(); - const targetSize = k ** n; - let sequence = '0'.repeat(n); - - seen.add(sequence); - build(sequence); - return sequence; - - function build(curr) { - if (seen.size === targetSize) return true; - - const prefix = curr.slice(-n + 1); - for (let digit = 0; digit < k; digit++) { - const next = prefix + digit; - if (!seen.has(next)) { - seen.add(next); - sequence += digit; - if (build(sequence)) return true; - sequence = sequence.slice(0, -1); - seen.delete(next); - } - } - return false; - } -}; diff --git a/solutions/0754-reach-a-number.js b/solutions/0754-reach-a-number.js deleted file mode 100644 index 4150f53f..00000000 --- a/solutions/0754-reach-a-number.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 754. Reach a Number - * https://leetcode.com/problems/reach-a-number/ - * Difficulty: Medium - * - * You are standing at position 0 on an infinite number line. There is a destination at - * position target. - * - * You can make some number of moves numMoves so that: - * - On each move, you can either go left or right. - * - During the ith move (starting from i == 1 to i == numMoves), you take i steps in the - * chosen direction. - * - * Given the integer target, return the minimum number of moves required (i.e., the minimum - * numMoves) to reach the destination. - */ - -/** - * @param {number} target - * @return {number} - */ -var reachNumber = function(target) { - const absTarget = Math.abs(target); - let moves = Math.floor(Math.sqrt(2 * absTarget)); - - while (true) { - const sum = moves * (moves + 1) / 2; - if (sum >= absTarget && (sum - absTarget) % 2 === 0) return moves; - moves++; - } -}; diff --git a/solutions/0756-pyramid-transition-matrix.js b/solutions/0756-pyramid-transition-matrix.js deleted file mode 100644 index 65392426..00000000 --- a/solutions/0756-pyramid-transition-matrix.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 756. Pyramid Transition Matrix - * https://leetcode.com/problems/pyramid-transition-matrix/ - * Difficulty: Medium - * - * You are stacking blocks to form a pyramid. Each block has a color, which is represented by - * a single letter. Each row of blocks contains one less block than the row beneath it and is - * centered on top. - * - * To make the pyramid aesthetically pleasing, there are only specific triangular patterns that - * are allowed. A triangular pattern consists of a single block stacked on top of two blocks. - * The patterns are given as a list of three-letter strings allowed, where the first two characters - * of a pattern represent the left and right bottom blocks respectively, and the third character - * is the top block. - * - * For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' - * (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left - * bottom and 'A' is on the right bottom. - * - * You start with a bottom row of blocks bottom, given as a single string, that you must use as - * the base of the pyramid. - * - * Given bottom and allowed, return true if you can build the pyramid all the way to the top such - * that every triangular pattern in the pyramid is in allowed, or false otherwise. - */ - -/** - * @param {string} bottom - * @param {string[]} allowed - * @return {boolean} - */ -var pyramidTransition = function(bottom, allowed) { - const transitions = new Map(); - for (const [left, right, top] of allowed) { - const key = left + right; - transitions.set(key, (transitions.get(key) || '') + top); - } - - function canBuild(row, nextRow = '') { - if (row.length === 1) return true; - if (nextRow.length === row.length - 1) return canBuild(nextRow); - - const pair = row.slice(nextRow.length, nextRow.length + 2); - const options = transitions.get(pair) || ''; - - for (const top of options) { - if (canBuild(row, nextRow + top)) return true; - } - return false; - } - - return canBuild(bottom); -}; diff --git a/solutions/0757-set-intersection-size-at-least-two.js b/solutions/0757-set-intersection-size-at-least-two.js deleted file mode 100644 index 7ee9b0b2..00000000 --- a/solutions/0757-set-intersection-size-at-least-two.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 757. Set Intersection Size At Least Two - * https://leetcode.com/problems/set-intersection-size-at-least-two/ - * Difficulty: Hard - * - * You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents - * all the integers from starti to endi inclusively. - * - * A containing set is an array nums where each interval from intervals has at least two - * integers in nums. - * - * For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] - * are containing sets. - * - * Return the minimum possible size of a containing set. - */ - -/** - * @param {number[][]} intervals - * @return {number} - */ -var intersectionSizeTwo = function(intervals) { - intervals.sort((a, b) => a[1] - b[1] || b[0] - a[0]); - let size = 0; - let smallest = -1; - let secondSmallest = -1; - - for (const [start, end] of intervals) { - const hasTwo = start <= smallest; - const hasOne = start <= secondSmallest; - - if (hasTwo) continue; - if (hasOne) { - smallest = secondSmallest; - secondSmallest = end; - size++; - } else { - smallest = end - 1; - secondSmallest = end; - size += 2; - } - } - - return size; -}; diff --git a/solutions/0761-special-binary-string.js b/solutions/0761-special-binary-string.js deleted file mode 100644 index 63fa5c32..00000000 --- a/solutions/0761-special-binary-string.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 761. Special Binary String - * https://leetcode.com/problems/special-binary-string/ - * Difficulty: Hard - * - * Special binary strings are binary strings with the following two properties: - * - The number of 0's is equal to the number of 1's. - * - Every prefix of the binary string has at least as many 1's as 0's. - * - * You are given a special binary string s. - * - * A move consists of choosing two consecutive, non-empty, special substrings of s, - * and swapping them. Two strings are consecutive if the last character of the first - * string is exactly one index before the first character of the second string. - * - * Return the lexicographically largest resulting string possible after applying - * the mentioned operations on the string. - */ - -/** - * @param {string} s - * @return {string} - */ -function makeLargestSpecial(s) { - if (s.length <= 2) return s; - - let count = 0; - let start = 0; - const specials = []; - - for (let i = 0; i < s.length; i++) { - count += s[i] === '1' ? 1 : -1; - - if (count === 0) { - specials.push('1' + makeLargestSpecial(s.slice(start + 1, i)) + '0'); - start = i + 1; - } - } - - return specials.sort().reverse().join(''); -} diff --git a/solutions/0764-largest-plus-sign.js b/solutions/0764-largest-plus-sign.js deleted file mode 100644 index 512bfddf..00000000 --- a/solutions/0764-largest-plus-sign.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 764. Largest Plus Sign - * https://leetcode.com/problems/largest-plus-sign/ - * Difficulty: Medium - * - * You are given an integer n. You have an n x n binary grid grid with all values initially - * 1's except for some indices given in the array mines. The ith element of the array mines - * is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. - * - * Return the order of the largest axis-aligned plus sign of 1's contained in grid. If - * there is none, return 0. - * - * An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four - * arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could - * be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is - * checked for 1's. - */ - -/** - * @param {number} n - * @param {number[][]} mines - * @return {number} - */ -function orderOfLargestPlusSign(n, mines) { - const grid = Array(n).fill().map(() => Array(n).fill(1)); - mines.forEach(([x, y]) => grid[x][y] = 0); - - const left = Array(n).fill().map(() => Array(n).fill(0)); - const right = Array(n).fill().map(() => Array(n).fill(0)); - const up = Array(n).fill().map(() => Array(n).fill(0)); - const down = Array(n).fill().map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - left[i][j] = grid[i][j] ? (j > 0 ? left[i][j-1] + 1 : 1) : 0; - up[i][j] = grid[i][j] ? (i > 0 ? up[i-1][j] + 1 : 1) : 0; - } - } - - for (let i = n - 1; i >= 0; i--) { - for (let j = n - 1; j >= 0; j--) { - right[i][j] = grid[i][j] ? (j < n-1 ? right[i][j+1] + 1 : 1) : 0; - down[i][j] = grid[i][j] ? (i < n-1 ? down[i+1][j] + 1 : 1) : 0; - } - } - - let maxOrder = 0; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - maxOrder = Math.max( - maxOrder, - Math.min(left[i][j], right[i][j], up[i][j], down[i][j]) - ); - } - } - - return maxOrder; -} diff --git a/solutions/0765-couples-holding-hands.js b/solutions/0765-couples-holding-hands.js deleted file mode 100644 index e464cc7f..00000000 --- a/solutions/0765-couples-holding-hands.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 765. Couples Holding Hands - * https://leetcode.com/problems/couples-holding-hands/ - * Difficulty: Hard - * - * There are n couples sitting in 2n seats arranged in a row and want to hold hands. - * - * The people and seats are represented by an integer array row where row[i] is the ID of the - * person sitting in the ith seat. The couples are numbered in order, the first couple being - * (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). - * - * Return the minimum number of swaps so that every couple is sitting side by side. A swap - * consists of choosing any two people, then they stand up and switch seats. - */ - -/** - * @param {number[]} row - * @return {number} - */ -function minSwapsCouples(row) { - const n = row.length / 2; - const partner = new Array(2 * n); - const position = new Array(2 * n); - - for (let i = 0; i < 2 * n; i++) { - partner[i] = i % 2 === 0 ? i + 1 : i - 1; - position[row[i]] = i; - } - - let swaps = 0; - for (let i = 0; i < 2 * n; i += 2) { - const current = row[i]; - const expected = partner[current]; - const nextPerson = row[i + 1]; - - if (nextPerson !== expected) { - row[i + 1] = expected; - row[position[expected]] = nextPerson; - position[nextPerson] = position[expected]; - position[expected] = i + 1; - swaps++; - } - } - - return swaps; -} diff --git a/solutions/0766-toeplitz-matrix.js b/solutions/0766-toeplitz-matrix.js deleted file mode 100644 index 3dabc686..00000000 --- a/solutions/0766-toeplitz-matrix.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 766. Toeplitz Matrix - * https://leetcode.com/problems/toeplitz-matrix/ - * Difficulty: Easy - * - * Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. - * - * A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. - */ - -/** - * @param {number[][]} matrix - * @return {boolean} - */ -function isToeplitzMatrix(matrix) { - const rows = matrix.length; - const cols = matrix[0].length; - - for (let r = 0; r < rows - 1; r++) { - for (let c = 0; c < cols - 1; c++) { - if (matrix[r][c] !== matrix[r + 1][c + 1]) { - return false; - } - } - } - - return true; -} diff --git a/solutions/0767-reorganize-string.js b/solutions/0767-reorganize-string.js deleted file mode 100644 index b76729a6..00000000 --- a/solutions/0767-reorganize-string.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 767. Reorganize String - * https://leetcode.com/problems/reorganize-string/ - * Difficulty: Medium - * - * Given a string s, rearrange the characters of s so that any two adjacent characters are - * not the same. - * - * Return any possible rearrangement of s or return "" if not possible. - */ - -/** - * @param {string} s - * @return {string} - */ -var reorganizeString = function(s) { - const charCount = new Map(); - for (const char of s) { - charCount.set(char, (charCount.get(char) || 0) + 1); - } - - const maxHeap = [...charCount.entries()] - .sort((a, b) => b[1] - a[1]); - - if (maxHeap[0][1] > Math.ceil(s.length / 2)) { - return ''; - } - - const result = []; - let index = 0; - - while (maxHeap.length) { - const [char, count] = maxHeap.shift(); - for (let i = 0; i < count; i++) { - result[index] = char; - index += 2; - if (index >= s.length) index = 1; - } - } - - return result.join(''); -}; diff --git a/solutions/0768-max-chunks-to-make-sorted-ii.js b/solutions/0768-max-chunks-to-make-sorted-ii.js deleted file mode 100644 index ec519b62..00000000 --- a/solutions/0768-max-chunks-to-make-sorted-ii.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 768. Max Chunks To Make Sorted II - * https://leetcode.com/problems/max-chunks-to-make-sorted-ii/ - * Difficulty: Hard - * - * You are given an integer array arr. - * - * We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. - * After concatenating them, the result should equal the sorted array. - * - * Return the largest number of chunks we can make to sort the array. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var maxChunksToSorted = function(arr) { - const stack = []; - - for (const num of arr) { - if (stack.length === 0 || stack[stack.length - 1] <= num) { - stack.push(num); - } else { - const max = stack.pop(); - while (stack.length && stack[stack.length - 1] > num) { - stack.pop(); - } - stack.push(max); - } - } - - return stack.length; -}; diff --git a/solutions/0769-max-chunks-to-make-sorted.js b/solutions/0769-max-chunks-to-make-sorted.js deleted file mode 100644 index e0869491..00000000 --- a/solutions/0769-max-chunks-to-make-sorted.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 769. Max Chunks To Make Sorted - * https://leetcode.com/problems/max-chunks-to-make-sorted/ - * Difficulty: Medium - * - * You are given an integer array arr of length n that represents a permutation of the integers - * in the range [0, n - 1]. - * - * We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. - * After concatenating them, the result should equal the sorted array. - * - * Return the largest number of chunks we can make to sort the array. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var maxChunksToSorted = function(arr) { - let result = 0; - - for (let i = 0, max = 0; i < arr.length; i++) { - max = Math.max(max, arr[i]); - if (max === i) { - result++; - } - } - - return result; -}; diff --git a/solutions/0770-basic-calculator-iv.js b/solutions/0770-basic-calculator-iv.js deleted file mode 100644 index 4f588a25..00000000 --- a/solutions/0770-basic-calculator-iv.js +++ /dev/null @@ -1,230 +0,0 @@ -/** - * 770. Basic Calculator IV - * https://leetcode.com/problems/basic-calculator-iv/ - * Difficulty: Hard - * - * Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} - * (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing - * the simplified expression, such as ["-1*a","14"] - * - An expression alternates chunks and symbols, with a space separating each chunk and symbol. - * - A chunk is either an expression in parentheses, a variable, or a non-negative integer. - * - A variable is a string of lowercase letters (not including digits.) Note that variables can - * be multiple letters, and note that variables never have a leading coefficient or unary operator - * like "2x" or "-x". - * - * Expressions are evaluated in the usual order: brackets first, then multiplication, then addition - * and subtraction. - * - * - For example, expression = "1 + 2 * 3" has an answer of ["7"]. - * - * The format of the output is as follows: - * - For each term of free variables with a non-zero coefficient, we write the free variables within - * a term in sorted order lexicographically. - * - For example, we would never write a term like "b*a*c", only "a*b*c". - * - Terms have degrees equal to the number of free variables being multiplied, counting - * multiplicity. We write the largest degree terms of our answer first, breaking ties by - * lexicographic order ignoring the leading coefficient of the term. - * - For example, "a*a*b*c" has degree 4. - * - The leading coefficient of the term is placed directly to the left with an asterisk separating - * it from the variables (if they exist.) A leading coefficient of 1 is still printed. - * - An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]. - * - Terms (including constant terms) with coefficient 0 are not included. - * - For example, an expression of "0" has an output of []. - * - * Note: You may assume that the given expression is always valid. All intermediate results will be - * in the range of [-231, 231 - 1]. - */ - -/** - * @param {string} expression - * @param {string[]} evalvars - * @param {number[]} evalints - * @return {string[]} - */ -var basicCalculatorIV = function(expression, evalvars, evalints) { - const map = new Map(); - for (let i = 0; i < evalvars.length; i++) { - map.set(evalvars[i], evalints[i]); - } - - const result = parse(expression, map); - return result.toStringArray(); - - function parse(expr, map) { - const tokens = tokenize(expr); - return parseExpr(tokens, 0, map)[0]; - } - - function tokenize(expr) { - const tokens = []; - let i = 0; - - while (i < expr.length) { - if (expr[i] === ' ') { - i++; continue; - } - - if ('+-*()'.includes(expr[i])) { - tokens.push(expr[i++]); - continue; - } - - if (/[a-z]/.test(expr[i])) { - let variable = ''; - while (i < expr.length && /[a-z]/.test(expr[i])) { - variable += expr[i++]; - } - tokens.push(variable); - continue; - } - - if (/\d/.test(expr[i])) { - let num = ''; - while (i < expr.length && /\d/.test(expr[i])) { - num += expr[i++]; - } - tokens.push(parseInt(num)); - continue; - } - - i++; - } - - return tokens; - } - - function parseExpr(tokens, start, map) { - let [left, pos] = parseTerm(tokens, start, map); - - while (pos < tokens.length && (tokens[pos] === '+' || tokens[pos] === '-')) { - const op = tokens[pos]; - const [right, nextPos] = parseTerm(tokens, pos + 1, map); - - left = op === '+' ? left.add(right) : left.subtract(right); - pos = nextPos; - } - - return [left, pos]; - } - - function parseTerm(tokens, start, map) { - let [left, pos] = parseFactor(tokens, start, map); - - while (pos < tokens.length && tokens[pos] === '*') { - const [right, nextPos] = parseFactor(tokens, pos + 1, map); - left = left.multiply(right); - pos = nextPos; - } - - return [left, pos]; - } - - function parseFactor(tokens, start, map) { - const token = tokens[start]; - - if (token === '(') { - const [expr, pos] = parseExpr(tokens, start + 1, map); - return [expr, pos + 1]; - } - - if (typeof token === 'string' && /[a-z]/.test(token)) { - return map.has(token) - ? [new Expression([new Term(map.get(token))]), start + 1] - : [new Expression([new Term(1, [token])]), start + 1]; - } - - if (typeof token === 'number') { - return [new Expression([new Term(token)]), start + 1]; - } - - throw new Error(`Unexpected token: ${token}`); - } -}; - -class Term { - constructor(coefficient = 0, variables = []) { - this.coefficient = coefficient; - this.variables = [...variables].sort(); - } - - multiply(other) { - return new Term( - this.coefficient * other.coefficient, - [...this.variables, ...other.variables].sort() - ); - } - - toString() { - if (this.coefficient === 0) return ''; - if (this.variables.length === 0) return `${this.coefficient}`; - return `${this.coefficient}*${this.variables.join('*')}`; - } - - get degree() { - return this.variables.length; - } - - compare(other) { - if (this.degree !== other.degree) return other.degree - this.degree; - - for (let i = 0; i < this.degree; i++) { - if (this.variables[i] !== other.variables[i]) { - return this.variables[i].localeCompare(other.variables[i]); - } - } - return 0; - } -} - -class Expression { - constructor(terms = []) { - this.terms = terms; - } - - add(other, multiplier = 1) { - const termMap = new Map(); - - for (const term of this.terms) { - const key = term.variables.join('*'); - termMap.set(key, term); - } - - for (const term of other.terms) { - const key = term.variables.join('*'); - if (termMap.has(key)) { - termMap.get(key).coefficient += term.coefficient * multiplier; - } else { - const newTerm = new Term(term.coefficient * multiplier, term.variables); - this.terms.push(newTerm); - termMap.set(key, newTerm); - } - } - - this.terms = this.terms.filter(term => term.coefficient !== 0); - return this; - } - - subtract(other) { - return this.add(other, -1); - } - - multiply(other) { - const result = new Expression(); - - for (const term1 of this.terms) { - for (const term2 of other.terms) { - const product = term1.multiply(term2); - if (product.coefficient !== 0) { - result.add(new Expression([product])); - } - } - } - - return result; - } - - toStringArray() { - this.terms.sort((a, b) => a.compare(b)); - return this.terms.map(term => term.toString()).filter(Boolean); - } -} diff --git a/solutions/0771-jewels-and-stones.js b/solutions/0771-jewels-and-stones.js deleted file mode 100644 index db728558..00000000 --- a/solutions/0771-jewels-and-stones.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 771. Jewels and Stones - * https://leetcode.com/problems/jewels-and-stones/ - * Difficulty: Easy - * - * You're given strings jewels representing the types of stones that are jewels, and stones - * representing the stones you have. Each character in stones is a type of stone you have. - * You want to know how many of the stones you have are also jewels. - * - * Letters are case sensitive, so "a" is considered a different type of stone from "A". - */ - -/** - * @param {string} jewels - * @param {string} stones - * @return {number} - */ -var numJewelsInStones = function(jewels, stones) { - const set = new Set(jewels); - let result = 0; - - for (const stone of stones) { - if (set.has(stone)) { - result++; - } - } - - return result; -}; diff --git a/solutions/0773-sliding-puzzle.js b/solutions/0773-sliding-puzzle.js deleted file mode 100644 index c8345ead..00000000 --- a/solutions/0773-sliding-puzzle.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 773. Sliding Puzzle - * https://leetcode.com/problems/sliding-puzzle/ - * Difficulty: Hard - * - * On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by - * 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. - * - * The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. - * - * Given the puzzle board board, return the least number of moves required so that the state of the - * board is solved. If it is impossible for the state of the board to be solved, return -1. - */ - -/** - * @param {number[][]} board - * @return {number} - */ -var slidingPuzzle = function(board) { - const target = '123450'; - const moves = [ - [1, 3], [0, 2, 4], [1, 5], - [0, 4], [1, 3, 5], [2, 4] - ]; - - const start = board.flat().join(''); - if (start === target) return 0; - - const queue = [[start, 0]]; - const seen = new Set([start]); - - while (queue.length) { - const [state, steps] = queue.shift(); - const index = state.indexOf('0'); - - for (const next of moves[index]) { - const chars = state.split(''); - [chars[index], chars[next]] = [chars[next], chars[index]]; - const nextState = chars.join(''); - - if (nextState === target) return steps + 1; - - if (!seen.has(nextState)) { - seen.add(nextState); - queue.push([nextState, steps + 1]); - } - } - } - - return -1; -}; diff --git a/solutions/0775-global-and-local-inversions.js b/solutions/0775-global-and-local-inversions.js deleted file mode 100644 index 63b42d04..00000000 --- a/solutions/0775-global-and-local-inversions.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 775. Global and Local Inversions - * https://leetcode.com/problems/global-and-local-inversions/ - * Difficulty: Medium - * - * You are given an integer array nums of length n which represents a permutation of all the - * integers in the range [0, n - 1]. - * - * The number of global inversions is the number of the different pairs (i, j) where: - * - 0 <= i < j < n - * - nums[i] > nums[j] - * - * The number of local inversions is the number of indices i where: - * - 0 <= i < n - 1 - * - nums[i] > nums[i + 1] - * - * Return true if the number of global inversions is equal to the number of local inversions. - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var isIdealPermutation = function(nums) { - for (let i = 0; i < nums.length; i++) { - if (Math.abs(nums[i] - i) > 1) { - return false; - } - } - return true; -}; diff --git a/solutions/0777-swap-adjacent-in-lr-string.js b/solutions/0777-swap-adjacent-in-lr-string.js deleted file mode 100644 index bdf0cb3c..00000000 --- a/solutions/0777-swap-adjacent-in-lr-string.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 777. Swap Adjacent in LR String - * https://leetcode.com/problems/swap-adjacent-in-lr-string/ - * Difficulty: Medium - * - * In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either - * replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given - * the starting string start and the ending string result, return True if and only if there exists - * a sequence of moves to transform start to result. - */ - -/** - * @param {string} start - * @param {string} result - * @return {boolean} - */ -var canTransform = function(start, result) { - if (start.replace(/X/g, '') !== result.replace(/X/g, '')) { - return false; - } - - let i = 0; - let j = 0; - const n = start.length; - - while (i < n && j < n) { - while (i < n && start[i] === 'X') i++; - while (j < n && result[j] === 'X') j++; - - if (i === n && j === n) return true; - if (i === n || j === n) return false; - - if (start[i] !== result[j]) return false; - - if (start[i] === 'L' && i < j) return false; - if (start[i] === 'R' && i > j) return false; - - i++; - j++; - } - - return true; -}; diff --git a/solutions/0778-swim-in-rising-water.js b/solutions/0778-swim-in-rising-water.js deleted file mode 100644 index 19e6ff0c..00000000 --- a/solutions/0778-swim-in-rising-water.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 778. Swim in Rising Water - * https://leetcode.com/problems/swim-in-rising-water/ - * Difficulty: Hard - * - * You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation - * at that point (i, j). - * - * The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from - * a square to another 4-directionally adjacent square if and only if the elevation of both squares - * individually are at most t. You can swim infinite distances in zero time. Of course, you must - * stay within the boundaries of the grid during your swim. - * - * Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start - * at the top left square (0, 0). - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var swimInWater = function(grid) { - const n = grid.length; - let left = grid[0][0]; - let right = n * n - 1; - - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - - const canReachDestination = (time) => { - if (grid[0][0] > time) return false; - - const visited = Array(n).fill().map(() => Array(n).fill(false)); - const queue = [[0, 0]]; - visited[0][0] = true; - - while (queue.length > 0) { - const [row, col] = queue.shift(); - - if (row === n - 1 && col === n - 1) { - return true; - } - - for (const [dr, dc] of directions) { - const newRow = row + dr; - const newCol = col + dc; - - if ( - newRow >= 0 && newRow < n && newCol >= 0 && newCol < n - && !visited[newRow][newCol] && grid[newRow][newCol] <= time - ) { - queue.push([newRow, newCol]); - visited[newRow][newCol] = true; - } - } - } - - return false; - }; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - - if (canReachDestination(mid)) { - right = mid; - } else { - left = mid + 1; - } - } - - return left; -}; diff --git a/solutions/0779-k-th-symbol-in-grammar.js b/solutions/0779-k-th-symbol-in-grammar.js deleted file mode 100644 index 760ae8cc..00000000 --- a/solutions/0779-k-th-symbol-in-grammar.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 779. K-th Symbol in Grammar - * https://leetcode.com/problems/k-th-symbol-in-grammar/ - * Difficulty: Medium - * - * We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every - * subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and - * each occurrence of 1 with 10. - * - * - For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110. - * - * Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var kthGrammar = function(n, k) { - if (n === 1) return 0; - - const length = 1 << (n - 1); - const mid = length / 2; - - if (k <= mid) { - return kthGrammar(n - 1, k); - } else { - return 1 - kthGrammar(n - 1, k - mid); - } -}; diff --git a/solutions/0780-reaching-points.js b/solutions/0780-reaching-points.js deleted file mode 100644 index 9d61c1c1..00000000 --- a/solutions/0780-reaching-points.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 780. Reaching Points - * https://leetcode.com/problems/reaching-points/ - * Difficulty: Hard - * - * Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point - * (sx, sy) to the point (tx, ty) through some operations, or false otherwise. - * - * The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y). - */ - -/** - * @param {number} sx - * @param {number} sy - * @param {number} tx - * @param {number} ty - * @return {boolean} - */ -var reachingPoints = function(sx, sy, tx, ty) { - while (tx >= sx && ty >= sy) { - if (tx === sx && ty === sy) { - return true; - } - - if (tx > ty) { - // If we can directly reach sx by making proper subtractions - if (ty === sy) { - return (tx - sx) % ty === 0; - } - tx %= ty; - } else { - // If we can directly reach sy by making proper subtractions - if (tx === sx) { - return (ty - sy) % tx === 0; - } - ty %= tx; - } - } - - return false; -}; diff --git a/solutions/0781-rabbits-in-forest.js b/solutions/0781-rabbits-in-forest.js deleted file mode 100644 index fab28fde..00000000 --- a/solutions/0781-rabbits-in-forest.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 781. Rabbits in Forest - * https://leetcode.com/problems/rabbits-in-forest/ - * Difficulty: Medium - * - * There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have - * the same color as you?" and collected the answers in an integer array answers where answers[i] - * is the answer of the ith rabbit. - * - * Given the array answers, return the minimum number of rabbits that could be in the forest. - */ - -/** - * @param {number[]} answers - * @return {number} - */ -var numRabbits = function(answers) { - const colorGroups = {}; - let totalRabbits = 0; - - for (const answer of answers) { - if (answer === 0) { - totalRabbits++; - continue; - } - - if (!colorGroups[answer] || colorGroups[answer] === 0) { - totalRabbits += answer + 1; - colorGroups[answer] = answer; - } else { - colorGroups[answer]--; - } - } - - return totalRabbits; -}; diff --git a/solutions/0782-transform-to-chessboard.js b/solutions/0782-transform-to-chessboard.js deleted file mode 100644 index 1cfd8128..00000000 --- a/solutions/0782-transform-to-chessboard.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 782. Transform to Chessboard - * https://leetcode.com/problems/transform-to-chessboard/ - * Difficulty: Hard - * - * You are given an n x n binary grid board. In each move, you can swap any two rows with each - * other, or any two columns with each other. - * - * Return the minimum number of moves to transform the board into a chessboard board. If the - * task is impossible, return -1. - * - * A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent. - */ - -/** - * @param {number[][]} board - * @return {number} - */ -var movesToChessboard = function(board) { - const n = board.length; - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if ((board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) === 1) { - return -1; - } - } - } - - let rowSum = 0; - let colSum = 0; - let rowSwaps = 0; - let colSwaps = 0; - - for (let i = 0; i < n; i++) { - rowSum += board[0][i]; - colSum += board[i][0]; - - if (board[i][0] === i % 2) rowSwaps++; - if (board[0][i] === i % 2) colSwaps++; - } - - if (rowSum !== Math.floor(n / 2) && rowSum !== Math.ceil(n / 2)) return -1; - if (colSum !== Math.floor(n / 2) && colSum !== Math.ceil(n / 2)) return -1; - - if (n % 2 === 1) { - if (rowSwaps % 2 === 1) rowSwaps = n - rowSwaps; - if (colSwaps % 2 === 1) colSwaps = n - colSwaps; - } else { - rowSwaps = Math.min(rowSwaps, n - rowSwaps); - colSwaps = Math.min(colSwaps, n - colSwaps); - } - - return Math.floor((rowSwaps + colSwaps) / 2); -}; diff --git a/solutions/0785-is-graph-bipartite.js b/solutions/0785-is-graph-bipartite.js deleted file mode 100644 index 6f59c59c..00000000 --- a/solutions/0785-is-graph-bipartite.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 785. Is Graph Bipartite? - * https://leetcode.com/problems/is-graph-bipartite/ - * Difficulty: Medium - * - * There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. - * You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent - * to. More formally, for each v in graph[u], there is an undirected edge between node u and - * node v. The graph has the following properties: - * - There are no self-edges (graph[u] does not contain u). - * - There are no parallel edges (graph[u] does not contain duplicate values). - * - If v is in graph[u], then u is in graph[v] (the graph is undirected). - * - The graph may not be connected, meaning there may be two nodes u and v such that there is - * no path between them. - * - * A graph is bipartite if the nodes can be partitioned into two independent sets A and B such - * that every edge in the graph connects a node in set A and a node in set B. - * - * Return true if and only if it is bipartite. - */ - -/** - * @param {number[][]} graph - * @return {boolean} - */ -var isBipartite = function(graph) { - const n = graph.length; - const colors = new Array(n).fill(-1); - - for (let i = 0; i < n; i++) { - if (colors[i] === -1 && !colorGraph(i, 0, graph, colors)) { - return false; - } - } - - return true; -}; - -function colorGraph(start, color, graph, colors) { - const queue = [start]; - colors[start] = color; - - while (queue.length > 0) { - const node = queue.shift(); - const nextColor = 1 - colors[node]; - - for (const neighbor of graph[node]) { - if (colors[neighbor] === -1) { - colors[neighbor] = nextColor; - queue.push(neighbor); - } else if (colors[neighbor] !== nextColor) { - return false; - } - } - } - - return true; -} diff --git a/solutions/0786-k-th-smallest-prime-fraction.js b/solutions/0786-k-th-smallest-prime-fraction.js deleted file mode 100644 index 77715507..00000000 --- a/solutions/0786-k-th-smallest-prime-fraction.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 786. K-th Smallest Prime Fraction - * https://leetcode.com/problems/k-th-smallest-prime-fraction/ - * Difficulty: Medium - * - * You are given a sorted integer array arr containing 1 and prime numbers, where all the integers - * of arr are unique. You are also given an integer k. - * - * For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]. - * - * Return the kth smallest fraction considered. Return your answer as an array of integers of size - * 2, where answer[0] == arr[i] and answer[1] == arr[j]. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {number[]} - */ -var kthSmallestPrimeFraction = function(arr, k) { - const n = arr.length; - let left = 0; - let right = 1; - - while (left < right) { - const mid = (left + right) / 2; - let count = 0; - let maxFraction = [0, 1]; - let j = 1; - - for (let i = 0; i < n - 1; i++) { - while (j < n && arr[i] > mid * arr[j]) { - j++; - } - - count += n - j; - - if (j < n && arr[i] * maxFraction[1] > maxFraction[0] * arr[j]) { - maxFraction = [arr[i], arr[j]]; - } - } - - if (count === k) { - return maxFraction; - } else if (count < k) { - left = mid; - } else { - right = mid; - } - } - - return []; -}; diff --git a/solutions/0787-cheapest-flights-within-k-stops.js b/solutions/0787-cheapest-flights-within-k-stops.js deleted file mode 100644 index 178daa0b..00000000 --- a/solutions/0787-cheapest-flights-within-k-stops.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 787. Cheapest Flights Within K Stops - * https://leetcode.com/problems/cheapest-flights-within-k-stops/ - * Difficulty: Medium - * - * There are n cities connected by some number of flights. You are given an array flights where - * flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city - * toi with cost pricei. - * - * You are also given three integers src, dst, and k, return the cheapest price from src to dst - * with at most k stops. If there is no such route, return -1. - */ - -/** - * @param {number} n - * @param {number[][]} flights - * @param {number} src - * @param {number} dst - * @param {number} k - * @return {number} - */ -var findCheapestPrice = function(n, flights, src, dst, k) { - const MAX_INT = Number.MAX_SAFE_INTEGER; - let prices = new Array(n).fill(MAX_INT); - prices[src] = 0; - - for (let i = 0; i <= k; i++) { - const tempPrices = [...prices]; - - for (const [from, to, price] of flights) { - if (prices[from] === MAX_INT) continue; - - const newPrice = prices[from] + price; - if (newPrice < tempPrices[to]) { - tempPrices[to] = newPrice; - } - } - - prices = tempPrices; - } - - return prices[dst] === MAX_INT ? -1 : prices[dst]; -}; diff --git a/solutions/0788-rotated-digits.js b/solutions/0788-rotated-digits.js deleted file mode 100644 index 433d43ff..00000000 --- a/solutions/0788-rotated-digits.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 788. Rotated Digits - * https://leetcode.com/problems/rotated-digits/ - * Difficulty: Medium - * - * An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid - * number that is different from x. Each digit must be rotated - we cannot choose to leave it alone. - * - * A number is valid if each digit remains a digit after rotation. For example: - * - 0, 1, and 8 rotate to themselves, - * - 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other - * words, 2 or 5 gets mirrored), - * - 6 and 9 rotate to each other, and - * - the rest of the numbers do not rotate to any other number and become invalid. - * - * Given an integer n, return the number of good integers in the range [1, n]. - */ - -/** - * @param {number} n - * @return {number} - */ -var rotatedDigits = function(n) { - let result = 0; - - for (let i = 1; i <= n; i++) { - if (verify(i)) { - result++; - } - } - - return result; - - function verify(num) { - const digits = num.toString().split(''); - let result = false; - - for (const digit of digits) { - if (digit === '3' || digit === '4' || digit === '7') { - return false; - } - - if (digit === '2' || digit === '5' || digit === '6' || digit === '9') { - result = true; - } - } - - return result; - } -}; diff --git a/solutions/0789-escape-the-ghosts.js b/solutions/0789-escape-the-ghosts.js deleted file mode 100644 index 26046d94..00000000 --- a/solutions/0789-escape-the-ghosts.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 789. Escape The Ghosts - * https://leetcode.com/problems/escape-the-ghosts/ - * Difficulty: Medium - * - * You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point - * [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying - * to get to. There are several ghosts on the map with their starting positions given as a 2D - * array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. - * All inputs are integral coordinates. - * - * Each turn, you and all the ghosts may independently choose to either move 1 unit in any of - * the four cardinal directions: north, east, south, or west, or stay still. All actions happen - * simultaneously. - * - * You escape if and only if you can reach the target before any ghost reaches you. If you reach - * any square (including the target) at the same time as a ghost, it does not count as an escape. - * - * Return true if it is possible to escape regardless of how the ghosts move, otherwise return - * false. - */ - -/** - * @param {number[][]} ghosts - * @param {number[]} target - * @return {boolean} - */ -var escapeGhosts = function(ghosts, target) { - const distanceToTarget = calcDistance([0, 0], target); - - for (const ghost of ghosts) { - const ghostDistance = calcDistance(ghost, target); - if (ghostDistance <= distanceToTarget) { - return false; - } - } - - return true; -}; - -function calcDistance(point1, point2) { - return Math.abs(point1[0] - point2[0]) + Math.abs(point1[1] - point2[1]); -} diff --git a/solutions/0792-number-of-matching-subsequences.js b/solutions/0792-number-of-matching-subsequences.js deleted file mode 100644 index 8723a6be..00000000 --- a/solutions/0792-number-of-matching-subsequences.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 792. Number of Matching Subsequences - * https://leetcode.com/problems/number-of-matching-subsequences/ - * Difficulty: Medium - * - * Given a string s and an array of strings words, return the number of words[i] that is a - * subsequence of s. - * - * A subsequence of a string is a new string generated from the original string with some - * characters (can be none) deleted without changing the relative order of the remaining - * characters. - * - * For example, "ace" is a subsequence of "abcde". - */ - -/** - * @param {string} s - * @param {string[]} words - * @return {number} - */ -var numMatchingSubseq = function(s, words) { - const charMap = new Map(); - - for (let i = 0; i < 26; i++) { - const char = String.fromCharCode(97 + i); - charMap.set(char, []); - } - - for (const word of words) { - const firstChar = word[0]; - const wordInfo = { word, index: 0 }; - charMap.get(firstChar).push(wordInfo); - } - - let count = 0; - - for (const char of s) { - const bucket = charMap.get(char); - charMap.set(char, []); - - for (const wordInfo of bucket) { - wordInfo.index++; - - if (wordInfo.index === wordInfo.word.length) { - count++; - } else { - const nextChar = wordInfo.word[wordInfo.index]; - charMap.get(nextChar).push(wordInfo); - } - } - } - - return count; -}; diff --git a/solutions/0793-preimage-size-of-factorial-zeroes-function.js b/solutions/0793-preimage-size-of-factorial-zeroes-function.js deleted file mode 100644 index 516f25c5..00000000 --- a/solutions/0793-preimage-size-of-factorial-zeroes-function.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * 793. Preimage Size of Factorial Zeroes Function - * https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/ - * Difficulty: Hard - * - * Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x - * and by convention, 0! = 1. - * - * For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because - * 11! = 39916800 has two zeroes at the end. - * - * Given an integer k, return the number of non-negative integers x have the property that f(x) = k. - */ - -/** - * @param {number} k - * @return {number} - */ -var preimageSizeFZF = function(k) { - return findUpperBound(k) - findLowerBound(k); -}; - -function findLowerBound(k) { - let left = 0; - let right = 5 * (10 ** 10); - - while (left < right) { - const mid = Math.floor((left + right) / 2); - const zeroes = countTrailingZeroes(mid); - - if (zeroes < k) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; -} - -function findUpperBound(k) { - let left = 0; - let right = 5 * (10 ** 10); - - while (left < right) { - const mid = Math.floor((left + right) / 2); - const zeroes = countTrailingZeroes(mid); - - if (zeroes <= k) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; -} - -function countTrailingZeroes(n) { - let count = 0; - let powerOfFive = 5; - - while (n >= powerOfFive) { - count += Math.floor(n / powerOfFive); - powerOfFive *= 5; - } - - return count; -} diff --git a/solutions/0794-valid-tic-tac-toe-state.js b/solutions/0794-valid-tic-tac-toe-state.js deleted file mode 100644 index ad3415be..00000000 --- a/solutions/0794-valid-tic-tac-toe-state.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 794. Valid Tic-Tac-Toe State - * https://leetcode.com/problems/valid-tic-tac-toe-state/ - * Difficulty: Medium - * - * Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible - * to reach this board position during the course of a valid tic-tac-toe game. - * - * The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character - * represents an empty square. - * - * Here are the rules of Tic-Tac-Toe: - * - Players take turns placing characters into empty squares ' '. - * - The first player always places 'X' characters, while the second player always places 'O' - * characters. - * - 'X' and 'O' characters are always placed into empty squares, never filled ones. - * - The game ends when there are three of the same (non-empty) character filling any row, - * column, or diagonal. - * - The game also ends if all squares are non-empty. - * - No more moves can be played if the game is over. - */ - -/** - * @param {string[]} board - * @return {boolean} - */ -var validTicTacToe = function(board) { - let xCount = 0; - let oCount = 0; - - for (const row of board) { - for (const cell of row) { - if (cell === 'X') xCount++; - if (cell === 'O') oCount++; - } - } - - if (xCount !== oCount && xCount !== oCount + 1) return false; - - const hasWon = player => { - for (let i = 0; i < 3; i++) { - if (board[i] === player.repeat(3)) return true; - if (board[0][i] === player && board[1][i] === player && board[2][i] === player) return true; - } - - return (board[0][0] === player && board[1][1] === player && board[2][2] === player) - || (board[0][2] === player && board[1][1] === player && board[2][0] === player); - }; - - const xWin = hasWon('X'); - const oWin = hasWon('O'); - - if (xWin && xCount !== oCount + 1) return false; - if (oWin && xCount !== oCount) return false; - if (xWin && oWin) return false; - - return true; -}; diff --git a/solutions/0795-number-of-subarrays-with-bounded-maximum.js b/solutions/0795-number-of-subarrays-with-bounded-maximum.js deleted file mode 100644 index f357ea31..00000000 --- a/solutions/0795-number-of-subarrays-with-bounded-maximum.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 795. Number of Subarrays with Bounded Maximum - * https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/ - * Difficulty: Medium - * - * Given an integer array nums and two integers left and right, return the number of contiguous - * non-empty subarrays such that the value of the maximum array element in that subarray is in - * the range [left, right]. - * - * The test cases are generated so that the answer will fit in a 32-bit integer. - */ - -/** - * @param {number[]} nums - * @param {number} left - * @param {number} right - * @return {number} - */ -var numSubarrayBoundedMax = function(nums, left, right) { - let result = 0; - let validCount = 0; - let prevInvalidGreater = -1; - - for (let i = 0; i < nums.length; i++) { - if (nums[i] > right) { - validCount = 0; - prevInvalidGreater = i; - } else if (nums[i] >= left) { - validCount = i - prevInvalidGreater; - } - - result += validCount; - } - - return result; -}; diff --git a/solutions/0797-all-paths-from-source-to-target.js b/solutions/0797-all-paths-from-source-to-target.js deleted file mode 100644 index ceef7471..00000000 --- a/solutions/0797-all-paths-from-source-to-target.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 797. All Paths From Source to Target - * https://leetcode.com/problems/all-paths-from-source-to-target/ - * Difficulty: Medium - * - * Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths - * from node 0 to node n - 1 and return them in any order. - * - * The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., - * there is a directed edge from node i to node graph[i][j]). - */ - -/** - * @param {number[][]} graph - * @return {number[][]} - */ -var allPathsSourceTarget = function(graph) { - const target = graph.length - 1; - const paths = []; - - const dfs = (node, path) => { - if (node === target) { - paths.push([...path]); - return; - } - - for (const neighbor of graph[node]) { - path.push(neighbor); - dfs(neighbor, path); - path.pop(); - } - }; - - dfs(0, [0]); - return paths; -}; diff --git a/solutions/0798-smallest-rotation-with-highest-score.js b/solutions/0798-smallest-rotation-with-highest-score.js deleted file mode 100644 index a1e013e9..00000000 --- a/solutions/0798-smallest-rotation-with-highest-score.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 798. Smallest Rotation with Highest Score - * https://leetcode.com/problems/smallest-rotation-with-highest-score/ - * Difficulty: Hard - * - * You are given an array nums. You can rotate it by a non-negative integer k so that the array - * becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. - * Afterward, any entries that are less than or equal to their index are worth one point. - * - * For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. - * This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], - * 2 <= 3 [one point], 4 <= 4 [one point]. - * - * Return the rotation index k that corresponds to the highest score we can achieve if we rotated - * nums by it. If there are multiple answers, return the smallest such index k. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var bestRotation = function(nums) { - const n = nums.length; - const changes = new Array(n).fill(0); - - for (let i = 0; i < n; i++) { - const lowIndex = (i + 1) % n; - const highIndex = (i - nums[i] + 1 + n) % n; - - changes[lowIndex]++; - changes[highIndex]--; - - if (lowIndex > highIndex) { - changes[0]++; - } - } - - let maxScore = 0; - let maxIndex = 0; - let currentScore = 0; - - for (let i = 0; i < n; i++) { - currentScore += changes[i]; - if (currentScore > maxScore) { - maxScore = currentScore; - maxIndex = i; - } - } - - return maxIndex; -}; diff --git a/solutions/0799-champagne-tower.js b/solutions/0799-champagne-tower.js deleted file mode 100644 index 9e05f1f2..00000000 --- a/solutions/0799-champagne-tower.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 799. Champagne Tower - * https://leetcode.com/problems/champagne-tower/ - * Difficulty: Medium - * - * We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and - * so on until the 100th row. Each glass holds one cup of champagne. - * - * Then, some champagne is poured into the first glass at the top. When the topmost glass is full, - * any excess liquid poured will fall equally to the glass immediately to the left and right of it. - * When those glasses become full, any excess champagne will fall equally to the left and right of - * those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the - * floor.) - * - * For example, after one cup of champagne is poured, the top most glass is full. After two cups - * of champagne are poured, the two glasses on the second row are half full. After three cups of - * champagne are poured, those two cups become full - there are 3 full glasses total now. After - * four cups of champagne are poured, the third row has the middle glass half full, and the two - * outside glasses are a quarter full, as pictured below. - */ - -/** - * @param {number} poured - * @param {number} queryRow - * @param {number} queryGlass - * @return {number} - */ -var champagneTower = function(poured, queryRow, queryGlass) { - const tower = new Array(101).fill().map(() => new Array(101).fill(0)); - tower[0][0] = poured; - - for (let row = 0; row <= queryRow; row++) { - for (let glass = 0; glass <= row; glass++) { - const excess = (tower[row][glass] - 1) / 2; - - if (excess > 0) { - tower[row + 1][glass] += excess; - tower[row + 1][glass + 1] += excess; - } - } - } - - return Math.min(1, tower[queryRow][queryGlass]); -}; diff --git a/solutions/0801-minimum-swaps-to-make-sequences-increasing.js b/solutions/0801-minimum-swaps-to-make-sequences-increasing.js deleted file mode 100644 index 267ebaaa..00000000 --- a/solutions/0801-minimum-swaps-to-make-sequences-increasing.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 801. Minimum Swaps To Make Sequences Increasing - * https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/ - * Difficulty: Hard - * - * You are given two integer arrays of the same length nums1 and nums2. In one operation, you are - * allowed to swap nums1[i] with nums2[i]. - * - * For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to - * obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8]. - * - * Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The - * test cases are generated so that the given input always makes it possible. - * - * An array arr is strictly increasing if and only if - * arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1]. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var minSwap = function(nums1, nums2) { - let noSwap = 0; - let swap = 1; - - for (let i = 1; i < nums1.length; i++) { - let nextNoSwap = Infinity; - let nextSwap = Infinity; - - const canKeepBoth = nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]; - const canSwapBoth = nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]; - - if (canKeepBoth) { - nextNoSwap = Math.min(nextNoSwap, noSwap); - nextSwap = Math.min(nextSwap, swap + 1); - } - - if (canSwapBoth) { - nextNoSwap = Math.min(nextNoSwap, swap); - nextSwap = Math.min(nextSwap, noSwap + 1); - } - - noSwap = nextNoSwap; - swap = nextSwap; - } - - return Math.min(noSwap, swap); -}; diff --git a/solutions/0803-bricks-falling-when-hit.js b/solutions/0803-bricks-falling-when-hit.js deleted file mode 100644 index 90d29791..00000000 --- a/solutions/0803-bricks-falling-when-hit.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * 803. Bricks Falling When Hit - * https://leetcode.com/problems/bricks-falling-when-hit/ - * Difficulty: Hard - * - * You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty - * space. A brick is stable if: - * - It is directly connected to the top of the grid, or - * - At least one other brick in its four adjacent cells is stable. - * - * You are also given an array hits, which is a sequence of erasures we want to apply. Each time - * we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location - * (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure - * and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not - * land on other stable bricks). - * - * Return an array result, where each result[i] is the number of bricks that will fall after the - * ith erasure is applied. - * - * Note that an erasure may refer to a location with no brick, and if it does, no bricks drop. - */ - -/** - * @param {number[][]} grid - * @param {number[][]} hits - * @return {number[]} - */ -var hitBricks = function(grid, hits) { - const rows = grid.length; - const cols = grid[0].length; - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - const fallenBricks = new Array(hits.length).fill(0); - - hits.forEach(([x, y]) => { - if (grid[x][y] === 1) grid[x][y] = 2; - }); - - for (let col = 0; col < cols; col++) markStableBricks(0, col, grid); - - for (let i = hits.length - 1; i >= 0; i--) { - const [x, y] = hits[i]; - if (grid[x][y] !== 2) continue; - - grid[x][y] = 1; - if (hasStableNeighbor(x, y, grid)) { - fallenBricks[i] = markStableBricks(x, y, grid) - 1; - } - } - - return fallenBricks; - - function markStableBricks(x, y, grid) { - if (x < 0 || x >= rows || y < 0 || y >= cols || grid[x][y] !== 1) return 0; - - grid[x][y] = 3; - return 1 + directions.reduce((count, [dx, dy]) => { - return count + markStableBricks(x + dx, y + dy, grid); - }, 0); - } - - function hasStableNeighbor(x, y, grid) { - if (x === 0) return true; - - return directions.some(([dx, dy]) => { - const newX = x + dx; - const newY = y + dy; - return newX >= 0 && newX < rows && newY >= 0 && newY < cols && grid[newX][newY] === 3; - }); - } -}; diff --git a/solutions/0805-split-array-with-same-average.js b/solutions/0805-split-array-with-same-average.js deleted file mode 100644 index 257921c7..00000000 --- a/solutions/0805-split-array-with-same-average.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 805. Split Array With Same Average - * https://leetcode.com/problems/split-array-with-same-average/ - * Difficulty: Hard - * - * You are given an integer array nums. - * - * You should move each element of nums into one of the two arrays A and B such that A and B are - * non-empty, and average(A) == average(B). - * - * Return true if it is possible to achieve that and false otherwise. - * - * Note that for an array arr, average(arr) is the sum of all the elements of arr over the length - * of arr. - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var splitArraySameAverage = function(nums) { - if (nums.length <= 1) return false; - const sum = nums.reduce((acc, num) => acc + num, 0); - const dp = Array(Math.floor(nums.length / 2) + 1).fill().map(() => new Set()); - dp[0].add(0); - - for (const num of nums) { - for (let size = Math.min(Math.floor(nums.length / 2), dp.length - 1); size > 0; size--) { - for (const prevSum of dp[size - 1]) { - dp[size].add(prevSum + num); - } - } - } - - for (let size = 1; size <= Math.floor(nums.length / 2); size++) { - const targetSum = sum * size / nums.length; - - if (targetSum % 1 === 0 && dp[size].has(targetSum)) { - return true; - } - } - - return false; -}; diff --git a/solutions/0806-number-of-lines-to-write-string.js b/solutions/0806-number-of-lines-to-write-string.js deleted file mode 100644 index 8faecfc0..00000000 --- a/solutions/0806-number-of-lines-to-write-string.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 806. Number of Lines To Write String - * https://leetcode.com/problems/number-of-lines-to-write-string/ - * Difficulty: Easy - * - * You are given a string s of lowercase English letters and an array widths denoting how many - * pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', - * widths[1] is the width of 'b', and so on. - * - * You are trying to write s across several lines, where each line is no longer than 100 pixels. - * Starting at the beginning of s, write as many letters on the first line such that the total - * width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many - * letters as you can on the second line. Continue this process until you have written all of s. - * - * Return an array result of length 2 where: - * - result[0] is the total number of lines. - * - result[1] is the width of the last line in pixels. - */ - -/** - * @param {number[]} widths - * @param {string} s - * @return {number[]} - */ -var numberOfLines = function(widths, s) { - let lines = 1; - let width = 0; - - for (const char of s) { - const charWidth = widths[char.charCodeAt(0) - 97]; - - if (width + charWidth > 100) { - lines++; - width = charWidth; - } else { - width += charWidth; - } - } - - return [lines, width]; -}; diff --git a/solutions/0807-max-increase-to-keep-city-skyline.js b/solutions/0807-max-increase-to-keep-city-skyline.js deleted file mode 100644 index efa02a04..00000000 --- a/solutions/0807-max-increase-to-keep-city-skyline.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 807. Max Increase to Keep City Skyline - * https://leetcode.com/problems/max-increase-to-keep-city-skyline/ - * Difficulty: Medium - * - * There is a city composed of n x n blocks, where each block contains a single building shaped - * like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where - * grid[r][c] represents the height of the building located in the block at row r and column c. - * - * A city's skyline is the outer contour formed by all the building when viewing the side of the - * city from a distance. The skyline from each cardinal direction north, east, south, and west - * may be different. - * - * We are allowed to increase the height of any number of buildings by any amount (the amount can - * be different per building). The height of a 0-height building can also be increased. However, - * increasing the height of a building should not affect the city's skyline from any cardinal - * direction. - * - * Return the maximum total sum that the height of the buildings can be increased by without - * changing the city's skyline from any cardinal direction. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var maxIncreaseKeepingSkyline = function(grid) { - let result = 0; - const rowMaxes = grid.map(row => Math.max(...row)); - const columnMaxes = grid.map((row, index) => grid.map(row => row[index])) - .map(row => Math.max(...row)); - - for (let i = 0; i < grid.length; i++) { - for (let j = 0; j < grid[i].length; j++) { - const currentHeight = grid[i][j]; - const minHeight = Math.min( - Math.max(rowMaxes[i], currentHeight), - Math.max(columnMaxes[j], currentHeight) - ); - - result += (minHeight - currentHeight); - } - } - - return result; -}; diff --git a/solutions/0808-soup-servings.js b/solutions/0808-soup-servings.js deleted file mode 100644 index 796b6bb0..00000000 --- a/solutions/0808-soup-servings.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 808. Soup Servings - * https://leetcode.com/problems/soup-servings/ - * Difficulty: Medium - * - * There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. - * There are four kinds of operations: - * 1. Serve 100 ml of soup A and 0 ml of soup B, - * 2. Serve 75 ml of soup A and 25 ml of soup B, - * 3. Serve 50 ml of soup A and 50 ml of soup B, and - * 4. Serve 25 ml of soup A and 75 ml of soup B. - * - * When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will - * choose from the four operations with an equal probability 0.25. If the remaining volume of - * soup is not enough to complete the operation, we will serve as much as possible. We stop once - * we no longer have some quantity of both types of soup. - * - * Note that we do not have an operation where all 100 ml's of soup B are used first. - * - * Return the probability that soup A will be empty first, plus half the probability that A and B - * become empty at the same time. Answers within 10-5 of the actual answer will be accepted. - */ - -/** - * @param {number} n - * @return {number} - */ -var soupServings = function(n) { - if (n >= 4800) return 1.0; - - n = Math.ceil(n / 25); - const memo = new Map(); - - function calculateProbability(a, b) { - if (a <= 0 && b <= 0) return 0.5; - if (a <= 0) return 1.0; - if (b <= 0) return 0.0; - - const key = a * 10000 + b; - if (memo.has(key)) return memo.get(key); - - const probability = 0.25 * ( - calculateProbability(a - 4, b) + calculateProbability(a - 3, b - 1) - + calculateProbability(a - 2, b - 2) + calculateProbability(a - 1, b - 3) - ); - - memo.set(key, probability); - return probability; - } - - return calculateProbability(n, n); -}; diff --git a/solutions/0809-expressive-words.js b/solutions/0809-expressive-words.js deleted file mode 100644 index a6ce09a8..00000000 --- a/solutions/0809-expressive-words.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 809. Expressive Words - * https://leetcode.com/problems/expressive-words/ - * Difficulty: Medium - * - * Sometimes people repeat letters to represent extra feeling. For example: - * - "hello" -> "heeellooo" - * - "hi" -> "hiiii" - * - * In these strings like "heeellooo", we have groups of adjacent letters that are all the - * same: "h", "eee", "ll", "ooo". - * - * You are given a string s and an array of query strings words. A query word is stretchy - * if it can be made to be equal to s by any number of applications of the following extension - * operation: choose a group consisting of characters c, and add some number of characters - * c to the group so that the size of the group is three or more. - * - * For example, starting with "hello", we could do an extension on the group "o" to get - * "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. - * Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If - * s = "helllllooo", then the query word "hello" would be stretchy because of these two - * extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s. - * - * Return the number of query strings that are stretchy. - */ - -/** - * @param {string} s - * @param {string[]} words - * @return {number} - */ -var expressiveWords = function(s, words) { - let result = 0; - - for (const word of words) { - if (verify(s, word)) { - result++; - } - } - - return result; -}; - -function verify(s, word) { - let i = 0; - let j = 0; - - while (i < s.length && j < word.length) { - if (s[i] !== word[j]) return false; - - const char = s[i]; - let sCount = 0; - - while (i < s.length && s[i] === char) { - sCount++; - i++; - } - - let wordCount = 0; - - while (j < word.length && word[j] === char) { - wordCount++; - j++; - } - - if (wordCount > sCount) return false; - if (sCount > wordCount && sCount < 3) return false; - } - - return i === s.length && j === word.length; -} diff --git a/solutions/0810-chalkboard-xor-game.js b/solutions/0810-chalkboard-xor-game.js deleted file mode 100644 index 86ba85ae..00000000 --- a/solutions/0810-chalkboard-xor-game.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 810. Chalkboard XOR Game - * https://leetcode.com/problems/chalkboard-xor-game/ - * Difficulty: Hard - * - * You are given an array of integers nums represents the numbers written on a chalkboard. - * - * Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting - * first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to - * become 0, then that player loses. The bitwise XOR of one element is that element itself, and - * the bitwise XOR of no elements is 0. - * - * Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard - * equal to 0, then that player wins. - * - * Return true if and only if Alice wins the game, assuming both players play optimally. - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var xorGame = function(nums) { - const total = nums.reduce((xor, num) => xor ^ num, 0); - if (total === 0) return true; - return nums.length % 2 === 0; -}; diff --git a/solutions/0811-subdomain-visit-count.js b/solutions/0811-subdomain-visit-count.js deleted file mode 100644 index 9be91726..00000000 --- a/solutions/0811-subdomain-visit-count.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 811. Subdomain Visit Count - * https://leetcode.com/problems/subdomain-visit-count/ - * Difficulty: Medium - * - * A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have - * "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". - * When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains - * "leetcode.com" and "com" implicitly. - * - * A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" - * where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. - * - * For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that - * discuss.leetcode.com was visited 9001 times. - * - * Given an array of count-paired domains cpdomains, return an array of the count-paired domains of - * each subdomain in the input. You may return the answer in any order. - */ - -/** - * @param {string[]} cpdomains - * @return {string[]} - */ -var subdomainVisits = function(cpdomains) { - const domainCount = new Map(); - - for (const cpdomain of cpdomains) { - const [countStr, domain] = cpdomain.split(' '); - const count = parseInt(countStr); - const subdomains = getSubdomains(domain); - - for (const subdomain of subdomains) { - domainCount.set(subdomain, (domainCount.get(subdomain) || 0) + count); - } - } - - const result = []; - for (const [domain, count] of domainCount) { - result.push(`${count} ${domain}`); - } - - return result; -}; - -function getSubdomains(domain) { - const parts = domain.split('.'); - const subdomains = []; - - for (let i = 0; i < parts.length; i++) { - subdomains.push(parts.slice(i).join('.')); - } - - return subdomains; -} diff --git a/solutions/0812-largest-triangle-area.js b/solutions/0812-largest-triangle-area.js deleted file mode 100644 index 63d9ee4a..00000000 --- a/solutions/0812-largest-triangle-area.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 812. Largest Triangle Area - * https://leetcode.com/problems/largest-triangle-area/ - * Difficulty: Easy - * - * Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of - * the largest triangle that can be formed by any three different points. Answers within 10-5 of - * the actual answer will be accepted. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var largestTriangleArea = function(points) { - let maxArea = 0; - - for (let i = 0; i < points.length; i++) { - for (let j = i + 1; j < points.length; j++) { - for (let k = j + 1; k < points.length; k++) { - const area = calculateTriangleArea(points[i], points[j], points[k]); - maxArea = Math.max(maxArea, area); - } - } - } - - return maxArea; -}; - -function calculateTriangleArea(p1, p2, p3) { - const [[x1, y1], [x2, y2], [x3, y3]] = [p1, p2, p3]; - return Math.abs( - (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2 - ); -} diff --git a/solutions/0813-largest-sum-of-averages.js b/solutions/0813-largest-sum-of-averages.js deleted file mode 100644 index 736126c0..00000000 --- a/solutions/0813-largest-sum-of-averages.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 813. Largest Sum of Averages - * https://leetcode.com/problems/largest-sum-of-averages/ - * Difficulty: Medium - * - * You are given an integer array nums and an integer k. You can partition the array into at most - * k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each - * subarray. - * - * Note that the partition must use every integer in nums, and that the score is not necessarily - * an integer. - * - * Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 - * of the actual answer will be accepted. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var largestSumOfAverages = function(nums, k) { - const prefixSum = new Array(nums.length + 1).fill(0); - for (let i = 0; i < nums.length; i++) { - prefixSum[i + 1] = prefixSum[i] + nums[i]; - } - - const dp = new Array(nums.length).fill(0).map(() => new Array(k + 1).fill(0)); - - for (let i = 0; i < nums.length; i++) { - dp[i][1] = calculateAverage(i, nums.length - 1); - } - - for (let partitions = 2; partitions <= k; partitions++) { - for (let start = 0; start < nums.length - partitions + 1; start++) { - for (let end = start; end < nums.length - partitions + 1; end++) { - dp[start][partitions] = Math.max( - dp[start][partitions], - calculateAverage(start, end) + dp[end + 1][partitions - 1] - ); - } - } - } - - return dp[0][k]; - - function calculateAverage(i, j) { - return (prefixSum[j + 1] - prefixSum[i]) / (j - i + 1); - } -}; diff --git a/solutions/0814-binary-tree-pruning.js b/solutions/0814-binary-tree-pruning.js deleted file mode 100644 index d93d6f90..00000000 --- a/solutions/0814-binary-tree-pruning.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 814. Binary Tree Pruning - * https://leetcode.com/problems/binary-tree-pruning/ - * Difficulty: Medium - * - * Given the root of a binary tree, return the same tree where every subtree (of the given tree) - * not containing a 1 has been removed. - * - * A subtree of a node node is node plus every node that is a descendant of 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 {TreeNode} - */ -var pruneTree = function(root) { - if (!root) return null; - root.left = pruneTree(root.left); - root.right = pruneTree(root.right); - if (!root.left && !root.right && root.val === 0) { - return null; - } - return root; -}; diff --git a/solutions/0815-bus-routes.js b/solutions/0815-bus-routes.js deleted file mode 100644 index bd2db50b..00000000 --- a/solutions/0815-bus-routes.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 815. Bus Routes - * https://leetcode.com/problems/bus-routes/ - * Difficulty: Hard - * - * You are given an array routes representing bus routes where routes[i] is a bus route that - * the ith bus repeats forever. - * - * For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence - * 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. - * - * You will start at the bus stop source (You are not on any bus initially), and you want to - * go to the bus stop target. You can travel between bus stops by buses only. - * - * Return the least number of buses you must take to travel from source to target. - * - * Return -1 if it is not possible. - */ - - -/** - * @param {number[][]} routes - * @param {number} source - * @param {number} target - * @return {number} - */ -var numBusesToDestination = function(routes, source, target) { - if (source === target) return 0; - - const stopToBuses = new Map(); - - for (let busId = 0; busId < routes.length; busId++) { - for (const stop of routes[busId]) { - if (!stopToBuses.has(stop)) { - stopToBuses.set(stop, []); - } - stopToBuses.get(stop).push(busId); - } - } - if (!stopToBuses.has(source) || !stopToBuses.has(target)) return -1; - - const visitedBuses = new Set(); - const visitedStops = new Set([source]); - const queue = [[source, 0]]; - - while (queue.length > 0) { - const [currentStop, busCount] = queue.shift(); - if (currentStop === target) return busCount; - for (const busId of stopToBuses.get(currentStop)) { - if (visitedBuses.has(busId)) continue; - visitedBuses.add(busId); - for (const nextStop of routes[busId]) { - if (visitedStops.has(nextStop)) continue; - visitedStops.add(nextStop); - queue.push([nextStop, busCount + 1]); - if (nextStop === target) return busCount + 1; - } - } - } - - return -1; -}; diff --git a/solutions/0816-ambiguous-coordinates.js b/solutions/0816-ambiguous-coordinates.js deleted file mode 100644 index ca26ad1f..00000000 --- a/solutions/0816-ambiguous-coordinates.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 816. Ambiguous Coordinates - * https://leetcode.com/problems/ambiguous-coordinates/ - * Difficulty: Medium - * - * We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, - * decimal points, and spaces and ended up with the string s. - * - For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)". - * - * Return a list of strings representing all possibilities for what our original coordinates could - * have been. - * - * Our original representation never had extraneous zeroes, so we never started with numbers like - * "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with - * fewer digits. Also, a decimal point within a number never occurs without at least one digit - * occurring before it, so we never started with numbers like ".1". - * - * The final answer list can be returned in any order. All coordinates in the final answer have - * exactly one space between them (occurring after the comma.) - */ - -/** - * @param {string} s - * @return {string[]} - */ -var ambiguousCoordinates = function(s) { - const digits = s.slice(1, s.length - 1); - const result = []; - - for (let i = 1; i < digits.length; i++) { - const leftPart = digits.substring(0, i); - const rightPart = digits.substring(i); - - const validLeftCoords = getValidCoordinates(leftPart); - const validRightCoords = getValidCoordinates(rightPart); - - for (const left of validLeftCoords) { - for (const right of validRightCoords) { - result.push(`(${left}, ${right})`); - } - } - } - - return result; -}; - -function getValidCoordinates(s) { - const coords = []; - - if (isValidInteger(s)) { - coords.push(s); - } - - for (let i = 1; i < s.length; i++) { - const integerPart = s.substring(0, i); - const decimalPart = s.substring(i); - - if (isValidInteger(integerPart) && isValidDecimal(decimalPart)) { - coords.push(`${integerPart}.${decimalPart}`); - } - } - - return coords; -} - -function isValidInteger(s) { - return s === '0' || s[0] !== '0'; -} - -function isValidDecimal(s) { - return s[s.length - 1] !== '0'; -} diff --git a/solutions/0817-linked-list-components.js b/solutions/0817-linked-list-components.js deleted file mode 100644 index b3ee38da..00000000 --- a/solutions/0817-linked-list-components.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 817. Linked List Components - * https://leetcode.com/problems/linked-list-components/ - * Difficulty: Medium - * - * You are given the head of a linked list containing unique integer values and an integer array - * nums that is a subset of the linked list values. - * - * Return the number of connected components in nums where two values are connected if they appear - * consecutively in 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 - * @param {number[]} nums - * @return {number} - */ -var numComponents = function(head, nums) { - const numSet = new Set(nums); - let componentCount = 0; - let inComponent = false; - - let current = head; - while (current) { - if (numSet.has(current.val)) { - if (!inComponent) { - componentCount++; - inComponent = true; - } - } else { - inComponent = false; - } - current = current.next; - } - - return componentCount; -}; diff --git a/solutions/0818-race-car.js b/solutions/0818-race-car.js deleted file mode 100644 index f75a53b6..00000000 --- a/solutions/0818-race-car.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 818. Race Car - * https://leetcode.com/problems/race-car/ - * Difficulty: Hard - * - * Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into - * negative positions. Your car drives automatically according to a sequence of instructions - * 'A' (accelerate) and 'R' (reverse): - * - When you get an instruction 'A', your car does the following: - * - position += speed - * - speed *= 2 - * - When you get an instruction 'R', your car does the following: - * - If your speed is positive then speed = -1 - * - otherwise speed = 1 - * - * Your position stays the same. - * - * For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your - * speed goes to 1 --> 2 --> 4 --> -1. - * - * Given a target position target, return the length of the shortest sequence of instructions - * to get there. - */ - -/** - * @param {number} target - * @return {number} - */ -var racecar = function(target) { - const dp = new Array(target + 1).fill(Infinity); - dp[0] = 0; - - for (let i = 1; i <= target; i++) { - const k = Math.ceil(Math.log2(i + 1)); - - if ((1 << k) - 1 === i) { - dp[i] = k; - continue; - } - - dp[i] = k + 1 + dp[(1 << k) - 1 - i]; - - for (let j = 0; j < k - 1; j++) { - dp[i] = Math.min( - dp[i], - (k - 1) + 1 + j + 1 + dp[i - ((1 << (k - 1)) - 1) + (1 << j) - 1] - ); - } - } - - return dp[target]; -}; diff --git a/solutions/0820-short-encoding-of-words.js b/solutions/0820-short-encoding-of-words.js deleted file mode 100644 index 2297339f..00000000 --- a/solutions/0820-short-encoding-of-words.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 820. Short Encoding of Words - * https://leetcode.com/problems/short-encoding-of-words/ - * Difficulty: Medium - * - * A valid encoding of an array of words is any reference string s and array of indices - * such that: - * - words.length == indices.length - * - The reference string s ends with the '#' character. - * - For each index indices[i], the substring of s starting from indices[i] and up to - * (but not including) the next '#' character is equal to words[i]. - * - * Given an array of words, return the length of the shortest reference string s possible - * of any valid encoding of words. - */ - -/** - * @param {string[]} words - * @return {number} - */ -var minimumLengthEncoding = function(words) { - const uniqueWords = [...new Set(words)]; - const wordSet = new Set(uniqueWords); - - for (const word of uniqueWords) { - for (let i = 1; i < word.length; i++) { - const suffix = word.slice(i); - wordSet.delete(suffix); - } - } - - let result = 0; - for (const word of wordSet) { - result += word.length + 1; - } - - return result; -}; diff --git a/solutions/0822-card-flipping-game.js b/solutions/0822-card-flipping-game.js deleted file mode 100644 index 9a2becbb..00000000 --- a/solutions/0822-card-flipping-game.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 822. Card Flipping Game - * https://leetcode.com/problems/card-flipping-game/ - * Difficulty: Medium - * - * You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has - * the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, - * each card is placed on a table such that the front number is facing up and the other is facing - * down. You may flip over any number of cards (possibly zero). - * - * After flipping the cards, an integer is considered good if it is facing down on some card and - * not facing up on any card. - * - * Return the minimum possible good integer after flipping the cards. If there are no good integers, - * return 0. - */ - -/** - * @param {number[]} fronts - * @param {number[]} backs - * @return {number} - */ -var flipgame = function(fronts, backs) { - const impossibleValues = new Set(); - const n = fronts.length; - - for (let i = 0; i < n; i++) { - if (fronts[i] === backs[i]) { - impossibleValues.add(fronts[i]); - } - } - - let minGoodValue = Infinity; - - for (let i = 0; i < n; i++) { - if (!impossibleValues.has(fronts[i])) { - minGoodValue = Math.min(minGoodValue, fronts[i]); - } - - if (!impossibleValues.has(backs[i])) { - minGoodValue = Math.min(minGoodValue, backs[i]); - } - } - - return minGoodValue === Infinity ? 0 : minGoodValue; -}; diff --git a/solutions/0823-binary-trees-with-factors.js b/solutions/0823-binary-trees-with-factors.js deleted file mode 100644 index bb2e8dd0..00000000 --- a/solutions/0823-binary-trees-with-factors.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 823. Binary Trees With Factors - * https://leetcode.com/problems/binary-trees-with-factors/ - * Difficulty: Medium - * - * Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. - * - * We make a binary tree using these integers, and each number may be used for any number of times. - * Each non-leaf node's value should be equal to the product of the values of its children. - * - * Return the number of binary trees we can make. The answer may be too large so return the answer - * modulo 109 + 7. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var numFactoredBinaryTrees = function(arr) { - const MOD = 1e9 + 7; - const dp = {}; - const numMap = new Map(); - - arr.sort((a, b) => a - b); - for (let i = 0; i < arr.length; i++) { - numMap.set(arr[i], i); - } - - let result = 0; - for (let i = 0; i < arr.length; i++) { - dp[arr[i]] = 1; - for (let j = 0; j < i; j++) { - if (arr[i] % arr[j] === 0) { - const complement = arr[i] / arr[j]; - if (numMap.has(complement)) { - dp[arr[i]] = (dp[arr[i]] + dp[arr[j]] * dp[complement]) % MOD; - } - } - } - result = (result + dp[arr[i]]) % MOD; - } - - return result; -}; diff --git a/solutions/0825-friends-of-appropriate-ages.js b/solutions/0825-friends-of-appropriate-ages.js deleted file mode 100644 index 88450910..00000000 --- a/solutions/0825-friends-of-appropriate-ages.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 825. Friends Of Appropriate Ages - * https://leetcode.com/problems/friends-of-appropriate-ages/ - * Difficulty: Medium - * - * There are n persons on a social media website. You are given an integer array ages where ages[i] - * is the age of the ith person. - * - * A Person x will not send a friend request to a person y (x != y) if any of the following - * conditions is true: - * - age[y] <= 0.5 * age[x] + 7 - * - age[y] > age[x] - * - age[y] > 100 && age[x] < 100 - * - * Otherwise, x will send a friend request to y. - * - * Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person - * will not send a friend request to themself. - * - * Return the total number of friend requests made. - */ - -/** - * @param {number[]} ages - * @return {number} - */ -var numFriendRequests = function(ages) { - const ageCount = new Array(121).fill(0); - - for (const age of ages) { - ageCount[age]++; - } - - let result = 0; - for (let ageX = 1; ageX <= 120; ageX++) { - if (ageCount[ageX] === 0) continue; - for (let ageY = 1; ageY <= 120; ageY++) { - if (ageCount[ageY] === 0) continue; - if (ageY <= 0.5 * ageX + 7) continue; - if (ageY > ageX) continue; - if (ageY > 100 && ageX < 100) continue; - if (ageX === ageY) { - result += ageCount[ageX] * (ageCount[ageY] - 1); - } else { - result += ageCount[ageX] * ageCount[ageY]; - } - } - } - - return result; -}; diff --git a/solutions/0826-most-profit-assigning-work.js b/solutions/0826-most-profit-assigning-work.js deleted file mode 100644 index 0af0f6f9..00000000 --- a/solutions/0826-most-profit-assigning-work.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 826. Most Profit Assigning Work - * https://leetcode.com/problems/most-profit-assigning-work/ - * Difficulty: Medium - * - * You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: - * - difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and - * - worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with - * difficulty at most worker[j]). - * - * Every worker can be assigned at most one job, but one job can be completed multiple times. - * - For example, if three workers attempt the same job that pays $1, then the total profit will - * be $3. If a worker cannot complete any job, their profit is $0. - * - * Return the maximum profit we can achieve after assigning the workers to the jobs. - */ - -/** - * @param {number[]} difficulty - * @param {number[]} profit - * @param {number[]} worker - * @return {number} - */ -var maxProfitAssignment = function(difficulty, profit, worker) { - const jobs = difficulty.map((d, i) => [d, profit[i]]); - jobs.sort((a, b) => a[0] - b[0]); - - const n = jobs.length; - const bestProfit = new Array(n); - let maxProfit = 0; - - for (let i = 0; i < n; i++) { - maxProfit = Math.max(maxProfit, jobs[i][1]); - bestProfit[i] = [jobs[i][0], maxProfit]; - } - - return worker.reduce((total, ability) => { - let left = 0; - let right = n - 1; - - while (left <= right) { - const mid = (left + right) >> 1; - bestProfit[mid][0] <= ability ? left = mid + 1 : right = mid - 1; - } - - return total + (right >= 0 ? bestProfit[right][1] : 0); - }, 0); -}; diff --git a/solutions/0828-count-unique-characters-of-all-substrings-of-a-given-string.js b/solutions/0828-count-unique-characters-of-all-substrings-of-a-given-string.js deleted file mode 100644 index 8b17dd79..00000000 --- a/solutions/0828-count-unique-characters-of-all-substrings-of-a-given-string.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 828. Count Unique Characters of All Substrings of a Given String - * https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/ - * Difficulty: Hard - * - * Let's define a function countUniqueChars(s) that returns the number of unique characters in s. - * - For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are - * the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5. - * - * Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test - * cases are generated such that the answer fits in a 32-bit integer. - * - * Notice that some substrings can be repeated so in this case you have to count the repeated - * ones too. - */ - -/** - * @param {string} s - * @return {number} - */ -var uniqueLetterString = function(s) { - const n = s.length; - const lastPositions = {}; - let result = 0; - - for (let i = 0; i < n; i++) { - const char = s[i]; - if (!lastPositions[char]) lastPositions[char] = [-1, -1]; - - const [prevPrev, prev] = lastPositions[char]; - result += (i - prev) * (prev - prevPrev); - lastPositions[char] = [prev, i]; - } - - for (const char of Object.keys(lastPositions)) { - const [prev, pos] = lastPositions[char]; - if (pos >= 0) result += (n - pos) * (pos - prev); - } - - return result; -}; diff --git a/solutions/0829-consecutive-numbers-sum.js b/solutions/0829-consecutive-numbers-sum.js deleted file mode 100644 index 3ae32ace..00000000 --- a/solutions/0829-consecutive-numbers-sum.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 829. Consecutive Numbers Sum - * https://leetcode.com/problems/consecutive-numbers-sum/ - * Difficulty: Hard - * - * Given an integer n, return the number of ways you can write n as the sum of consecutive - * positive integers. - */ - -/** - * @param {number} n - * @return {number} - */ -var consecutiveNumbersSum = function(n) { - let result = 0; - - for (let k = 1; k < Math.sqrt(2 * n); k++) { - const numerator = n - (k * (k - 1)) / 2; - if (numerator % k === 0) { - const startingNum = numerator / k; - if (startingNum > 0) { - result++; - } - } - } - - return result; -}; diff --git a/solutions/0832-flipping-an-image.js b/solutions/0832-flipping-an-image.js deleted file mode 100644 index 9e92cc10..00000000 --- a/solutions/0832-flipping-an-image.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 832. Flipping an Image - * https://leetcode.com/problems/flipping-an-image/ - * Difficulty: Easy - * - * Given an n x n binary matrix image, flip the image horizontally, then invert it, and - * return the resulting image. - * - * To flip an image horizontally means that each row of the image is reversed. - * - For example, flipping [1,1,0] horizontally results in [0,1,1]. - * - * To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. - * - For example, inverting [0,1,1] results in [1,0,0]. - */ - -/** - * @param {number[][]} image - * @return {number[][]} - */ -var flipAndInvertImage = function(image) { - return image.map(row => row.reverse().map(num => 1 ^ num)); -}; diff --git a/solutions/0833-find-and-replace-in-string.js b/solutions/0833-find-and-replace-in-string.js deleted file mode 100644 index 66dfe232..00000000 --- a/solutions/0833-find-and-replace-in-string.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 833. Find And Replace in String - * https://leetcode.com/problems/find-and-replace-in-string/ - * Difficulty: Medium - * - * You are given a 0-indexed string s that you must perform k replacement operations on. - * The replacement operations are given as three 0-indexed parallel arrays, indices, sources, - * and targets, all of length k. - * - * To complete the ith replacement operation: - * 1. Check if the substring sources[i] occurs at index indices[i] in the original string s. - * 2. If it does not occur, do nothing. - * 3. Otherwise if it does occur, replace that substring with targets[i]. - * - * For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then - * the result of this replacement will be "eeecd". - * - * All replacement operations must occur simultaneously, meaning the replacement operations should - * not affect the indexing of each other. The testcases will be generated such that the replacements - * will not overlap. - * - * - For example, a testcase with s = "abc", indices = [0, 1], and sources = ["ab","bc"] will not be - * generated because the "ab" and "bc" replacements overlap. - * - * Return the resulting string after performing all replacement operations on s. - * - * A substring is a contiguous sequence of characters in a string. - */ - -/** - * @param {string} s - * @param {number[]} indices - * @param {string[]} sources - * @param {string[]} targets - * @return {string} - */ -var findReplaceString = function(s, indices, sources, targets) { - const replacements = []; - - for (let i = 0; i < indices.length; i++) { - const index = indices[i]; - const source = sources[i]; - const target = targets[i]; - - if (s.substring(index, index + source.length) === source) { - replacements.push({ index, source, target }); - } - } - - replacements.sort((a, b) => b.index - a.index); - - let result = s; - for (const { index, source, target } of replacements) { - result = result.substring(0, index) + target + result.substring(index + source.length); - } - - return result; -}; diff --git a/solutions/0834-sum-of-distances-in-tree.js b/solutions/0834-sum-of-distances-in-tree.js deleted file mode 100644 index 661920e3..00000000 --- a/solutions/0834-sum-of-distances-in-tree.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 834. Sum of Distances in Tree - * https://leetcode.com/problems/sum-of-distances-in-tree/ - * Difficulty: Hard - * - * There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. - * - * You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there - * is an edge between nodes ai and bi in the tree. - * - * Return an array answer of length n where answer[i] is the sum of the distances between the ith - * node in the tree and all other nodes. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number[]} - */ -var sumOfDistancesInTree = function(n, edges) { - const graph = Array.from({ length: n }, () => []); - const count = new Array(n).fill(1); - const result = new Array(n).fill(0); - - for (const [a, b] of edges) { - graph[a].push(b); - graph[b].push(a); - } - - function dfs1(node, parent) { - for (const child of graph[node]) { - if (child !== parent) { - dfs1(child, node); - count[node] += count[child]; - result[node] += result[child] + count[child]; - } - } - } - - function dfs2(node, parent) { - for (const child of graph[node]) { - if (child !== parent) { - result[child] = result[node] - count[child] + (n - count[child]); - dfs2(child, node); - } - } - } - - dfs1(0, -1); - dfs2(0, -1); - - return result; -}; diff --git a/solutions/0835-image-overlap.js b/solutions/0835-image-overlap.js deleted file mode 100644 index 77aa69de..00000000 --- a/solutions/0835-image-overlap.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 835. Image Overlap - * https://leetcode.com/problems/image-overlap/ - * Difficulty: Medium - * - * You are given two images, img1 and img2, represented as binary, square matrices of size n x n. - * A binary matrix has only 0s and 1s as values. - * - * We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down - * any number of units. We then place it on top of the other image. We can then calculate the - * overlap by counting the number of positions that have a 1 in both images. - * - * Note also that a translation does not include any kind of rotation. Any 1 bits that are - * translated outside of the matrix borders are erased. - * - * Return the largest possible overlap. - */ - -/** - * @param {number[][]} img1 - * @param {number[][]} img2 - * @return {number} - */ -var largestOverlap = function(img1, img2) { - const positions1 = []; - const positions2 = []; - - for (let i = 0; i < img1.length; i++) { - for (let j = 0; j < img1.length; j++) { - if (img1[i][j] === 1) { - positions1.push([i, j]); - } - if (img2[i][j] === 1) { - positions2.push([i, j]); - } - } - } - - if (positions1.length === 0 || positions2.length === 0) { - return 0; - } - - const translations = new Map(); - let maxOverlap = 0; - - for (const [r1, c1] of positions1) { - for (const [r2, c2] of positions2) { - const translation = `${r2 - r1},${c2 - c1}`; - - if (!translations.has(translation)) { - translations.set(translation, 0); - } - - translations.set(translation, translations.get(translation) + 1); - maxOverlap = Math.max(maxOverlap, translations.get(translation)); - } - } - - return maxOverlap; -}; diff --git a/solutions/0836-rectangle-overlap.js b/solutions/0836-rectangle-overlap.js deleted file mode 100644 index f615d7a3..00000000 --- a/solutions/0836-rectangle-overlap.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 836. Rectangle Overlap - * https://leetcode.com/problems/rectangle-overlap/ - * Difficulty: Easy - * - * An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the - * coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. - * Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel - * to the Y-axis. - * - * Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles - * that only touch at the corner or edges do not overlap. - * - * Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return - * false. - */ - -/** - * @param {number[]} rec1 - * @param {number[]} rec2 - * @return {boolean} - */ -var isRectangleOverlap = function(rec1, rec2) { - const [x1, y1, x2, y2] = rec1; - const [a1, b1, a2, b2] = rec2; - return x1 < a2 && a1 < x2 && y1 < b2 && b1 < y2; -}; diff --git a/solutions/0837-new-21-game.js b/solutions/0837-new-21-game.js deleted file mode 100644 index e0f76328..00000000 --- a/solutions/0837-new-21-game.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 837. New 21 Game - * https://leetcode.com/problems/new-21-game/ - * Difficulty: Medium - * - * Alice plays the following game, loosely based on the card game "21". - * - * Alice starts with 0 points and draws numbers while she has less than k points. During each draw, - * she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an - * integer. Each draw is independent and the outcomes have equal probabilities. - * - * Alice stops drawing numbers when she gets k or more points. - * - * Return the probability that Alice has n or fewer points. - * - * Answers within 10-5 of the actual answer are considered accepted. - */ - -/** - * @param {number} n - * @param {number} k - * @param {number} maxPts - * @return {number} - */ -var new21Game = function(n, k, maxPts) { - if (k === 0 || n >= k + maxPts - 1) return 1.0; - - const dp = new Array(n + 1).fill(0); - dp[0] = 1.0; - - let sum = 1.0; - for (let i = 1; i <= n; i++) { - dp[i] = sum / maxPts; - if (i < k) { - sum += dp[i]; - } - if (i >= maxPts) { - sum -= dp[i - maxPts]; - } - } - - let result = 0; - for (let i = k; i <= n; i++) { - result += dp[i]; - } - - return result; -}; diff --git a/solutions/0838-push-dominoes.js b/solutions/0838-push-dominoes.js deleted file mode 100644 index 5839ee3c..00000000 --- a/solutions/0838-push-dominoes.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 838. Push Dominoes - * https://leetcode.com/problems/push-dominoes/ - * Difficulty: Medium - * - * There are n dominoes in a line, and we place each domino vertically upright. In the beginning, - * we simultaneously push some of the dominoes either to the left or to the right. - * - * After each second, each domino that is falling to the left pushes the adjacent domino on the - * left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on - * the right. - * - * When a vertical domino has dominoes falling on it from both sides, it stays still due to the - * balance of the forces. - * - * For the purposes of this question, we will consider that a falling domino expends no additional - * force to a falling or already fallen domino. - * - * You are given a string dominoes representing the initial state where: - * - dominoes[i] = 'L', if the ith domino has been pushed to the left, - * - dominoes[i] = 'R', if the ith domino has been pushed to the right, and - * - dominoes[i] = '.', if the ith domino has not been pushed. - * - * Return a string representing the final state. - */ - -/** - * @param {string} dominoes - * @return {string} - */ -var pushDominoes = function(dominoes) { - const forces = new Array(dominoes.length).fill(0); - - let force = 0; - for (let i = 0; i < dominoes.length; i++) { - if (dominoes[i] === 'R') { - force = dominoes.length; - } else if (dominoes[i] === 'L') { - force = 0; - } else { - force = Math.max(force - 1, 0); - } - forces[i] += force; - } - - force = 0; - for (let i = dominoes.length - 1; i >= 0; i--) { - if (dominoes[i] === 'L') { - force = dominoes.length; - } else if (dominoes[i] === 'R') { - force = 0; - } else { - force = Math.max(force - 1, 0); - } - forces[i] -= force; - } - - return forces.map(f => { - if (f > 0) return 'R'; - if (f < 0) return 'L'; - return '.'; - }).join(''); -}; diff --git a/solutions/0839-similar-string-groups.js b/solutions/0839-similar-string-groups.js deleted file mode 100644 index 0069ad5a..00000000 --- a/solutions/0839-similar-string-groups.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 839. Similar String Groups - * https://leetcode.com/problems/similar-string-groups/ - * Difficulty: Hard - * - * Two strings, X and Y, are considered similar if either they are identical or we can make them - * equivalent by swapping at most two letters (in distinct positions) within the string X. - * - * For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and - * "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". - * - * Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. - * Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, - * each group is such that a word is in the group if and only if it is similar to at least one - * other word in the group. - * - * We are given a list strs of strings where every string in strs is an anagram of every other - * string in strs. How many groups are there? - */ - -/** - * @param {string[]} strs - * @return {number} - */ -var numSimilarGroups = function(strs) { - const parent = Array.from({ length: strs.length }, (_, i) => i); - const rank = new Array(strs.length).fill(0); - - for (let i = 0; i < strs.length; i++) { - for (let j = i + 1; j < strs.length; j++) { - if (areSimilar(strs[i], strs[j])) union(i, j); - } - } - - const groups = new Set(); - for (let i = 0; i < strs.length; i++) groups.add(find(i)); - - return groups.size; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - const rootX = find(x); - const rootY = find(y); - - if (rootX === rootY) return; - - if (rank[rootX] < rank[rootY]) { - parent[rootX] = rootY; - } else { - parent[rootY] = rootX; - if (rank[rootX] === rank[rootY]) rank[rootX]++; - } - } - - function areSimilar(a, b) { - if (a === b) return true; - - let diff = 0; - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i] && ++diff > 2) return false; - } - - return diff === 2; - } -}; diff --git a/solutions/0840-magic-squares-in-grid.js b/solutions/0840-magic-squares-in-grid.js deleted file mode 100644 index 869c18e5..00000000 --- a/solutions/0840-magic-squares-in-grid.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 840. Magic Squares In Grid - * https://leetcode.com/problems/magic-squares-in-grid/ - * Difficulty: Medium - * - * A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, - * column, and both diagonals all have the same sum. - * - * Given a row x col grid of integers, how many 3 x 3 magic square subgrids are there? - * - * Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up - * to 15. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var numMagicSquaresInside = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - - if (rows < 3 || cols < 3) return 0; - - let result = 0; - for (let r = 0; r <= rows - 3; r++) { - for (let c = 0; c <= cols - 3; c++) { - if (isMagicSquare(grid, r, c)) result++; - } - } - - return result; -}; - -function isMagicSquare(grid, r, c) { - if (grid[r + 1][c + 1] !== 5) return false; - - const cells = [ - grid[r][c], grid[r][c + 1], grid[r][c + 2], - grid[r + 1][c], grid[r + 1][c + 1], grid[r + 1][c + 2], - grid[r + 2][c], grid[r + 2][c + 1], grid[r + 2][c + 2] - ]; - - if (!cells.every(val => val >= 1 && val <= 9) || new Set(cells).size !== 9) return false; - - return ( - grid[r][c] + grid[r][c + 1] + grid[r][c + 2] === 15 - && grid[r + 1][c] + grid[r + 1][c + 1] + grid[r + 1][c + 2] === 15 - && grid[r + 2][c] + grid[r + 2][c + 1] + grid[r + 2][c + 2] === 15 - && grid[r][c] + grid[r + 1][c] + grid[r + 2][c] === 15 - && grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 2][c + 1] === 15 - && grid[r][c + 2] + grid[r + 1][c + 2] + grid[r + 2][c + 2] === 15 - && grid[r][c] + grid[r + 1][c + 1] + grid[r + 2][c + 2] === 15 - && grid[r][c + 2] + grid[r + 1][c + 1] + grid[r + 2][c] === 15 - ); -} diff --git a/solutions/0842-split-array-into-fibonacci-sequence.js b/solutions/0842-split-array-into-fibonacci-sequence.js deleted file mode 100644 index e717708b..00000000 --- a/solutions/0842-split-array-into-fibonacci-sequence.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 842. Split Array into Fibonacci Sequence - * https://leetcode.com/problems/split-array-into-fibonacci-sequence/ - * Difficulty: Medium - * - * You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like - * sequence [123, 456, 579]. - * - * Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: - * - 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type), - * - f.length >= 3, and - * - f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. - * - * Note that when splitting the string into pieces, each piece must not have extra leading zeroes, - * except if the piece is the number 0 itself. - * - * Return any Fibonacci-like sequence split from num, or return [] if it cannot be done. - */ - -/** - * @param {string} num - * @return {number[]} - */ -var splitIntoFibonacci = function(num) { - const result = []; - const MAX_INT = 2 ** 31 - 1; - backtrack(0); - return result; - - function backtrack(index) { - if (index === num.length && result.length >= 3) return true; - for (let length = 1; length <= num.length - index; length++) { - if (num[index] === '0' && length > 1) break; - const current = parseInt(num.substring(index, index + length)); - if (current > MAX_INT) break; - if (result.length >= 2) { - const sum = result[result.length - 1] + result[result.length - 2]; - if (current > sum) break; - if (current < sum) continue; - } - result.push(current); - if (backtrack(index + length)) return true; - result.pop(); - } - return false; - } -}; diff --git a/solutions/0843-guess-the-word.js b/solutions/0843-guess-the-word.js deleted file mode 100644 index 036a0ca9..00000000 --- a/solutions/0843-guess-the-word.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 843. Guess the Word - * https://leetcode.com/problems/guess-the-word/ - * Difficulty: Hard - * - * You are given an array of unique strings words where words[i] is six letters long. One word of - * words was chosen as a secret word. - * - * You are also given the helper object Master. You may call Master.guess(word) where word is a - * six-letter-long string, and it must be from words. Master.guess(word) returns: - * - -1 if word is not from words, or - * - an integer representing the number of exact matches (value and position) of your guess to - * the secret word. - * - * There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum - * number of times you can call Master.guess(word). - * - * For each test case, you should call Master.guess with the secret word without exceeding the - * maximum number of allowed guesses. You will get: - * - "Either you took too many guesses, or you did not find the secret word." if you called - * Master.guess more than allowedGuesses times or if you did not call Master.guess with the - * secret word, or - * - "You guessed the secret word correctly." if you called Master.guess with the secret word - * with the number of calls to Master.guess less than or equal to allowedGuesses. - * - * The test cases are generated such that you can guess the secret word with a reasonable - * strategy (other than using the bruteforce method). - */ - -/** - * @param {string[]} words - * @param {Master} master - * @return {void} - */ -var findSecretWord = function(words, master) { - for (let attempt = 0; attempt < 30; attempt++) { - const randomWord = words[Math.floor(Math.random() * words.length)]; - const matchCount = master.guess(randomWord); - - if (matchCount === 6) return; - - words = words.filter(word => - matchCount === -1 - ? countMatches(word, randomWord) === 0 - : countMatches(word, randomWord) === matchCount - ); - } - - function countMatches(word1, word2) { - let matches = 0; - for (let i = 0; i < word1.length; i++) { - if (word1[i] === word2[i]) matches++; - } - return matches; - } -}; diff --git a/solutions/0844-backspace-string-compare.js b/solutions/0844-backspace-string-compare.js deleted file mode 100644 index c5dab2e4..00000000 --- a/solutions/0844-backspace-string-compare.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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/solutions/0845-longest-mountain-in-array.js b/solutions/0845-longest-mountain-in-array.js deleted file mode 100644 index 7692212d..00000000 --- a/solutions/0845-longest-mountain-in-array.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 845. Longest Mountain in Array - * https://leetcode.com/problems/longest-mountain-in-array/ - * Difficulty: Medium - * - * You may recall that an array arr is a mountain array if and only if: - * - arr.length >= 3 - * - There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: - * - arr[0] < arr[1] < ... < arr[i - 1] < arr[i] - * - arr[i] > arr[i + 1] > ... > arr[arr.length - 1] - * - * Given an integer array arr, return the length of the longest subarray, which is a - * mountain. Return 0 if there is no mountain subarray. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var longestMountain = function(arr) { - const n = arr.length; - if (n < 3) return 0; - - let maxLength = 0; - let i = 1; - - while (i < n - 1) { - const isPeak = arr[i] > arr[i - 1] && arr[i] > arr[i + 1]; - if (!isPeak) { - i++; - continue; - } - let leftBound = i - 1; - while (leftBound > 0 && arr[leftBound - 1] < arr[leftBound]) { - leftBound--; - } - let rightBound = i + 1; - while (rightBound < n - 1 && arr[rightBound] > arr[rightBound + 1]) { - rightBound++; - } - const mountainLength = rightBound - leftBound + 1; - maxLength = Math.max(maxLength, mountainLength); - i = rightBound + 1; - } - - return maxLength; -}; diff --git a/solutions/0847-shortest-path-visiting-all-nodes.js b/solutions/0847-shortest-path-visiting-all-nodes.js deleted file mode 100644 index f15b5eac..00000000 --- a/solutions/0847-shortest-path-visiting-all-nodes.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 847. Shortest Path Visiting All Nodes - * https://leetcode.com/problems/shortest-path-visiting-all-nodes/ - * Difficulty: Hard - * - * You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an - * array graph where graph[i] is a list of all the nodes connected with node i by an edge. - * - * Return the length of the shortest path that visits every node. You may start and stop at any - * node, you may revisit nodes multiple times, and you may reuse edges. - */ - -/** - * @param {number[][]} graph - * @return {number} - */ -var shortestPathLength = function(graph) { - const n = graph.length; - - if (n === 1) return 0; - - const allVisited = (1 << n) - 1; - const queue = []; - const visited = new Set(); - - for (let i = 0; i < n; i++) { - const initialState = (1 << i); - queue.push([i, initialState, 0]); - visited.add(`${i},${initialState}`); - } - - while (queue.length > 0) { - const [node, state, distance] = queue.shift(); - if (state === allVisited) { - return distance; - } - for (const neighbor of graph[node]) { - const newState = state | (1 << neighbor); - const key = `${neighbor},${newState}`; - if (!visited.has(key)) { - visited.add(key); - queue.push([neighbor, newState, distance + 1]); - } - } - } - - return -1; -}; diff --git a/solutions/0848-shifting-letters.js b/solutions/0848-shifting-letters.js deleted file mode 100644 index 0ca7b33a..00000000 --- a/solutions/0848-shifting-letters.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 848. Shifting Letters - * https://leetcode.com/problems/shifting-letters/ - * Difficulty: Medium - * - * You are given a string s of lowercase English letters and an integer array shifts of the - * same length. - * - * Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that - * 'z' becomes 'a'). - * - * For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. - * - * Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. - * - * Return the final string after all such shifts to s are applied. - */ - -/** - * @param {string} s - * @param {number[]} shifts - * @return {string} - */ -var shiftingLetters = function(s, shifts) { - const cumulativeShifts = new Array(s.length).fill(0); - - cumulativeShifts[s.length - 1] = shifts[s.length - 1] % 26; - for (let i = s.length - 2; i >= 0; i--) { - cumulativeShifts[i] = (cumulativeShifts[i + 1] + shifts[i]) % 26; - } - - let result = ''; - for (let i = 0; i < s.length; i++) { - const charCode = s.charCodeAt(i); - const shiftedCode = ((charCode - 97 + cumulativeShifts[i]) % 26) + 97; - result += String.fromCharCode(shiftedCode); - } - - return result; -}; diff --git a/solutions/0849-maximize-distance-to-closest-person.js b/solutions/0849-maximize-distance-to-closest-person.js deleted file mode 100644 index b59dd148..00000000 --- a/solutions/0849-maximize-distance-to-closest-person.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 849. Maximize Distance to Closest Person - * https://leetcode.com/problems/maximize-distance-to-closest-person/ - * Difficulty: Medium - * - * You are given an array representing a row of seats where seats[i] = 1 represents a person - * sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). - * - * There is at least one empty seat, and at least one person sitting. - * - * Alex wants to sit in the seat such that the distance between him and the closest person to - * him is maximized. - * - * Return that maximum distance to the closest person. - */ - -/** - * @param {number[]} seats - * @return {number} - */ -var maxDistToClosest = function(seats) { - let lastOccupied = -1; - let result = 0; - - for (let i = 0; i < seats.length; i++) { - if (seats[i] === 1) { - if (lastOccupied === -1) { - result = i; - } else { - result = Math.max(result, Math.floor((i - lastOccupied) / 2)); - } - lastOccupied = i; - } - } - - if (lastOccupied !== seats.length - 1) { - result = Math.max(result, seats.length - 1 - lastOccupied); - } - - return result; -}; diff --git a/solutions/0850-rectangle-area-ii.js b/solutions/0850-rectangle-area-ii.js deleted file mode 100644 index 7a4b58fe..00000000 --- a/solutions/0850-rectangle-area-ii.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 850. Rectangle Area II - * https://leetcode.com/problems/rectangle-area-ii/ - * Difficulty: Hard - * - * You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] - * denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and - * (xi2, yi2) are the coordinates of the top-right corner. - * - * Calculate the total area covered by all rectangles in the plane. Any area covered by two or more - * rectangles should only be counted once. - * - * Return the total area. Since the answer may be too large, return it modulo 109 + 7. - */ - -/** - * @param {number[][]} rectangles - * @return {number} - */ -var rectangleArea = function(rectangles) { - const MOD = 1e9 + 7; - const events = []; - const xCoords = new Set(); - const yCoords = new Set(); - - for (const [x1, y1, x2, y2] of rectangles) { - xCoords.add(x1); - xCoords.add(x2); - yCoords.add(y1); - yCoords.add(y2); - events.push([x1, 1, y1, y2]); - events.push([x2, -1, y1, y2]); - } - - const xArray = [...xCoords].sort((a, b) => a - b); - const yArray = [...yCoords].sort((a, b) => a - b); - - const xMap = new Map(); - const yMap = new Map(); - - for (let i = 0; i < xArray.length; i++) { - xMap.set(xArray[i], i); - } - - for (let i = 0; i < yArray.length; i++) { - yMap.set(yArray[i], i); - } - - const grid = Array(xArray.length).fill(0).map(() => Array(yArray.length).fill(0)); - - for (const [x1, y1, x2, y2] of rectangles) { - for (let x = xMap.get(x1); x < xMap.get(x2); x++) { - for (let y = yMap.get(y1); y < yMap.get(y2); y++) { - grid[x][y] = 1; - } - } - } - - let totalArea = 0; - - for (let x = 0; x < xArray.length - 1; x++) { - for (let y = 0; y < yArray.length - 1; y++) { - if (grid[x][y]) { - const width = xArray[x + 1] - xArray[x]; - const height = yArray[y + 1] - yArray[y]; - totalArea = (totalArea + width * height) % MOD; - } - } - } - - return totalArea; -}; diff --git a/solutions/0851-loud-and-rich.js b/solutions/0851-loud-and-rich.js deleted file mode 100644 index f2fda135..00000000 --- a/solutions/0851-loud-and-rich.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 851. Loud and Rich - * https://leetcode.com/problems/loud-and-rich/ - * Difficulty: Medium - * - * There is a group of n people labeled from 0 to n - 1 where each person has a different amount - * of money and a different level of quietness. - * - * You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than - * bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given - * data in richer are logically correct (i.e., the data will not lead you to a situation where x - * is richer than y and y is richer than x at the same time). - * - * Return an integer array answer where answer[x] = y if y is the least quiet person (that is, - * the person y with the smallest value of quiet[y]) among all people who definitely have equal - * to or more money than the person x. - */ - -/** - * @param {number[][]} richer - * @param {number[]} quiet - * @return {number[]} - */ -var loudAndRich = function(richer, quiet) { - const graph = new Array(quiet.length).fill().map(() => []); - const result = new Array(quiet.length).fill(-1); - - for (const [a, b] of richer) { - graph[b].push(a); - } - - function dfs(person) { - if (result[person] !== -1) return result[person]; - - let quietestPerson = person; - - for (const richerPerson of graph[person]) { - const candidate = dfs(richerPerson); - if (quiet[candidate] < quiet[quietestPerson]) { - quietestPerson = candidate; - } - } - - result[person] = quietestPerson; - return quietestPerson; - } - - for (let i = 0; i < quiet.length; i++) { - dfs(i); - } - - return result; -}; diff --git a/solutions/0852-peak-index-in-a-mountain-array.js b/solutions/0852-peak-index-in-a-mountain-array.js deleted file mode 100644 index 404ae5f0..00000000 --- a/solutions/0852-peak-index-in-a-mountain-array.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 852. Peak Index in a Mountain Array - * https://leetcode.com/problems/peak-index-in-a-mountain-array/ - * Difficulty: Medium - * - * You are given an integer mountain array arr of length n where the values increase to a peak - * element and then decrease. - * - * Return the index of the peak element. - * - * Your task is to solve it in O(log(n)) time complexity. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var peakIndexInMountainArray = function(arr) { - let left = 0; - let right = arr.length - 1; - - while (left < right) { - const middle = Math.floor((left + right) / 2); - - if (arr[middle] > arr[middle + 1]) { - right = middle; - } else { - left = middle + 1; - } - } - - return left; -}; diff --git a/solutions/0853-car-fleet.js b/solutions/0853-car-fleet.js deleted file mode 100644 index cff9b211..00000000 --- a/solutions/0853-car-fleet.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 853. Car Fleet - * https://leetcode.com/problems/car-fleet/ - * Difficulty: Medium - * - * There are n cars at given miles away from the starting mile 0, traveling to reach the mile - * target. - * - * You are given two integer array position and speed, both of length n, where position[i] - * is the starting mile of the ith car and speed[i] is the speed of the ith car in miles per hour. - * - * A car cannot pass another car, but it can catch up and then travel next to it at the speed of - * the slower car. - * - * A car fleet is a car or cars driving next to each other. The speed of the car fleet is the - * minimum speed of any car in the fleet. - * - * If a car catches up to a car fleet at the mile target, it will still be considered as part - * of the car fleet. - * - * Return the number of car fleets that will arrive at the destination. - */ - -/** - * @param {number} target - * @param {number[]} position - * @param {number[]} speed - * @return {number} - */ -var carFleet = function(target, position, speed) { - const cars = position.map((pos, i) => ({ - position: pos, - timeToTarget: (target - pos) / speed[i] - })); - cars.sort((a, b) => b.position - a.position); - - let slowestTime = 0; - let result = 0; - for (const car of cars) { - if (car.timeToTarget > slowestTime) { - result++; - slowestTime = car.timeToTarget; - } - } - - return result; -}; diff --git a/solutions/0854-k-similar-strings.js b/solutions/0854-k-similar-strings.js deleted file mode 100644 index d1b48a75..00000000 --- a/solutions/0854-k-similar-strings.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 854. K-Similar Strings - * https://leetcode.com/problems/k-similar-strings/ - * Difficulty: Hard - * - * Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions - * of two letters in s1 exactly k times so that the resulting string equals s2. - * - * Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar. - */ - -/** - * @param {string} s1 - * @param {string} s2 - * @return {number} - */ -var kSimilarity = function(s1, s2) { - if (s1 === s2) return 0; - const queue = [s1]; - const visited = new Set([s1]); - let swaps = 0; - - while (queue.length) { - const size = queue.length; - for (let i = 0; i < size; i++) { - const current = queue.shift(); - if (current === s2) return swaps; - let j = 0; - while (j < current.length && current[j] === s2[j]) j++; - for (let k = j + 1; k < current.length; k++) { - if (current[k] === s2[j] && current[k] !== s2[k]) { - const nextStr = swap(current, j, k); - - if (!visited.has(nextStr)) { - if (nextStr === s2) return swaps + 1; - visited.add(nextStr); - queue.push(nextStr); - } - } - } - } - swaps++; - } - - return swaps; -}; - -function swap(str, i, j) { - const chars = str.split(''); - [chars[i], chars[j]] = [chars[j], chars[i]]; - return chars.join(''); -} diff --git a/solutions/0855-exam-room.js b/solutions/0855-exam-room.js deleted file mode 100644 index 1cc1ffa0..00000000 --- a/solutions/0855-exam-room.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * 855. Exam Room - * https://leetcode.com/problems/exam-room/ - * Difficulty: Medium - * - * There is an exam room with n seats in a single row labeled from 0 to n - 1. - * - * When a student enters the room, they must sit in the seat that maximizes the distance to the - * closest person. If there are multiple such seats, they sit in the seat with the lowest number. - * If no one is in the room, then the student sits at seat number 0. - * - * Design a class that simulates the mentioned exam room. - * - * Implement the ExamRoom class: - * - ExamRoom(int n) Initializes the object of the exam room with the number of the seats n. - * - int seat() Returns the label of the seat at which the next student will set. - * - void leave(int p) Indicates that the student sitting at seat p will leave the room. It is - * guaranteed that there will be a student sitting at seat p. - */ - -/** - * @param {number} n - Number of seats in the exam room - */ -var ExamRoom = function(n) { - this.n = n; - this.seats = []; -}; - -/** - * @return {number} - */ -ExamRoom.prototype.seat = function() { - if (this.seats.length === 0) { - this.seats.push(0); - return 0; - } - - let maxDistance = this.seats[0]; - let chosenSeat = 0; - - for (let i = 1; i < this.seats.length; i++) { - const distance = Math.floor((this.seats[i] - this.seats[i-1]) / 2); - if (distance > maxDistance) { - maxDistance = distance; - chosenSeat = Math.floor((this.seats[i] + this.seats[i-1]) / 2); - } - } - - const endDistance = this.n - 1 - this.seats[this.seats.length - 1]; - if (endDistance > maxDistance) { - chosenSeat = this.n - 1; - maxDistance = endDistance; - } - - const insertPosition = this.findInsertPosition(chosenSeat); - this.seats.splice(insertPosition, 0, chosenSeat); - - return chosenSeat; -}; - -/** - * @param {number} p - * @return {void} - */ -ExamRoom.prototype.leave = function(p) { - const index = this.seats.indexOf(p); - this.seats.splice(index, 1); -}; - -/** - * @param {number} seat - * @return {number} - */ -ExamRoom.prototype.findInsertPosition = function(seat) { - let left = 0; - let right = this.seats.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (this.seats[mid] < seat) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return left; -}; diff --git a/solutions/0856-score-of-parentheses.js b/solutions/0856-score-of-parentheses.js deleted file mode 100644 index 7c4b800e..00000000 --- a/solutions/0856-score-of-parentheses.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 856. Score of Parentheses - * https://leetcode.com/problems/score-of-parentheses/ - * Difficulty: Medium - * - * Given a balanced parentheses string s, return the score of the string. - * - * The score of a balanced parentheses string is based on the following rule: - * - "()" has score 1. - * - AB has score A + B, where A and B are balanced parentheses strings. - * - (A) has score 2 * A, where A is a balanced parentheses string. - */ - -/** - * @param {string} s - * @return {number} - */ -var scoreOfParentheses = function(s) { - const stack = [0]; - - for (const char of s) { - if (char === '(') { - stack.push(0); - } else { - const value = stack.pop(); - stack[stack.length - 1] += Math.max(2 * value, 1); - } - } - - return stack[0]; -}; diff --git a/solutions/0857-minimum-cost-to-hire-k-workers.js b/solutions/0857-minimum-cost-to-hire-k-workers.js deleted file mode 100644 index d4252c68..00000000 --- a/solutions/0857-minimum-cost-to-hire-k-workers.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 857. Minimum Cost to Hire K Workers - * https://leetcode.com/problems/minimum-cost-to-hire-k-workers/ - * Difficulty: Hard - * - * There are n workers. You are given two integer arrays quality and wage where quality[i] is the - * quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker. - * - * We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must - * pay them according to the following rules: - * 1. Every worker in the paid group must be paid at least their minimum wage expectation. - * 2. In the group, each worker's pay must be directly proportional to their quality. This means - * if a worker’s quality is double that of another worker in the group, then they must be paid - * twice as much as the other worker. - * - * Given the integer k, return the least amount of money needed to form a paid group satisfying - * the above conditions. Answers within 10-5 of the actual answer will be accepted. - */ - -/** - * @param {number[]} quality - * @param {number[]} wage - * @param {number} k - * @return {number} - */ -var mincostToHireWorkers = function(quality, wage, k) { - const workers = quality.map((q, i) => ({ ratio: wage[i] / q, quality: q })) - .sort((a, b) => a.ratio - b.ratio); - - let result = Infinity; - let qualitySum = 0; - const maxHeap = new MaxPriorityQueue(); - - for (const worker of workers) { - maxHeap.enqueue(worker.quality); - qualitySum += worker.quality; - - if (maxHeap.size() > k) { - qualitySum -= maxHeap.dequeue(); - } - - if (maxHeap.size() === k) { - result = Math.min(result, qualitySum * worker.ratio); - } - } - - return result; -}; diff --git a/solutions/0858-mirror-reflection.js b/solutions/0858-mirror-reflection.js deleted file mode 100644 index 60470566..00000000 --- a/solutions/0858-mirror-reflection.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 858. Mirror Reflection - * https://leetcode.com/problems/mirror-reflection/ - * Difficulty: Medium - * - * There is a special square room with mirrors on each of the four walls. Except for the southwest - * corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. - * - * The square room has walls of length p and a laser ray from the southwest corner first meets the - * east wall at a distance q from the 0th receptor. - * - * Given the two integers p and q, return the number of the receptor that the ray meets first. - * - * The test cases are guaranteed so that the ray will meet a receptor eventually. - */ - -/** - * @param {number} p - * @param {number} q - * @return {number} - */ -var mirrorReflection = function(p, q) { - const gcd = findGCD(p, q); - const m = q / gcd; - const n = p / gcd; - - if (m % 2 === 0) return 0; - return n % 2 === 1 ? 1 : 2; -}; - -function findGCD(a, b) { - return b === 0 ? a : findGCD(b, a % b); -} diff --git a/solutions/0859-buddy-strings.js b/solutions/0859-buddy-strings.js deleted file mode 100644 index 5b092d0b..00000000 --- a/solutions/0859-buddy-strings.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 859. Buddy Strings - * https://leetcode.com/problems/buddy-strings/ - * Difficulty: Easy - * - * Given two strings s and goal, return true if you can swap two letters in s so the result is - * equal to goal, otherwise, return false. - * - * Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and - * swapping the characters at s[i] and s[j]. - * - * For example, swapping at indices 0 and 2 in "abcd" results in "cbad". - */ - -/** - * @param {string} s - * @param {string} goal - * @return {boolean} - */ -var buddyStrings = function(s, goal) { - if (s.length !== goal.length) return false; - - const differences = []; - const charCount = new Map(); - let hasDuplicate = false; - - for (let i = 0; i < s.length; i++) { - if (s[i] !== goal[i]) { - differences.push(i); - if (differences.length > 2) return false; - } - charCount.set(s[i], (charCount.get(s[i]) || 0) + 1); - if (charCount.get(s[i]) > 1) hasDuplicate = true; - } - - if (differences.length === 0) return hasDuplicate; - if (differences.length !== 2) return false; - - const [first, second] = differences; - return s[first] === goal[second] && s[second] === goal[first]; -}; diff --git a/solutions/0860-lemonade-change.js b/solutions/0860-lemonade-change.js deleted file mode 100644 index f728c9c3..00000000 --- a/solutions/0860-lemonade-change.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 860. Lemonade Change - * https://leetcode.com/problems/lemonade-change/ - * Difficulty: Easy - * - * At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you - * and order one at a time (in the order specified by bills). Each customer will only buy one - * lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to - * each customer so that the net transaction is that the customer pays $5. - * - * Note that you do not have any change in hand at first. - * - * Given an integer array bills where bills[i] is the bill the ith customer pays, return true if - * you can provide every customer with the correct change, or false otherwise. - */ - -/** - * @param {number[]} bills - * @return {boolean} - */ -var lemonadeChange = function(bills) { - let fives = 0; - let tens = 0; - - for (const bill of bills) { - if (bill === 5) { - fives++; - } else if (bill === 10) { - if (fives === 0) return false; - fives--; - tens++; - } else { - if (tens > 0 && fives > 0) { - tens--; - fives--; - } else if (fives >= 3) { - fives -= 3; - } else { - return false; - } - } - } - - return true; -}; diff --git a/solutions/0861-score-after-flipping-matrix.js b/solutions/0861-score-after-flipping-matrix.js deleted file mode 100644 index b6fd1818..00000000 --- a/solutions/0861-score-after-flipping-matrix.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 861. Score After Flipping Matrix - * https://leetcode.com/problems/score-after-flipping-matrix/ - * Difficulty: Medium - * - * You are given an m x n binary matrix grid. - * - * A move consists of choosing any row or column and toggling each value in that row or - * column (i.e., changing all 0's to 1's, and all 1's to 0's). - * - * Every row of the matrix is interpreted as a binary number, and the score of the matrix - * is the sum of these numbers. - * - * Return the highest possible score after making any number of moves (including zero moves). - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var matrixScore = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - - for (let row = 0; row < rows; row++) { - if (grid[row][0] === 0) { - for (let col = 0; col < cols; col++) { - grid[row][col] ^= 1; - } - } - } - - let result = rows * (1 << (cols - 1)); - - for (let col = 1; col < cols; col++) { - let onesCount = 0; - for (let row = 0; row < rows; row++) { - onesCount += grid[row][col]; - } - const maxOnes = Math.max(onesCount, rows - onesCount); - result += maxOnes * (1 << (cols - 1 - col)); - } - - return result; -}; diff --git a/solutions/0862-shortest-subarray-with-sum-at-least-k.js b/solutions/0862-shortest-subarray-with-sum-at-least-k.js deleted file mode 100644 index 4fe151de..00000000 --- a/solutions/0862-shortest-subarray-with-sum-at-least-k.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 862. Shortest Subarray with Sum at Least K - * https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/ - * Difficulty: Hard - * - * Given an integer array nums and an integer k, return the length of the shortest non-empty - * subarray of nums with a sum of at least k. If there is no such subarray, return -1. - * - * A subarray is a contiguous part of an array. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var shortestSubarray = function(nums, k) { - const prefixSums = [0]; - for (let i = 0; i < nums.length; i++) { - prefixSums.push(prefixSums[i] + nums[i]); - } - - const deque = []; - let shortestLength = Infinity; - - for (let i = 0; i < prefixSums.length; i++) { - while (deque.length && prefixSums[i] - prefixSums[deque[0]] >= k) { - shortestLength = Math.min(shortestLength, i - deque.shift()); - } - while (deque.length && prefixSums[i] <= prefixSums[deque[deque.length - 1]]) { - deque.pop(); - } - deque.push(i); - } - - return shortestLength === Infinity ? -1 : shortestLength; -}; diff --git a/solutions/0863-all-nodes-distance-k-in-binary-tree.js b/solutions/0863-all-nodes-distance-k-in-binary-tree.js deleted file mode 100644 index 524e4cdd..00000000 --- a/solutions/0863-all-nodes-distance-k-in-binary-tree.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 863. All Nodes Distance K in Binary Tree - * https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/ - * Difficulty: Medium - * - * Given the root of a binary tree, the value of a target node target, and an integer k, return an - * array of the values of all nodes that have a distance k from the target node. - * - * You can return the answer in any order. - */ - -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} target - * @param {number} k - * @return {number[]} - */ -var distanceK = function(root, target, k) { - const graph = new Map(); - const result = []; - - buildGraph(root, null); - findNodesAtDistance(target.val, 0, new Set()); - - return result; - - function buildGraph(node, parent) { - if (!node) return; - if (parent) { - graph.set(node.val, graph.get(node.val) || new Set()); - graph.get(node.val).add(parent.val); - graph.set(parent.val, graph.get(parent.val) || new Set()); - graph.get(parent.val).add(node.val); - } - buildGraph(node.left, node); - buildGraph(node.right, node); - } - - function findNodesAtDistance(currentVal, distance, visited) { - if (distance === k) { - result.push(currentVal); - return; - } - visited.add(currentVal); - const neighbors = graph.get(currentVal) || new Set(); - for (const neighbor of neighbors) { - if (!visited.has(neighbor)) { - findNodesAtDistance(neighbor, distance + 1, visited); - } - } - } -}; diff --git a/solutions/0864-shortest-path-to-get-all-keys.js b/solutions/0864-shortest-path-to-get-all-keys.js deleted file mode 100644 index 17c9c7c0..00000000 --- a/solutions/0864-shortest-path-to-get-all-keys.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * 864. Shortest Path to Get All Keys - * https://leetcode.com/problems/shortest-path-to-get-all-keys/ - * Difficulty: Hard - * - * You are given an m x n grid grid where: - * - '.' is an empty cell. - * - '#' is a wall. - * - '@' is the starting point. - * - Lowercase letters represent keys. - * - Uppercase letters represent locks. - * - * You start at the starting point and one move consists of walking one space in one of the - * four cardinal directions. You cannot walk outside the grid, or walk into a wall. - * - * If you walk over a key, you can pick it up and you cannot walk over a lock unless you have - * its corresponding key. - * - * For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first - * k letters of the English alphabet in the grid. This means that there is exactly one key for - * each lock, and one lock for each key; and also that the letters used to represent the keys - * and locks were chosen in the same order as the English alphabet. - * - * Return the lowest number of moves to acquire all keys. If it is impossible, return -1. - */ - -/** - * @param {string[]} grid - * @return {number} - */ -var shortestPathAllKeys = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - let startRow; - let startCol; - let totalKeys = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j] === '@') { - startRow = i; - startCol = j; - } else if (/[a-f]/.test(grid[i][j])) { - totalKeys++; - } - } - } - - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - const queue = [[startRow, startCol, 0, 0]]; - const visited = new Set([`${startRow},${startCol},0`]); - - while (queue.length) { - const [row, col, keys, steps] = queue.shift(); - if (keys === (1 << totalKeys) - 1) return steps; - for (const [dr, dc] of directions) { - const newRow = row + dr; - const newCol = col + dc; - - if (newRow >= 0 && newRow < rows && newCol >= 0 - && newCol < cols && grid[newRow][newCol] !== '#') { - const cell = grid[newRow][newCol]; - const newKeys = /[a-f]/.test(cell) - ? keys | (1 << (cell.charCodeAt(0) - 97)) - : keys; - - if (/[A-F]/.test(cell) && !(keys & (1 << (cell.charCodeAt(0) - 65)))) continue; - const state = `${newRow},${newCol},${newKeys}`; - if (!visited.has(state)) { - visited.add(state); - queue.push([newRow, newCol, newKeys, steps + 1]); - } - } - } - } - - return -1; -}; diff --git a/solutions/0865-smallest-subtree-with-all-the-deepest-nodes.js b/solutions/0865-smallest-subtree-with-all-the-deepest-nodes.js deleted file mode 100644 index 61ae3c26..00000000 --- a/solutions/0865-smallest-subtree-with-all-the-deepest-nodes.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 865. Smallest Subtree with all the Deepest Nodes - * https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/ - * Difficulty: Medium - * - * Given the root of a binary tree, the depth of each node is the shortest distance to the root. - * - * Return the smallest subtree such that it contains all the deepest nodes in the original tree. - * - * A node is called the deepest if it has the largest depth possible among any node in the entire - * tree. - * - * The subtree of a node is a tree consisting of that node, plus the set of all descendants of - * that 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 {TreeNode} - */ -var subtreeWithAllDeepest = function(root) { - return findDepthAndNode(root).node; - - function findDepthAndNode(node) { - if (!node) return { depth: 0, node: null }; - - const left = findDepthAndNode(node.left); - const right = findDepthAndNode(node.right); - - if (left.depth === right.depth) { - return { depth: left.depth + 1, node: node }; - } - const deeper = left.depth > right.depth ? left : right; - return { depth: deeper.depth + 1, node: deeper.node }; - } -}; diff --git a/solutions/0866-prime-palindrome.js b/solutions/0866-prime-palindrome.js deleted file mode 100644 index 462fca63..00000000 --- a/solutions/0866-prime-palindrome.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 866. Prime Palindrome - * https://leetcode.com/problems/prime-palindrome/ - * Difficulty: Medium - * - * Given an integer n, return the smallest prime palindrome greater than or equal to n. - * - * An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime - * number. - * - For example, 2, 3, 5, 7, 11, and 13 are all primes. - * - * An integer is a palindrome if it reads the same from left to right as it does from right to left. - * - For example, 101 and 12321 are palindromes. - * - * The test cases are generated so that the answer always exists and is in the range [2, 2 * 108]. - */ - -/** - * @param {number} n - * @return {number} - */ -var primePalindrome = function(start) { - while (true) { - const numStr = start.toString(); - if (numStr.length % 2 === 0 && start > 11) { - start = 10 ** Math.ceil(Math.log10(start + 1)); - continue; - } - if (!isPalindrome(numStr)) { - start++; - continue; - } - if (isPrime(start)) return start; - start++; - } -}; - -function isPrime(num) { - if (num <= 1) return false; - if (num <= 3) return true; - if (num % 2 === 0 || num % 3 === 0) return false; - for (let i = 3; i <= Math.sqrt(num) + 1; i += 2) { - if (num % i === 0) return false; - } - return true; -} - -function isPalindrome(str) { - let left = 0; - let right = str.length - 1; - while (left < right) { - if (str[left++] !== str[right--]) return false; - } - return true; -} diff --git a/solutions/0869-reordered-power-of-2.js b/solutions/0869-reordered-power-of-2.js deleted file mode 100644 index 74bd4cf5..00000000 --- a/solutions/0869-reordered-power-of-2.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 869. Reordered Power of 2 - * https://leetcode.com/problems/reordered-power-of-2/ - * Difficulty: Medium - * - * You are given an integer n. We reorder the digits in any order (including the original order) - * such that the leading digit is not zero. - * - * Return true if and only if we can do this so that the resulting number is a power of two. - */ - -/** - * @param {number} n - * @return {boolean} - */ -var reorderedPowerOf2 = function(n) { - const numSignature = getDigitCount(n); - const maxPower = Math.floor(Math.log2(10 ** 9)); - - for (let i = 0; i <= maxPower; i++) { - if (getDigitCount(1 << i) === numSignature) return true; - } - - return false; - - function getDigitCount(num) { - const count = Array(10).fill(0); - while (num > 0) { - count[num % 10]++; - num = Math.floor(num / 10); - } - return count.join(''); - } -}; diff --git a/solutions/0870-advantage-shuffle.js b/solutions/0870-advantage-shuffle.js deleted file mode 100644 index 982db9ca..00000000 --- a/solutions/0870-advantage-shuffle.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 870. Advantage Shuffle - * https://leetcode.com/problems/advantage-shuffle/ - * Difficulty: Medium - * - * You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 - * with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. - * - * Return any permutation of nums1 that maximizes its advantage with respect to nums2. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var advantageCount = function(nums1, nums2) { - const sortedNums1 = [...nums1].sort((a, b) => a - b); - const indexedNums2 = nums2.map((val, idx) => ({ val, idx })) - .sort((a, b) => a.val - b.val); - - const result = new Array(nums1.length); - let left = 0; - let right = nums1.length - 1; - - for (let i = nums1.length - 1; i >= 0; i--) { - const current = indexedNums2[i]; - if (sortedNums1[right] > current.val) { - result[current.idx] = sortedNums1[right--]; - } else { - result[current.idx] = sortedNums1[left++]; - } - } - - return result; -}; diff --git a/solutions/0871-minimum-number-of-refueling-stops.js b/solutions/0871-minimum-number-of-refueling-stops.js deleted file mode 100644 index 9fbb9132..00000000 --- a/solutions/0871-minimum-number-of-refueling-stops.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 871. Minimum Number of Refueling Stops - * https://leetcode.com/problems/minimum-number-of-refueling-stops/ - * Difficulty: Hard - * - * A car travels from a starting position to a destination which is target miles east of the - * starting position. - * - * There are gas stations along the way. The gas stations are represented as an array stations - * where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles - * east of the starting position and has fueli liters of gas. - * - * The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in - * it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, - * it may stop and refuel, transferring all the gas from the station into the car. - * - * Return the minimum number of refueling stops the car must make in order to reach its destination. - * If it cannot reach the destination, return -1. - * - * Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. - * If the car reaches the destination with 0 fuel left, it is still considered to have arrived. - */ - -/** - * @param {number} target - * @param {number} startFuel - * @param {number[][]} stations - * @return {number} - */ -var minRefuelStops = function(target, startFuel, stations) { - const dp = [startFuel]; - const stationCount = stations.length; - - for (let i = 0; i < stationCount; i++) { - dp.push(0); - for (let stops = i; stops >= 0; stops--) { - if (dp[stops] >= stations[i][0]) { - dp[stops + 1] = Math.max(dp[stops + 1], dp[stops] + stations[i][1]); - } - } - } - - for (let stops = 0; stops <= stationCount; stops++) { - if (dp[stops] >= target) return stops; - } - - return -1; -}; diff --git a/solutions/0874-walking-robot-simulation.js b/solutions/0874-walking-robot-simulation.js deleted file mode 100644 index 6dd25be6..00000000 --- a/solutions/0874-walking-robot-simulation.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 874. Walking Robot Simulation - * https://leetcode.com/problems/walking-robot-simulation/ - * Difficulty: Medium - * - * A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot receives an array - * of integers commands, which represents a sequence of moves that it needs to execute. There are - * only three possible types of instructions the robot can receive: - * - -2: Turn left 90 degrees. - * - -1: Turn right 90 degrees. - * - 1 <= k <= 9: Move forward k units, one unit at a time. - * - * Some of the grid squares are obstacles. The ith obstacle is at grid point - * obstacles[i] = (xi, yi). If the robot runs into an obstacle, it will stay in its current location - * (on the block adjacent to the obstacle) and move onto the next command. - * - * Return the maximum squared Euclidean distance that the robot reaches at any point in its path - * (i.e. if the distance is 5, return 25). - * - * Note: - * - There can be an obstacle at (0, 0). If this happens, the robot will ignore the obstacle until - * it has moved off the origin. However, it will be unable to return to (0, 0) due to the - * obstacle. - * - North means +Y direction. - * - East means +X direction. - * - South means -Y direction. - * - West means -X direction. - */ - -/** - * @param {number[]} commands - * @param {number[][]} obstacles - * @return {number} - */ -var robotSim = function(commands, obstacles) { - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - const obstacleSet = new Set(obstacles.map(([x, y]) => `${x},${y}`)); - - let x = 0; - let y = 0; - let directionIndex = 0; - let result = 0; - - for (const command of commands) { - if (command === -1) { - directionIndex = (directionIndex + 1) % 4; - } else if (command === -2) { - directionIndex = (directionIndex + 3) % 4; - } else { - const [dx, dy] = directions[directionIndex]; - for (let step = 0; step < command; step++) { - const nextX = x + dx; - const nextY = y + dy; - if (obstacleSet.has(`${nextX},${nextY}`)) break; - x = nextX; - y = nextY; - result = Math.max(result, x * x + y * y); - } - } - } - - return result; -}; diff --git a/solutions/0875-koko-eating-bananas.js b/solutions/0875-koko-eating-bananas.js deleted file mode 100644 index 68ee313c..00000000 --- a/solutions/0875-koko-eating-bananas.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 875. Koko Eating Bananas - * https://leetcode.com/problems/koko-eating-bananas/ - * Difficulty: Medium - * - * Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. - * The guards have gone and will come back in h hours. - * - * Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of - * bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats - * all of them instead and will not eat any more bananas during this hour. - * - * Koko likes to eat slowly but still wants to finish eating all the bananas before the guards - * return. - * - * Return the minimum integer k such that she can eat all the bananas within h hours. - */ - -/** - * @param {number[]} piles - * @param {number} h - * @return {number} - */ -var minEatingSpeed = function(piles, h) { - const fn = speed => piles.reduce((sum, pile) => sum + Math.ceil(pile / speed), 0); - let min = 1; - let max = Math.max(...piles); - let result = max; - - while (min <= max) { - const middle = Math.floor((min + max) / 2); - - if (fn(middle) <= h) { - result = middle; - max = middle - 1; - } else { - min = middle + 1; - } - } - - return result; -}; diff --git a/solutions/0877-stone-game.js b/solutions/0877-stone-game.js deleted file mode 100644 index 007b050a..00000000 --- a/solutions/0877-stone-game.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 877. Stone Game - * https://leetcode.com/problems/stone-game/ - * Difficulty: Medium - * - * Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a - * row, and each pile has a positive integer number of stones piles[i]. - * - * The objective of the game is to end with the most stones. The total number of stones across all - * the piles is odd, so there are no ties. - * - * Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile - * of stones either from the beginning or from the end of the row. This continues until there are - * no more piles left, at which point the person with the most stones wins. - * - * Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. - */ - -/** - * @param {number[]} piles - * @return {boolean} - */ -var stoneGame = function(piles) { - return true; -}; diff --git a/solutions/0878-nth-magical-number.js b/solutions/0878-nth-magical-number.js deleted file mode 100644 index a8f9c691..00000000 --- a/solutions/0878-nth-magical-number.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 878. Nth Magical Number - * https://leetcode.com/problems/nth-magical-number/ - * Difficulty: Hard - * - * A positive integer is magical if it is divisible by either a or b. - * - * Given the three integers n, a, and b, return the nth magical number. Since the answer may be - * very large, return it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} a - * @param {number} b - */ -var nthMagicalNumber = function(n, a, b) { - const MOD = 1e9 + 7; - const lcm = (a * b) / gcd(a, b); - const cycleNumbers = lcm / a + lcm / b - 1; - const cycles = Math.floor(n / cycleNumbers); - const remainder = n % cycleNumbers; - - const result = (cycles * lcm) % MOD; - if (remainder === 0) return result; - - let left = 1; - let right = lcm; - while (left < right) { - const mid = left + Math.floor((right - left) / 2); - const count = Math.floor(mid / a) + Math.floor(mid / b) - Math.floor(mid / lcm); - if (count < remainder) left = mid + 1; - else right = mid; - } - - return (result + left) % MOD; - - function gcd(x, y) { - return y === 0 ? x : gcd(y, x % y); - } -}; diff --git a/solutions/0879-profitable-schemes.js b/solutions/0879-profitable-schemes.js deleted file mode 100644 index 948d5169..00000000 --- a/solutions/0879-profitable-schemes.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 879. Profitable Schemes - * https://leetcode.com/problems/profitable-schemes/ - * Difficulty: Hard - * - * There is a group of n members, and a list of various crimes they could commit. The ith crime - * generates a profit[i] and requires group[i] members to participate in it. If a member - * participates in one crime, that member can't participate in another crime. - * - * Let's call a profitable scheme any subset of these crimes that generates at least minProfit - * profit, and the total number of members participating in that subset of crimes is at most n. - * - * Return the number of schemes that can be chosen. Since the answer may be very large, return - * it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} minProfit - * @param {number[]} group - * @param {number[]} profit - * @return {number} - */ -var profitableSchemes = function(n, minProfit, group, profit) { - const MOD = 1e9 + 7; - const dp = Array.from({ length: group.length + 1 }, () => - Array.from({ length: n + 1 }, () => new Array(minProfit + 1).fill(0)) - ); - - dp[0][0][0] = 1; - - for (let crime = 1; crime <= group.length; crime++) { - const membersNeeded = group[crime - 1]; - const profitGained = profit[crime - 1]; - - for (let members = 0; members <= n; members++) { - for (let currentProfit = 0; currentProfit <= minProfit; currentProfit++) { - dp[crime][members][currentProfit] = dp[crime - 1][members][currentProfit]; - - if (members >= membersNeeded) { - const prevProfit = Math.max(0, currentProfit - profitGained); - dp[crime][members][currentProfit] = (dp[crime][members][currentProfit] - + dp[crime - 1][members - membersNeeded][prevProfit]) % MOD; - } - } - } - } - - let result = 0; - for (let members = 0; members <= n; members++) { - result = (result + dp[group.length][members][minProfit]) % MOD; - } - - return result; -}; diff --git a/solutions/0880-decoded-string-at-index.js b/solutions/0880-decoded-string-at-index.js deleted file mode 100644 index 08fb95d6..00000000 --- a/solutions/0880-decoded-string-at-index.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 880. Decoded String at Index - * https://leetcode.com/problems/decoded-string-at-index/ - * Difficulty: Medium - * - * You are given an encoded string s. To decode the string to a tape, the encoded string is read - * one character at a time and the following steps are taken: - * - If the character read is a letter, that letter is written onto the tape. - * - If the character read is a digit d, the entire current tape is repeatedly written d - 1 - * more times in total. - * - * Given an integer k, return the kth letter (1-indexed) in the decoded string. - */ - -/** - * @param {string} s - * @param {number} k - * @return {string} - */ -var decodeAtIndex = function(s, k) { - let tapeLength = 0; - let i = 0; - - while (tapeLength < k) { - if (isLetter(s[i])) { - tapeLength++; - } else { - tapeLength *= parseInt(s[i]); - } - i++; - } - - while (i--) { - if (isLetter(s[i])) { - if (tapeLength === k) return s[i]; - tapeLength--; - } else { - tapeLength = Math.floor(tapeLength / parseInt(s[i])); - k = k % tapeLength || tapeLength; - } - } -}; - -function isLetter(char) { - return /[a-z]/.test(char); -} diff --git a/solutions/0881-boats-to-save-people.js b/solutions/0881-boats-to-save-people.js deleted file mode 100644 index e11b6ff8..00000000 --- a/solutions/0881-boats-to-save-people.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 881. Boats to Save People - * https://leetcode.com/problems/boats-to-save-people/ - * Difficulty: Medium - * - * You are given an array people where people[i] is the weight of the ith person, and an infinite - * number of boats where each boat can carry a maximum weight of limit. Each boat carries at - * most two people at the same time, provided the sum of the weight of those people is at most - * limit. - * - * Return the minimum number of boats to carry every given person. - */ - -/** - * @param {number[]} people - * @param {number} limit - * @return {number} - */ -var numRescueBoats = function(people, limit) { - people.sort((a, b) => a - b); - let boats = 0; - let left = 0; - let right = people.length - 1; - - while (left <= right) { - if (left < right && people[left] + people[right] <= limit) { - left++; - right--; - } else { - right--; - } - boats++; - } - - return boats; -}; diff --git a/solutions/0882-reachable-nodes-in-subdivided-graph.js b/solutions/0882-reachable-nodes-in-subdivided-graph.js deleted file mode 100644 index 11dcf1be..00000000 --- a/solutions/0882-reachable-nodes-in-subdivided-graph.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * 882. Reachable Nodes In Subdivided Graph - * https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/ - * Difficulty: Hard - * - * You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. - * You decide to subdivide each edge in the graph into a chain of nodes, with the number of new - * nodes varying between each edge. - * - * The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there - * is an edge between nodes ui and vi in the original graph, and cnti is the total number of new - * nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide - * the edge. - * - * To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The - * new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., - * [xcnti-1, xcnti], [xcnti, vi]. - * - * In this new graph, you want to know how many nodes are reachable from the node 0, where a node - * is reachable if the distance is maxMoves or less. - * - * Given the original graph and maxMoves, return the number of nodes that are reachable from node - * 0 in the new graph. - */ - -/** - * @param {number[][]} edges - * @param {number} maxMoves - * @param {number} n - * @return {number} - */ -var reachableNodes = function(edges, maxMoves, n) { - const graph = {}; - for (let i = 0; i < n; i++) { - graph[i] = []; - } - - for (const [u, v, w] of edges) { - graph[u].push([v, w]); - graph[v].push([u, w]); - } - - const dist = {}; - for (let i = 0; i < n; i++) { - dist[i] = Infinity; - } - dist[0] = 0; - - const used = {}; - const pq = [[0, 0]]; - while (pq.length) { - pq.sort((a, b) => a[0] - b[0]); - const [d, node] = pq.shift(); - - if (d > dist[node]) continue; - - for (const [nei, weight] of graph[node]) { - const edgeId = `${Math.min(node, nei)}-${Math.max(node, nei)}`; - const dirId = node < nei ? 0 : 1; - - if (!used[edgeId]) { - used[edgeId] = [0, 0]; - } - used[edgeId][dirId] = Math.min(maxMoves - d, weight); - if (d + weight + 1 <= maxMoves && d + weight + 1 < dist[nei]) { - dist[nei] = d + weight + 1; - pq.push([dist[nei], nei]); - } - } - } - - let result = 0; - for (let i = 0; i < n; i++) { - if (dist[i] <= maxMoves) result++; - } - - for (const [u, v, cnt] of edges) { - const edgeId = `${Math.min(u, v)}-${Math.max(u, v)}`; - if (used[edgeId]) { - const totalUsed = used[edgeId][0] + used[edgeId][1]; - result += Math.min(cnt, totalUsed); - } - } - - return result; -}; diff --git a/solutions/0883-projection-area-of-3d-shapes.js b/solutions/0883-projection-area-of-3d-shapes.js deleted file mode 100644 index e5d56ba0..00000000 --- a/solutions/0883-projection-area-of-3d-shapes.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 883. Projection Area of 3D Shapes - * https://leetcode.com/problems/projection-area-of-3d-shapes/ - * Difficulty: Easy - * - * You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned - * with the x, y, and z axes. - * - * Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). - * - * We view the projection of these cubes onto the xy, yz, and zx planes. - * - * A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. - * We are viewing the "shadow" when looking at the cubes from the top, the front, and the side. - * - * Return the total area of all three projections. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var projectionArea = function(grid) { - let topView = 0; - let frontView = 0; - let sideView = 0; - - for (let i = 0; i < grid.length; i++) { - let maxRow = 0; - let maxCol = 0; - - for (let j = 0; j < grid.length; j++) { - if (grid[i][j] > 0) topView++; - maxRow = Math.max(maxRow, grid[i][j]); - maxCol = Math.max(maxCol, grid[j][i]); - } - - frontView += maxRow; - sideView += maxCol; - } - - return topView + frontView + sideView; -}; diff --git a/solutions/0885-spiral-matrix-iii.js b/solutions/0885-spiral-matrix-iii.js deleted file mode 100644 index e0fcb881..00000000 --- a/solutions/0885-spiral-matrix-iii.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 885. Spiral Matrix III - * https://leetcode.com/problems/spiral-matrix-iii/ - * Difficulty: Medium - * - * You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner - * is at the first row and column in the grid, and the southeast corner is at the last row and - * column. - * - * You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you - * move outside the grid's boundary, we continue our walk outside the grid (but may return to the - * grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. - * - * Return an array of coordinates representing the positions of the grid in the order you visited - * them. - */ - -/** - * @param {number} rows - * @param {number} cols - * @param {number} rStart - * @param {number} cStart - * @return {number[][]} - */ -var spiralMatrixIII = function(rows, cols, rStart, cStart) { - const result = []; - const total = rows * cols; - let row = rStart; - let col = cStart; - let step = 1; - let direction = 0; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - - result.push([row, col]); - - while (result.length < total) { - for (let i = 0; i < 2; i++) { - const [dr, dc] = directions[direction]; - for (let j = 0; j < step; j++) { - row += dr; - col += dc; - if (row >= 0 && row < rows && col >= 0 && col < cols) { - result.push([row, col]); - } - } - direction = (direction + 1) % 4; - } - step++; - } - - return result; -}; diff --git a/solutions/0886-possible-bipartition.js b/solutions/0886-possible-bipartition.js deleted file mode 100644 index 6f425c7d..00000000 --- a/solutions/0886-possible-bipartition.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 886. Possible Bipartition - * https://leetcode.com/problems/possible-bipartition/ - * Difficulty: Medium - * - * We want to split a group of n people (labeled from 1 to n) into two groups of any size. - * Each person may dislike some other people, and they should not go into the same group. - * - * Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that - * the person labeled ai does not like the person labeled bi, return true if it is possible - * to split everyone into two groups in this way. - */ - -/** - * @param {number} n - * @param {number[][]} dislikes - * @return {boolean} - */ -var possibleBipartition = function(n, dislikes) { - const graph = Array.from({ length: n + 1 }, () => []); - dislikes.forEach(([a, b]) => { - graph[a].push(b); - graph[b].push(a); - }); - - const colors = new Array(n + 1).fill(0); - - function colorGraph(person, color) { - colors[person] = color; - for (const neighbor of graph[person]) { - if (colors[neighbor] === color) return false; - if (colors[neighbor] === 0 && !colorGraph(neighbor, -color)) return false; - } - return true; - } - - for (let person = 1; person <= n; person++) { - if (colors[person] === 0 && !colorGraph(person, 1)) return false; - } - - return true; -}; diff --git a/solutions/0887-super-egg-drop.js b/solutions/0887-super-egg-drop.js deleted file mode 100644 index e80349b7..00000000 --- a/solutions/0887-super-egg-drop.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 887. Super Egg Drop - * https://leetcode.com/problems/super-egg-drop/ - * Difficulty: Hard - * - * You are given k identical eggs and you have access to a building with n floors labeled - * from 1 to n. - * - * You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a - * floor higher than f will break, and any egg dropped at or below floor f will not break. - * - * Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). - * If the egg breaks, you can no longer use it. However, if the egg does not break, you may - * reuse it in future moves. - * - * Return the minimum number of moves that you need to determine with certainty what the - * value of f is. - */ - -/** - * @param {number} k - * @param {number} n - * @return {number} - */ -var superEggDrop = function(k, n) { - const dp = new Array(k + 1).fill().map(() => new Array(n + 1).fill(0)); - - function solve(eggs, floors) { - if (floors === 0 || floors === 1) return floors; - if (eggs === 1) return floors; - if (dp[eggs][floors]) return dp[eggs][floors]; - - let minMoves = floors; - let low = 1; - let high = floors; - - while (low <= high) { - const middle = Math.floor((low + high) / 2); - const breakCase = solve(eggs - 1, middle - 1); - const noBreakCase = solve(eggs, floors - middle); - const moves = 1 + Math.max(breakCase, noBreakCase); - - minMoves = Math.min(minMoves, moves); - if (breakCase < noBreakCase) low = middle + 1; - else high = middle - 1; - } - - dp[eggs][floors] = minMoves; - return minMoves; - } - - return solve(k, n); -}; diff --git a/solutions/0888-fair-candy-swap.js b/solutions/0888-fair-candy-swap.js deleted file mode 100644 index fece1244..00000000 --- a/solutions/0888-fair-candy-swap.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 888. Fair Candy Swap - * https://leetcode.com/problems/fair-candy-swap/ - * Difficulty: Easy - * - * Alice and Bob have a different total number of candies. You are given two integer arrays - * aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of - * candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy - * that Bob has. - * - * Since they are friends, they would like to exchange one candy box each so that after the - * exchange, they both have the same total amount of candy. The total amount of candy a - * person has is the sum of the number of candies in each box they have. - * - * Return an integer array answer where answer[0] is the number of candies in the box that - * Alice must exchange, and answer[1] is the number of candies in the box that Bob must - * exchange. If there are multiple answers, you may return any one of them. It is guaranteed - * that at least one answer exists. - */ - -/** - * @param {number[]} aliceSizes - * @param {number[]} bobSizes - * @return {number[]} - */ -var fairCandySwap = function(aliceSizes, bobSizes) { - const aliceTotal = aliceSizes.reduce((sum, size) => sum + size, 0); - const bobTotal = bobSizes.reduce((sum, size) => sum + size, 0); - const diff = (aliceTotal - bobTotal) / 2; - const bobSet = new Set(bobSizes); - - for (const aliceBox of aliceSizes) { - const targetBobBox = aliceBox - diff; - if (bobSet.has(targetBobBox)) { - return [aliceBox, targetBobBox]; - } - } -}; diff --git a/solutions/0891-sum-of-subsequence-widths.js b/solutions/0891-sum-of-subsequence-widths.js deleted file mode 100644 index c43078f8..00000000 --- a/solutions/0891-sum-of-subsequence-widths.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 891. Sum of Subsequence Widths - * https://leetcode.com/problems/sum-of-subsequence-widths/ - * Difficulty: Hard - * - * The width of a sequence is the difference between the maximum and minimum elements - * in the sequence. - * - * Given an array of integers nums, return the sum of the widths of all the non-empty - * subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. - * - * A subsequence is a sequence that can be derived from an array by deleting some or - * no elements without changing the order of the remaining elements. For example, - * [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var sumSubseqWidths = function(nums) { - const MOD = 1e9 + 7; - const n = nums.length; - const powers = [1]; - - nums.sort((a, b) => a - b); - for (let i = 1; i < n; i++) { - powers[i] = (powers[i - 1] * 2) % MOD; - } - - let result = 0; - for (let i = 0; i < n; i++) { - const contribution = (nums[i] * (powers[i] - powers[n - 1 - i] + MOD)) % MOD; - result = (result + contribution) % MOD; - } - - return result; -}; diff --git a/solutions/0892-surface-area-of-3d-shapes.js b/solutions/0892-surface-area-of-3d-shapes.js deleted file mode 100644 index 46994ced..00000000 --- a/solutions/0892-surface-area-of-3d-shapes.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 892. Surface Area of 3D Shapes - * https://leetcode.com/problems/surface-area-of-3d-shapes/ - * Difficulty: Easy - * - * You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value - * v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). - * - * After placing these cubes, you have decided to glue any directly adjacent cubes to - * each other, forming several irregular 3D shapes. - * - * Return the total surface area of the resulting shapes. - * - * Note: The bottom face of each shape counts toward its surface area. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var surfaceArea = function(grid) { - let result = 0; - - for (let row = 0; row < grid.length; row++) { - for (let col = 0; col < grid.length; col++) { - if (grid[row][col]) { - result += 2 + 4 * grid[row][col]; - - result -= row > 0 ? Math.min(grid[row][col], grid[row - 1][col]) * 2 : 0; - result -= col > 0 ? Math.min(grid[row][col], grid[row][col - 1]) * 2 : 0; - } - } - } - - return result; -}; diff --git a/solutions/0893-groups-of-special-equivalent-strings.js b/solutions/0893-groups-of-special-equivalent-strings.js deleted file mode 100644 index 0def287e..00000000 --- a/solutions/0893-groups-of-special-equivalent-strings.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 893. Groups of Special-Equivalent Strings - * https://leetcode.com/problems/groups-of-special-equivalent-strings/ - * Difficulty: Medium - * - * You are given an array of strings of the same length words. - * - * In one move, you can swap any two even indexed characters or any two odd indexed characters of - * a string words[i]. - * - * Two strings words[i] and words[j] are special-equivalent if after any number of moves, - * words[i] == words[j]. - * - For example, words[i] = "zzxy" and words[j] = "xyzz" are special-equivalent because we may - * make the moves "zzxy" -> "xzzy" -> "xyzz". - * - * A group of special-equivalent strings from words is a non-empty subset of words such that: - * - Every pair of strings in the group are special equivalent, and - * - The group is the largest size possible (i.e., there is not a string words[i] not in the - * group such that words[i] is special-equivalent to every string in the group). - * - * Return the number of groups of special-equivalent strings from words. - */ - -/** - * @param {string[]} words - * @return {number} - */ -var numSpecialEquivGroups = function(words) { - return new Set(words.map(normalizeWord)).size; - - function normalizeWord(word) { - const evenChars = []; - const oddChars = []; - for (let i = 0; i < word.length; i++) { - if (i % 2 === 0) evenChars.push(word[i]); - else oddChars.push(word[i]); - } - return `${evenChars.sort().join('')}-${oddChars.sort().join('')}`; - } -}; diff --git a/solutions/0894-all-possible-full-binary-trees.js b/solutions/0894-all-possible-full-binary-trees.js deleted file mode 100644 index 24990789..00000000 --- a/solutions/0894-all-possible-full-binary-trees.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 894. All Possible Full Binary Trees - * https://leetcode.com/problems/all-possible-full-binary-trees/ - * Difficulty: Medium - * - * Given an integer n, return a list of all possible full binary trees with n nodes. Each node - * of each tree in the answer must have Node.val == 0. - * - * Each element of the answer is the root node of one possible tree. You may return the final - * list of trees in any order. - * - * A full binary tree is a binary tree where each node has exactly 0 or 2 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 {number} n - * @return {TreeNode[]} - */ -var allPossibleFBT = function(n) { - const memo = new Map(); - return generateTrees(n); - - function generateTrees(nodes) { - if (nodes % 2 === 0) return []; - if (nodes === 1) return [new TreeNode(0)]; - if (memo.has(nodes)) return memo.get(nodes); - - const result = []; - for (let leftNodes = 1; leftNodes < nodes - 1; leftNodes += 2) { - const rightNodes = nodes - 1 - leftNodes; - const leftTrees = generateTrees(leftNodes); - const rightTrees = generateTrees(rightNodes); - - for (const left of leftTrees) { - for (const right of rightTrees) { - result.push(new TreeNode(0, left, right)); - } - } - } - - memo.set(nodes, result); - return result; - } -}; diff --git a/solutions/0895-maximum-frequency-stack.js b/solutions/0895-maximum-frequency-stack.js deleted file mode 100644 index af5ce827..00000000 --- a/solutions/0895-maximum-frequency-stack.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 895. Maximum Frequency Stack - * https://leetcode.com/problems/maximum-frequency-stack/ - * Difficulty: Hard - * - * Design a stack-like data structure to push elements to the stack and pop the most frequent - * element from the stack. - * - * Implement the FreqStack class: - * - FreqStack() constructs an empty frequency stack. - * - void push(int val) pushes an integer val onto the top of the stack. - * - int pop() removes and returns the most frequent element in the stack. - * - If there is a tie for the most frequent element, the element closest to the stack's - * top is removed and returned. - */ - -var FreqStack = function() { - this.frequencyMap = new Map(); - this.groupMap = new Map(); - this.maxFrequency = 0; -}; - -/** - * @param {number} val - * @return {void} - */ -FreqStack.prototype.push = function(val) { - const frequency = (this.frequencyMap.get(val) || 0) + 1; - this.frequencyMap.set(val, frequency); - this.maxFrequency = Math.max(this.maxFrequency, frequency); - - if (!this.groupMap.has(frequency)) { - this.groupMap.set(frequency, []); - } - this.groupMap.get(frequency).push(val); -}; - -/** - * @return {number} - */ -FreqStack.prototype.pop = function() { - const topGroup = this.groupMap.get(this.maxFrequency); - const val = topGroup.pop(); - - this.frequencyMap.set(val, this.maxFrequency - 1); - if (topGroup.length === 0) { - this.groupMap.delete(this.maxFrequency); - this.maxFrequency--; - } - - return val; -}; diff --git a/solutions/0896-monotonic-array.js b/solutions/0896-monotonic-array.js deleted file mode 100644 index bc621274..00000000 --- a/solutions/0896-monotonic-array.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 896. Monotonic Array - * https://leetcode.com/problems/monotonic-array/ - * Difficulty: Easy - * - * An array is monotonic if it is either monotone increasing or monotone decreasing. - * - * An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums - * is monotone decreasing if for all i <= j, nums[i] >= nums[j]. - * - * Given an integer array nums, return true if the given array is monotonic, or false otherwise. - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var isMonotonic = function(nums) { - const isIncreasing = nums.every((num, i) => i === 0 || num >= nums[i - 1]); - const isDecreasing = nums.every((num, i) => i === 0 || num <= nums[i - 1]); - return isIncreasing || isDecreasing; -}; diff --git a/solutions/0897-increasing-order-search-tree.js b/solutions/0897-increasing-order-search-tree.js deleted file mode 100644 index 06f4d6f9..00000000 --- a/solutions/0897-increasing-order-search-tree.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 897. Increasing Order Search Tree - * https://leetcode.com/problems/increasing-order-search-tree/ - * Difficulty: Easy - * - * Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost - * node in the tree is now the root of the tree, and every node has no left child and only one - * 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 {TreeNode} - */ -var increasingBST = function(root) { - const result = new TreeNode(0); - let current = result; - - inorderTraversal(root); - return result.right; - - function inorderTraversal(node) { - if (!node) return; - - inorderTraversal(node.left); - current.right = new TreeNode(node.val); - current = current.right; - inorderTraversal(node.right); - } -}; diff --git a/solutions/0898-bitwise-ors-of-subarrays.js b/solutions/0898-bitwise-ors-of-subarrays.js deleted file mode 100644 index 2ab9ece0..00000000 --- a/solutions/0898-bitwise-ors-of-subarrays.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 898. Bitwise ORs of Subarrays - * https://leetcode.com/problems/bitwise-ors-of-subarrays/ - * Difficulty: Medium - * - * Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty - * subarrays of arr. - * - * The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise - * OR of a subarray of one integer is that integer. - * - * A subarray is a contiguous non-empty sequence of elements within an array. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var subarrayBitwiseORs = function(arr) { - const results = new Set(); - let previous = new Set(); - - for (const num of arr) { - const current = new Set([num]); - for (const prev of previous) { - current.add(prev | num); - } - previous = current; - previous.forEach(val => results.add(val)); - } - - return results.size; -}; diff --git a/solutions/0899-orderly-queue.js b/solutions/0899-orderly-queue.js deleted file mode 100644 index 7e53d95a..00000000 --- a/solutions/0899-orderly-queue.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 899. Orderly Queue - * https://leetcode.com/problems/orderly-queue/ - * Difficulty: Hard - * - * You are given a string s and an integer k. You can choose one of the first k letters of s - * and append it at the end of the string. - * - * Return the lexicographically smallest string you could have after applying the mentioned - * step any number of moves. - */ - -/** - * @param {string} s - * @param {number} k - * @return {string} - */ -var orderlyQueue = function(s, k) { - if (k === 1) { - let smallest = s; - for (let i = 0; i < s.length; i++) { - const rotated = s.slice(i) + s.slice(0, i); - if (rotated < smallest) smallest = rotated; - } - return smallest; - } - return [...s].sort().join(''); -}; diff --git a/solutions/0900-rle-iterator.js b/solutions/0900-rle-iterator.js deleted file mode 100644 index 0fc4263c..00000000 --- a/solutions/0900-rle-iterator.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 900. RLE Iterator - * https://leetcode.com/problems/rle-iterator/ - * Difficulty: Medium - * - * We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length - * encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the - * number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence. - * - For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5]. - * encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr. - * - * Given a run-length encoded array, design an iterator that iterates through it. - * - * Implement the RLEIterator class: - * - RLEIterator(int[] encoded) Initializes the object with the encoded array encoded. - * - int next(int n) Exhausts the next n elements and returns the last element exhausted in this - * way. If there is no element left to exhaust, return -1 instead. - */ - -/** - * @param {number[]} encoding - */ -var RLEIterator = function(encoding) { - this.pairs = []; - this.index = 0; - this.count = 0; - - for (let i = 0; i < encoding.length; i += 2) { - if (encoding[i] > 0) { - this.pairs.push([encoding[i], encoding[i + 1]]); - } - } -}; - -/** - * @param {number} n - * @return {number} - */ -RLEIterator.prototype.next = function(n) { - while (n > 0 && this.index < this.pairs.length) { - const available = this.pairs[this.index][0] - this.count; - - if (n <= available) { - this.count += n; - return this.pairs[this.index][1]; - } - - n -= available; - this.count = 0; - this.index++; - } - - return -1; -}; diff --git a/solutions/0902-numbers-at-most-n-given-digit-set.js b/solutions/0902-numbers-at-most-n-given-digit-set.js deleted file mode 100644 index 9927ed31..00000000 --- a/solutions/0902-numbers-at-most-n-given-digit-set.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 902. Numbers At Most N Given Digit Set - * https://leetcode.com/problems/numbers-at-most-n-given-digit-set/ - * Difficulty: Hard - * - * Given an array of digits which is sorted in non-decreasing order. You can write numbers using - * each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write - * numbers such as '13', '551', and '1351315'. - * - * Return the number of positive integers that can be generated that are less than or equal to - * a given integer n. - */ - -/** - * @param {string[]} digits - * @param {number} n - * @return {number} - */ -var atMostNGivenDigitSet = function(digits, n) { - const str = n.toString(); - const digitCount = digits.length; - let result = 0; - - for (let i = 1; i < str.length; i++) { - result += Math.pow(digitCount, i); - } - - function countValid(prefixLen) { - if (prefixLen === str.length) return 1; - - const currentDigit = str[prefixLen]; - let valid = 0; - - for (const digit of digits) { - if (digit < currentDigit) { - valid += Math.pow(digitCount, str.length - prefixLen - 1); - } else if (digit === currentDigit) { - valid += countValid(prefixLen + 1); - } else { - break; - } - } - - return valid; - } - - return result + countValid(0); -}; diff --git a/solutions/0903-valid-permutations-for-di-sequence.js b/solutions/0903-valid-permutations-for-di-sequence.js deleted file mode 100644 index d48f4a4b..00000000 --- a/solutions/0903-valid-permutations-for-di-sequence.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 903. Valid Permutations for DI Sequence - * https://leetcode.com/problems/valid-permutations-for-di-sequence/ - * Difficulty: Hard - * - * You are given a string s of length n where s[i] is either: - * - 'D' means decreasing, or - * - 'I' means increasing. - * - * A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a - * valid permutation if for all valid i: - * - If s[i] == 'D', then perm[i] > perm[i + 1], and - * - If s[i] == 'I', then perm[i] < perm[i + 1]. - * - * Return the number of valid permutations perm. Since the answer may be large, return it - * modulo 109 + 7. - */ - -/** - * @param {string} s - * @return {number} - */ -var numPermsDISequence = function(s) { - const MOD = 1e9 + 7; - const n = s.length; - const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0)); - - dp[0][0] = 1; - - for (let len = 1; len <= n; len++) { - for (let curr = 0; curr <= len; curr++) { - if (s[len - 1] === 'D') { - for (let prev = curr; prev < len; prev++) { - dp[len][curr] = (dp[len][curr] + dp[len - 1][prev]) % MOD; - } - } else { - for (let prev = 0; prev < curr; prev++) { - dp[len][curr] = (dp[len][curr] + dp[len - 1][prev]) % MOD; - } - } - } - } - - let result = 0; - for (let num = 0; num <= n; num++) { - result = (result + dp[n][num]) % MOD; - } - - return result; -}; diff --git a/solutions/0904-fruit-into-baskets.js b/solutions/0904-fruit-into-baskets.js deleted file mode 100644 index 9a8417a0..00000000 --- a/solutions/0904-fruit-into-baskets.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 904. Fruit Into Baskets - * https://leetcode.com/problems/fruit-into-baskets/ - * Difficulty: Medium - * - * You are visiting a farm that has a single row of fruit trees arranged from left to right. - * The trees are represented by an integer array fruits where fruits[i] is the type of fruit - * the ith tree produces. - * - * You want to collect as much fruit as possible. However, the owner has some strict rules - * that you must follow: - * - You only have two baskets, and each basket can only hold a single type of fruit. There - * is no limit on the amount of fruit each basket can hold. - * - Starting from any tree of your choice, you must pick exactly one fruit from every tree - * (including the start tree) while moving to the right. The picked fruits must fit in one - * of your baskets. - * - Once you reach a tree with fruit that cannot fit in your baskets, you must stop. - * - * Given the integer array fruits, return the maximum number of fruits you can pick. - */ - -/** - * @param {number[]} fruits - * @return {number} - */ -var totalFruit = function(fruits) { - const map = new Map(); - let result = 0; - let start = 0; - - for (let end = 0; end < fruits.length; end++) { - map.set(fruits[end], (map.get(fruits[end]) || 0) + 1); - - while (map.size > 2) { - map.set(fruits[start], map.get(fruits[start]) - 1); - if (map.get(fruits[start]) === 0) { - map.delete(fruits[start]); - } - start++; - } - - result = Math.max(result, end - start + 1); - } - - return result; -}; diff --git a/solutions/0906-super-palindromes.js b/solutions/0906-super-palindromes.js deleted file mode 100644 index f5b9967c..00000000 --- a/solutions/0906-super-palindromes.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 906. Super Palindromes - * https://leetcode.com/problems/super-palindromes/ - * Difficulty: Hard - * - * Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also - * the square of a palindrome. - * - * Given two positive integers left and right represented as strings, return the number of - * super-palindromes integers in the inclusive range [left, right]. - */ - -/** - * @param {string} left - * @param {string} right - * @return {number} - */ -var superpalindromesInRange = function(lowerBound, upperBound) { - let result = 9n >= lowerBound && 9n <= upperBound ? 1 : 0; - - const isPalindrome = sequence => { - for (let start = 0, end = sequence.length - 1; start < end; start++, end--) { - if (sequence[start] !== sequence[end]) return false; - } - return true; - }; - - for (let base = 1; base < 19684; base++) { - const ternary = base.toString(3); - if (isPalindrome(ternary)) { - const square = BigInt(ternary) * BigInt(ternary); - if (square > upperBound) return result; - if (square >= lowerBound && isPalindrome(square.toString())) { - result++; - } - } - } - - return result; -}; diff --git a/solutions/0907-sum-of-subarray-minimums.js b/solutions/0907-sum-of-subarray-minimums.js deleted file mode 100644 index 31965e5c..00000000 --- a/solutions/0907-sum-of-subarray-minimums.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 907. Sum of Subarray Minimums - * https://leetcode.com/problems/sum-of-subarray-minimums/ - * Difficulty: Medium - * - * Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) - * subarray of arr. Since the answer may be large, return the answer modulo 109 + 7. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var sumSubarrayMins = function(arr) { - const MOD = 1e9 + 7; - const left = new Array(arr.length); - const right = new Array(arr.length); - const stack = []; - - for (let i = 0; i < arr.length; i++) { - while (stack.length && arr[stack[stack.length - 1]] > arr[i]) { - stack.pop(); - } - left[i] = stack.length ? i - stack[stack.length - 1] : i + 1; - stack.push(i); - } - - stack.length = 0; - for (let i = arr.length - 1; i >= 0; i--) { - while (stack.length && arr[stack[stack.length - 1]] >= arr[i]) { - stack.pop(); - } - right[i] = stack.length ? stack[stack.length - 1] - i : arr.length - i; - stack.push(i); - } - - let result = 0; - for (let i = 0; i < arr.length; i++) { - result = (result + arr[i] * left[i] * right[i]) % MOD; - } - - return result; -}; diff --git a/solutions/0908-smallest-range-i.js b/solutions/0908-smallest-range-i.js deleted file mode 100644 index 881e0b5a..00000000 --- a/solutions/0908-smallest-range-i.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 908. Smallest Range I - * https://leetcode.com/problems/smallest-range-i/ - * Difficulty: Easy - * - * You are given an integer array nums and an integer k. - * - * In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to - * nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most - * once for each index i. - * - * The score of nums is the difference between the maximum and minimum elements in nums. - * - * Return the minimum score of nums after applying the mentioned operation at most once for each - * index in it. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var smallestRangeI = function(nums, k) { - return Math.max(Math.max(...nums) - Math.min(...nums) - 2 * k, 0); -}; diff --git a/solutions/0910-smallest-range-ii.js b/solutions/0910-smallest-range-ii.js deleted file mode 100644 index 0bf09fe1..00000000 --- a/solutions/0910-smallest-range-ii.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 910. Smallest Range II - * https://leetcode.com/problems/smallest-range-ii/ - * Difficulty: Medium - * - * You are given an integer array nums and an integer k. - * - * For each index i where 0 <= i < nums.length, change nums[i] to be either - * nums[i] + k or nums[i] - k. - * - * The score of nums is the difference between the maximum and minimum elements - * in nums. - * - * Return the minimum score of nums after changing the values at each index. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var smallestRangeII = function(nums, k) { - nums.sort((a, b) => a - b); - - let result = nums[nums.length - 1] - nums[0]; - for (let i = 0; i < nums.length - 1; i++) { - const high = Math.max(nums[nums.length - 1] - k, nums[i] + k); - const low = Math.min(nums[0] + k, nums[i + 1] - k); - result = Math.min(result, high - low); - } - - return result; -}; diff --git a/solutions/0911-online-election.js b/solutions/0911-online-election.js deleted file mode 100644 index 78f3d764..00000000 --- a/solutions/0911-online-election.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 911. Online Election - * https://leetcode.com/problems/online-election/ - * Difficulty: Medium - * - * You are given two integer arrays persons and times. In an election, the ith vote was cast for - * persons[i] at time times[i]. - * - * For each query at a time t, find the person that was leading the election at time t. Votes - * cast at time t will count towards our query. In the case of a tie, the most recent vote (among - * tied candidates) wins. - * - * Implement the TopVotedCandidate class: - * - TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and - * times arrays. - * - int q(int t) Returns the number of the person that was leading the election at time t according - * to the mentioned rules. - */ - -/** - * @param {number[]} persons - * @param {number[]} times - */ -var TopVotedCandidate = function(persons, times) { - this.times = times; - this.leaders = []; - const voteCount = new Map(); - let maxVotes = 0; - let currentLeader = 0; - - for (let i = 0; i < persons.length; i++) { - const votes = (voteCount.get(persons[i]) || 0) + 1; - voteCount.set(persons[i], votes); - - if (votes >= maxVotes) { - maxVotes = votes; - currentLeader = persons[i]; - } - this.leaders[i] = currentLeader; - } -}; - -/** - * @param {number} t - * @return {number} - */ -TopVotedCandidate.prototype.q = function(t) { - let left = 0; - let right = this.times.length - 1; - - while (left <= right) { - const middle = Math.floor((left + right) / 2); - if (this.times[middle] <= t) { - left = middle + 1; - } else { - right = middle - 1; - } - } - - return this.leaders[right]; -}; diff --git a/solutions/0913-cat-and-mouse.js b/solutions/0913-cat-and-mouse.js deleted file mode 100644 index 6358c546..00000000 --- a/solutions/0913-cat-and-mouse.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * 913. Cat and Mouse - * https://leetcode.com/problems/cat-and-mouse/ - * Difficulty: Hard - * - * A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. - * - * The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of - * the graph. - * - * The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and - * there is a hole at node 0. - * - * During each player's turn, they must travel along one edge of the graph that meets where they - * are. For example, if the Mouse is at node 1, it must travel to any node in graph[1]. - * - * Additionally, it is not allowed for the Cat to travel to the Hole (node 0). - * - * Then, the game can end in three ways: - * - If ever the Cat occupies the same node as the Mouse, the Cat wins. - * - If ever the Mouse reaches the Hole, the Mouse wins. - * - If ever a position is repeated (i.e., the players are in the same position as a previous - * turn, and it is the same player's turn to move), the game is a draw. - * - * Given a graph, and assuming both players play optimally, return - * - 1 if the mouse wins the game, - * - 2 if the cat wins the game, or - * - 0 if the game is a draw. - */ - -/** - * @param {number[][]} graph - * @return {number} - */ -var catMouseGame = function(graph) { - const MOUSE_TURN = 0; - const CAT_TURN = 1; - const MOUSE_WIN = 1; - const CAT_WIN = 2; - const n = graph.length; - - const color = new Array(n).fill().map(() => { - return new Array(n).fill().map(() => new Array(2).fill(0)); - }); - - const degree = new Array(n).fill().map(() => { - return new Array(n).fill().map(() => new Array(2).fill(0)); - }); - - const queue = []; - - for (let i = 0; i < n; i++) { - for (let turn = 0; turn < 2; turn++) { - color[0][i][turn] = MOUSE_WIN; - queue.push([0, i, turn, MOUSE_WIN]); - - if (i > 0) { - color[i][i][turn] = CAT_WIN; - queue.push([i, i, turn, CAT_WIN]); - } - } - } - - for (let m = 0; m < n; m++) { - for (let c = 0; c < n; c++) { - degree[m][c][MOUSE_TURN] = graph[m].length; - degree[m][c][CAT_TURN] = graph[c].length; - - for (let x = 0; x < graph[c].length; x++) { - if (graph[c][x] === 0) { - degree[m][c][CAT_TURN]--; - break; - } - } - } - } - - while (queue.length > 0) { - const [mouse, cat, turn, result] = queue.shift(); - - const prevTurn = 1 - turn; - const prevPositions = []; - - if (prevTurn === MOUSE_TURN) { - for (const prevMouse of graph[mouse]) { - prevPositions.push([prevMouse, cat]); - } - } else { - for (const prevCat of graph[cat]) { - if (prevCat !== 0) { - prevPositions.push([mouse, prevCat]); - } - } - } - - for (const [prevMouse, prevCat] of prevPositions) { - if (color[prevMouse][prevCat][prevTurn] !== 0) continue; - - if ((prevTurn === MOUSE_TURN && result === MOUSE_WIN) - || (prevTurn === CAT_TURN && result === CAT_WIN)) { - color[prevMouse][prevCat][prevTurn] = result; - queue.push([prevMouse, prevCat, prevTurn, result]); - } else { - degree[prevMouse][prevCat][prevTurn]--; - if (degree[prevMouse][prevCat][prevTurn] === 0) { - color[prevMouse][prevCat][prevTurn] = result; - queue.push([prevMouse, prevCat, prevTurn, result]); - } - } - } - } - - return color[1][2][MOUSE_TURN]; -}; diff --git a/solutions/0915-partition-array-into-disjoint-intervals.js b/solutions/0915-partition-array-into-disjoint-intervals.js deleted file mode 100644 index 90218e64..00000000 --- a/solutions/0915-partition-array-into-disjoint-intervals.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 915. Partition Array into Disjoint Intervals - * https://leetcode.com/problems/partition-array-into-disjoint-intervals/ - * Difficulty: Medium - * - * Given an integer array nums, partition it into two (contiguous) subarrays left and right so that: - * - Every element in left is less than or equal to every element in right. - * - left and right are non-empty. - * - left has the smallest possible size. - * - * Return the length of left after such a partitioning. - * - * Test cases are generated such that partitioning exists. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var partitionDisjoint = function(nums) { - let leftMax = nums[0]; - let currentMax = nums[0]; - let partitionIndex = 0; - - for (let i = 1; i < nums.length; i++) { - if (nums[i] < leftMax) { - partitionIndex = i; - leftMax = currentMax; - } - currentMax = Math.max(currentMax, nums[i]); - } - - return partitionIndex + 1; -}; diff --git a/solutions/0917-reverse-only-letters.js b/solutions/0917-reverse-only-letters.js deleted file mode 100644 index 1c1fe818..00000000 --- a/solutions/0917-reverse-only-letters.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 917. Reverse Only Letters - * https://leetcode.com/problems/reverse-only-letters/ - * Difficulty: Easy - * - * Given a string s, reverse the string according to the following rules: - * - All the characters that are not English letters remain in the same position. - * - All the English letters (lowercase or uppercase) should be reversed. - * - * Return s after reversing it. - */ - -/** - * @param {string} s - * @return {string} - */ -var reverseOnlyLetters = function(s) { - const chars = s.split(''); - let left = 0; - let right = s.length - 1; - - while (left < right) { - while (left < right && !/[a-zA-Z]/.test(chars[left])) { - left++; - } - while (left < right && !/[a-zA-Z]/.test(chars[right])) { - right--; - } - [chars[left], chars[right]] = [chars[right], chars[left]]; - left++; - right--; - } - - return chars.join(''); -}; diff --git a/solutions/0919-complete-binary-tree-inserter.js b/solutions/0919-complete-binary-tree-inserter.js deleted file mode 100644 index ab02f185..00000000 --- a/solutions/0919-complete-binary-tree-inserter.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 919. Complete Binary Tree Inserter - * https://leetcode.com/problems/complete-binary-tree-inserter/ - * Difficulty: Medium - * - * A complete binary tree is a binary tree in which every level, except possibly the last, - * is completely filled, and all nodes are as far left as possible. - * - * Design an algorithm to insert a new node to a complete binary tree keeping it complete - * after the insertion. - * - * Implement the CBTInserter class: - * - CBTInserter(TreeNode root) Initializes the data structure with the root of the complete - * binary tree. - * - int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that - * the tree remains complete, and returns the value of the parent of the inserted TreeNode. - * - TreeNode get_root() Returns the root node of the tree. - */ - -/** - * 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 - */ -var CBTInserter = function(root) { - this.root = root; - this.deque = []; - - const queue = [root]; - while (queue.length) { - const node = queue.shift(); - if (!node.left || !node.right) this.deque.push(node); - if (node.left) queue.push(node.left); - if (node.right) queue.push(node.right); - } -}; - -/** - * @param {number} val - * @return {number} - */ -CBTInserter.prototype.insert = function(val) { - const node = new TreeNode(val); - const parent = this.deque[0]; - if (!parent.left) { - parent.left = node; - } else { - parent.right = node; - this.deque.shift(); - } - this.deque.push(node); - return parent.val; -}; - -/** - * @return {TreeNode} - */ -CBTInserter.prototype.get_root = function() { - return this.root; -}; diff --git a/solutions/0920-number-of-music-playlists.js b/solutions/0920-number-of-music-playlists.js deleted file mode 100644 index 4b5656fa..00000000 --- a/solutions/0920-number-of-music-playlists.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 920. Number of Music Playlists - * https://leetcode.com/problems/number-of-music-playlists/ - * Difficulty: Hard - * - * Your music player contains n different songs. You want to listen to goal songs (not necessarily - * different) during your trip. To avoid boredom, you will create a playlist so that: - * - Every song is played at least once. - * - A song can only be played again only if k other songs have been played. - * - * Given n, goal, and k, return the number of possible playlists that you can create. Since the - * answer can be very large, return it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} goal - * @param {number} k - * @return {number} - */ -var numMusicPlaylists = function(n, goal, k) { - const MOD = 1e9 + 7; - const dp = new Array(goal + 1).fill().map(() => new Array(n + 1).fill(0)); - dp[0][0] = 1; - - for (let songs = 1; songs <= goal; songs++) { - for (let uniques = 1; uniques <= Math.min(songs, n); uniques++) { - dp[songs][uniques] = dp[songs - 1][uniques - 1] * (n - (uniques - 1)); - if (uniques > k) { - dp[songs][uniques] += dp[songs - 1][uniques] * (uniques - k); - } - dp[songs][uniques] %= MOD; - } - } - - return dp[goal][n]; -}; diff --git a/solutions/0921-minimum-add-to-make-parentheses-valid.js b/solutions/0921-minimum-add-to-make-parentheses-valid.js deleted file mode 100644 index 7b11691f..00000000 --- a/solutions/0921-minimum-add-to-make-parentheses-valid.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 921. Minimum Add to Make Parentheses Valid - * https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ - * Difficulty: Medium - * - * A parentheses string is valid if and only if: - * - It is the empty string, - * - 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. - * - * You are given a parentheses string s. In one move, you can insert a parenthesis at any position - * of the string. - * - For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing - * parenthesis to be "())))". - * - * Return the minimum number of moves required to make s valid. - */ - -/** - * @param {string} s - * @return {number} - */ -var minAddToMakeValid = function(s) { - let openCount = 0; - let unmatchedClose = 0; - - for (const character of s) { - if (character === '(') { - openCount++; - } else if (openCount > 0) { - openCount--; - } else { - unmatchedClose++; - } - } - - return openCount + unmatchedClose; -}; diff --git a/solutions/0923-3sum-with-multiplicity.js b/solutions/0923-3sum-with-multiplicity.js deleted file mode 100644 index 6897c47a..00000000 --- a/solutions/0923-3sum-with-multiplicity.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 923. 3Sum With Multiplicity - * https://leetcode.com/problems/3sum-with-multiplicity/ - * Difficulty: Medium - * - * Given an integer array arr, and an integer target, return the number of tuples i, j, k such - * that i < j < k and arr[i] + arr[j] + arr[k] == target. - * - * As the answer can be very large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} arr - * @param {number} target - * @return {number} - */ -var threeSumMulti = function(arr, target) { - const MOD = 1e9 + 7; - const counts = new Map(); - let result = 0; - - for (const num of arr) { - counts.set(num, (counts.get(num) || 0) + 1); - } - - const uniqueNums = [...counts.keys()].sort((a, b) => a - b); - - for (let i = 0; i < uniqueNums.length; i++) { - const num1 = uniqueNums[i]; - for (let j = i; j < uniqueNums.length; j++) { - const num2 = uniqueNums[j]; - const num3 = target - num1 - num2; - - if (num3 < num2) continue; - - const count1 = counts.get(num1); - const count2 = counts.get(num2); - const count3 = counts.get(num3) || 0; - - if (num1 === num2 && num2 === num3) { - result = (result + (count1 * (count1 - 1) * (count1 - 2)) / 6) % MOD; - } else if (num1 === num2) { - result = (result + (count1 * (count1 - 1) * count3) / 2) % MOD; - } else if (num2 === num3) { - result = (result + (count1 * count2 * (count2 - 1)) / 2) % MOD; - } else { - result = (result + count1 * count2 * count3) % MOD; - } - } - } - - return result; -}; diff --git a/solutions/0924-minimize-malware-spread.js b/solutions/0924-minimize-malware-spread.js deleted file mode 100644 index 9a8e5613..00000000 --- a/solutions/0924-minimize-malware-spread.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 924. Minimize Malware Spread - * https://leetcode.com/problems/minimize-malware-spread/ - * Difficulty: Hard - * - * You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith - * node is directly connected to the jth node if graph[i][j] == 1. - * - * Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, - * and at least one of those two nodes is infected by malware, both nodes will be infected b - * malware. This spread of malware will continue until no more nodes can be infected in this manner. - * - * Suppose M(initial) is the final number of nodes infected with malware in the entire network after - * the spread of malware stops. We will remove exactly one node from initial. - * - * Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed - * to minimize M(initial), return such a node with the smallest index. - * - * Note that if a node was removed from the initial list of infected nodes, it might still be - * infected later due to the malware spread. - */ - -/** - * @param {number[][]} graph - * @param {number[]} initial - * @return {number} - */ -var minMalwareSpread = function(graph, initial) { - const n = graph.length; - const parent = new Array(n).fill().map((_, i) => i); - const size = new Array(n).fill(1); - - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - if (graph[i][j] === 1) { - union(i, j); - } - } - } - - let maxSize = 0; - let result = Math.min(...initial); - - for (const node of initial) { - const root = find(node); - let componentInfected = 0; - - for (const infectedNode of initial) { - if (find(infectedNode) === root) { - componentInfected++; - } - } - - if (componentInfected === 1 && size[root] > maxSize) { - maxSize = size[root]; - result = node; - } else if (componentInfected === 1 && size[root] === maxSize) { - result = Math.min(result, node); - } - } - - return result; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - const rootX = find(x); - const rootY = find(y); - if (rootX !== rootY) { - parent[rootX] = rootY; - size[rootY] += size[rootX]; - } - } -}; diff --git a/solutions/0927-three-equal-parts.js b/solutions/0927-three-equal-parts.js deleted file mode 100644 index ca923f16..00000000 --- a/solutions/0927-three-equal-parts.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 927. Three Equal Parts - * https://leetcode.com/problems/three-equal-parts/ - * Difficulty: Hard - * - * You are given an array arr which consists of only zeros and ones, divide the array into three - * non-empty parts such that all of these parts represent the same binary value. - * - * If it is possible, return any [i, j] with i + 1 < j, such that: - * - arr[0], arr[1], ..., arr[i] is the first part, - * - arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and - * - arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. - * - All three parts have equal binary values. - * - * If it is not possible, return [-1, -1]. - * - * Note that the entire part is used when considering what binary value it represents. For example, - * [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] - * represent the same value. - */ - -/** - * @param {number[]} arr - * @return {number[]} - */ -var threeEqualParts = function(arr) { - const totalOnes = arr.reduce((sum, num) => sum + num, 0); - if (totalOnes % 3 !== 0) { - return [-1, -1]; - } - if (totalOnes === 0) { - return [0, arr.length - 1]; - } - - const onesPerPart = totalOnes / 3; - let firstStart = -1; - let secondStart = -1; - let thirdStart = -1; - let onesCount = 0; - for (let i = 0; i < arr.length; i++) { - if (arr[i] === 1) { - onesCount++; - if (onesCount === 1) firstStart = i; - if (onesCount === onesPerPart + 1) secondStart = i; - if (onesCount === 2 * onesPerPart + 1) thirdStart = i; - } - } - - const patternLength = arr.length - thirdStart; - if (secondStart - firstStart < patternLength || thirdStart - secondStart < patternLength) { - return [-1, -1]; - } - for (let i = 0; i < patternLength; i++) { - if (arr[firstStart + i] !== arr[secondStart + i] - || arr[firstStart + i] !== arr[thirdStart + i]) { - return [-1, -1]; - } - } - - const i = firstStart + patternLength - 1; - const j = secondStart + patternLength; - - return [i, j]; -}; diff --git a/solutions/0928-minimize-malware-spread-ii.js b/solutions/0928-minimize-malware-spread-ii.js deleted file mode 100644 index c8b17fe7..00000000 --- a/solutions/0928-minimize-malware-spread-ii.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * 928. Minimize Malware Spread II - * https://leetcode.com/problems/minimize-malware-spread-ii/ - * Difficulty: Hard - * - * You are given a network of n nodes represented as an n x n adjacency matrix graph, where the - * ith node is directly connected to the jth node if graph[i][j] == 1. - * - * Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, - * and at least one of those two nodes is infected by malware, both nodes will be infected by - * malware. This spread of malware will continue until no more nodes can be infected in this manner. - * - * Suppose M(initial) is the final number of nodes infected with malware in the entire network after - * the spread of malware stops. - * - * We will remove exactly one node from initial, completely removing it and any connections from - * this node to any other node. - * - * Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed - * to minimize M(initial), return such a node with the smallest index. - */ - -/** - * @param {number[][]} graph - * @param {number[]} initial - * @return {number} - */ -var minMalwareSpread = function(graph, initial) { - const n = graph.length; - const initialSet = new Set(initial); - - initial.sort((a, b) => a - b); - - const infected = new Set(initial); - const queue = [...initial]; - - for (let i = 0; i < queue.length; i++) { - const node = queue[i]; - for (let neighbor = 0; neighbor < n; neighbor++) { - if (graph[node][neighbor] === 1 && !infected.has(neighbor)) { - infected.add(neighbor); - queue.push(neighbor); - } - } - } - - const sourcesMap = new Array(n).fill().map(() => []); - - for (const initialNode of initial) { - const reachable = new Set(); - const visited = new Set(initial); - visited.delete(initialNode); - - const q = [initialNode]; - while (q.length > 0) { - const node = q.shift(); - reachable.add(node); - - for (let neighbor = 0; neighbor < n; neighbor++) { - if (graph[node][neighbor] === 1 && !visited.has(neighbor)) { - visited.add(neighbor); - q.push(neighbor); - } - } - } - - for (let node = 0; node < n; node++) { - if (reachable.has(node) && !initialSet.has(node)) { - sourcesMap[node].push(initialNode); - } - } - } - - const savedCounts = new Map(); - for (let node = 0; node < n; node++) { - if (sourcesMap[node].length === 1) { - const source = sourcesMap[node][0]; - savedCounts.set(source, (savedCounts.get(source) || 0) + 1); - } - } - - let maxSaved = 0; - let result = initial[0]; - - for (const node of initial) { - const saved = savedCounts.get(node) || 0; - if (saved > maxSaved) { - maxSaved = saved; - result = node; - } else if (saved === maxSaved && node < result) { - result = node; - } - } - - return result; -}; diff --git a/solutions/0930-binary-subarrays-with-sum.js b/solutions/0930-binary-subarrays-with-sum.js deleted file mode 100644 index 0f1e2406..00000000 --- a/solutions/0930-binary-subarrays-with-sum.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 930. Binary Subarrays With Sum - * https://leetcode.com/problems/binary-subarrays-with-sum/ - * Difficulty: Medium - * - * Given a binary array nums and an integer goal, return the number of non-empty subarrays - * with a sum goal. - * - * A subarray is a contiguous part of the array. - */ - -/** - * @param {number[]} nums - * @param {number} goal - * @return {number} - */ -var numSubarraysWithSum = function(nums, goal) { - const map = new Map([[0, 1]]); - let result = 0; - let sum = 0; - - for (const num of nums) { - sum += num; - result += map.get(sum - goal) || 0; - map.set(sum, (map.get(sum) || 0) + 1); - } - - return result; -}; diff --git a/solutions/0931-minimum-falling-path-sum.js b/solutions/0931-minimum-falling-path-sum.js deleted file mode 100644 index 5312a139..00000000 --- a/solutions/0931-minimum-falling-path-sum.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 931. Minimum Falling Path Sum - * https://leetcode.com/problems/minimum-falling-path-sum/ - * Difficulty: Medium - * - * Given an n x n array of integers matrix, return the minimum sum of any falling path - * through matrix. - * - * A falling path starts at any element in the first row and chooses the element in the - * next row that is either directly below or diagonally left/right. Specifically, the - * next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), - * or (row + 1, col + 1). - */ - -/** - * @param {number[][]} matrix - * @return {number} - */ -var minFallingPathSum = function(matrix) { - let previousRow = [...matrix[0]]; - - for (let row = 1; row < matrix.length; row++) { - const currentRow = new Array(matrix.length); - for (let col = 0; col < matrix.length; col++) { - const leftDiagonal = col > 0 ? previousRow[col - 1] : Infinity; - const directlyAbove = previousRow[col]; - const rightDiagonal = col < matrix.length - 1 ? previousRow[col + 1] : Infinity; - currentRow[col] = matrix[row][col] + Math.min(leftDiagonal, directlyAbove, rightDiagonal); - } - previousRow = currentRow; - } - - return Math.min(...previousRow); -}; diff --git a/solutions/0932-beautiful-array.js b/solutions/0932-beautiful-array.js deleted file mode 100644 index 1d422937..00000000 --- a/solutions/0932-beautiful-array.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 932. Beautiful Array - * https://leetcode.com/problems/beautiful-array/ - * Difficulty: Medium - * - * An array nums of length n is beautiful if: - * - nums is a permutation of the integers in the range [1, n]. - * - For every 0 <= i < j < n, there is no index k with i < k < j where - * 2 * nums[k] == nums[i] + nums[j]. - * - * Given the integer n, return any beautiful array nums of length n. - * There will be at least one valid answer for the given n. - */ - -/** - * @param {number} n - * @return {number[]} - */ -var beautifulArray = function(n) { - const memo = new Map(); - return helper(n); - - function helper(size) { - if (memo.has(size)) return memo.get(size); - if (size === 1) return [1]; - - const odds = helper(Math.ceil(size / 2)); - const evens = helper(Math.floor(size / 2)); - const result = [ - ...odds.map(x => x * 2 - 1), - ...evens.map(x => x * 2) - ]; - - memo.set(size, result); - return result; - } -}; diff --git a/solutions/0934-shortest-bridge.js b/solutions/0934-shortest-bridge.js deleted file mode 100644 index 5d045a9f..00000000 --- a/solutions/0934-shortest-bridge.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 934. Shortest Bridge - * https://leetcode.com/problems/shortest-bridge/ - * Difficulty: Medium - * - * You are given an n x n binary matrix grid where 1 represents land and 0 represents water. - * - * An island is a 4-directionally connected group of 1's not connected to any other 1's. - * There are exactly two islands in grid. - * - * You may change 0's to 1's to connect the two islands to form one island. - * - * Return the smallest number of 0's you must flip to connect the two islands. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var shortestBridge = function(grid) { - const n = grid.length; - const queue = []; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - - outer: for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if (grid[i][j] === 1) { - findFirstIsland(i, j); - break outer; - } - } - } - - let distance = 0; - while (queue.length) { - const size = queue.length; - for (let i = 0; i < size; i++) { - const [row, col] = queue.shift(); - for (const [dx, dy] of directions) { - const newRow = row + dx; - const newCol = col + dy; - if (newRow < 0 || newRow >= n || newCol < 0 || newCol >= n - || grid[newRow][newCol] === 2) continue; - if (grid[newRow][newCol] === 1) return distance; - grid[newRow][newCol] = 2; - queue.push([newRow, newCol]); - } - } - distance++; - } - - return distance; - - function findFirstIsland(row, col) { - if (row < 0 || row >= n || col < 0 || col >= n || grid[row][col] !== 1) return; - grid[row][col] = 2; - queue.push([row, col]); - for (const [dx, dy] of directions) { - findFirstIsland(row + dx, col + dy); - } - } -}; diff --git a/solutions/0935-knight-dialer.js b/solutions/0935-knight-dialer.js deleted file mode 100644 index 2fb2b8c4..00000000 --- a/solutions/0935-knight-dialer.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 935. Knight Dialer - * https://leetcode.com/problems/knight-dialer/ - * Difficulty: Medium - * - * The chess knight has a unique movement, it may move two squares vertically and one square - * horizontally, or two squares horizontally and one square vertically (with both forming - * the shape of an L). The possible movements of chess knight are shown in this diagram: - * - * A chess knight can move as indicated in the chess diagram below. - * - * We have a chess knight and a phone pad as shown below, the knight can only stand on a - * numeric cell (i.e. blue cell). - * - * Given an integer n, return how many distinct phone numbers of length n we can dial. - * - * You are allowed to place the knight on any numeric cell initially and then you should - * perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps. - * - * As the answer may be very large, return the answer modulo 109 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -var knightDialer = function(n) { - const MOD = 1e9 + 7; - const moves = [ - [4, 6], [6, 8], [7, 9], [4, 8], - [0, 3, 9], [], [0, 1, 7], [2, 6], - [1, 3], [2, 4] - ]; - let prevCounts = new Array(10).fill(1); - - for (let jump = 1; jump < n; jump++) { - const currCounts = new Array(10).fill(0); - for (let digit = 0; digit < 10; digit++) { - for (const nextDigit of moves[digit]) { - currCounts[nextDigit] = (currCounts[nextDigit] + prevCounts[digit]) % MOD; - } - } - prevCounts = currCounts; - } - - return prevCounts.reduce((sum, count) => (sum + count) % MOD, 0); -}; diff --git a/solutions/0936-stamping-the-sequence.js b/solutions/0936-stamping-the-sequence.js deleted file mode 100644 index 6cb12b5a..00000000 --- a/solutions/0936-stamping-the-sequence.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * 936. Stamping The Sequence - * https://leetcode.com/problems/stamping-the-sequence/ - * Difficulty: Hard - * - * You are given two strings stamp and target. Initially, there is a string s of length - * target.length with all s[i] == '?'. - * - * In one turn, you can place stamp over s and replace every letter in the s with the - * corresponding letter from stamp. - * - * For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. - * In one turn you can: - * - place stamp at index 0 of s to obtain "abc??", - * - place stamp at index 1 of s to obtain "?abc?", or - * - place stamp at index 2 of s to obtain "??abc". - * - * Note that stamp must be fully contained in the boundaries of s in order to stamp - * (i.e., you cannot place stamp at index 3 of s). - * - * We want to convert s to target using at most 10 * target.length turns. - * - * Return an array of the index of the left-most letter being stamped at each turn. If we - * cannot obtain target from s within 10 * target.length turns, return an empty array. - */ - -/** - * @param {string} stamp - * @param {string} target - * @return {number[]} - */ -var movesToStamp = function(stamp, target) { - const stampLength = stamp.length; - const targetLength = target.length; - const moves = []; - const targetArray = target.split(''); - let totalReplaced = 0; - - function tryStampAt(position) { - let canStamp = false; - let hasUnstamped = false; - - for (let i = 0; i < stampLength; i++) { - const currentChar = targetArray[position + i]; - if (currentChar === '?') continue; - if (currentChar !== stamp[i]) return false; - hasUnstamped = true; - } - - if (hasUnstamped) { - for (let i = 0; i < stampLength; i++) { - if (targetArray[position + i] !== '?') { - targetArray[position + i] = '?'; - totalReplaced++; - } - } - canStamp = true; - } - - return canStamp; - } - - const maxMoves = 10 * targetLength; - while (moves.length <= maxMoves) { - let madeChange = false; - for (let i = 0; i <= targetLength - stampLength; i++) { - if (tryStampAt(i)) { - moves.push(i); - madeChange = true; - break; - } - } - if (!madeChange) break; - if (totalReplaced === targetLength) return moves.reverse(); - } - - return []; -}; diff --git a/solutions/0938-range-sum-of-bst.js b/solutions/0938-range-sum-of-bst.js deleted file mode 100644 index b8096967..00000000 --- a/solutions/0938-range-sum-of-bst.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 938. Range Sum of BST - * https://leetcode.com/problems/range-sum-of-bst/ - * Difficulty: Easy - * - * Given the root node of a binary search tree and two integers low and high, return the sum - * of values of all nodes with a value in the inclusive range [low, high]. - */ - -/** - * 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} low - * @param {number} high - * @return {number} - */ -var rangeSumBST = function(root, low, high) { - return traverse(root); - - function traverse(node) { - if (!node) return 0; - const value = node.val; - if (value < low) return traverse(node.right); - if (value > high) return traverse(node.left); - return value + traverse(node.left) + traverse(node.right); - } -}; diff --git a/solutions/0939-minimum-area-rectangle.js b/solutions/0939-minimum-area-rectangle.js deleted file mode 100644 index ff178558..00000000 --- a/solutions/0939-minimum-area-rectangle.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 939. Minimum Area Rectangle - * https://leetcode.com/problems/minimum-area-rectangle/ - * Difficulty: Medium - * - * You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. - * - * Return the minimum area of a rectangle formed from these points, with sides parallel to the - * X and Y axes. If there is not any such rectangle, return 0. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var minAreaRect = function(points) { - const pointSet = new Set(points.map(([x, y]) => `${x},${y}`)); - let result = 0; - - for (let i = 0; i < points.length; i++) { - const [x1, y1] = points[i]; - for (let j = i + 1; j < points.length; j++) { - const [x2, y2] = points[j]; - if (x1 !== x2 && y1 !== y2) { - if (pointSet.has(`${x1},${y2}`) && pointSet.has(`${x2},${y1}`)) { - const area = Math.abs(x1 - x2) * Math.abs(y1 - y2); - result = result === 0 ? area : Math.min(result, area); - } - } - } - } - - return result; -}; diff --git a/solutions/0940-distinct-subsequences-ii.js b/solutions/0940-distinct-subsequences-ii.js deleted file mode 100644 index 75bfddb3..00000000 --- a/solutions/0940-distinct-subsequences-ii.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 940. Distinct Subsequences II - * https://leetcode.com/problems/distinct-subsequences-ii/ - * Difficulty: Hard - * - * Given a string s, return the number of distinct non-empty subsequences of s. Since the answer - * may be very large, return it modulo 109 + 7. - * - * 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 - * @return {number} - */ -var distinctSubseqII = function(s) { - const MOD = 1e9 + 7; - const lastOccurrence = new Array(26).fill(-1); - const dp = new Array(s.length + 1).fill(0); - dp[0] = 1; - - for (let i = 0; i < s.length; i++) { - const charIndex = s.charCodeAt(i) - 97; - dp[i + 1] = (dp[i] * 2) % MOD; - if (lastOccurrence[charIndex] !== -1) { - dp[i + 1] = (dp[i + 1] - dp[lastOccurrence[charIndex]] + MOD) % MOD; - } - lastOccurrence[charIndex] = i; - } - - return (dp[s.length] - 1 + MOD) % MOD; -}; diff --git a/solutions/0941-valid-mountain-array.js b/solutions/0941-valid-mountain-array.js deleted file mode 100644 index ab21d61d..00000000 --- a/solutions/0941-valid-mountain-array.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 941. Valid Mountain Array - * https://leetcode.com/problems/valid-mountain-array/ - * Difficulty: Easy - * - * Given an array of integers arr, return true if and only if it is a valid mountain array. - * - * Recall that arr is a mountain array if and only if: - * - arr.length >= 3 - * - There exists some i with 0 < i < arr.length - 1 such that: - * - arr[0] < arr[1] < ... < arr[i - 1] < arr[i] - * - arr[i] > arr[i + 1] > ... > arr[arr.length - 1] - */ - -/** - * @param {number[]} arr - * @return {boolean} - */ -var validMountainArray = function(arr) { - if (arr.length < 3) return false; - - const peakIndex = arr.indexOf(Math.max(...arr)); - if (peakIndex === 0 || peakIndex === arr.length - 1) return false; - - for (let i = 1; i < peakIndex; i++) { - if (arr[i] <= arr[i - 1]) return false; - } - - for (let i = peakIndex + 1; i < arr.length; i++) { - if (arr[i] >= arr[i - 1]) return false; - } - - return true; -}; diff --git a/solutions/0942-di-string-match.js b/solutions/0942-di-string-match.js deleted file mode 100644 index 1cf3b528..00000000 --- a/solutions/0942-di-string-match.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 942. DI String Match - * https://leetcode.com/problems/di-string-match/ - * Difficulty: Easy - * - * A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented - * as a string s of length n where: - * - s[i] == 'I' if perm[i] < perm[i + 1], and - * - s[i] == 'D' if perm[i] > perm[i + 1]. - * - * Given a string s, reconstruct the permutation perm and return it. If there are multiple valid - * permutations perm, return any of them. - */ - -/** - * @param {string} s - * @return {number[]} - */ -var diStringMatch = function(s) { - const result = []; - let low = 0; - let high = s.length; - - for (const char of s) { - if (char === 'I') { - result.push(low); - low++; - } else { - result.push(high); - high--; - } - } - - result.push(low); - return result; -}; diff --git a/solutions/0943-find-the-shortest-superstring.js b/solutions/0943-find-the-shortest-superstring.js deleted file mode 100644 index d7d0b714..00000000 --- a/solutions/0943-find-the-shortest-superstring.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 943. Find the Shortest Superstring - * https://leetcode.com/problems/find-the-shortest-superstring/ - * Difficulty: Hard - * - * Given an array of strings words, return the smallest string that contains each string in words - * as a substring. If there are multiple valid strings of the smallest length, return any of them. - * - * You may assume that no string in words is a substring of another string in words. - */ - -/** - * @param {string[]} words - * @return {string} - */ -var shortestSuperstring = function(words) { - const n = words.length; - const overlap = Array(n).fill().map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if (i !== j) { - for (let k = Math.min(words[i].length, words[j].length); k > 0; k--) { - if (words[i].slice(-k) === words[j].slice(0, k)) { - overlap[i][j] = k; - break; - } - } - } - } - } - - const dp = new Array(1 << n).fill().map(() => new Array(n).fill('')); - for (let i = 0; i < n; i++) { - dp[1 << i][i] = words[i]; - } - - for (let mask = 1; mask < (1 << n); mask++) { - for (let i = 0; i < n; i++) { - if (!(mask & (1 << i))) continue; - for (let j = 0; j < n; j++) { - if (mask & (1 << j)) continue; - const nextMask = mask | (1 << j); - const candidate = dp[mask][i] + words[j].slice(overlap[i][j]); - if (dp[nextMask][j] === '' || candidate.length < dp[nextMask][j].length) { - dp[nextMask][j] = candidate; - } - } - } - } - - let result = dp[(1 << n) - 1][0]; - for (let i = 1; i < n; i++) { - if (dp[(1 << n) - 1][i].length < result.length) { - result = dp[(1 << n) - 1][i]; - } - } - - return result; -}; diff --git a/solutions/0944-delete-columns-to-make-sorted.js b/solutions/0944-delete-columns-to-make-sorted.js deleted file mode 100644 index a38647b9..00000000 --- a/solutions/0944-delete-columns-to-make-sorted.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 944. Delete Columns to Make Sorted - * https://leetcode.com/problems/delete-columns-to-make-sorted/ - * Difficulty: Easy - * - * You are given an array of n strings strs, all of the same length. - * - * The strings can be arranged such that there is one on each line, making a grid. - * - * For example, strs = ["abc", "bce", "cae"] can be arranged as follows: - * - abc - * - bce - * - cae - * - * You want to delete the columns that are not sorted lexicographically. In the above - * example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted, - * while column 1 ('b', 'c', 'a') is not, so you would delete column 1. - * - * Return the number of columns that you will delete. - */ - -/** - * @param {string[]} strs - * @return {number} - */ -var minDeletionSize = function(strs) { - let result = 0; - - for (let col = 0; col < strs[0].length; col++) { - for (let row = 1; row < strs.length; row++) { - if (strs[row][col] < strs[row - 1][col]) { - result++; - break; - } - } - } - - return result; -}; diff --git a/solutions/0945-minimum-increment-to-make-array-unique.js b/solutions/0945-minimum-increment-to-make-array-unique.js deleted file mode 100644 index 97f42ceb..00000000 --- a/solutions/0945-minimum-increment-to-make-array-unique.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 945. Minimum Increment to Make Array Unique - * https://leetcode.com/problems/minimum-increment-to-make-array-unique/ - * Difficulty: Medium - * - * You are given an integer array nums. In one move, you can pick an index i where - * 0 <= i < nums.length and increment nums[i] by 1. - * - * Return the minimum number of moves to make every value in nums unique. - * - * The test cases are generated so that the answer fits in a 32-bit integer. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minIncrementForUnique = function(nums) { - nums.sort((a, b) => a - b); - let result = 0; - - for (let i = 1, previous = nums[0]; i < nums.length; i++) { - if (nums[i] <= previous) { - previous++; - result += previous - nums[i]; - } else { - previous = nums[i]; - } - } - - return result; -}; diff --git a/solutions/0946-validate-stack-sequences.js b/solutions/0946-validate-stack-sequences.js deleted file mode 100644 index eb9cf29f..00000000 --- a/solutions/0946-validate-stack-sequences.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 946. Validate Stack Sequences - * https://leetcode.com/problems/validate-stack-sequences/ - * Difficulty: Medium - * - * Given two integer arrays pushed and popped each with distinct values, return true if this could - * have been the result of a sequence of push and pop operations on an initially empty stack, or - * false otherwise. - */ - -/** - * @param {number[]} pushed - * @param {number[]} popped - * @return {boolean} - */ -var validateStackSequences = function(pushed, popped) { - const stack = []; - let popIndex = 0; - - for (const number of pushed) { - stack.push(number); - - while (stack.length && stack[stack.length - 1] === popped[popIndex]) { - stack.pop(); - popIndex++; - } - } - - return stack.length === 0; -}; diff --git a/solutions/0947-most-stones-removed-with-same-row-or-column.js b/solutions/0947-most-stones-removed-with-same-row-or-column.js deleted file mode 100644 index 3957ebe5..00000000 --- a/solutions/0947-most-stones-removed-with-same-row-or-column.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 947. Most Stones Removed with Same Row or Column - * https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ - * Difficulty: Medium - * - * On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may - * have at most one stone. - * - * A stone can be removed if it shares either the same row or the same column as another stone - * that has not been removed. - * - * Given an array stones of length n where stones[i] = [xi, yi] represents the location of the - * ith stone, return the largest possible number of stones that can be removed. - */ - -/** - * @param {number[][]} stones - * @return {number} - */ -var removeStones = function(stones) { - const parent = new Map(); - const find = (stoneIndex) => { - if (!parent.has(stoneIndex)) { - parent.set(stoneIndex, stoneIndex); - } - if (parent.get(stoneIndex) !== stoneIndex) { - parent.set(stoneIndex, find(parent.get(stoneIndex))); - } - return parent.get(stoneIndex); - }; - - const union = (stone1, stone2) => { - parent.set(find(stone1), find(stone2)); - }; - - const stoneMap = new Map(); - for (let i = 0; i < stones.length; i++) { - const [row, col] = stones[i]; - const rowKey = `r${row}`; - const colKey = `c${col}`; - - if (stoneMap.has(rowKey)) { - union(i, stoneMap.get(rowKey)); - } else { - stoneMap.set(rowKey, i); - } - - if (stoneMap.has(colKey)) { - union(i, stoneMap.get(colKey)); - } else { - stoneMap.set(colKey, i); - } - } - - const uniqueGroups = new Set(); - for (let i = 0; i < stones.length; i++) { - uniqueGroups.add(find(i)); - } - - return stones.length - uniqueGroups.size; -}; diff --git a/solutions/0948-bag-of-tokens.js b/solutions/0948-bag-of-tokens.js deleted file mode 100644 index 122abcbb..00000000 --- a/solutions/0948-bag-of-tokens.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 948. Bag of Tokens - * https://leetcode.com/problems/bag-of-tokens/ - * Difficulty: Medium - * - * You start with an initial power of power, an initial score of 0, and a bag of tokens given as - * an integer array tokens, where each tokens[i] denotes the value of tokeni. - * - * Your goal is to maximize the total score by strategically playing these tokens. In one move, - * you can play an unplayed token in one of the two ways (but not both for the same token): - * - Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] - * power and gaining 1 score. - * - Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power - * and losing 1 score. - * - * Return the maximum possible score you can achieve after playing any number of tokens. - */ - -/** - * @param {number[]} tokens - * @param {number} power - * @return {number} - */ -var bagOfTokensScore = function(tokens, power) { - let score = 0; - let result = 0; - let left = 0; - let right = tokens.length - 1; - - tokens.sort((a, b) => a - b); - - while (left <= right && (power >= tokens[left] || score > 0)) { - while (left <= right && power >= tokens[left]) { - power -= tokens[left]; - score++; - left++; - } - result = Math.max(result, score); - - if (left <= right && score > 0) { - power += tokens[right]; - score--; - right--; - } - } - - return result; -}; diff --git a/solutions/0949-largest-time-for-given-digits.js b/solutions/0949-largest-time-for-given-digits.js deleted file mode 100644 index 853bb86e..00000000 --- a/solutions/0949-largest-time-for-given-digits.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 949. Largest Time for Given Digits - * https://leetcode.com/problems/largest-time-for-given-digits/ - * Difficulty: Medium - * - * Given an array arr of 4 digits, find the latest 24-hour time that can be made using - * each digit exactly once. - * - * 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between - * 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. - * - * Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return - * an empty string. - */ - -/** - * @param {number[]} arr - * @return {string} - */ -var largestTimeFromDigits = function(arr) { - let result = ''; - helper(arr, new Array(4).fill(false), []); - return result; - - function helper(digits, used, current) { - if (current.length === 4) { - const hours = parseInt(current.slice(0, 2).join('')); - const minutes = parseInt(current.slice(2).join('')); - if (hours <= 23 && minutes <= 59) { - const time = `${current[0]}${current[1]}:${current[2]}${current[3]}`; - if (time > result) result = time; - } - return; - } - - for (let i = 0; i < digits.length; i++) { - if (!used[i]) { - used[i] = true; - current.push(digits[i]); - helper(digits, used, current); - current.pop(); - used[i] = false; - } - } - } -}; diff --git a/solutions/0950-reveal-cards-in-increasing-order.js b/solutions/0950-reveal-cards-in-increasing-order.js deleted file mode 100644 index 5f616046..00000000 --- a/solutions/0950-reveal-cards-in-increasing-order.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 950. Reveal Cards In Increasing Order - * https://leetcode.com/problems/reveal-cards-in-increasing-order/ - * Difficulty: Medium - * - * You are given an integer array deck. There is a deck of cards where every card has a - * unique integer. The integer on the ith card is deck[i]. - * - * You can order the deck in any order you want. Initially, all the cards start face down - * (unrevealed) in one deck. - * - * You will do the following steps repeatedly until all cards are revealed: - * 1. Take the top card of the deck, reveal it, and take it out of the deck. - * 2. If there are still cards in the deck then put the next top card of the deck at the - * bottom of the deck. - * 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. - * - * Return an ordering of the deck that would reveal the cards in increasing order. - * - * Note that the first entry in the answer is considered to be the top of the deck. - */ - -/** - * @param {number[]} deck - * @return {number[]} - */ -var deckRevealedIncreasing = function(deck) { - deck.sort((a, b) => b - a); - const result = []; - - for (const card of deck) { - if (result.length) { - result.unshift(result.pop()); - } - result.unshift(card); - } - - return result; -}; diff --git a/solutions/0951-flip-equivalent-binary-trees.js b/solutions/0951-flip-equivalent-binary-trees.js deleted file mode 100644 index 7549a253..00000000 --- a/solutions/0951-flip-equivalent-binary-trees.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 951. Flip Equivalent Binary Trees - * https://leetcode.com/problems/flip-equivalent-binary-trees/ - * Difficulty: Medium - * - * For a binary tree T, we can define a flip operation as follows: choose any node, and swap the - * left and right child subtrees. - * - * A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y - * after some number of flip operations. - * - * Given the roots of two binary trees root1 and root2, return true if the two trees are flip - * equivalent or false otherwise. - */ - -/** - * 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 flipEquiv = function(root1, root2) { - return helper(root1, root2); - - function helper(node1, node2) { - if (!node1 && !node2) return true; - if (!node1 || !node2 || node1.val !== node2.val) return false; - return (helper(node1.left, node2.left) && helper(node1.right, node2.right)) - || (helper(node1.left, node2.right) && helper(node1.right, node2.left)); - } -}; diff --git a/solutions/0952-largest-component-size-by-common-factor.js b/solutions/0952-largest-component-size-by-common-factor.js deleted file mode 100644 index 81ff05c1..00000000 --- a/solutions/0952-largest-component-size-by-common-factor.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 952. Largest Component Size by Common Factor - * https://leetcode.com/problems/largest-component-size-by-common-factor/ - * Difficulty: Hard - * - * You are given an integer array of unique positive integers nums. Consider the following graph: - * - There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], - * - There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common - * factor greater than 1. - * - * Return the size of the largest connected component in the graph. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var largestComponentSize = function(nums) { - const max = Math.max(...nums); - const parent = new Array(max + 1).fill().map((_, i) => i); - const rank = new Array(max + 1).fill(0); - - for (const num of nums) { - for (let factor = 2; factor * factor <= num; factor++) { - if (num % factor === 0) { - union(parent, rank, num, factor); - union(parent, rank, num, num / factor); - } - } - } - - const map = new Map(); - let result = 0; - - for (const num of nums) { - const root = find(parent, num); - map.set(root, (map.get(root) || 0) + 1); - result = Math.max(result, map.get(root)); - } - - return result; - - function find(parent, x) { - if (parent[x] !== x) { - parent[x] = find(parent, parent[x]); - } - return parent[x]; - } - - function union(parent, rank, x, y) { - const rootX = find(parent, x); - const rootY = find(parent, y); - if (rootX !== rootY) { - if (rank[rootX] < rank[rootY]) { - parent[rootX] = rootY; - } else if (rank[rootX] > rank[rootY]) { - parent[rootY] = rootX; - } else { - parent[rootY] = rootX; - rank[rootX]++; - } - } - } -}; diff --git a/solutions/0953-verifying-an-alien-dictionary.js b/solutions/0953-verifying-an-alien-dictionary.js deleted file mode 100644 index 820f03e7..00000000 --- a/solutions/0953-verifying-an-alien-dictionary.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 953. Verifying an Alien Dictionary - * https://leetcode.com/problems/verifying-an-alien-dictionary/ - * Difficulty: Easy - * - * In an alien language, surprisingly, they also use English lowercase letters, but possibly - * in a different order. The order of the alphabet is some permutation of lowercase letters. - * - * Given a sequence of words written in the alien language, and the order of the alphabet, - * return true if and only if the given words are sorted lexicographically in this alien language. - */ - -/** - * @param {string[]} words - * @param {string} order - * @return {boolean} - */ -var isAlienSorted = function(words, order) { - const map = new Map(order.split('').map((char, index) => [char, index])); - - for (let i = 0; i < words.length - 1; i++) { - if (!helper(words[i], words[i + 1])) return false; - } - - return true; - - function helper(word1, word2) { - for (let i = 0; i < word1.length; i++) { - if (i >= word2.length) return false; - const char1 = map.get(word1[i]); - const char2 = map.get(word2[i]); - if (char1 < char2) return true; - if (char1 > char2) return false; - } - return true; - } -}; diff --git a/solutions/0954-array-of-doubled-pairs.js b/solutions/0954-array-of-doubled-pairs.js deleted file mode 100644 index 6cd531d9..00000000 --- a/solutions/0954-array-of-doubled-pairs.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 954. Array of Doubled Pairs - * https://leetcode.com/problems/array-of-doubled-pairs/ - * Difficulty: Medium - * - * Given an integer array of even length arr, return true if it is possible to reorder arr such - * that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise. - */ - -/** - * @param {number[]} arr - * @return {boolean} - */ -var canReorderDoubled = function(arr) { - const map = new Map(); - arr.sort((a, b) => Math.abs(a) - Math.abs(b)); - - for (const num of arr) { - map.set(num, (map.get(num) || 0) + 1); - } - for (const num of arr) { - if (map.get(num) === 0) continue; - if (!map.has(2 * num) || map.get(2 * num) === 0) return false; - - map.set(num, map.get(num) - 1); - map.set(2 * num, map.get(2 * num) - 1); - } - - return true; -}; diff --git a/solutions/0955-delete-columns-to-make-sorted-ii.js b/solutions/0955-delete-columns-to-make-sorted-ii.js deleted file mode 100644 index f261cc4a..00000000 --- a/solutions/0955-delete-columns-to-make-sorted-ii.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 955. Delete Columns to Make Sorted II - * https://leetcode.com/problems/delete-columns-to-make-sorted-ii/ - * Difficulty: Medium - * - * You are given an array of n strings strs, all of the same length. - * - * We may choose any deletion indices, and we delete all the characters in those indices - * for each string. - * - * For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then - * the final array after deletions is ["bef", "vyz"]. - * - * Suppose we chose a set of deletion indices answer such that after deletions, the final - * array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] - * <= ... <= strs[n - 1]). Return the minimum possible value of answer.length. - */ - -/** - * @param {string[]} strs - * @return {number} - */ -var minDeletionSize = function(strs) { - let previousSorted = new Array(strs.length).fill(''); - let result = 0; - - for (let col = 0; col < strs[0].length; col++) { - const currentSorted = previousSorted.slice(); - let isValid = true; - - for (let row = 0; row < strs.length; row++) { - currentSorted[row] += strs[row][col]; - if (row > 0 && currentSorted[row] < currentSorted[row - 1]) { - isValid = false; - break; - } - } - - if (isValid) { - previousSorted = currentSorted; - } else { - result++; - } - } - - return result; -}; diff --git a/solutions/0956-tallest-billboard.js b/solutions/0956-tallest-billboard.js deleted file mode 100644 index 358b4ef2..00000000 --- a/solutions/0956-tallest-billboard.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 956. Tallest Billboard - * https://leetcode.com/problems/tallest-billboard/ - * Difficulty: Hard - * - * You are installing a billboard and want it to have the largest height. The billboard will have - * two steel supports, one on each side. Each steel support must be an equal height. - * - * You are given a collection of rods that can be welded together. For example, if you have rods - * of lengths 1, 2, and 3, you can weld them together to make a support of length 6. - * - * Return the largest possible height of your billboard installation. If you cannot support the - * billboard, return 0. - */ - -/** - * @param {number[]} rods - * @return {number} - */ -var tallestBillboard = function(rods) { - const differences = new Map([[0, 0]]); - - for (const rod of rods) { - const currentDiffs = new Map(differences); - - for (const [diff, taller] of currentDiffs) { - const shorter = taller - diff; - const newDiff = diff + rod; - const newTaller = taller + rod; - differences.set(newDiff, Math.max(differences.get(newDiff) || 0, newTaller)); - - const diffAbs = Math.abs(diff - rod); - const diffMax = Math.max(shorter + rod, taller); - differences.set(diffAbs, Math.max(differences.get(diffAbs) || 0, diffMax)); - } - } - - return differences.get(0) || 0; -}; diff --git a/solutions/0957-prison-cells-after-n-days.js b/solutions/0957-prison-cells-after-n-days.js deleted file mode 100644 index b6dd88d0..00000000 --- a/solutions/0957-prison-cells-after-n-days.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 957. Prison Cells After N Days - * https://leetcode.com/problems/prison-cells-after-n-days/ - * Difficulty: Medium - * - * There are 8 prison cells in a row and each cell is either occupied or vacant. - * - * Each day, whether the cell is occupied or vacant changes according to the following rules: - * - If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell - * becomes occupied. - * - Otherwise, it becomes vacant. - * - * Note that because the prison is a row, the first and the last cells in the row can't have two - * adjacent neighbors. - * - * You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and - * cells[i] == 0 if the ith cell is vacant, and you are given an integer n. - * - * Return the state of the prison after n days (i.e., n such changes described above). - */ - -/** - * @param {number[]} cells - * @param {number} n - * @return {number[]} - */ -var prisonAfterNDays = function(cells, n) { - const nextState = cells => [ - 0, - ...Array.from({ length: 6 }, (_, i) => cells[i] === cells[i + 2] ? 1 : 0), - 0 - ]; - - let current = [...cells]; - const seen = new Map(); - let cycleLength = 0; - - while (n > 0) { - const stateKey = current.join(''); - if (seen.has(stateKey)) { - const cycleStart = seen.get(stateKey); - cycleLength = cycleStart - n; - n %= cycleLength; - } - seen.set(stateKey, n); - if (n > 0) { - current = nextState(current); - n--; - } - } - - return current; -}; diff --git a/solutions/0958-check-completeness-of-a-binary-tree.js b/solutions/0958-check-completeness-of-a-binary-tree.js deleted file mode 100644 index ad58422d..00000000 --- a/solutions/0958-check-completeness-of-a-binary-tree.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 958. Check Completeness of a Binary Tree - * https://leetcode.com/problems/check-completeness-of-a-binary-tree/ - * Difficulty: Medium - * - * Given the root of a binary tree, determine if it is a complete binary tree. - * - * In a complete binary tree, every level, except possibly the last, is completely filled, and - * all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes - * inclusive at the last level h. - */ - -/** - * 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 isCompleteTree = function(root) { - const queue = [root]; - let foundNull = false; - - while (queue.length) { - const node = queue.shift(); - if (!node) { - foundNull = true; - continue; - } - if (foundNull) return false; - queue.push(node.left); - queue.push(node.right); - } - - return true; -}; diff --git a/solutions/0959-regions-cut-by-slashes.js b/solutions/0959-regions-cut-by-slashes.js deleted file mode 100644 index ba2ee564..00000000 --- a/solutions/0959-regions-cut-by-slashes.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 959. Regions Cut By Slashes - * https://leetcode.com/problems/regions-cut-by-slashes/ - * Difficulty: Medium - * - * An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of - * a '/', '\', or blank space ' '. These characters divide the square into contiguous - * regions. - * - * Given the grid grid represented as a string array, return the number of regions. - * - * Note that backslash characters are escaped, so a '\' is represented as '\\'. - */ - -/** - * @param {string[]} grid - * @return {number} - */ -var regionsBySlashes = function(grid) { - const size = grid.length * 3; - const matrix = new Array(size).fill().map(() => new Array(size).fill(0)); - - for (let row = 0; row < grid.length; row++) { - for (let col = 0; col < grid.length; col++) { - const baseRow = row * 3; - const baseCol = col * 3; - if (grid[row][col] === '/') { - matrix[baseRow][baseCol + 2] = 1; - matrix[baseRow + 1][baseCol + 1] = 1; - matrix[baseRow + 2][baseCol] = 1; - } else if (grid[row][col] === '\\') { - matrix[baseRow][baseCol] = 1; - matrix[baseRow + 1][baseCol + 1] = 1; - matrix[baseRow + 2][baseCol + 2] = 1; - } - } - } - - let result = 0; - for (let row = 0; row < size; row++) { - for (let col = 0; col < size; col++) { - if (matrix[row][col] === 0) { - helper(row, col); - result++; - } - } - } - - return result; - - function helper(x, y) { - if (x < 0 || x >= size || y < 0 || y >= size || matrix[x][y] !== 0) return; - matrix[x][y] = 1; - helper(x + 1, y); - helper(x - 1, y); - helper(x, y + 1); - helper(x, y - 1); - } -}; diff --git a/solutions/0960-delete-columns-to-make-sorted-iii.js b/solutions/0960-delete-columns-to-make-sorted-iii.js deleted file mode 100644 index ea571754..00000000 --- a/solutions/0960-delete-columns-to-make-sorted-iii.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 960. Delete Columns to Make Sorted III - * https://leetcode.com/problems/delete-columns-to-make-sorted-iii/ - * Difficulty: Hard - * - * You are given an array of n strings strs, all of the same length. - * - * We may choose any deletion indices, and we delete all the characters in those indices - * for each string. - * - * For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then - * the final array after deletions is ["bef", "vyz"]. - * - * Suppose we chose a set of deletion indices answer such that after deletions, the final - * array has every string (row) in lexicographic order. (i.e., - * (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), - * and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), - * and so on). Return the minimum possible value of answer.length. - */ - -/** - * @param {string[]} strs - * @return {number} - */ -var minDeletionSize = function(strs) { - const isValid = (input, a, b) => input.every(row => row[a] <= row[b]); - const cols = strs[0].length; - const dp = new Array(cols).fill(1); - - for (let i = 1; i < cols; i++) { - for (let j = 0; j < i; j++) { - if (isValid(strs, j, i)) { - dp[i] = Math.max(dp[i], dp[j] + 1); - } - } - } - - return cols - Math.max(...dp); -}; diff --git a/solutions/0961-n-repeated-element-in-size-2n-array.js b/solutions/0961-n-repeated-element-in-size-2n-array.js deleted file mode 100644 index 6ecd7d83..00000000 --- a/solutions/0961-n-repeated-element-in-size-2n-array.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 961. N-Repeated Element in Size 2N Array - * https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ - * Difficulty: Easy - * - * You are given an integer array nums with the following properties: - * - nums.length == 2 * n. - * - nums contains n + 1 unique elements. - * - Exactly one element of nums is repeated n times. - * - * Return the element that is repeated n times. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var repeatedNTimes = function(nums) { - const map = {}; - for (let i = 0; i < nums.length; i++) { - if (!map[nums[i]]) map[nums[i]] = 1; - else return nums[i]; - } -}; diff --git a/solutions/0962-maximum-width-ramp.js b/solutions/0962-maximum-width-ramp.js deleted file mode 100644 index 464c9a59..00000000 --- a/solutions/0962-maximum-width-ramp.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 962. Maximum Width Ramp - * https://leetcode.com/problems/maximum-width-ramp/ - * Difficulty: Medium - * - * A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. - * The width of such a ramp is j - i. - * - * Given an integer array nums, return the maximum width of a ramp in nums. If there is no - * ramp in nums, return 0. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxWidthRamp = function(nums) { - const stack = []; - let result = 0; - - for (let i = 0; i < nums.length; i++) { - if (!stack.length || nums[stack.at(-1)] > nums[i]) { - stack.push(i); - } - } - - for (let j = nums.length - 1; j >= 0; j--) { - while (stack.length && nums[stack.at(-1)] <= nums[j]) { - result = Math.max(result, j - stack.pop()); - } - } - - return result; -}; diff --git a/solutions/0963-minimum-area-rectangle-ii.js b/solutions/0963-minimum-area-rectangle-ii.js deleted file mode 100644 index eb7615f1..00000000 --- a/solutions/0963-minimum-area-rectangle-ii.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 963. Minimum Area Rectangle II - * https://leetcode.com/problems/minimum-area-rectangle-ii/ - * Difficulty: Medium - * - * You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. - * - * Return the minimum area of any rectangle formed from these points, with sides not necessarily - * parallel to the X and Y axes. If there is not any such rectangle, return 0. - * - * Answers within 10^-5 of the actual answer will be accepted. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var minAreaFreeRect = function(points) { - const n = points.length; - const set = new Set(points.map(p => `${p[0]},${p[1]}`)); - let result = 0; - - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - const [x1, y1] = points[i]; - const [x2, y2] = points[j]; - const dx1 = x2 - x1; - const dy1 = y2 - y1; - - for (let k = 0; k < n; k++) { - if (k === i || k === j) continue; - const [x3, y3] = points[k]; - const dx2 = x3 - x1; - const dy2 = y3 - y1; - - if (dx1 * dx2 + dy1 * dy2 !== 0) continue; - - const x4 = x2 + dx2; - const y4 = y2 + dy2; - - if (set.has(`${x4},${y4}`)) { - const area = Math.sqrt(dx1 * dx1 + dy1 * dy1) * Math.sqrt(dx2 * dx2 + dy2 * dy2); - result = result === 0 ? area : Math.min(result, area); - } - } - } - } - - return result; -}; diff --git a/solutions/0964-least-operators-to-express-number.js b/solutions/0964-least-operators-to-express-number.js deleted file mode 100644 index d14d9a50..00000000 --- a/solutions/0964-least-operators-to-express-number.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 964. Least Operators to Express Number - * https://leetcode.com/problems/least-operators-to-express-number/ - * Difficulty: Hard - * - * Given a single positive integer x, we will write an expression of the form - * x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, - * subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, - * we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. - * - * When writing such an expression, we adhere to the following conventions: - * - The division operator (/) returns rational numbers. - * - There are no parentheses placed anywhere. - * - We use the usual order of operations: multiplication and division happen before - * addition and subtraction. - * - It is not allowed to use the unary negation operator (-). For example, "x - x" is - * a valid expression as it only uses subtraction, but "-x + x" is not because it uses - * negation. - * - * We would like to write an expression with the least number of operators such that the - * expression equals the given target. Return the least number of operators used. - */ - -/** - * @param {number} x - * @param {number} target - * @return {number} - */ -var leastOpsExpressTarget = function(x, target) { - let costP = 0; - let costN = 0; - let power = 0; - let minP; - let minN; - - while (target > 0) { - const digit = target % x; - target = Math.floor(target / x); - - if (power > 0) { - const nextPositive = Math.min(digit * power + costP, (digit + 1) * power + costN); - const nextNegative = Math.min((x - digit) * power + costP, (x - digit - 1) * power + costN); - costP = nextPositive; - costN = nextNegative; - } else { - costP = digit * 2; - costN = (x - digit) * 2; - } - - minP = costP; - minN = costN; - power++; - } - - return Math.min(minP, power + minN) - 1; -}; diff --git a/solutions/0965-univalued-binary-tree.js b/solutions/0965-univalued-binary-tree.js deleted file mode 100644 index b4c3c682..00000000 --- a/solutions/0965-univalued-binary-tree.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 965. Univalued Binary Tree - * https://leetcode.com/problems/univalued-binary-tree/ - * Difficulty: Easy - * - * A binary tree is uni-valued if every node in the tree has the same value. - * - * Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise. - */ - -/** - * 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 isUnivalTree = function(root) { - const traverse = n => !n ? true : n.val === root.val && isUnivalTree(n); - return traverse(root.left) && traverse(root.right); -}; diff --git a/solutions/0967-numbers-with-same-consecutive-differences.js b/solutions/0967-numbers-with-same-consecutive-differences.js deleted file mode 100644 index c4eb0331..00000000 --- a/solutions/0967-numbers-with-same-consecutive-differences.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 967. Numbers With Same Consecutive Differences - * https://leetcode.com/problems/numbers-with-same-consecutive-differences/ - * Difficulty: Medium - * - * Given two integers n and k, return an array of all the integers of length n where the difference - * between every two consecutive digits is k. You may return the answer in any order. - * - * Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number[]} - */ -var numsSameConsecDiff = function(n, k) { - const result = []; - - for (let digit = 1; digit <= 9; digit++) { - buildNumber(digit, n - 1); - } - - return result; - - function buildNumber(current, digitsLeft) { - if (digitsLeft === 0) { - result.push(current); - return; - } - - const lastDigit = current % 10; - - if (lastDigit + k <= 9) { - buildNumber(current * 10 + lastDigit + k, digitsLeft - 1); - } - - if (k !== 0 && lastDigit - k >= 0) { - buildNumber(current * 10 + lastDigit - k, digitsLeft - 1); - } - } -}; diff --git a/solutions/0968-binary-tree-cameras.js b/solutions/0968-binary-tree-cameras.js deleted file mode 100644 index bd1df9bc..00000000 --- a/solutions/0968-binary-tree-cameras.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 968. Binary Tree Cameras - * https://leetcode.com/problems/binary-tree-cameras/ - * Difficulty: Hard - * - * You are given the root of a binary tree. We install cameras on the tree nodes where each camera - * at a node can monitor its parent, itself, and its immediate children. - * - * Return the minimum number of cameras needed to monitor all nodes of the tree. - */ - -/** - * 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 minCameraCover = function(root) { - let cameras = 0; - const rootState = traverse(root); - return rootState === 0 ? cameras + 1 : cameras; - - function traverse(node) { - if (!node) return 1; - - const left = traverse(node.left); - const right = traverse(node.right); - - if (left === 0 || right === 0) { - cameras++; - return 2; - } - - if (left === 2 || right === 2) { - return 1; - } - - return 0; - } -}; diff --git a/solutions/0969-pancake-sorting.js b/solutions/0969-pancake-sorting.js deleted file mode 100644 index 1c280ca5..00000000 --- a/solutions/0969-pancake-sorting.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 969. Pancake Sorting - * https://leetcode.com/problems/pancake-sorting/ - * Difficulty: Medium - * - * Given an array of integers arr, sort the array by performing a series of pancake flips. - * - * In one pancake flip we do the following steps: - * - Choose an integer k where 1 <= k <= arr.length. - * - Reverse the sub-array arr[0...k-1] (0-indexed). - * - * For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse - * the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3. - * - * Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. - * Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct. - */ - -/** - * @param {number[]} arr - * @return {number[]} - */ -var pancakeSort = function(arr) { - const result = []; - let end = arr.length; - - while (end > 1) { - const maxIndex = arr.indexOf(end); - - if (maxIndex !== end - 1) { - if (maxIndex !== 0) { - result.push(maxIndex + 1); - reverse(arr, maxIndex); - } - result.push(end); - reverse(arr, end - 1); - } - end--; - } - - return result; -}; - -function reverse(arr, k) { - let left = 0; - while (left < k) { - [arr[left], arr[k]] = [arr[k], arr[left]]; - left++; - k--; - } -} diff --git a/solutions/0971-flip-binary-tree-to-match-preorder-traversal.js b/solutions/0971-flip-binary-tree-to-match-preorder-traversal.js deleted file mode 100644 index 1034260c..00000000 --- a/solutions/0971-flip-binary-tree-to-match-preorder-traversal.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 971. Flip Binary Tree To Match Preorder Traversal - * https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/ - * Difficulty: Medium - * - * You are given the root of a binary tree with n nodes, where each node is uniquely assigned a - * value from 1 to n. You are also given a sequence of n values voyage, which is the desired - * pre-order traversal of the binary tree. - * - * Any node in the binary tree can be flipped by swapping its left and right subtrees. For - * example, flipping node 1 will have the following effect. - * - * Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. - * - * Return a list of the values of all flipped nodes. You may return the answer in any order. - * If it is impossible to flip the nodes in the tree to make the pre-order traversal match - * voyage, return the list [-1]. - */ - -/** - * 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[]} voyage - * @return {number[]} - */ -var flipMatchVoyage = function(root, voyage) { - const flips = []; - let index = 0; - return traverse(root) ? flips : [-1]; - - function traverse(node) { - if (!node) return true; - if (node.val !== voyage[index++]) return false; - - if (!node.left) return traverse(node.right); - if (node.left.val === voyage[index]) return traverse(node.left) && traverse(node.right); - - flips.push(node.val); - [node.left, node.right] = [node.right, node.left]; - return traverse(node.left) && traverse(node.right); - } -}; diff --git a/solutions/0972-equal-rational-numbers.js b/solutions/0972-equal-rational-numbers.js deleted file mode 100644 index 66c177db..00000000 --- a/solutions/0972-equal-rational-numbers.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 972. Equal Rational Numbers - * https://leetcode.com/problems/equal-rational-numbers/ - * Difficulty: Hard - * - * Given two strings s and t, each of which represents a non-negative rational number, return true - * if and only if they represent the same number. The strings may use parentheses to denote the - * repeating part of the rational number. - * - * A rational number can be represented using up to three parts: , , - * and a . The number will be represented in one of the following three ways: - * - - * - For example, 12, 0, and 123. - * - <.> - * - For example, 0.5, 1., 2.12, and 123.0001. - * - <.><(><)> - * - For example, 0.1(6), 1.(9), 123.00(1212). - * - * The repeating portion of a decimal expansion is conventionally denoted within a pair of round - * brackets. For example: - * - 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66). - */ - -/** - * @param {string} s - * @param {string} t - * @return {boolean} - */ -var isRationalEqual = function(s, t) { - const valueS = parseRational(s); - const valueT = parseRational(t); - return Math.abs(valueS - valueT) < 1e-10; - - function parseRational(str) { - const [integer, decimal] = str.split('.'); - if (!decimal) return parseInt(integer, 10); - - const openParen = decimal.indexOf('('); - if (openParen === -1) return parseInt(integer, 10) + parseFloat(`0.${decimal}`); - - const nonRepeating = decimal.slice(0, openParen); - const repeating = decimal.slice(openParen + 1, -1); - const nonRepeatValue = nonRepeating ? parseFloat(`0.${nonRepeating}`) : 0; - const repeatValue = parseInt(repeating, 10) / (10 ** repeating.length - 1) - / (10 ** nonRepeating.length); - - return parseInt(integer, 10) + nonRepeatValue + repeatValue; - } -}; diff --git a/solutions/0973-k-closest-points-to-origin.js b/solutions/0973-k-closest-points-to-origin.js deleted file mode 100644 index aafbaf26..00000000 --- a/solutions/0973-k-closest-points-to-origin.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 973. K Closest Points to Origin - * https://leetcode.com/problems/k-closest-points-to-origin/ - * Difficulty: Medium - * - * Given an array of points where points[i] = [xi, yi] represents a point on the X-Y - * plane and an integer k, return the k closest points to the origin (0, 0). - * - * The distance between two points on the X-Y plane is the Euclidean distance - * (i.e., √(x1 - x2)2 + (y1 - y2)2). - * - * You may return the answer in any order. The answer is guaranteed to be unique - * (except for the order that it is in). - */ - -/** - * @param {number[][]} points - * @param {number} k - * @return {number[][]} - */ -var kClosest = function(points, k) { - const getDistance = (x, y) => x * x + y * y; - - return points - .map(point => ({ point, dist: getDistance(point[0], point[1]) })) - .sort((a, b) => a.dist - b.dist) - .slice(0, k) - .map(item => item.point); -}; diff --git a/solutions/0974-subarray-sums-divisible-by-k.js b/solutions/0974-subarray-sums-divisible-by-k.js deleted file mode 100644 index 9c93e956..00000000 --- a/solutions/0974-subarray-sums-divisible-by-k.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 974. Subarray Sums Divisible by K - * https://leetcode.com/problems/subarray-sums-divisible-by-k/ - * Difficulty: Medium - * - * Given an integer array nums and an integer k, return the number of non-empty subarrays - * that have a sum divisible by k. - * - * A subarray is a contiguous part of an array. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var subarraysDivByK = function(nums, k) { - const remainderCount = new Map([[0, 1]]); - let sum = 0; - let result = 0; - - for (const num of nums) { - sum += num; - const remainder = ((sum % k) + k) % k; - result += remainderCount.get(remainder) || 0; - remainderCount.set(remainder, (remainderCount.get(remainder) || 0) + 1); - } - - return result; -}; diff --git a/solutions/0975-odd-even-jump.js b/solutions/0975-odd-even-jump.js deleted file mode 100644 index b63b8062..00000000 --- a/solutions/0975-odd-even-jump.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 975. Odd Even Jump - * https://leetcode.com/problems/odd-even-jump/ - * Difficulty: Hard - * - * You are given an integer array arr. From some starting index, you can make a series of jumps. - * The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, - * 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are - * numbered, not the indices. - * - * You may jump forward from index i to index j (with i < j) in the following way: - * - During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that - * arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such - * indices j, you can only jump to the smallest such index j. - * - During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that - * arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such - * indices j, you can only jump to the smallest such index j. - * - It may be the case that for some index i, there are no legal jumps. - * - * A starting index is good if, starting from that index, you can reach the end of the array (index - * arr.length - 1) by jumping some number of times (possibly 0 or more than once). - * - * Return the number of good starting indices. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var oddEvenJumps = function(arr) { - const oddCanReach = new Array(arr.length).fill(false); - const evenCanReach = new Array(arr.length).fill(false); - oddCanReach[arr.length - 1] = true; - evenCanReach[arr.length - 1] = true; - let result = 1; - - const sortedIndices = Array.from({ length: arr.length }, (_, i) => i); - sortedIndices.sort((a, b) => arr[a] - arr[b] || a - b); - - const oddNext = new Array(arr.length); - const evenNext = new Array(arr.length); - const stack = []; - - for (const i of sortedIndices) { - while (stack.length && stack[stack.length - 1] < i) { - oddNext[stack.pop()] = i; - } - stack.push(i); - } - - sortedIndices.sort((a, b) => arr[b] - arr[a] || a - b); - stack.length = 0; - - for (const i of sortedIndices) { - while (stack.length && stack[stack.length - 1] < i) { - evenNext[stack.pop()] = i; - } - stack.push(i); - } - - for (let i = arr.length - 2; i >= 0; i--) { - if (oddNext[i] !== undefined) { - oddCanReach[i] = evenCanReach[oddNext[i]]; - if (oddCanReach[i]) result++; - } - if (evenNext[i] !== undefined) { - evenCanReach[i] = oddCanReach[evenNext[i]]; - } - } - - return result; -}; diff --git a/solutions/0977-squares-of-a-sorted-array.js b/solutions/0977-squares-of-a-sorted-array.js deleted file mode 100644 index e1a37507..00000000 --- a/solutions/0977-squares-of-a-sorted-array.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 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); -}; diff --git a/solutions/0978-longest-turbulent-subarray.js b/solutions/0978-longest-turbulent-subarray.js deleted file mode 100644 index a5bbbb77..00000000 --- a/solutions/0978-longest-turbulent-subarray.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 978. Longest Turbulent Subarray - * https://leetcode.com/problems/longest-turbulent-subarray/ - * Difficulty: Medium - * - * Given an integer array arr, return the length of a maximum size turbulent subarray of arr. - * - * A subarray is turbulent if the comparison sign flips between each adjacent pair of elements - * in the subarray. - * - * More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent - * if and only if: - * - For i <= k < j: - * - arr[k] > arr[k + 1] when k is odd, and - * - arr[k] < arr[k + 1] when k is even. - * - Or, for i <= k < j: - * - arr[k] > arr[k + 1] when k is even, and - * - arr[k] < arr[k + 1] when k is odd. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var maxTurbulenceSize = function(arr) { - let result = 1; - let inc = 1; - let dec = 1; - - for (let i = 1; i < arr.length; i++) { - if (arr[i] > arr[i - 1]) { - inc = dec + 1; - dec = 1; - } else if (arr[i] < arr[i - 1]) { - dec = inc + 1; - inc = 1; - } else { - inc = 1; - dec = 1; - } - result = Math.max(result, inc, dec); - } - - return result; -}; diff --git a/solutions/0979-distribute-coins-in-binary-tree.js b/solutions/0979-distribute-coins-in-binary-tree.js deleted file mode 100644 index 9165e272..00000000 --- a/solutions/0979-distribute-coins-in-binary-tree.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 979. Distribute Coins in Binary Tree - * https://leetcode.com/problems/distribute-coins-in-binary-tree/ - * Difficulty: Medium - * - * You are given the root of a binary tree with n nodes where each node in the tree has node.val - * coins. There are n coins in total throughout the whole tree. - * - * In one move, we may choose two adjacent nodes and move one coin from one node to another. - * A move may be from parent to child, or from child to parent. - * - * Return the minimum number of moves required to make every node have exactly one coin. - */ - -/** - * 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 distributeCoins = function(root) { - let result = 0; - traverse(root); - return result; - - function traverse(node) { - if (!node) return 0; - - const leftExcess = traverse(node.left); - const rightExcess = traverse(node.right); - const totalExcess = node.val + leftExcess + rightExcess - 1; - - result += Math.abs(leftExcess) + Math.abs(rightExcess); - - return totalExcess; - } -}; diff --git a/solutions/0980-unique-paths-iii.js b/solutions/0980-unique-paths-iii.js deleted file mode 100644 index 9ab7e533..00000000 --- a/solutions/0980-unique-paths-iii.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 980. Unique Paths III - * https://leetcode.com/problems/unique-paths-iii/ - * Difficulty: Hard - * - * You are given an m x n integer array grid where grid[i][j] could be: - * - 1 representing the starting square. There is exactly one starting square. - * - 2 representing the ending square. There is exactly one ending square. - * - 0 representing empty squares we can walk over. - * - -1 representing obstacles that we cannot walk over. - * - * Return the number of 4-directional walks from the starting square to the ending - * square, that walk over every non-obstacle square exactly once. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var uniquePathsIII = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - let emptySquares = 0; - let startRow; - let startCol; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j] === 0) emptySquares++; - if (grid[i][j] === 1) [startRow, startCol] = [i, j]; - } - } - - function explorePaths(row, col, remaining) { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] < 0) { - return 0; - } - if (grid[row][col] === 2) { - return remaining === 0 ? 1 : 0; - } - - const current = grid[row][col]; - grid[row][col] = -1; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - let pathCount = 0; - - for (const [dr, dc] of directions) { - pathCount += explorePaths(row + dr, col + dc, remaining - 1); - } - - grid[row][col] = current; - return pathCount; - } - - return explorePaths(startRow, startCol, emptySquares + 1); -}; diff --git a/solutions/0981-time-based-key-value-store.js b/solutions/0981-time-based-key-value-store.js deleted file mode 100644 index ff488f90..00000000 --- a/solutions/0981-time-based-key-value-store.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 981. Time Based Key-Value Store - * https://leetcode.com/problems/time-based-key-value-store/ - * Difficulty: Medium - * - * Design a time-based key-value data structure that can store multiple values for the same key - * at different time stamps and retrieve the key's value at a certain timestamp. - * - * Implement the TimeMap class: - * - TimeMap() Initializes the object of the data structure. - * - void set(String key, String value, int timestamp) Stores the key key with the value value - * at the given time timestamp. - * - String get(String key, int timestamp) Returns a value such that set was called previously, - * with timestamp_prev <= timestamp. If there are multiple such values, it returns the value - * associated with the largest timestamp_prev. If there are no values, it returns "". - */ - -var TimeMap = function() { - this.store = new Map(); -}; - -/** - * @param {string} key - * @param {string} value - * @param {number} timestamp - * @return {void} - */ -TimeMap.prototype.set = function(key, value, timestamp) { - if (!this.store.has(key)) this.store.set(key, []); - this.store.get(key).push([timestamp, value]); -}; - -/** - * @param {string} key - * @param {number} timestamp - * @return {string} - */ -TimeMap.prototype.get = function(key, timestamp) { - if (!this.store.has(key)) return ''; - const entries = this.store.get(key); - let left = 0; - let right = entries.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const [midTime, midValue] = entries[mid]; - - if (midTime === timestamp) return midValue; - if (midTime < timestamp) left = mid + 1; - else right = mid - 1; - } - - return right >= 0 ? entries[right][1] : ''; -}; diff --git a/solutions/0982-triples-with-bitwise-and-equal-to-zero.js b/solutions/0982-triples-with-bitwise-and-equal-to-zero.js deleted file mode 100644 index c9fed561..00000000 --- a/solutions/0982-triples-with-bitwise-and-equal-to-zero.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 982. Triples with Bitwise AND Equal To Zero - * https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/ - * Difficulty: Hard - * - * Given an integer array nums, return the number of AND triples. - * - * An AND triple is a triple of indices (i, j, k) such that: - * - 0 <= i < nums.length - * - 0 <= j < nums.length - * - 0 <= k < nums.length - * - nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var countTriplets = function(nums) { - const map = new Map(); - - for (const first of nums) { - for (const second of nums) { - const pairAnd = first & second; - map.set(pairAnd, (map.get(pairAnd) || 0) + 1); - } - } - - let result = 0; - for (const third of nums) { - for (const [pair, count] of map) { - if ((pair & third) === 0) { - result += count; - } - } - } - - return result; -}; diff --git a/solutions/0983-minimum-cost-for-tickets.js b/solutions/0983-minimum-cost-for-tickets.js deleted file mode 100644 index e322fed9..00000000 --- a/solutions/0983-minimum-cost-for-tickets.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 983. Minimum Cost For Tickets - * https://leetcode.com/problems/minimum-cost-for-tickets/ - * Difficulty: Medium - * - * You have planned some train traveling one year in advance. The days of the year in which you will - * travel are given as an integer array days. Each day is an integer from 1 to 365. - * - * Train tickets are sold in three different ways: - * - a 1-day pass is sold for costs[0] dollars, - * - a 7-day pass is sold for costs[1] dollars, and - * - a 30-day pass is sold for costs[2] dollars. - * - * The passes allow that many days of consecutive travel. - * - * For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, - * and 8. - * - * Return the minimum number of dollars you need to travel every day in the given list of days. - */ - -/** - * @param {number[]} days - * @param {number[]} costs - * @return {number} - */ -var mincostTickets = function(days, costs) { - const lastDay = days[days.length - 1]; - const travelDays = new Set(days); - const minCost = new Array(lastDay + 1).fill(0); - - for (let day = 1; day <= lastDay; day++) { - if (!travelDays.has(day)) { - minCost[day] = minCost[day - 1]; - continue; - } - - const oneDayCost = minCost[day - 1] + costs[0]; - const sevenDayCost = minCost[Math.max(0, day - 7)] + costs[1]; - const thirtyDayCost = minCost[Math.max(0, day - 30)] + costs[2]; - - minCost[day] = Math.min(oneDayCost, sevenDayCost, thirtyDayCost); - } - - return minCost[lastDay]; -}; diff --git a/solutions/0984-string-without-aaa-or-bbb.js b/solutions/0984-string-without-aaa-or-bbb.js deleted file mode 100644 index 9e7ffc42..00000000 --- a/solutions/0984-string-without-aaa-or-bbb.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 984. String Without AAA or BBB - * https://leetcode.com/problems/string-without-aaa-or-bbb/ - * Difficulty: Medium - * - * Given two integers a and b, return any string s such that: - * - s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters, - * - The substring 'aaa' does not occur in s, and - * - The substring 'bbb' does not occur in s. - */ - -/** - * @param {number} a - * @param {number} b - * @return {string} - */ -var strWithout3a3b = function(a, b) { - let result = ''; - - while (a > 0 || b > 0) { - if (a > b && a > 0 && !result.endsWith('aa')) { - result += 'a'; - a--; - } else if (b > 0 && !result.endsWith('bb')) { - result += 'b'; - b--; - } else if (a > 0) { - result += 'a'; - a--; - } else { - result += 'b'; - b--; - } - } - - return result; -}; diff --git a/solutions/0986-interval-list-intersections.js b/solutions/0986-interval-list-intersections.js deleted file mode 100644 index a76ba509..00000000 --- a/solutions/0986-interval-list-intersections.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 986. Interval List Intersections - * https://leetcode.com/problems/interval-list-intersections/ - * Difficulty: Medium - * - * You are given two lists of closed intervals, firstList and secondList, where - * firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of - * intervals is pairwise disjoint and in sorted order. - * - * Return the intersection of these two interval lists. - * - * A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. - * - * The intersection of two closed intervals is a set of real numbers that are either empty - * or represented as a closed interval. For example, the intersection of [1, 3] and - * [2, 4] is [2, 3]. - */ - -/** - * @param {number[][]} firstList - * @param {number[][]} secondList - * @return {number[][]} - */ -var intervalIntersection = function(firstList, secondList) { - const result = []; - let i = 0; - let j = 0; - - while (i < firstList.length && j < secondList.length) { - const start = Math.max(firstList[i][0], secondList[j][0]); - const end = Math.min(firstList[i][1], secondList[j][1]); - - if (start <= end) { - result.push([start, end]); - } - - if (firstList[i][1] < secondList[j][1]) { - i++; - } else { - j++; - } - } - - return result; -}; diff --git a/solutions/0987-vertical-order-traversal-of-a-binary-tree.js b/solutions/0987-vertical-order-traversal-of-a-binary-tree.js deleted file mode 100644 index 94b171e3..00000000 --- a/solutions/0987-vertical-order-traversal-of-a-binary-tree.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 987. Vertical Order Traversal of a Binary Tree - * https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ - * Difficulty: Hard - * - * Given the root of a binary tree, calculate the vertical order traversal of the binary tree. - * - * For each node at position (row, col), its left and right children will be at positions - * (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). - * - * The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each - * column index starting from the leftmost column and ending on the rightmost column. There may - * be multiple nodes in the same row and same column. In such a case, sort these nodes by their - * values. - * - * Return the vertical order traversal of the binary tree. - */ - -/** - * 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 verticalTraversal = function(root) { - const nodes = []; - - function traverse(node, row, col) { - if (!node) return; - nodes.push([col, row, node.val]); - traverse(node.left, row + 1, col - 1); - traverse(node.right, row + 1, col + 1); - } - - traverse(root, 0, 0); - nodes.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]); - - const result = []; - let currentCol = nodes[0][0]; - let currentGroup = []; - - for (const [col, _, val] of nodes) { - if (col !== currentCol) { - result.push(currentGroup); - currentGroup = [val]; - currentCol = col; - } else { - currentGroup.push(val); - } - } - - result.push(currentGroup); - return result; -}; diff --git a/solutions/0988-smallest-string-starting-from-leaf.js b/solutions/0988-smallest-string-starting-from-leaf.js deleted file mode 100644 index 08c48eb8..00000000 --- a/solutions/0988-smallest-string-starting-from-leaf.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 988. Smallest String Starting From Leaf - * https://leetcode.com/problems/smallest-string-starting-from-leaf/ - * Difficulty: Medium - * - * You are given the root of a binary tree where each node has a value in the range [0, 25] - * representing the letters 'a' to 'z'. - * - * Return the lexicographically smallest string that starts at a leaf of this tree and ends - * at the root. - * - * As a reminder, any shorter prefix of a string is lexicographically smaller. - * - * For example, "ab" is lexicographically smaller than "aba". - * - * A leaf of a node is a node that has 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 {string} - */ -var smallestFromLeaf = function(root) { - let result = null; - traverse(root, []); - return result || ''; - - function traverse(node, path) { - if (!node) return; - - path.unshift(String.fromCharCode(node.val + 97)); - - if (!node.left && !node.right) { - const current = path.join(''); - if (!result || current < result) { - result = current; - } - } - - traverse(node.left, path); - traverse(node.right, path); - path.shift(); - } -}; diff --git a/solutions/0990-satisfiability-of-equality-equations.js b/solutions/0990-satisfiability-of-equality-equations.js deleted file mode 100644 index d30bcb34..00000000 --- a/solutions/0990-satisfiability-of-equality-equations.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 990. Satisfiability of Equality Equations - * https://leetcode.com/problems/satisfiability-of-equality-equations/ - * Difficulty: Medium - * - * You are given an array of strings equations that represent relationships between variables where - * each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or - * "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent - * one-letter variable names. - * - * Return true if it is possible to assign integers to variable names so as to satisfy all the given - * equations, or false otherwise. - */ - -/** - * @param {string[]} equations - * @return {boolean} - */ -var equationsPossible = function(equations) { - const parent = new Array(26).fill(0).map((_, i) => i); - - for (const equation of equations) { - if (equation[1] === '=') { - const x = equation[0].charCodeAt(0) - 97; - const y = equation[3].charCodeAt(0) - 97; - union(x, y); - } - } - - for (const equation of equations) { - if (equation[1] === '!') { - const x = equation[0].charCodeAt(0) - 97; - const y = equation[3].charCodeAt(0) - 97; - if (find(x) === find(y)) { - return false; - } - } - } - - return true; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - parent[find(x)] = find(y); - } -}; diff --git a/solutions/0991-broken-calculator.js b/solutions/0991-broken-calculator.js deleted file mode 100644 index 7dd62328..00000000 --- a/solutions/0991-broken-calculator.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 991. Broken Calculator - * https://leetcode.com/problems/broken-calculator/ - * Difficulty: Medium - * - * There is a broken calculator that has the integer startValue on its display initially. - * In one operation, you can: - * - multiply the number on display by 2, or - * - subtract 1 from the number on display. - * - * Given two integers startValue and target, return the minimum number of operations needed - * to display target on the calculator. - */ - -/** - * @param {number} startValue - * @param {number} target - * @return {number} - */ -var brokenCalc = function(startValue, target) { - let operations = 0; - let current = target; - - while (current > startValue) { - if (current % 2 === 0) { - current = current / 2; - } else { - current++; - } - operations++; - } - - return operations + startValue - current; -}; diff --git a/solutions/0992-subarrays-with-k-different-integers.js b/solutions/0992-subarrays-with-k-different-integers.js deleted file mode 100644 index de53eb5a..00000000 --- a/solutions/0992-subarrays-with-k-different-integers.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 992. Subarrays with K Different Integers - * https://leetcode.com/problems/subarrays-with-k-different-integers/ - * Difficulty: Hard - * - * Given an integer array nums and an integer k, return the number of good subarrays of nums. - * - * A good array is an array where the number of different integers in that array is exactly k. - * - * For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. - * - * A subarray is a contiguous part of an array. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var subarraysWithKDistinct = function(nums, k) { - return countAtMostK(k) - countAtMostK(k - 1); - - function countAtMostK(distinct) { - const map = new Map(); - let left = 0; - let result = 0; - - for (let right = 0; right < nums.length; right++) { - map.set(nums[right], (map.get(nums[right]) || 0) + 1); - - while (map.size > distinct) { - map.set(nums[left], map.get(nums[left]) - 1); - if (map.get(nums[left]) === 0) { - map.delete(nums[left]); - } - left++; - } - - result += right - left + 1; - } - - return result; - } -}; diff --git a/solutions/0993-cousins-in-binary-tree.js b/solutions/0993-cousins-in-binary-tree.js deleted file mode 100644 index 12621f03..00000000 --- a/solutions/0993-cousins-in-binary-tree.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 993. Cousins in Binary Tree - * https://leetcode.com/problems/cousins-in-binary-tree/ - * Difficulty: Easy - * - * Given the root of a binary tree with unique values and the values of two different nodes of the - * tree x and y, return true if the nodes corresponding to the values x and y in the tree are - * cousins, or false otherwise. - * - * Two nodes of a binary tree are cousins if they have the same depth with different parents. - * - * Note that in a binary tree, the root node is at the depth 0, and children of each depth k node - * are at the depth k + 1. - */ - -/** - * 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} x - * @param {number} y - * @return {boolean} - */ -var isCousins = function(root, x, y) { - let xDepth = 0; - let yDepth = 0; - let xParent = null; - - traverse(root, 0, null); - - return xDepth === yDepth && xParent !== yParent; - - function traverse(node, depth, parent) { - if (!node) return; - - if (node.val === x) { - xDepth = depth; - xParent = parent; - } - if (node.val === y) { - yDepth = depth; - yParent = parent; - } - - traverse(node.left, depth + 1, node); - traverse(node.right, depth + 1, node); - } -}; diff --git a/solutions/0995-minimum-number-of-k-consecutive-bit-flips.js b/solutions/0995-minimum-number-of-k-consecutive-bit-flips.js deleted file mode 100644 index de8b84cd..00000000 --- a/solutions/0995-minimum-number-of-k-consecutive-bit-flips.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 995. Minimum Number of K Consecutive Bit Flips - * https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/ - * Difficulty: Hard - * - * You are given a binary array nums and an integer k. - * - * A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in - * the subarray to 1, and every 1 in the subarray to 0. - * - * Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is - * not possible, return -1. - * - * A subarray is a contiguous part of an array. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var minKBitFlips = function(nums, k) { - const queue = []; - let flipCount = 0; - let result = 0; - - for (let i = 0; i < nums.length; i++) { - if (queue.length && queue[0] === i) { - queue.shift(); - flipCount--; - } - - if ((nums[i] + flipCount) % 2 === 0) { - if (i + k > nums.length) return -1; - result++; - flipCount++; - queue.push(i + k); - } - } - - return result; -}; diff --git a/solutions/0996-number-of-squareful-arrays.js b/solutions/0996-number-of-squareful-arrays.js deleted file mode 100644 index b9578cc5..00000000 --- a/solutions/0996-number-of-squareful-arrays.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 996. Number of Squareful Arrays - * https://leetcode.com/problems/number-of-squareful-arrays/ - * Difficulty: Hard - * - * An array is squareful if the sum of every pair of adjacent elements is a perfect square. - * - * Given an integer array nums, return the number of permutations of nums that are squareful. - * - * Two permutations perm1 and perm2 are different if there is some index i such that - * perm1[i] != perm2[i]. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var numSquarefulPerms = function(nums) { - nums.sort((a, b) => a - b); - const length = nums.length; - const used = new Array(length).fill(false); - let result = 0; - - generatePermutations(0, length); - return result; - - function isPerfectSquare(num) { - const sqrt = Math.sqrt(num); - return Number.isInteger(sqrt); - } - - function generatePermutations(prevNum, remaining) { - if (remaining === 0) { - result++; - return; - } - - for (let i = 0; i < length; i++) { - if (!used[i] && (i === 0 || nums[i] !== nums[i-1] || used[i-1]) - && (remaining === length || isPerfectSquare(prevNum + nums[i]))) { - used[i] = true; - generatePermutations(nums[i], remaining - 1); - used[i] = false; - } - } - } -}; diff --git a/solutions/0998-maximum-binary-tree-ii.js b/solutions/0998-maximum-binary-tree-ii.js deleted file mode 100644 index 055cb23a..00000000 --- a/solutions/0998-maximum-binary-tree-ii.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 998. Maximum Binary Tree II - * https://leetcode.com/problems/maximum-binary-tree-ii/ - * Difficulty: Medium - * - * A maximum tree is a tree where every node has a value greater than any other value - * in its subtree. - * - * You are given the root of a maximum binary tree and an integer val. - * - * Just as in the previous problem, the given tree was constructed from a list a - * (root = Construct(a)) recursively with the following Construct(a) routine: - * - If a is empty, return null. - * - Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i]. - * - The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]). - * - The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]). - * - Return root. - * - * Note that we were not given a directly, only a root node root = Construct(a). - * - * Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has - * unique values. - * - * Return Construct(b). - */ - -/** - * 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 insertIntoMaxTree = function(root, val) { - if (!root || val > root.val) { - const newRoot = createNode(val); - newRoot.left = root; - return newRoot; - } - - root.right = insertIntoMaxTree(root.right, val); - return root; - - function createNode(value) { - return new TreeNode(value); - } -}; diff --git a/solutions/0999-available-captures-for-rook.js b/solutions/0999-available-captures-for-rook.js deleted file mode 100644 index eef0f6f5..00000000 --- a/solutions/0999-available-captures-for-rook.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 999. Available Captures for Rook - * https://leetcode.com/problems/available-captures-for-rook/ - * Difficulty: Easy - * - * You are given an 8 x 8 matrix representing a chessboard. There is exactly one white rook - * represented by 'R', some number of white bishops 'B', and some number of black pawns 'p'. - * Empty squares are represented by '.'. - * - * A rook can move any number of squares horizontally or vertically (up, down, left, right) - * until it reaches another piece or the edge of the board. A rook is attacking a pawn if it - * can move to the pawn's square in one move. - * - * Note: A rook cannot move through other pieces, such as bishops or pawns. This means a rook - * cannot attack a pawn if there is another piece blocking the path. - * - * Return the number of pawns the white rook is attacking. - */ - -/** - * @param {character[][]} board - * @return {number} - */ -var numRookCaptures = function(board) { - let rookRow; - let rookCol; - - for (let i = 0; i < 8; i++) { - for (let j = 0; j < 8; j++) { - if (board[i][j] === 'R') { - rookRow = i; - rookCol = j; - break; - } - } - } - - const result = countPawns(-1, 0) + countPawns(1, 0) - + countPawns(0, -1) + countPawns(0, 1); - - return result; - - function countPawns(rowStep, colStep) { - let row = rookRow + rowStep; - let col = rookCol + colStep; - - while (row >= 0 && row < 8 && col >= 0 && col < 8) { - if (board[row][col] === 'p') return 1; - if (board[row][col] === 'B') return 0; - row += rowStep; - col += colStep; - } - return 0; - } -}; diff --git a/solutions/1000-minimum-cost-to-merge-stones.js b/solutions/1000-minimum-cost-to-merge-stones.js deleted file mode 100644 index d85a8d2a..00000000 --- a/solutions/1000-minimum-cost-to-merge-stones.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1000. Minimum Cost to Merge Stones - * https://leetcode.com/problems/minimum-cost-to-merge-stones/ - * Difficulty: Hard - * - * There are n piles of stones arranged in a row. The ith pile has stones[i] stones. - * - * A move consists of merging exactly k consecutive piles into one pile, and the cost of - * this move is equal to the total number of stones in these k piles. - * - * Return the minimum cost to merge all piles of stones into one pile. If it is impossible, - * return -1. - */ - -/** - * @param {number[]} stones - * @param {number} k - * @return {number} - */ -var mergeStones = function(stones, k) { - const n = stones.length; - if ((n - 1) % (k - 1) !== 0) return -1; - - const prefixSums = new Array(n + 1).fill(0); - for (let i = 0; i < n; i++) { - prefixSums[i + 1] = prefixSums[i] + stones[i]; - } - - const dp = new Array(n).fill().map(() => new Array(n).fill(0)); - - for (let len = k; len <= n; len++) { - for (let start = 0; start + len <= n; start++) { - const end = start + len - 1; - dp[start][end] = Infinity; - - for (let mid = start; mid < end; mid += k - 1) { - dp[start][end] = Math.min( - dp[start][end], - dp[start][mid] + dp[mid + 1][end] - ); - } - - if ((len - 1) % (k - 1) === 0) { - dp[start][end] += prefixSums[end + 1] - prefixSums[start]; - } - } - } - - return dp[0][n - 1]; -}; diff --git a/solutions/1001-grid-illumination.js b/solutions/1001-grid-illumination.js deleted file mode 100644 index a9debaf5..00000000 --- a/solutions/1001-grid-illumination.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 1001. Grid Illumination - * https://leetcode.com/problems/grid-illumination/ - * Difficulty: Hard - * - * There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially - * turned off. - * - * You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that - * the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it - * is turned on. - * - * When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, - * or diagonal. - * - * You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, - * determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off - * the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its - * cell shares either a side or corner with grid[rowj][colj]. - * - * Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was - * illuminated, or 0 if the lamp was not. - */ - -/** - * @param {number} n - * @param {number[][]} lamps - * @param {number[][]} queries - * @return {number[]} - */ -var gridIllumination = function(n, lamps, queries) { - const rowCount = new Map(); - const colCount = new Map(); - const diag1Count = new Map(); - const diag2Count = new Map(); - const lampSet = new Set(); - - for (const [r, c] of lamps) { - if (!lampSet.has(`${r},${c}`)) { - lampSet.add(`${r},${c}`); - rowCount.set(r, (rowCount.get(r) || 0) + 1); - colCount.set(c, (colCount.get(c) || 0) + 1); - diag1Count.set(r - c, (diag1Count.get(r - c) || 0) + 1); - diag2Count.set(r + c, (diag2Count.get(r + c) || 0) + 1); - } - } - - const directions = [[0, 0], [0, 1], [0, -1], [1, 0], [1, 1], [1, -1], [-1, 0], [-1, 1], [-1, -1]]; - const result = new Array(queries.length); - - for (let i = 0; i < queries.length; i++) { - const [r, c] = queries[i]; - result[i] = (rowCount.get(r) > 0 || colCount.get(c) > 0 - || diag1Count.get(r - c) > 0 || diag2Count.get(r + c) > 0) ? 1 : 0; - - for (const [dr, dc] of directions) { - const newR = r + dr; - const newC = c + dc; - const key = `${newR},${newC}`; - - if (newR >= 0 && newR < n && newC >= 0 && newC < n && lampSet.has(key)) { - lampSet.delete(key); - rowCount.set(newR, rowCount.get(newR) - 1); - colCount.set(newC, colCount.get(newC) - 1); - diag1Count.set(newR - newC, diag1Count.get(newR - newC) - 1); - diag2Count.set(newR + newC, diag2Count.get(newR + newC) - 1); - } - } - } - - return result; -}; diff --git a/solutions/1003-check-if-word-is-valid-after-substitutions.js b/solutions/1003-check-if-word-is-valid-after-substitutions.js deleted file mode 100644 index d577aa0c..00000000 --- a/solutions/1003-check-if-word-is-valid-after-substitutions.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1003. Check If Word Is Valid After Substitutions - * https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/ - * Difficulty: Medium - * - * Given a string s, determine if it is valid. - * - * A string s is valid if, starting with an empty string t = "", you can transform t into s after - * performing the following operation any number of times: - * - Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, - * where t == tleft + tright. Note that tleft and tright may be empty. - * - * Return true if s is a valid string, otherwise, return false. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var isValid = function(s) { - const stack = []; - - for (const char of s) { - if (char === 'c') { - if (stack.length < 2 || stack.pop() !== 'b' || stack.pop() !== 'a') { - return false; - } - } else { - stack.push(char); - } - } - - return stack.length === 0; -}; diff --git a/solutions/1004-max-consecutive-ones-iii.js b/solutions/1004-max-consecutive-ones-iii.js deleted file mode 100644 index ec74165e..00000000 --- a/solutions/1004-max-consecutive-ones-iii.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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/solutions/1006-clumsy-factorial.js b/solutions/1006-clumsy-factorial.js deleted file mode 100644 index 8e1ec29b..00000000 --- a/solutions/1006-clumsy-factorial.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1006. Clumsy Factorial - * https://leetcode.com/problems/clumsy-factorial/ - * Difficulty: Medium - * - * The factorial of a positive integer n is the product of all positive integers less - * than or equal to n. - * - For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. - * - * We make a clumsy factorial using the integers in decreasing order by swapping out the - * multiply operations for a fixed rotation of operations with multiply '*', divide '/', - * add '+', and subtract '-' in this order. - * - For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. - * - * However, these operations are still applied using the usual order of operations of - * arithmetic. We do all multiplication and division steps before any addition or - * subtraction steps, and multiplication and division steps are processed left to right. - * - * Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11. - * - * Given an integer n, return the clumsy factorial of n. - */ - -/** - * @param {number} n - * @return {number} - */ -var clumsy = function(n) { - if (n <= 2) return n; - if (n === 3) return 6; - - let result = Math.floor(n * (n - 1) / (n - 2)) + (n - 3); - n -= 4; - - while (n >= 4) { - result -= Math.floor(n * (n - 1) / (n - 2)) - (n - 3); - n -= 4; - } - - if (n === 3) result -= 6; - else if (n === 2) result -= 2; - else if (n === 1) result -= 1; - - return result; -}; diff --git a/solutions/1007-minimum-domino-rotations-for-equal-row.js b/solutions/1007-minimum-domino-rotations-for-equal-row.js deleted file mode 100644 index 93f28ff5..00000000 --- a/solutions/1007-minimum-domino-rotations-for-equal-row.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1007. Minimum Domino Rotations For Equal Row - * https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ - * Difficulty: Medium - * - * In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the - * ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) - * - * We may rotate the ith domino, so that tops[i] and bottoms[i] swap values. - * - * Return the minimum number of rotations so that all the values in tops are the same, or all - * the values in bottoms are the same. - * - * If it cannot be done, return -1. - */ - -/** - * @param {number[]} tops - * @param {number[]} bottoms - * @return {number} - */ -var minDominoRotations = function(tops, bottoms) { - const topResult = countRotations(tops[0]); - if (topResult !== -1) return topResult; - - return countRotations(bottoms[0]); - - function countRotations(target) { - let topCount = 0; - let bottomCount = 0; - - for (let i = 0; i < tops.length; i++) { - if (tops[i] !== target && bottoms[i] !== target) return -1; - topCount += tops[i] !== target ? 1 : 0; - bottomCount += bottoms[i] !== target ? 1 : 0; - } - - return Math.min(topCount, bottomCount); - } -}; diff --git a/solutions/1008-construct-binary-search-tree-from-preorder-traversal.js b/solutions/1008-construct-binary-search-tree-from-preorder-traversal.js deleted file mode 100644 index 27e1f95b..00000000 --- a/solutions/1008-construct-binary-search-tree-from-preorder-traversal.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1008. Construct Binary Search Tree from Preorder Traversal - * https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ - * Difficulty: Medium - * - * Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., - * binary search tree), construct the tree and return its root. - * - * It is guaranteed that there is always possible to find a binary search tree with the given - * requirements for the given test cases. - * - * A binary search tree is a binary tree where for every node, any descendant of Node.left has - * a value strictly less than Node.val, and any descendant of Node.right has a value strictly - * greater than Node.val. - * - * A preorder traversal of a binary tree displays the value of the node first, then traverses - * Node.left, then traverses Node.right. - */ - -/** - * 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[]} preorder - * @return {TreeNode} - */ -var bstFromPreorder = function(preorder) { - let index = 0; - return buildBST(Infinity); - - function buildBST(bound) { - if (index >= preorder.length || preorder[index] > bound) return null; - - const node = new TreeNode(preorder[index++]); - node.left = buildBST(node.val); - node.right = buildBST(bound); - - return node; - } -}; diff --git a/solutions/1011-capacity-to-ship-packages-within-d-days.js b/solutions/1011-capacity-to-ship-packages-within-d-days.js deleted file mode 100644 index fe648ede..00000000 --- a/solutions/1011-capacity-to-ship-packages-within-d-days.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1011. Capacity To Ship Packages Within D Days - * https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/ - * Difficulty: Medium - * - * A conveyor belt has packages that must be shipped from one port to another within days days. - * - * The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship - * with packages on the conveyor belt (in the order given by weights). We may not load more weight - * than the maximum weight capacity of the ship. - * - * Return the least weight capacity of the ship that will result in all the packages on the conveyor - * belt being shipped within days days. - */ - -/** - * @param {number[]} weights - * @param {number} days - * @return {number} - */ -var shipWithinDays = function(weights, days) { - let left = Math.max(...weights); - let right = weights.reduce((sum, weight) => sum + weight, 0); - - while (left < right) { - const mid = Math.floor((left + right) / 2); - let currentDays = 1; - let currentWeight = 0; - - for (const weight of weights) { - if (currentWeight + weight > mid) { - currentDays++; - currentWeight = weight; - } else { - currentWeight += weight; - } - } - - if (currentDays > days) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; -}; diff --git a/solutions/1012-numbers-with-repeated-digits.js b/solutions/1012-numbers-with-repeated-digits.js deleted file mode 100644 index 066ef137..00000000 --- a/solutions/1012-numbers-with-repeated-digits.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1012. Numbers With Repeated Digits - * https://leetcode.com/problems/numbers-with-repeated-digits/ - * Difficulty: Hard - * - * Given an integer n, return the number of positive integers in the range [1, n] that have at - * least one repeated digit. - */ - -/** - * @param {number} n - * @return {number} - */ -var numDupDigitsAtMostN = function(n) { - const digits = String(n).split('').map(Number); - const length = digits.length; - let result = 0; - - function calculatePermutations(size, available) { - let total = 1; - for (let i = 0; i < size; i++) { - total *= available - i; - } - return total; - } - - for (let i = 1; i < length; i++) { - result += 9 * calculatePermutations(i - 1, 9); - } - - const used = new Set(); - for (let i = 0; i < length; i++) { - const start = i === 0 ? 1 : 0; - const limit = digits[i]; - - for (let d = start; d < limit; d++) { - if (!used.has(d)) { - result += calculatePermutations(length - i - 1, 10 - used.size - 1); - } - } - - if (used.has(digits[i])) break; - used.add(digits[i]); - if (i === length - 1) result++; - } - - return n - result; -}; diff --git a/solutions/1013-partition-array-into-three-parts-with-equal-sum.js b/solutions/1013-partition-array-into-three-parts-with-equal-sum.js deleted file mode 100644 index 17a33f75..00000000 --- a/solutions/1013-partition-array-into-three-parts-with-equal-sum.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1013. Partition Array Into Three Parts With Equal Sum - * https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/ - * Difficulty: Easy - * - * Given an array of integers arr, return true if we can partition the array into three - * non-empty parts with equal sums. - * - * Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] - * + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] - * + ... + arr[arr.length - 1]) - */ - -/** - * @param {number[]} arr - * @return {boolean} - */ -var canThreePartsEqualSum = function(arr) { - const totalSum = arr.reduce((sum, num) => sum + num, 0); - if (totalSum % 3 !== 0) return false; - - const targetSum = totalSum / 3; - let partsFound = 0; - let currentSum = 0; - - for (const num of arr) { - currentSum += num; - if (currentSum === targetSum) { - partsFound++; - currentSum = 0; - } - } - - return partsFound >= 3; -}; diff --git a/solutions/1014-best-sightseeing-pair.js b/solutions/1014-best-sightseeing-pair.js deleted file mode 100644 index fda6662a..00000000 --- a/solutions/1014-best-sightseeing-pair.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1014. Best Sightseeing Pair - * https://leetcode.com/problems/best-sightseeing-pair/ - * Difficulty: Medium - * - * You are given an integer array values where values[i] represents the value of the ith sightseeing - * spot. Two sightseeing spots i and j have a distance j - i between them. - * - * The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the - * values of the sightseeing spots, minus the distance between them. - * - * Return the maximum score of a pair of sightseeing spots. - */ - -/** - * @param {number[]} values - * @return {number} - */ -var maxScoreSightseeingPair = function(values) { - let maxLeft = values[0]; - let result = 0; - - for (let j = 1; j < values.length; j++) { - result = Math.max(result, maxLeft + values[j] - j); - maxLeft = Math.max(maxLeft, values[j] + j); - } - - return result; -}; diff --git a/solutions/1015-smallest-integer-divisible-by-k.js b/solutions/1015-smallest-integer-divisible-by-k.js deleted file mode 100644 index 0f990afd..00000000 --- a/solutions/1015-smallest-integer-divisible-by-k.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1015. Smallest Integer Divisible by K - * https://leetcode.com/problems/smallest-integer-divisible-by-k/ - * Difficulty: Medium - * - * Given a positive integer k, you need to find the length of the smallest positive integer n such - * that n is divisible by k, and n only contains the digit 1. - * - * Return the length of n. If there is no such n, return -1. - * - * Note: n may not fit in a 64-bit signed integer. - */ - -/** - * @param {number} k - * @return {number} - */ -var smallestRepunitDivByK = function(k) { - if (k % 2 === 0 || k % 5 === 0) return -1; - let remainder = 0; - let length = 1; - - while (length <= k) { - remainder = (remainder * 10 + 1) % k; - if (remainder === 0) return length; - length++; - } - - return -1; -}; diff --git a/solutions/1016-binary-string-with-substrings-representing-1-to-n.js b/solutions/1016-binary-string-with-substrings-representing-1-to-n.js deleted file mode 100644 index 074c9470..00000000 --- a/solutions/1016-binary-string-with-substrings-representing-1-to-n.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1016. Binary String With Substrings Representing 1 To N - * https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/ - * Difficulty: Medium - * - * Given a binary string s and a positive integer n, return true if the binary representation of - * all the integers in the range [1, n] are substrings of s, or false otherwise. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} s - * @param {number} n - * @return {boolean} - */ -var queryString = function(binaryString, maxNumber) { - return hasAllSubstrings(binaryString, maxNumber); - - function hasAllSubstrings(str, num) { - for (let i = 1; i <= num; i++) { - if (!str.includes(i.toString(2))) return false; - } - return true; - } -}; diff --git a/solutions/1017-convert-to-base-2.js b/solutions/1017-convert-to-base-2.js deleted file mode 100644 index 1972fbdd..00000000 --- a/solutions/1017-convert-to-base-2.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 1017. Convert to Base -2 - * https://leetcode.com/problems/convert-to-base-2/ - * Difficulty: Medium - * - * Given an integer n, return a binary string representing its representation in base -2. - * - * Note that the returned string should not have leading zeros unless the string is "0". - */ - -/** - * @param {number} n - * @return {string} - */ -var baseNeg2 = function(number) { - if (number === 0) return '0'; - - let result = ''; - let current = number; - - while (current !== 0) { - const remainder = current & 1; - result = remainder + result; - current = (current - remainder) / -2; - } - - return result; -}; diff --git a/solutions/1018-binary-prefix-divisible-by-5.js b/solutions/1018-binary-prefix-divisible-by-5.js deleted file mode 100644 index 5900ce2b..00000000 --- a/solutions/1018-binary-prefix-divisible-by-5.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1018. Binary Prefix Divisible By 5 - * https://leetcode.com/problems/binary-prefix-divisible-by-5/ - * Difficulty: Easy - * - * You are given a binary array nums (0-indexed). - * - * We define xi as the number whose binary representation is the subarray nums[0..i] - * (from most-significant-bit to least-significant-bit). - * - * For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5. - * - * Return an array of booleans answer where answer[i] is true if xi is divisible by 5. - */ - -/** - * @param {number[]} nums - * @return {boolean[]} - */ -var prefixesDivBy5 = function(nums) { - const result = new Array(nums.length); - - for (let i = 0, current = 0; i < nums.length; i++) { - current = (current * 2 + nums[i]) % 5; - result[i] = current === 0; - } - - return result; -}; diff --git a/solutions/1019-next-greater-node-in-linked-list.js b/solutions/1019-next-greater-node-in-linked-list.js deleted file mode 100644 index 439163d3..00000000 --- a/solutions/1019-next-greater-node-in-linked-list.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1019. Next Greater Node In Linked List - * https://leetcode.com/problems/next-greater-node-in-linked-list/ - * Difficulty: Medium - * - * You are given the head of a linked list with n nodes. - * - * For each node in the list, find the value of the next greater node. That is, for each node, - * find the value of the first node that is next to it and has a strictly larger value than it. - * - * Return an integer array answer where answer[i] is the value of the next greater node of the - * ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0. - */ - -/** - * 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 nextLargerNodes = function(head) { - const values = []; - let current = head; - - while (current) { - values.push(current.val); - current = current.next; - } - - const result = new Array(values.length).fill(0); - const stack = []; - - for (let i = 0; i < values.length; i++) { - while (stack.length && values[stack[stack.length - 1]] < values[i]) { - result[stack.pop()] = values[i]; - } - stack.push(i); - } - - return result; -}; diff --git a/solutions/1020-number-of-enclaves.js b/solutions/1020-number-of-enclaves.js deleted file mode 100644 index fbc6e1b0..00000000 --- a/solutions/1020-number-of-enclaves.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1020. Number of Enclaves - * https://leetcode.com/problems/number-of-enclaves/ - * Difficulty: Medium - * - * You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents - * a land cell. - * - * A move consists of walking from one land cell to another adjacent (4-directionally) land cell - * or walking off the boundary of the grid. - * - * Return the number of land cells in grid for which we cannot walk off the boundary of the grid - * in any number of moves. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var numEnclaves = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - - for (let i = 0; i < rows; i++) { - exploreBoundary(i, 0); - exploreBoundary(i, cols - 1); - } - - for (let j = 0; j < cols; j++) { - exploreBoundary(0, j); - exploreBoundary(rows - 1, j); - } - - let result = 0; - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - result += grid[i][j]; - } - } - - return result; - - function exploreBoundary(row, col) { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 1) return; - grid[row][col] = 0; - exploreBoundary(row + 1, col); - exploreBoundary(row - 1, col); - exploreBoundary(row, col + 1); - exploreBoundary(row, col - 1); - } -}; diff --git a/solutions/1021-remove-outermost-parentheses.js b/solutions/1021-remove-outermost-parentheses.js deleted file mode 100644 index 5fc2fe58..00000000 --- a/solutions/1021-remove-outermost-parentheses.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1021. Remove Outermost Parentheses - * https://leetcode.com/problems/remove-outermost-parentheses/ - * Difficulty: Easy - * - * A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid - * parentheses strings, and + represents string concatenation. - * - For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. - * - * A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to - * split it into s = A + B, with A and B nonempty valid parentheses strings. - * - * Given a valid parentheses string s, consider its primitive decomposition: s = P1 - * + P2 + ... + Pk, where Pi are primitive valid parentheses strings. - * - * Return s after removing the outermost parentheses of every primitive string in the primitive - * decomposition of s. - */ - -/** - * @param {string} s - * @return {string} - */ -var removeOuterParentheses = function(s) { - let result = ''; - let depth = 0; - - for (const char of s) { - if (char === '(') { - if (depth > 0) result += char; - depth++; - } else { - depth--; - if (depth > 0) result += char; - } - } - - return result; -}; diff --git a/solutions/1024-video-stitching.js b/solutions/1024-video-stitching.js deleted file mode 100644 index 2e69b83b..00000000 --- a/solutions/1024-video-stitching.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1024. Video Stitching - * https://leetcode.com/problems/video-stitching/ - * Difficulty: Medium - * - * You are given a series of video clips from a sporting event that lasted time seconds. - * These video clips can be overlapping with each other and have varying lengths. - * - * Each video clip is described by an array clips where clips[i] = [starti, endi] indicates - * that the ith clip started at starti and ended at endi. - * - * We can cut these clips into segments freely. - * - For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. - * - * Return the minimum number of clips needed so that we can cut the clips into segments that - * cover the entire sporting event [0, time]. If the task is impossible, return -1. - */ - -/** - * @param {number[][]} clips - * @param {number} time - * @return {number} - */ -var videoStitching = function(clips, time) { - let count = 0; - let currentEnd = 0; - let nextEnd = 0; - - clips.sort((a, b) => a[0] - b[0]); - - for (let i = 0; i < clips.length && currentEnd < time;) { - count++; - while (i < clips.length && clips[i][0] <= currentEnd) { - nextEnd = Math.max(nextEnd, clips[i][1]); - i++; - } - if (nextEnd === currentEnd) return -1; - currentEnd = nextEnd; - } - - return currentEnd >= time ? count : -1; -}; diff --git a/solutions/1025-divisor-game.js b/solutions/1025-divisor-game.js deleted file mode 100644 index 2a19f105..00000000 --- a/solutions/1025-divisor-game.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1025. Divisor Game - * https://leetcode.com/problems/divisor-game/ - * Difficulty: Easy - * - * Alice and Bob take turns playing a game, with Alice starting first. - * - * Initially, there is a number n on the chalkboard. On each player's turn, that player makes a - * move consisting of: - * - Choosing any x with 0 < x < n and n % x == 0. - * - Replacing the number n on the chalkboard with n - x. - * - * Also, if a player cannot make a move, they lose the game. - * - * Return true if and only if Alice wins the game, assuming both players play optimally. - */ - -/** - * @param {number} n - * @return {boolean} - */ -var divisorGame = function(n) { - return n % 2 === 0; -}; diff --git a/solutions/1026-maximum-difference-between-node-and-ancestor.js b/solutions/1026-maximum-difference-between-node-and-ancestor.js deleted file mode 100644 index 551a490b..00000000 --- a/solutions/1026-maximum-difference-between-node-and-ancestor.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1026. Maximum Difference Between Node and Ancestor - * https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ - * Difficulty: Medium - * - * Given the root of a binary tree, find the maximum value v for which there exist different nodes - * a and b where v = |a.val - b.val| and a is an ancestor of b. - * - * A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an - * ancestor of b. - */ - -/** - * 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 maxAncestorDiff = function(root) { - return traverse(root, root.val, root.val); - - function traverse(node, maxVal, minVal) { - if (!node) return maxVal - minVal; - - maxVal = Math.max(maxVal, node.val); - minVal = Math.min(minVal, node.val); - - return Math.max( - traverse(node.left, maxVal, minVal), - traverse(node.right, maxVal, minVal) - ); - } -}; diff --git a/solutions/1027-longest-arithmetic-subsequence.js b/solutions/1027-longest-arithmetic-subsequence.js deleted file mode 100644 index 2a685c86..00000000 --- a/solutions/1027-longest-arithmetic-subsequence.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1027. Longest Arithmetic Subsequence - * https://leetcode.com/problems/longest-arithmetic-subsequence/ - * Difficulty: Medium - * - * Given an array nums of integers, return the length of the longest arithmetic - * subsequence in nums. - * - * Note that: - * - 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. - * - A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value - * (for 0 <= i < seq.length - 1). - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var longestArithSeqLength = function(nums) { - const dp = new Array(nums.length).fill().map(() => new Map()); - let result = 2; - - for (let i = 1; i < nums.length; i++) { - for (let j = 0; j < i; j++) { - const diff = nums[i] - nums[j]; - const prevLength = dp[j].get(diff) || 1; - dp[i].set(diff, prevLength + 1); - result = Math.max(result, prevLength + 1); - } - } - - return result; -}; diff --git a/solutions/1029-two-city-scheduling.js b/solutions/1029-two-city-scheduling.js deleted file mode 100644 index d3493af5..00000000 --- a/solutions/1029-two-city-scheduling.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1029. Two City Scheduling - * https://leetcode.com/problems/two-city-scheduling/ - * Difficulty: Medium - * - * A company is planning to interview 2n people. Given the array costs where - * costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, - * and the cost of flying the ith person to city b is bCosti. - * - * Return the minimum cost to fly every person to a city such that exactly n people - * arrive in each city. - */ - -/** - * @param {number[][]} costs - * @return {number} - */ -/** - * @param {number[][]} costs - * @return {number} - */ -var twoCitySchedCost = function(costs) { - return costs - .sort((a, b) => (a[0] - a[1]) - (b[0] - b[1])) - .reduce((sum, [a, b], index) => sum + (index < costs.length / 2 ? a : b), 0); -}; diff --git a/solutions/1030-matrix-cells-in-distance-order.js b/solutions/1030-matrix-cells-in-distance-order.js deleted file mode 100644 index d24b4937..00000000 --- a/solutions/1030-matrix-cells-in-distance-order.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1030. Matrix Cells in Distance Order - * https://leetcode.com/problems/matrix-cells-in-distance-order/ - * Difficulty: Easy - * - * You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and - * you are on the cell with the coordinates (rCenter, cCenter). - * - * Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, - * cCenter) from the smallest distance to the largest distance. You may return the answer in any - * order that satisfies this condition. - * - * The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. - */ - -/** - * @param {number} rows - * @param {number} cols - * @param {number} rCenter - * @param {number} cCenter - * @return {number[][]} - */ -var allCellsDistOrder = function(rows, cols, rCenter, cCenter) { - const result = []; - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - result.push([row, col]); - } - } - return result.sort((a, b) => { - return Math.abs(a[0] - rCenter) + Math.abs(a[1] - cCenter) - - Math.abs(b[0] - rCenter) - Math.abs(b[1] - cCenter); - }); -}; diff --git a/solutions/1031-maximum-sum-of-two-non-overlapping-subarrays.js b/solutions/1031-maximum-sum-of-two-non-overlapping-subarrays.js deleted file mode 100644 index bf1a874a..00000000 --- a/solutions/1031-maximum-sum-of-two-non-overlapping-subarrays.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1031. Maximum Sum of Two Non-Overlapping Subarrays - * https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/ - * Difficulty: Medium - * - * Given an integer array nums and two integers firstLen and secondLen, return the maximum sum - * of elements in two non-overlapping subarrays with lengths firstLen and secondLen. - * - * The array with length firstLen could occur before or after the array with length secondLen, - * but they have to be non-overlapping. - * - * A subarray is a contiguous part of an array. - */ - -/** - * @param {number[]} nums - * @param {number} firstLen - * @param {number} secondLen - * @return {number} - */ -var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) { - const prefixSums = getPrefixSums(nums); - let maxFirst = 0; - let maxSecond = 0; - let result = 0; - - for (let i = firstLen; i <= nums.length - secondLen; i++) { - maxFirst = Math.max(maxFirst, prefixSums[i] - prefixSums[i - firstLen]); - const secondSum = prefixSums[i + secondLen] - prefixSums[i]; - result = Math.max(result, maxFirst + secondSum); - } - - for (let i = secondLen; i <= nums.length - firstLen; i++) { - maxSecond = Math.max(maxSecond, prefixSums[i] - prefixSums[i - secondLen]); - const firstSum = prefixSums[i + firstLen] - prefixSums[i]; - result = Math.max(result, maxSecond + firstSum); - } - - return result; - - function getPrefixSums(arr) { - const sums = [0]; - for (let i = 0; i < arr.length; i++) { - sums.push(sums[i] + arr[i]); - } - return sums; - } -}; diff --git a/solutions/1032-stream-of-characters.js b/solutions/1032-stream-of-characters.js deleted file mode 100644 index bb4653dc..00000000 --- a/solutions/1032-stream-of-characters.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1032. Stream of Characters - * https://leetcode.com/problems/stream-of-characters/ - * Difficulty: Hard - * - * Design an algorithm that accepts a stream of characters and checks if a suffix of these - * characters is a string of a given array of strings words. - * - * For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) - * 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters - * "axyz" matches "xyz" from words. - * - * Implement the StreamChecker class: - * - StreamChecker(String[] words) Initializes the object with the strings array words. - * - boolean query(char letter) Accepts a new character from the stream and returns true if any - * non-empty suffix from the stream forms a word that is in words. - */ - -/** - * @param {string[]} words - */ -var StreamChecker = function(words) { - this.trie = {}; - this.stream = []; - - words.forEach(word => buildTrie(word, this.trie)); - - function buildTrie(word, trie) { - let node = trie; - for (let i = word.length - 1; i >= 0; i--) { - const char = word[i]; - node[char] = node[char] || {}; - node = node[char]; - } - node.isEnd = true; - } -}; - -/** - * @param {character} letter - * @return {boolean} - */ -StreamChecker.prototype.query = function(letter) { - this.stream.push(letter); - let node = this.trie; - - for (let i = this.stream.length - 1; i >= 0; i--) { - const char = this.stream[i]; - if (!node[char]) return false; - node = node[char]; - if (node.isEnd) return true; - } - - return false; -}; diff --git a/solutions/1033-moving-stones-until-consecutive.js b/solutions/1033-moving-stones-until-consecutive.js deleted file mode 100644 index db22b604..00000000 --- a/solutions/1033-moving-stones-until-consecutive.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1033. Moving Stones Until Consecutive - * https://leetcode.com/problems/moving-stones-until-consecutive/ - * Difficulty: Medium - * - * There are three stones in different positions on the X-axis. You are given three integers a, b, - * and c, the positions of the stones. - * - * In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position - * stone), and move it to an unoccupied position between those endpoints. Formally, let's say the - * stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either - * position x or position z, and move that stone to an integer position k, with x < k < z and - * k != y. - * - * The game ends when you cannot make any more moves (i.e., the stones are in three consecutive - * positions). - * - * Return an integer array answer of length 2 where: - * - answer[0] is the minimum number of moves you can play, and - * - answer[1] is the maximum number of moves you can play. - */ - -/** - * @param {number} a - * @param {number} b - * @param {number} c - * @return {number[]} - */ -var numMovesStones = function(a, b, c) { - const positions = [a, b, c].sort((x, y) => x - y); - const minGap = Math.min(positions[1] - positions[0], positions[2] - positions[1]); - const totalGap = positions[2] - positions[0] - 2; - - const minMoves = positions[1] - positions[0] === 1 && positions[2] - positions[1] === 1 - ? 0 : minGap <= 2 ? 1 : 2; - const maxMoves = totalGap; - - return [minMoves, maxMoves]; -}; diff --git a/solutions/1034-coloring-a-border.js b/solutions/1034-coloring-a-border.js deleted file mode 100644 index 4b482377..00000000 --- a/solutions/1034-coloring-a-border.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 1034. Coloring A Border - * https://leetcode.com/problems/coloring-a-border/ - * Difficulty: Medium - * - * You are given an m x n integer matrix grid, and three integers row, col, and color. Each value - * in the grid represents the color of the grid square at that location. - * - * Two squares are called adjacent if they are next to each other in any of the 4 directions. - * - * Two squares belong to the same connected component if they have the same color and they are - * adjacent. - * - * The border of a connected component is all the squares in the connected component that are - * either adjacent to (at least) a square not in the component, or on the boundary of the grid - * (the first or last row or column). - * - * You should color the border of the connected component that contains the square grid[row][col] - * with color. - * - * Return the final grid. - */ - -/** - * @param {number[][]} grid - * @param {number} row - * @param {number} col - * @param {number} color - * @return {number[][]} - */ -var colorBorder = function(grid, row, col, color) { - const rows = grid.length; - const cols = grid[0].length; - const visited = new Set(); - const originalColor = grid[row][col]; - const borders = new Set(); - - function findBorders(r, c) { - if (r < 0 || r >= rows || c < 0 || c >= cols - || visited.has(`${r},${c}`) || grid[r][c] !== originalColor) { - return; - } - - visited.add(`${r},${c}`); - - if (r === 0 || r === rows - 1 || c === 0 || c === cols - 1 - || (r > 0 && grid[r - 1][c] !== originalColor) - || (r < rows - 1 && grid[r + 1][c] !== originalColor) - || (c > 0 && grid[r][c - 1] !== originalColor) - || (c < cols - 1 && grid[r][c + 1] !== originalColor)) { - borders.add(`${r},${c}`); - } - - findBorders(r - 1, c); - findBorders(r + 1, c); - findBorders(r, c - 1); - findBorders(r, c + 1); - } - - findBorders(row, col); - borders.forEach(pos => { - const [r, c] = pos.split(',').map(Number); - grid[r][c] = color; - }); - - return grid; -}; diff --git a/solutions/1035-uncrossed-lines.js b/solutions/1035-uncrossed-lines.js deleted file mode 100644 index 9be2c66b..00000000 --- a/solutions/1035-uncrossed-lines.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1035. Uncrossed Lines - * https://leetcode.com/problems/uncrossed-lines/ - * Difficulty: Medium - * - * You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 - * (in the order they are given) on two separate horizontal lines. - * - * We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] - * such that: - * - nums1[i] == nums2[j], and - * - the line we draw does not intersect any other connecting (non-horizontal) line. - * - * Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only - * belong to one connecting line). - * - * Return the maximum number of connecting lines we can draw in this way. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var maxUncrossedLines = function(nums1, nums2) { - const m = nums1.length; - const n = nums2.length; - - const dp = new Array(m + 1).fill().map(() => new Array(n + 1).fill(0)); - - for (let i = 1; i <= m; i++) { - for (let j = 1; j <= n; j++) { - if (nums1[i - 1] === nums2[j - 1]) { - dp[i][j] = dp[i - 1][j - 1] + 1; - } else { - dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); - } - } - } - - return dp[m][n]; -}; diff --git a/solutions/1036-escape-a-large-maze.js b/solutions/1036-escape-a-large-maze.js deleted file mode 100644 index dc720df5..00000000 --- a/solutions/1036-escape-a-large-maze.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1036. Escape a Large Maze - * https://leetcode.com/problems/escape-a-large-maze/ - * Difficulty: Hard - * - * There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid - * square are (x, y). - * - * We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. - * There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents - * a blocked square with coordinates (xi, yi). - * - * Each move, we can walk one square north, east, south, or west if the square is not in - * the array of blocked squares. We are also not allowed to walk outside of the grid. - * - * Return true if and only if it is possible to reach the target square from the source - * square through a sequence of valid moves. - */ - -/** - * @param {number[][]} blocked - * @param {number[]} source - * @param {number[]} target - * @return {boolean} - */ -var isEscapePossible = function(blocked, source, target) { - const MAX = 1e6; - const LIMIT = 19900; - const blockedSet = new Set(blocked.map(([x, y]) => `${x},${y}`)); - - if (!helper(source, target)) { - return false; - } - - return helper(target, source); - - function helper(start, goal) { - const queue = [start]; - const visited = new Set([`${start[0]},${start[1]}`]); - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - - while (queue.length && visited.size <= LIMIT) { - const [x, y] = queue.shift(); - - for (const [dx, dy] of directions) { - const newX = x + dx; - const newY = y + dy; - const key = `${newX},${newY}`; - - if (newX < 0 || newX >= MAX || newY < 0 || newY >= MAX - || blockedSet.has(key) || visited.has(key)) { - continue; - } - - if (newX === goal[0] && newY === goal[1]) { - return true; - } - - queue.push([newX, newY]); - visited.add(key); - } - } - - return visited.size > LIMIT; - } -}; diff --git a/solutions/1038-binary-search-tree-to-greater-sum-tree.js b/solutions/1038-binary-search-tree-to-greater-sum-tree.js deleted file mode 100644 index 0617d146..00000000 --- a/solutions/1038-binary-search-tree-to-greater-sum-tree.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1038. Binary Search Tree to Greater Sum Tree - * https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ - * Difficulty: Medium - * - * Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every - * key of the original BST is changed to the original key plus the sum of all keys greater - * than the original key in BST. - * - * As a reminder, a binary search tree is a tree that satisfies these constraints: - * - 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 {TreeNode} - */ -var bstToGst = function(root) { - let sum = 0; - traverse(root); - return root; - - function traverse(node) { - if (!node) return; - traverse(node.right); - sum += node.val; - node.val = sum; - traverse(node.left); - } -}; diff --git a/solutions/1039-minimum-score-triangulation-of-polygon.js b/solutions/1039-minimum-score-triangulation-of-polygon.js deleted file mode 100644 index ee5066c5..00000000 --- a/solutions/1039-minimum-score-triangulation-of-polygon.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1039. Minimum Score Triangulation of Polygon - * https://leetcode.com/problems/minimum-score-triangulation-of-polygon/ - * Difficulty: Medium - * - * You have a convex n-sided polygon where each vertex has an integer value. You are given an - * integer array values where values[i] is the value of the ith vertex in clockwise order. - * - * Polygon triangulation is a process where you divide a polygon into a set of triangles and - * the vertices of each triangle must also be vertices of the original polygon. Note that no - * other shapes other than triangles are allowed in the division. This process will result - * in n - 2 triangles. - * - * You will triangulate the polygon. For each triangle, the weight of that triangle is the - * product of the values at its vertices. The total score of the triangulation is the sum of - * these weights over all n - 2 triangles. - * - * Return the minimum possible score that you can achieve with some triangulation of the polygon. - */ - -/** - * @param {number[]} values - * @return {number} - */ -var minScoreTriangulation = function(values) { - const n = values.length; - const dp = new Array(n).fill().map(() => new Array(n).fill(0)); - - for (let len = 2; len < n; len++) { - for (let start = 0; start + len < n; start++) { - const end = start + len; - dp[start][end] = Infinity; - - for (let mid = start + 1; mid < end; mid++) { - const score = dp[start][mid] + dp[mid][end] + values[start] * values[mid] * values[end]; - dp[start][end] = Math.min(dp[start][end], score); - } - } - } - - return dp[0][n - 1]; -}; diff --git a/solutions/1040-moving-stones-until-consecutive-ii.js b/solutions/1040-moving-stones-until-consecutive-ii.js deleted file mode 100644 index d8f215f6..00000000 --- a/solutions/1040-moving-stones-until-consecutive-ii.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1040. Moving Stones Until Consecutive II - * https://leetcode.com/problems/moving-stones-until-consecutive-ii/ - * Difficulty: Medium - * - * There are some stones in different positions on the X-axis. You are given an integer array - * stones, the positions of the stones. - * - * Call a stone an endpoint stone if it has the smallest or largest position. In one move, you - * pick up an endpoint stone and move it to an unoccupied position so that it is no longer an - * endpoint stone. - * - In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint - * stone at position 5, since moving it to any position (such as 0, or 3) will still keep that - * stone as an endpoint stone. - * - * The game ends when you cannot make any more moves (i.e., the stones are in three consecutive - * positions). - * - * Return an integer array answer of length 2 where: - * - answer[0] is the minimum number of moves you can play, and - * - answer[1] is the maximum number of moves you can play. - */ - -/** - * @param {number[]} stones - * @return {number[]} - */ -var numMovesStonesII = function(stones) { - stones.sort((a, b) => a - b); - const n = stones.length; - const maxMoves = Math.max(stones[n - 1] - stones[1] - n + 2, stones[n - 2] - stones[0] - n + 2); - let minMoves = n; - - let left = 0; - for (let right = 0; right < n; right++) { - while (stones[right] - stones[left] + 1 > n) { - left++; - } - const windowSize = right - left + 1; - if (windowSize === n - 1 && stones[right] - stones[left] + 1 === n - 1) { - minMoves = Math.min(minMoves, 2); - } else { - minMoves = Math.min(minMoves, n - windowSize); - } - } - - return [minMoves, maxMoves]; -}; diff --git a/solutions/1042-flower-planting-with-no-adjacent.js b/solutions/1042-flower-planting-with-no-adjacent.js deleted file mode 100644 index 2759f6cb..00000000 --- a/solutions/1042-flower-planting-with-no-adjacent.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1042. Flower Planting With No Adjacent - * https://leetcode.com/problems/flower-planting-with-no-adjacent/ - * Difficulty: Medium - * - * You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes - * a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of - * 4 types of flowers. - * - * All gardens have at most 3 paths coming into or leaving it. - * - * Your task is to choose a flower type for each garden such that, for any two gardens connected - * by a path, they have different types of flowers. - * - * Return any such a choice as an array answer, where answer[i] is the type of flower planted in - * the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer - * exists. - */ - -/** - * @param {number} n - * @param {number[][]} paths - * @return {number[]} - */ -var gardenNoAdj = function(n, paths) { - const graph = Array.from({ length: n }, () => new Set()); - const result = new Array(n).fill(0); - - for (const [x, y] of paths) { - graph[x - 1].add(y - 1); - graph[y - 1].add(x - 1); - } - - for (let garden = 0; garden < n; garden++) { - const usedColors = new Set(); - for (const neighbor of graph[garden]) { - usedColors.add(result[neighbor]); - } - - for (let color = 1; color <= 4; color++) { - if (!usedColors.has(color)) { - result[garden] = color; - break; - } - } - } - - return result; -}; diff --git a/solutions/1043-partition-array-for-maximum-sum.js b/solutions/1043-partition-array-for-maximum-sum.js deleted file mode 100644 index 246dd1cf..00000000 --- a/solutions/1043-partition-array-for-maximum-sum.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1043. Partition Array for Maximum Sum - * https://leetcode.com/problems/partition-array-for-maximum-sum/ - * Difficulty: Medium - * - * Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. - * After partitioning, each subarray has their values changed to become the maximum value of that - * subarray. - * - * Return the largest sum of the given array after partitioning. Test cases are generated so that - * the answer fits in a 32-bit integer. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {number} - */ -var maxSumAfterPartitioning = function(arr, k) { - const dp = new Array(arr.length + 1).fill(0); - - for (let i = 1; i <= arr.length; i++) { - let maxVal = 0; - for (let j = 1; j <= Math.min(k, i); j++) { - maxVal = Math.max(maxVal, arr[i - j]); - dp[i] = Math.max(dp[i], dp[i - j] + maxVal * j); - } - } - - return dp[arr.length]; -}; diff --git a/solutions/1044-longest-duplicate-substring.js b/solutions/1044-longest-duplicate-substring.js deleted file mode 100644 index 083e3e30..00000000 --- a/solutions/1044-longest-duplicate-substring.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * 1044. Longest Duplicate Substring - * https://leetcode.com/problems/longest-duplicate-substring/ - * Difficulty: Hard - * - * Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 - * or more times. The occurrences may overlap. - * - * Return any duplicated substring that has the longest possible length. If s does not have a - * duplicated substring, the answer is "". - */ - -/** - * @param {string} s - * @return {string} - */ -var longestDupSubstring = function(s) { - const MOD = 1e9 + 7; - const BASE = 26; - let left = 1; - let right = s.length - 1; - let result = ''; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const candidate = checkLength(mid); - if (candidate) { - result = candidate; - left = mid + 1; - } else { - right = mid - 1; - } - } - - return result; - - function checkLength(len) { - let hash = 0; - const seen = new Map(); - let basePow = 1; - for (let i = 0; i < len - 1; i++) { - basePow = (basePow * BASE) % MOD; - } - - for (let i = 0; i < len; i++) { - hash = (hash * BASE + (s.charCodeAt(i) - 97)) % MOD; - } - - seen.set(hash, [0]); - - for (let i = 1; i <= s.length - len; i++) { - hash = (hash - ((s.charCodeAt(i - 1) - 97) * basePow) % MOD + MOD) % MOD; - hash = (hash * BASE + (s.charCodeAt(i + len - 1) - 97)) % MOD; - if (seen.has(hash)) { - const prevIndices = seen.get(hash); - const currSubstr = s.slice(i, i + len); - for (const prev of prevIndices) { - if (s.slice(prev, prev + len) === currSubstr) { - return currSubstr; - } - } - prevIndices.push(i); - } else { - seen.set(hash, [i]); - } - } - return ''; - } -}; diff --git a/solutions/1046-last-stone-weight.js b/solutions/1046-last-stone-weight.js deleted file mode 100644 index c7591364..00000000 --- a/solutions/1046-last-stone-weight.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1046. Last Stone Weight - * https://leetcode.com/problems/last-stone-weight/ - * Difficulty: Easy - * - * You are given an array of integers stones where stones[i] is the weight of the ith stone. - * - * We are playing a game with the stones. On each turn, we choose the heaviest two stones and - * smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The - * result of this smash is: - * - If x == y, both stones are destroyed, and - * - If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. - * - * At the end of the game, there is at most one stone left. - * - * Return the weight of the last remaining stone. If there are no stones left, return 0. - */ - -/** - * @param {number[]} stones - * @return {number} - */ -var lastStoneWeight = function(stones) { - const heap = stones.sort((a, b) => b - a); - - while (heap.length > 1) { - const heaviest = heap.shift(); - const secondHeaviest = heap.shift(); - if (heaviest !== secondHeaviest) { - heap.push(heaviest - secondHeaviest); - heap.sort((a, b) => b - a); - } - } - - return heap.length ? heap[0] : 0; -}; diff --git a/solutions/1048-longest-string-chain.js b/solutions/1048-longest-string-chain.js deleted file mode 100644 index 5c18311b..00000000 --- a/solutions/1048-longest-string-chain.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1048. Longest String Chain - * https://leetcode.com/problems/longest-string-chain/ - * Difficulty: Medium - * - * You are given an array of words where each word consists of lowercase English letters. - * - * wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in - * wordA without changing the order of the other characters to make it equal to wordB. - * - * For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad". - * - * A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is - * a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is - * trivially a word chain with k == 1. - * - * Return the length of the longest possible word chain with words chosen from the given list - * of words. - */ - -/** - * @param {string[]} words - * @return {number} - */ -var longestStrChain = function(words) { - const map = new Map(); - let result = 1; - - words.sort((a, b) => a.length - b.length); - - for (const word of words) { - let currentLength = 1; - for (let i = 0; i < word.length; i++) { - const prev = word.slice(0, i) + word.slice(i + 1); - if (map.has(prev)) { - currentLength = Math.max(currentLength, map.get(prev) + 1); - } - } - map.set(word, currentLength); - result = Math.max(result, currentLength); - } - - return result; -}; diff --git a/solutions/1049-last-stone-weight-ii.js b/solutions/1049-last-stone-weight-ii.js deleted file mode 100644 index 246b4721..00000000 --- a/solutions/1049-last-stone-weight-ii.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1049. Last Stone Weight II - * https://leetcode.com/problems/last-stone-weight-ii/ - * Difficulty: Medium - * - * You are given an array of integers stones where stones[i] is the weight of the ith stone. - * - * We are playing a game with the stones. On each turn, we choose any two stones and smash - * them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: - * - If x == y, both stones are destroyed, and - * - If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. - * - * At the end of the game, there is at most one stone left. - * - * Return the smallest possible weight of the left stone. If there are no stones left, return 0. - */ - -/** - * @param {number[]} stones - * @return {number} - */ -var lastStoneWeightII = function(stones) { - const totalSum = stones.reduce((sum, weight) => sum + weight, 0); - const target = Math.floor(totalSum / 2); - const set = new Set([0]); - - for (const stone of stones) { - const prev = new Set(set); - for (const sum of prev) { - if (sum + stone <= target) { - set.add(sum + stone); - } - } - } - - return totalSum - 2 * Math.max(...set); -}; diff --git a/solutions/1052-grumpy-bookstore-owner.js b/solutions/1052-grumpy-bookstore-owner.js deleted file mode 100644 index 0b150633..00000000 --- a/solutions/1052-grumpy-bookstore-owner.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1052. Grumpy Bookstore Owner - * https://leetcode.com/problems/grumpy-bookstore-owner/ - * Difficulty: Medium - * - * There is a bookstore owner that has a store open for n minutes. You are given an integer array - * customers of length n where customers[i] is the number of the customers that enter the store - * at the start of the ith minute and all those customers leave after the end of that minute. - * - * During certain minutes, the bookstore owner is grumpy. You are given a binary array grumpy - * where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise. - * - * When the bookstore owner is grumpy, the customers entering during that minute are not satisfied. - * Otherwise, they are satisfied. - * - * The bookstore owner knows a secret technique to remain not grumpy for minutes consecutive - * minutes, but this technique can only be used once. - * - * Return the maximum number of customers that can be satisfied throughout the day. - */ - -/** - * @param {number[]} customers - * @param {number[]} grumpy - * @param {number} minutes - * @return {number} - */ -var maxSatisfied = function(customers, grumpy, minutes) { - let baseSatisfied = 0; - let windowGain = 0; - let maxGain = 0; - - for (let i = 0; i < customers.length; i++) { - if (grumpy[i] === 0) { - baseSatisfied += customers[i]; - } - if (i < minutes) { - windowGain += grumpy[i] * customers[i]; - } else { - windowGain += grumpy[i] * customers[i] - grumpy[i - minutes] * customers[i - minutes]; - } - maxGain = Math.max(maxGain, windowGain); - } - - return baseSatisfied + maxGain; -}; diff --git a/solutions/1053-previous-permutation-with-one-swap.js b/solutions/1053-previous-permutation-with-one-swap.js deleted file mode 100644 index e5cfc434..00000000 --- a/solutions/1053-previous-permutation-with-one-swap.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1053. Previous Permutation With One Swap - * https://leetcode.com/problems/previous-permutation-with-one-swap/ - * Difficulty: Medium - * - * Given an array of positive integers arr (not necessarily distinct), return the lexicographically - * largest permutation that is smaller than arr, that can be made with exactly one swap. If it - * cannot be done, then return the same array. - * - * Note that a swap exchanges the positions of two numbers arr[i] and arr[j] - */ - -/** - * @param {number[]} arr - * @return {number[]} - */ -var prevPermOpt1 = function(arr) { - const result = [...arr]; - let swapIndex = -1; - - for (let i = arr.length - 2; i >= 0; i--) { - if (arr[i] > arr[i + 1]) { - swapIndex = i; - break; - } - } - - if (swapIndex === -1) return arr; - - let maxLessIndex = swapIndex + 1; - for (let j = swapIndex + 2; j < arr.length; j++) { - if (arr[j] < arr[swapIndex] && arr[j] > arr[maxLessIndex]) { - maxLessIndex = j; - } - } - - [result[swapIndex], result[maxLessIndex]] = [result[maxLessIndex], result[swapIndex]]; - - return result; -}; diff --git a/solutions/1054-distant-barcodes.js b/solutions/1054-distant-barcodes.js deleted file mode 100644 index 31d7beb6..00000000 --- a/solutions/1054-distant-barcodes.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1054. Distant Barcodes - * https://leetcode.com/problems/distant-barcodes/ - * Difficulty: Medium - * - * In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. - * - * Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, - * and it is guaranteed an answer exists. - */ - -/** - * @param {number[]} barcodes - * @return {number[]} - */ -var rearrangeBarcodes = function(barcodes) { - const frequencyMap = new Map(); - for (const code of barcodes) { - frequencyMap.set(code, (frequencyMap.get(code) || 0) + 1); - } - - const sortedCodes = [...frequencyMap.entries()] - .sort((a, b) => b[1] - a[1]); - - const result = new Array(barcodes.length); - let index = 0; - - for (const [code, count] of sortedCodes) { - for (let i = 0; i < count; i++) { - if (index >= barcodes.length) index = 1; - result[index] = code; - index += 2; - } - } - - return result; -}; diff --git a/solutions/1061-lexicographically-smallest-equivalent-string.js b/solutions/1061-lexicographically-smallest-equivalent-string.js deleted file mode 100644 index fbdab3b3..00000000 --- a/solutions/1061-lexicographically-smallest-equivalent-string.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1061. Lexicographically Smallest Equivalent String - * https://leetcode.com/problems/lexicographically-smallest-equivalent-string/ - * Difficulty: Medium - * - * You are given two strings of the same length s1 and s2 and a string baseStr. - * - * We say s1[i] and s2[i] are equivalent characters. - * - For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'. - * - * Equivalent characters follow the usual rules of any equivalence relation: - * - Reflexivity: 'a' == 'a'. - * - Symmetry: 'a' == 'b' implies 'b' == 'a'. - * - Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'. - * - * For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" - * are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent - * string of baseStr. - * - * Return the lexicographically smallest equivalent string of baseStr by using the equivalency - * information from s1 and s2. - */ - -/** - * @param {string} s1 - * @param {string} s2 - * @param {string} baseStr - * @return {string} - */ -var smallestEquivalentString = function(s1, s2, baseStr) { - const parent = Array(26).fill().map((_, i) => i); - - for (let i = 0; i < s1.length; i++) { - union(s1.charCodeAt(i) - 97, s2.charCodeAt(i) - 97); - } - - return baseStr.split('') - .map(char => String.fromCharCode(97 + find(char.charCodeAt(0) - 97))) - .join(''); - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - const rootX = find(x); - const rootY = find(y); - if (rootX < rootY) { - parent[rootY] = rootX; - } else if (rootX > rootY) { - parent[rootX] = rootY; - } - } -}; diff --git a/solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js b/solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js deleted file mode 100644 index 78ddca97..00000000 --- a/solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1072. Flip Columns For Maximum Number of Equal Rows - * https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/ - * Difficulty: Medium - * - * You are given an m x n binary matrix matrix. - * - * You can choose any number of columns in the matrix and flip every cell in that column - * (i.e., Change the value of the cell from 0 to 1 or vice versa). - * - * Return the maximum number of rows that have all values equal after some number of flips. - */ - -/** - * @param {number[][]} matrix - * @return {number} - */ -var maxEqualRowsAfterFlips = function(matrix) { - const rowPatterns = new Map(); - const rows = matrix.length; - const cols = matrix[0].length; - - for (let i = 0; i < rows; i++) { - let pattern = ''; - let flippedPattern = ''; - for (let j = 0; j < cols; j++) { - pattern += matrix[i][j]; - flippedPattern += 1 - matrix[i][j]; - } - rowPatterns.set(pattern, (rowPatterns.get(pattern) || 0) + 1); - rowPatterns.set(flippedPattern, (rowPatterns.get(flippedPattern) || 0) + 1); - } - - let result = 0; - for (const count of rowPatterns.values()) { - result = Math.max(result, count); - } - - return result; -}; diff --git a/solutions/1073-adding-two-negabinary-numbers.js b/solutions/1073-adding-two-negabinary-numbers.js deleted file mode 100644 index 0ff0d5aa..00000000 --- a/solutions/1073-adding-two-negabinary-numbers.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1073. Adding Two Negabinary Numbers - * https://leetcode.com/problems/adding-two-negabinary-numbers/ - * Difficulty: Medium - * - * Given two numbers arr1 and arr2 in base -2, return the result of adding them together. - * - * Each number is given in array format: as an array of 0s and 1s, from most significant - * bit to least significant bit. For example, arr = [1,1,0,1] represents the number - * (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to - * have no leading zeros: either arr == [0] or arr[0] == 1. - * - * Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s - * with no leading zeros. - */ - -/** - * @param {number[]} arr1 - * @param {number[]} arr2 - * @return {number[]} - */ -var addNegabinary = function(arr1, arr2) { - const result = []; - let i = arr1.length - 1; - let j = arr2.length - 1; - let carry = 0; - - while (i >= 0 || j >= 0 || carry !== 0) { - const x = i >= 0 ? arr1[i--] : 0; - const y = j >= 0 ? arr2[j--] : 0; - const sum = x + y + carry; - - result.unshift(sum & 1); - carry = sum >= 2 ? -1 : sum < 0 ? 1 : 0; - } - - while (result.length > 1 && result[0] === 0) { - result.shift(); - } - - return result; -}; diff --git a/solutions/1074-number-of-submatrices-that-sum-to-target.js b/solutions/1074-number-of-submatrices-that-sum-to-target.js deleted file mode 100644 index 30572280..00000000 --- a/solutions/1074-number-of-submatrices-that-sum-to-target.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1074. Number of Submatrices That Sum to Target - * https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/ - * Difficulty: Hard - * - * Given a matrix and a target, return the number of non-empty submatrices that sum to target. - * - * A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and - * y1 <= y <= y2. - * - * Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some - * coordinate that is different: for example, if x1 != x1'. - */ - -/** - * @param {number[][]} matrix - * @param {number} target - * @return {number} - */ -var numSubmatrixSumTarget = function(matrix, target) { - const rows = matrix.length; - const cols = matrix[0].length; - let result = 0; - - for (let i = 0; i < rows; i++) { - const prefixSums = new Array(cols).fill(0); - for (let j = i; j < rows; j++) { - const sumFreq = new Map([[0, 1]]); - let currentSum = 0; - - for (let k = 0; k < cols; k++) { - prefixSums[k] += matrix[j][k]; - currentSum += prefixSums[k]; - result += sumFreq.get(currentSum - target) || 0; - sumFreq.set(currentSum, (sumFreq.get(currentSum) || 0) + 1); - } - } - } - - return result; -}; diff --git a/solutions/1078-occurrences-after-bigram.js b/solutions/1078-occurrences-after-bigram.js deleted file mode 100644 index c207968b..00000000 --- a/solutions/1078-occurrences-after-bigram.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1078. Occurrences After Bigram - * https://leetcode.com/problems/occurrences-after-bigram/ - * Difficulty: Easy - * - * Given two strings first and second, consider occurrences in some text of the form "first second - * third", where second comes immediately after first, and third comes immediately after second. - * - * Return an array of all the words third for each occurrence of "first second third". - */ - -/** - * @param {string} text - * @param {string} first - * @param {string} second - * @return {string[]} - */ -var findOcurrences = function(text, first, second) { - const words = text.split(' '); - const result = []; - - for (let i = 0; i < words.length - 2; i++) { - if (words[i] === first && words[i + 1] === second) { - result.push(words[i + 2]); - } - } - - return result; -}; diff --git a/solutions/1080-insufficient-nodes-in-root-to-leaf-paths.js b/solutions/1080-insufficient-nodes-in-root-to-leaf-paths.js deleted file mode 100644 index ca034d35..00000000 --- a/solutions/1080-insufficient-nodes-in-root-to-leaf-paths.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1080. Insufficient Nodes in Root to Leaf Paths - * https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/ - * Difficulty: Medium - * - * Given the root of a binary tree and an integer limit, delete all insufficient nodes in the - * tree simultaneously, and return the root of the resulting binary tree. - * - * A node is insufficient if every root to leaf path intersecting this node has a sum strictly - * less than limit. - * - * 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} limit - * @return {TreeNode} - */ -var sufficientSubset = function(root, limit) { - return checkPath(root, 0) ? root : null; - - function checkPath(node, sum) { - if (!node) return false; - if (!node.left && !node.right) return sum + node.val >= limit; - - const leftValid = checkPath(node.left, sum + node.val); - const rightValid = checkPath(node.right, sum + node.val); - - if (!leftValid) node.left = null; - if (!rightValid) node.right = null; - - return leftValid || rightValid; - } -}; diff --git a/solutions/1089-duplicate-zeros.js b/solutions/1089-duplicate-zeros.js deleted file mode 100644 index 52728c4c..00000000 --- a/solutions/1089-duplicate-zeros.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1089. Duplicate Zeros - * https://leetcode.com/problems/duplicate-zeros/ - * Difficulty: Easy - * - * Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the - * remaining elements to the right. - * - * Note that elements beyond the length of the original array are not written. Do the above - * modifications to the input array in place and do not return anything. - */ - -/** - * @param {number[]} arr - * @return {void} Do not return anything, modify arr in-place instead. - */ -var duplicateZeros = function(arr) { - let zerosToAdd = 0; - - for (let i = 0; i < arr.length; i++) { - if (arr[i] === 0) zerosToAdd++; - } - - for (let i = arr.length - 1; i >= 0; i--) { - if (arr[i] === 0) { - zerosToAdd--; - if (i + zerosToAdd + 1 < arr.length) { - arr[i + zerosToAdd + 1] = 0; - } - } - if (i + zerosToAdd < arr.length) { - arr[i + zerosToAdd] = arr[i]; - } - } -}; diff --git a/solutions/1090-largest-values-from-labels.js b/solutions/1090-largest-values-from-labels.js deleted file mode 100644 index 9047e254..00000000 --- a/solutions/1090-largest-values-from-labels.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1090. Largest Values From Labels - * https://leetcode.com/problems/largest-values-from-labels/ - * Difficulty: Medium - * - * You are given n item's value and label as two integer arrays values and labels. You are also - * given two integers numWanted and useLimit. - * - * Your task is to find a subset of items with the maximum sum of their values such that: - * - The number of items is at most numWanted. - * - The number of items with the same label is at most useLimit. - * - * Return the maximum sum. - */ - -/** - * @param {number[]} values - * @param {number[]} labels - * @param {number} numWanted - * @param {number} useLimit - * @return {number} - */ -var largestValsFromLabels = function(values, labels, numWanted, useLimit) { - const items = values.map((value, index) => ({ value, label: labels[index] })); - items.sort((a, b) => b.value - a.value); - - const labelCount = new Map(); - let result = 0; - let itemsUsed = 0; - - for (const { value, label } of items) { - const currentCount = labelCount.get(label) || 0; - if (itemsUsed < numWanted && currentCount < useLimit) { - result += value; - labelCount.set(label, currentCount + 1); - itemsUsed++; - } - } - - return result; -}; diff --git a/solutions/1091-shortest-path-in-binary-matrix.js b/solutions/1091-shortest-path-in-binary-matrix.js deleted file mode 100644 index 49c46f97..00000000 --- a/solutions/1091-shortest-path-in-binary-matrix.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1091. Shortest Path in Binary Matrix - * https://leetcode.com/problems/shortest-path-in-binary-matrix/ - * Difficulty: Medium - * - * Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. - * If there is no clear path, return -1. - * - * A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the - * bottom-right cell (i.e., (n - 1, n - 1)) such that: - * - All the visited cells of the path are 0. - * - All the adjacent cells of the path are 8-directionally connected (i.e., they are different - * and they share an edge or a corner). - * - * The length of a clear path is the number of visited cells of this path. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var shortestPathBinaryMatrix = function(grid) { - const size = grid.length; - if (grid[0][0] === 1 || grid[size - 1][size - 1] === 1) return -1; - - const queue = [[0, 0, 1]]; - const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]; - grid[0][0] = 1; - - while (queue.length) { - const [row, col, distance] = queue.shift(); - if (row === size - 1 && col === size - 1) return distance; - - for (const [deltaRow, deltaCol] of directions) { - const newRow = row + deltaRow; - const newCol = col + deltaCol; - - if (newRow >= 0 && newRow < size && newCol >= 0 - && newCol < size && grid[newRow][newCol] === 0) { - queue.push([newRow, newCol, distance + 1]); - grid[newRow][newCol] = 1; - } - } - } - - return -1; -}; diff --git a/solutions/1093-statistics-from-a-large-sample.js b/solutions/1093-statistics-from-a-large-sample.js deleted file mode 100644 index 7d6bf073..00000000 --- a/solutions/1093-statistics-from-a-large-sample.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 1093. Statistics from a Large Sample - * https://leetcode.com/problems/statistics-from-a-large-sample/ - * Difficulty: Medium - * - * You are given a large sample of integers in the range [0, 255]. Since the sample is so large, - * it is represented by an array count where count[k] is the number of times that k appears in - * the sample. - * - * Calculate the following statistics: - * - minimum: The minimum element in the sample. - * - maximum: The maximum element in the sample. - * - mean: The average of the sample, calculated as the total sum of all elements divided by the - * total number of elements. - * - median: - * - If the sample has an odd number of elements, then the median is the middle element once - * the sample is sorted. - * - If the sample has an even number of elements, then the median is the average of the two - * middle elements once the sample is sorted. - * - mode: The number that appears the most in the sample. It is guaranteed to be unique. - * - * Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, - * mean, median, mode]. Answers within 10-5 of the actual answer will be accepted. - */ - -/** - * @param {number[]} count - * @return {number[]} - */ -var sampleStats = function(count) { - let minimum = 256; - let maximum = -1; - let sum = 0; - let totalCount = 0; - let mode = 0; - let maxFrequency = 0; - - for (let value = 0; value < 256; value++) { - const frequency = count[value]; - if (frequency > 0) { - minimum = Math.min(minimum, value); - maximum = Math.max(maximum, value); - sum += value * frequency; - totalCount += frequency; - if (frequency > maxFrequency) { - maxFrequency = frequency; - mode = value; - } - } - } - - const mean = sum / totalCount; - const median = findMedian(count, totalCount); - - return [minimum, maximum, mean, median, mode]; -}; - -function findMedian(count, totalCount) { - const isOdd = totalCount % 2 === 1; - const target = Math.floor(totalCount / 2); - let currentCount = 0; - let firstMedian = -1; - - for (let value = 0; value < 256; value++) { - currentCount += count[value]; - if (isOdd) { - if (currentCount > target) return value; - } else { - if (firstMedian === -1 && currentCount >= target) { - firstMedian = value; - } - if (currentCount > target) { - return (firstMedian + value) / 2; - } - } - } -} diff --git a/solutions/1094-car-pooling.js b/solutions/1094-car-pooling.js deleted file mode 100644 index 3d78e96a..00000000 --- a/solutions/1094-car-pooling.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1094. Car Pooling - * https://leetcode.com/problems/car-pooling/ - * Difficulty: Medium - * - * There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn - * around and drive west). - * - * You are given the integer capacity and an array trips where - * trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi - * passengers and the locations to pick them up and drop them off are fromi and toi respectively. - * The locations are given as the number of kilometers due east from the car's initial location. - * - * Return true if it is possible to pick up and drop off all passengers for all the given trips, - * or false otherwise. - */ - -/** - * @param {number[][]} trips - * @param {number} capacity - * @return {boolean} - */ -var carPooling = function(trips, capacity) { - const timeline = new Array(1001).fill(0); - - for (const [passengers, start, end] of trips) { - timeline[start] += passengers; - timeline[end] -= passengers; - } - - let currentPassengers = 0; - for (const change of timeline) { - currentPassengers += change; - if (currentPassengers > capacity) return false; - } - - return true; -}; diff --git a/solutions/1095-find-in-mountain-array.js b/solutions/1095-find-in-mountain-array.js deleted file mode 100644 index 02e89ce3..00000000 --- a/solutions/1095-find-in-mountain-array.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1095. Find in Mountain Array - * https://leetcode.com/problems/find-in-mountain-array/ - * Difficulty: Hard - * - * You may recall that an array arr is a mountain array if and only if: - * - arr.length >= 3 - * - There exists some i with 0 < i < arr.length - 1 such that: - * - arr[0] < arr[1] < ... < arr[i - 1] < arr[i] - * - arr[i] > arr[i + 1] > ... > arr[arr.length - 1] - * - * Given a mountain array mountainArr, return the minimum index such that - * mountainArr.get(index) == target. If such an index does not exist, return -1. - * - * You cannot access the mountain array directly. You may only access the array - * using a MountainArray interface: - * - MountainArray.get(k) returns the element of the array at index k (0-indexed). - * - MountainArray.length() returns the length of the array. - * - * Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. - * Also, any solutions that attempt to circumvent the judge will result in disqualification. - */ - -/** - * @param {number} target - * @param {MountainArray} mountainArr - * @return {number} - */ -var findInMountainArray = function(target, mountainArr) { - const length = mountainArr.length(); - - let left = 0; - let right = length - 1; - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (mountainArr.get(mid) < mountainArr.get(mid + 1)) { - left = mid + 1; - } else { - right = mid; - } - } - const peak = left; - - left = 0; - right = peak; - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const value = mountainArr.get(mid); - if (value === target) return mid; - if (value < target) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - left = peak; - right = length - 1; - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const value = mountainArr.get(mid); - if (value === target) return mid; - if (value > target) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return -1; -}; diff --git a/solutions/1096-brace-expansion-ii.js b/solutions/1096-brace-expansion-ii.js deleted file mode 100644 index b5cd470b..00000000 --- a/solutions/1096-brace-expansion-ii.js +++ /dev/null @@ -1,102 +0,0 @@ -/** - * 1096. Brace Expansion II - * https://leetcode.com/problems/brace-expansion-ii/ - * Difficulty: Hard - * - * Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) - * denote the set of words the expression represents. - * - * The grammar can best be understood through simple examples: - * - Single letters represent a singleton set containing that word. - * - R("a") = {"a"} - * - R("w") = {"w"} - * - When we take a comma-delimited list of two or more expressions, we take the union of - * possibilities. - * - R("{a,b,c}") = {"a","b","c"} - * - R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word - * at most once) - * - When we concatenate two expressions, we take the set of possible concatenations between two - * words where the first word comes from the first expression and the second word comes from - * the second expression. - * - R("{a,b}{c,d}") = {"ac","ad","bc","bd"} - * - R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", - * "acefg", "acefh"} - * - * Formally, the three rules for our grammar: - * - For every lowercase letter x, we have R(x) = {x}. - * - For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... - * - For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, - * where + denotes concatenation, and × denotes the cartesian product. - * - * Given an expression representing a set of words under the given grammar, return the sorted list - * of words that the expression represents. - */ - -/** - * @param {string} expression - * @return {string[]} - */ -var braceExpansionII = function(expression) { - function cartesian(set1, set2) { - const result = new Set(); - for (const a of set1) { - for (const b of set2) { - result.add(a + b); - } - } - return result; - } - - function evaluate(exp) { - let i = 0; - - function parseUnit() { - let result = new Set(); - - if (exp[i] === '{') { - i++; - result = parseExprList(); - i++; - } else { - result.add(exp[i]); - i++; - } - - return result; - } - - function parseExprList() { - const result = new Set(); - - const firstExpr = parseExpr(); - for (const word of firstExpr) { - result.add(word); - } - - while (i < exp.length && exp[i] === ',') { - i++; - const nextExpr = parseExpr(); - for (const word of nextExpr) { - result.add(word); - } - } - - return result; - } - - function parseExpr() { - let result = new Set(['']); - - while (i < exp.length && exp[i] !== ',' && exp[i] !== '}') { - const unit = parseUnit(); - result = cartesian(result, unit); - } - - return result; - } - - return parseExprList(); - } - - return [...evaluate(expression)].sort(); -}; diff --git a/solutions/1104-path-in-zigzag-labelled-binary-tree.js b/solutions/1104-path-in-zigzag-labelled-binary-tree.js deleted file mode 100644 index 1c16882e..00000000 --- a/solutions/1104-path-in-zigzag-labelled-binary-tree.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1104. Path In Zigzag Labelled Binary Tree - * https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/ - * Difficulty: Medium - * - * In an infinite binary tree where every node has two children, the nodes are labelled - * in row order. - * - * In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, - * while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. - * - * Given the label of a node in this tree, return the labels in the path from the root of the - * tree to the node with that label. - */ - -/** - * @param {number} label - * @return {number[]} - */ -var pathInZigZagTree = function(label) { - const result = []; - let current = label; - - while (current >= 1) { - result.unshift(current); - const level = Math.floor(Math.log2(current)); - current = Math.floor(((2 ** (level + 1)) - 1 + (2 ** level) - current) / 2); - } - - return result; -}; diff --git a/solutions/1105-filling-bookcase-shelves.js b/solutions/1105-filling-bookcase-shelves.js deleted file mode 100644 index d935b163..00000000 --- a/solutions/1105-filling-bookcase-shelves.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1105. Filling Bookcase Shelves - * https://leetcode.com/problems/filling-bookcase-shelves/ - * Difficulty: Medium - * - * You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness - * and height of the ith book. You are also given an integer shelfWidth. - * - * We want to place these books in order onto bookcase shelves that have a total width shelfWidth. - * - * We choose some of the books to place on this shelf such that the sum of their thickness is less - * than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the - * total height of the bookcase has increased by the maximum height of the books we just put down. - * We repeat this process until there are no more books to place. - * - * Note that at each step of the above process, the order of the books we place is the same order - * as the given sequence of books. - * - * For example, if we have an ordered list of 5 books, we might place the first and second book - * onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the - * last shelf. - * - * Return the minimum possible height that the total bookshelf can be after placing shelves in - * this manner. - */ - -/** - * @param {number[][]} books - * @param {number} shelfWidth - * @return {number} - */ -var minHeightShelves = function(books, shelfWidth) { - const dp = new Array(books.length + 1).fill(0); - - for (let i = 1; i <= books.length; i++) { - let width = books[i - 1][0]; - let height = books[i - 1][1]; - dp[i] = dp[i - 1] + height; - - let j = i - 2; - while (j >= 0 && width + books[j][0] <= shelfWidth) { - width += books[j][0]; - height = Math.max(height, books[j][1]); - dp[i] = Math.min(dp[i], dp[j] + height); - j--; - } - } - - return dp[books.length]; -}; diff --git a/solutions/1106-parsing-a-boolean-expression.js b/solutions/1106-parsing-a-boolean-expression.js deleted file mode 100644 index c806a033..00000000 --- a/solutions/1106-parsing-a-boolean-expression.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1106. Parsing A Boolean Expression - * https://leetcode.com/problems/parsing-a-boolean-expression/ - * Difficulty: Hard - * - * A boolean expression is an expression that evaluates to either true or false. It can be in - * one of the following shapes: - * - 't' that evaluates to true. - * - 'f' that evaluates to false. - * - '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. - * - '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner - * expressions subExpr1, subExpr2, ..., subExprn where n >= 1. - * - '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner - * expressions subExpr1, subExpr2, ..., subExprn where n >= 1. - * - * Given a string expression that represents a boolean expression, return the evaluation of - * that expression. - * - * It is guaranteed that the given expression is valid and follows the given rules. - */ - -/** - * @param {string} expression - * @return {boolean} - */ -var parseBoolExpr = function(expression) { - const stack = []; - - for (const char of expression) { - if (char === ')') { - const operands = []; - while (stack[stack.length - 1] !== '(') { - operands.push(stack.pop()); - } - stack.pop(); - const operator = stack.pop(); - - if (operator === '!') { - stack.push(!operands[0]); - } else if (operator === '&') { - stack.push(operands.every(val => val)); - } else if (operator === '|') { - stack.push(operands.some(val => val)); - } - } else if (char !== ',') { - stack.push(char === 't' ? true : char === 'f' ? false : char); - } - } - - return stack[0]; -}; diff --git a/solutions/1109-corporate-flight-bookings.js b/solutions/1109-corporate-flight-bookings.js deleted file mode 100644 index 7cc7789b..00000000 --- a/solutions/1109-corporate-flight-bookings.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1109. Corporate Flight Bookings - * https://leetcode.com/problems/corporate-flight-bookings/ - * Difficulty: Medium - * - * There are n flights that are labeled from 1 to n. - * - * You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] - * represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved - * for each flight in the range. - * - * Return an array answer of length n, where answer[i] is the total number of seats reserved for - * flight i. - */ - -/** - * @param {number[][]} bookings - * @param {number} n - * @return {number[]} - */ -var corpFlightBookings = function(bookings, n) { - const result = new Array(n).fill(0); - - for (const [start, end, count] of bookings) { - result[start - 1] += count; - if (end < n) result[end] -= count; - } - - for (let i = 1; i < n; i++) { - result[i] += result[i - 1]; - } - - return result; -}; diff --git a/solutions/1110-delete-nodes-and-return-forest.js b/solutions/1110-delete-nodes-and-return-forest.js deleted file mode 100644 index bf6875f4..00000000 --- a/solutions/1110-delete-nodes-and-return-forest.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1110. Delete Nodes And Return Forest - * https://leetcode.com/problems/delete-nodes-and-return-forest/ - * Difficulty: Medium - * - * Given the root of a binary tree, each node in the tree has a distinct value. - * - * After deleting all nodes with a value in toDelete, we are left with a forest (a disjoint - * union of trees). - * - * Return the roots of the trees in the remaining forest. You may return the result 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 - * @param {number[]} toDelete - * @return {TreeNode[]} - */ -var delNodes = function(root, toDelete) { - const deleteSet = new Set(toDelete); - const forest = []; - - traverse(root, true); - return forest; - - function traverse(node, isRoot) { - if (!node) return null; - - const shouldDelete = deleteSet.has(node.val); - if (isRoot && !shouldDelete) forest.push(node); - - node.left = traverse(node.left, shouldDelete); - node.right = traverse(node.right, shouldDelete); - - return shouldDelete ? null : node; - } -}; diff --git a/solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js b/solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js deleted file mode 100644 index 976fc2a9..00000000 --- a/solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1111. Maximum Nesting Depth of Two Valid Parentheses Strings - * https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/ - * Difficulty: Medium - * - * A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" - * characters only, and: - * - It is the empty string, or - * - It can be written as AB (A concatenated with B), where A and B are VPS's, or - * - It can be written as (A), where A is a VPS. - * - * We can similarly define the nesting depth depth(S) of any VPS S as follows: - * - depth("") = 0 - * - depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's - * - depth("(" + A + ")") = 1 + depth(A), where A is a VPS. - * - * For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), - * and ")(" and "(()" are not VPS's. - * - * Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's - * (and A.length + B.length = seq.length). - * - * Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. - * - * Return an answer array (of length seq.length) that encodes such a choice of A and B: - * answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple - * answers may exist, you may return any of them. - */ - -/** - * @param {string} seq - * @return {number[]} - */ -var maxDepthAfterSplit = function(seq) { - const result = new Array(seq.length); - let depth = 0; - - for (let i = 0; i < seq.length; i++) { - if (seq[i] === '(') { - result[i] = depth++ % 2; - } else { - result[i] = --depth % 2; - } - } - - return result; -}; diff --git a/solutions/1123-lowest-common-ancestor-of-deepest-leaves.js b/solutions/1123-lowest-common-ancestor-of-deepest-leaves.js deleted file mode 100644 index 2dfcb9e7..00000000 --- a/solutions/1123-lowest-common-ancestor-of-deepest-leaves.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1123. Lowest Common Ancestor of Deepest Leaves - * https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/ - * Difficulty: Medium - * - * Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. - * - * Recall that: - * - The node of a binary tree is a leaf if and only if it has no children - * - The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of - * its children is d + 1. - * - The lowest common ancestor of a set S of nodes, is the node A with the largest depth such - * that every node in S is in the subtree with root A. - */ - -/** - * 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 {TreeNode} - */ -var lcaDeepestLeaves = function(root) { - return findDepthAndNode(root).node; - - function findDepthAndNode(node) { - if (!node) return { depth: 0, node: null }; - - const left = findDepthAndNode(node.left); - const right = findDepthAndNode(node.right); - - if (left.depth === right.depth) { - return { depth: left.depth + 1, node: node }; - } - - const deeper = left.depth > right.depth ? left : right; - return { depth: deeper.depth + 1, node: deeper.node }; - } -}; diff --git a/solutions/1124-longest-well-performing-interval.js b/solutions/1124-longest-well-performing-interval.js deleted file mode 100644 index 33325ce5..00000000 --- a/solutions/1124-longest-well-performing-interval.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1124. Longest Well-Performing Interval - * https://leetcode.com/problems/longest-well-performing-interval/ - * Difficulty: Medium - * - * We are given hours, a list of the number of hours worked per day for a given employee. - * - * A day is considered to be a tiring day if and only if the number of hours worked is - * (strictly) greater than 8. - * - * A well-performing interval is an interval of days for which the number of tiring days - * is strictly larger than the number of non-tiring days. - * - * Return the length of the longest well-performing interval. - */ - -/** - * @param {number[]} hours - * @return {number} - */ -var longestWPI = function(hours) { - let result = 0; - let score = 0; - const seen = new Map(); - - for (let i = 0; i < hours.length; i++) { - score += hours[i] > 8 ? 1 : -1; - - if (score > 0) { - result = i + 1; - } else { - if (!seen.has(score)) { - seen.set(score, i); - } - if (seen.has(score - 1)) { - result = Math.max(result, i - seen.get(score - 1)); - } - } - } - - return result; -}; diff --git a/solutions/1125-smallest-sufficient-team.js b/solutions/1125-smallest-sufficient-team.js deleted file mode 100644 index a55196bb..00000000 --- a/solutions/1125-smallest-sufficient-team.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1125. Smallest Sufficient Team - * https://leetcode.com/problems/smallest-sufficient-team/ - * Difficulty: Hard - * - * In a project, you have a list of required skills reqSkills, and a list of people. The ith - * person people[i] contains a list of skills that the person has. - * - * Consider a sufficient team: a set of people such that for every required skill in reqSkills, - * there is at least one person in the team who has that skill. We can represent these teams by - * the index of each person. - * - * For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and - * people[3]. - * - * Return any sufficient team of the smallest possible size, represented by the index of each - * person. You may return the answer in any order. - * - * It is guaranteed an answer exists. - */ - -/** - * @param {string[]} reqSkills - * @param {string[][]} people - * @return {number[]} - */ -var smallestSufficientTeam = function(reqSkills, people) { - const skillCount = reqSkills.length; - const skillMap = new Map(reqSkills.map((skill, index) => [skill, 1 << index])); - const peopleSkills = people.map(skills => - skills.reduce((mask, skill) => mask | skillMap.get(skill), 0) - ); - const target = (1 << skillCount) - 1; - const dp = new Map([[0, []]]); - - for (let i = 0; i < people.length; i++) { - const currentSkill = peopleSkills[i]; - for (const [prevMask, team] of dp) { - const newMask = prevMask | currentSkill; - if (!dp.has(newMask) || dp.get(newMask).length > team.length + 1) { - dp.set(newMask, [...team, i]); - } - } - } - - return dp.get(target); -}; diff --git a/solutions/1128-number-of-equivalent-domino-pairs.js b/solutions/1128-number-of-equivalent-domino-pairs.js deleted file mode 100644 index c8ac1704..00000000 --- a/solutions/1128-number-of-equivalent-domino-pairs.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1128. Number of Equivalent Domino Pairs - * https://leetcode.com/problems/number-of-equivalent-domino-pairs/ - * Difficulty: Easy - * - * Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] - * if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino - * can be rotated to be equal to another domino. - * - * Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and - * dominoes[i] is equivalent to dominoes[j]. - */ - -/** - * @param {number[][]} dominoes - * @return {number} - */ -var numEquivDominoPairs = function(dominoes) { - const map = new Map(); - let result = 0; - - for (const [a, b] of dominoes) { - const key = Math.min(a, b) * 10 + Math.max(a, b); - const count = map.get(key) || 0; - result += count; - map.set(key, count + 1); - } - - return result; -}; diff --git a/solutions/1129-shortest-path-with-alternating-colors.js b/solutions/1129-shortest-path-with-alternating-colors.js deleted file mode 100644 index 34555ec7..00000000 --- a/solutions/1129-shortest-path-with-alternating-colors.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1129. Shortest Path with Alternating Colors - * https://leetcode.com/problems/shortest-path-with-alternating-colors/ - * Difficulty: Medium - * - * You are given an integer n, the number of nodes in a directed graph where the nodes are - * labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be - * self-edges and parallel edges. - * - * You are given two arrays redEdges and blueEdges where: - * - redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai - * to node bi in the graph, and - * - blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj - * to node vj in the graph. - * - * Return an array answer of length n, where each answer[x] is the length of the shortest - * path from node 0 to node x such that the edge colors alternate along the path, or -1 - * if such a path does not exist. - */ - -/** - * @param {number} n - * @param {number[][]} redEdges - * @param {number[][]} blueEdges - * @return {number[]} - */ -var shortestAlternatingPaths = function(n, redEdges, blueEdges) { - const redGraph = Array(n).fill().map(() => new Set()); - const blueGraph = Array(n).fill().map(() => new Set()); - - for (const [from, to] of redEdges) redGraph[from].add(to); - for (const [from, to] of blueEdges) blueGraph[from].add(to); - - const distances = Array(n).fill().map(() => [Infinity, Infinity]); - const queue = [[0, 0], [0, 1]]; - distances[0] = [0, 0]; - - while (queue.length) { - const [node, color] = queue.shift(); - const nextGraph = color ? redGraph : blueGraph; - const nextColor = 1 - color; - - for (const nextNode of nextGraph[node]) { - if (distances[nextNode][nextColor] === Infinity) { - distances[nextNode][nextColor] = distances[node][color] + 1; - queue.push([nextNode, nextColor]); - } - } - } - - return distances.map(([red, blue]) => { - const min = Math.min(red, blue); - return min === Infinity ? -1 : min; - }); -}; diff --git a/solutions/1130-minimum-cost-tree-from-leaf-values.js b/solutions/1130-minimum-cost-tree-from-leaf-values.js deleted file mode 100644 index 87da9ac9..00000000 --- a/solutions/1130-minimum-cost-tree-from-leaf-values.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1130. Minimum Cost Tree From Leaf Values - * https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ - * Difficulty: Medium - * - * Given an array arr of positive integers, consider all binary trees such that: - * - Each node has either 0 or 2 children; - * - The values of arr correspond to the values of each leaf in an in-order traversal of the tree. - * - The value of each non-leaf node is equal to the product of the largest leaf value in its left - * and right subtree, respectively. - * - * Among all possible binary trees considered, return the smallest possible sum of the values of - * each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. - * - * A node is a leaf if and only if it has zero children. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var mctFromLeafValues = function(arr) { - const stack = []; - let result = 0; - - for (const value of arr) { - while (stack.length && stack[stack.length - 1] <= value) { - const small = stack.pop(); - result += small * Math.min(stack[stack.length - 1] || Infinity, value); - } - stack.push(value); - } - - while (stack.length > 1) { - const small = stack.pop(); - result += small * stack[stack.length - 1]; - } - - return result; -}; diff --git a/solutions/1131-maximum-of-absolute-value-expression.js b/solutions/1131-maximum-of-absolute-value-expression.js deleted file mode 100644 index c264fef2..00000000 --- a/solutions/1131-maximum-of-absolute-value-expression.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1131. Maximum of Absolute Value Expression - * https://leetcode.com/problems/maximum-of-absolute-value-expression/ - * Difficulty: Medium - * - * Given two arrays of integers with equal lengths, return the maximum value of: - * - |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| - * - * where the maximum is taken over all 0 <= i, j < arr1.length. - */ - -/** - * @param {number[]} arr1 - * @param {number[]} arr2 - * @return {number} - */ -var maxAbsValExpr = function(arr1, arr2) { - const directions = [[1, 1], [1, -1], [-1, 1], [-1, -1]]; - let result = 0; - - for (const [dx, dy] of directions) { - let minSeen = Infinity; - let maxSeen = -Infinity; - - for (let i = 0; i < arr1.length; i++) { - const value = dx * arr1[i] + dy * arr2[i] + i; - minSeen = Math.min(minSeen, value); - maxSeen = Math.max(maxSeen, value); - } - - result = Math.max(result, maxSeen - minSeen); - } - - return result; -}; diff --git a/solutions/1138-alphabet-board-path.js b/solutions/1138-alphabet-board-path.js deleted file mode 100644 index 3ec2cbf5..00000000 --- a/solutions/1138-alphabet-board-path.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1138. Alphabet Board Path - * https://leetcode.com/problems/alphabet-board-path/ - * Difficulty: Medium - * - * On an alphabet board, we start at position (0, 0), corresponding to character board[0][0]. - * - * Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below. - * - * We may make the following moves: - * - 'U' moves our position up one row, if the position exists on the board; - * - 'D' moves our position down one row, if the position exists on the board; - * - 'L' moves our position left one column, if the position exists on the board; - * - 'R' moves our position right one column, if the position exists on the board; - * - '!' adds the character board[r][c] at our current position (r, c) to the answer. - * - * (Here, the only positions that exist on the board are positions with letters on them.) - * - * Return a sequence of moves that makes our answer equal to target in the minimum number of - * moves. You may return any path that does so. - */ - -/** - * @param {string} target - * @return {string} - */ -var alphabetBoardPath = function(target) { - let path = ''; - let row = 0; - let col = 0; - - for (const char of target) { - const code = char.charCodeAt(0) - 97; - const targetRow = Math.floor(code / 5); - const targetCol = code % 5; - - while (row > targetRow) path += 'U', row--; - while (col > targetCol) path += 'L', col--; - while (row < targetRow) path += 'D', row++; - while (col < targetCol) path += 'R', col++; - - path += '!'; - } - - return path; -}; diff --git a/solutions/1139-largest-1-bordered-square.js b/solutions/1139-largest-1-bordered-square.js deleted file mode 100644 index 161a8b8e..00000000 --- a/solutions/1139-largest-1-bordered-square.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1139. Largest 1-Bordered Square - * https://leetcode.com/problems/largest-1-bordered-square/ - * Difficulty: Medium - * - * Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid - * that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var largest1BorderedSquare = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const left = Array(rows).fill().map(() => Array(cols).fill(0)); - const top = Array(rows).fill().map(() => Array(cols).fill(0)); - let maxSide = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j]) { - left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1; - top[i][j] = i > 0 ? top[i - 1][j] + 1 : 1; - - let side = Math.min(left[i][j], top[i][j]); - while (side > maxSide) { - if (left[i - side + 1][j] >= side && top[i][j - side + 1] >= side) { - maxSide = side; - break; - } - side--; - } - } - } - } - - return maxSide * maxSide; -}; diff --git a/solutions/1140-stone-game-ii.js b/solutions/1140-stone-game-ii.js deleted file mode 100644 index 0dbe4efe..00000000 --- a/solutions/1140-stone-game-ii.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1140. Stone Game II - * https://leetcode.com/problems/stone-game-ii/ - * Difficulty: Medium - * - * Alice and Bob continue their games with piles of stones. There are a number of piles arranged - * in a row, and each pile has a positive integer number of stones piles[i]. The objective of - * the game is to end with the most stones. - * - * Alice and Bob take turns, with Alice starting first. - * - * On each player's turn, that player can take all the stones in the first X remaining piles, - * where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1. - * - * The game continues until all the stones have been taken. - * - * Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. - */ - -/** - * @param {number[]} piles - * @return {number} - */ -var stoneGameII = function(piles) { - const n = piles.length; - const cache = new Map(); - const suffixSums = new Array(n + 1).fill(0); - - for (let i = n - 1; i >= 0; i--) { - suffixSums[i] = suffixSums[i + 1] + piles[i]; - } - - return maxStones(0, 1); - - function maxStones(index, m) { - if (index >= n) return 0; - if (2 * m >= n - index) return suffixSums[index]; - - const key = `${index},${m}`; - if (cache.has(key)) return cache.get(key); - - let opponentMin = Infinity; - for (let x = 1; x <= 2 * m; x++) { - opponentMin = Math.min(opponentMin, maxStones(index + x, Math.max(m, x))); - } - - const result = suffixSums[index] - opponentMin; - cache.set(key, result); - return result; - } -}; diff --git a/solutions/1144-decrease-elements-to-make-array-zigzag.js b/solutions/1144-decrease-elements-to-make-array-zigzag.js deleted file mode 100644 index 4b485fbf..00000000 --- a/solutions/1144-decrease-elements-to-make-array-zigzag.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1144. Decrease Elements To Make Array Zigzag - * https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/ - * Difficulty: Medium - * - * Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. - * - * An array A is a zigzag array if either: - * - Every even-indexed element is greater than adjacent elements, ie. - * A[0] > A[1] < A[2] > A[3] < A[4] > ... - * - OR, every odd-indexed element is greater than adjacent elements, ie. - * A[0] < A[1] > A[2] < A[3] > A[4] < ... - * - * Return the minimum number of moves to transform the given array nums into a zigzag array. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var movesToMakeZigzag = function(nums) { - function calculateMoves(peakEven) { - let moves = 0; - const adjusted = [...nums]; - - for (let i = 0; i < adjusted.length; i++) { - if ((i % 2 === 0) === peakEven) { - const left = i > 0 ? adjusted[i - 1] : Infinity; - const right = i < adjusted.length - 1 ? adjusted[i + 1] : Infinity; - const target = Math.min(left, right) - 1; - if (adjusted[i] >= target) { - moves += adjusted[i] - target; - adjusted[i] = target; - } - } - } - - return moves; - } - - const evenPeaks = calculateMoves(true); - const oddPeaks = calculateMoves(false); - - return Math.min(evenPeaks, oddPeaks); -}; diff --git a/solutions/1145-binary-tree-coloring-game.js b/solutions/1145-binary-tree-coloring-game.js deleted file mode 100644 index 71319b50..00000000 --- a/solutions/1145-binary-tree-coloring-game.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1145. Binary Tree Coloring Game - * https://leetcode.com/problems/binary-tree-coloring-game/ - * Difficulty: Medium - * - * Two players play a turn based game on a binary tree. We are given the root of this binary tree, - * and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. - * - * Initially, the first player names a value x with 1 <= x <= n, and the second player names a value - * y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second - * player colors the node with value y blue. - * - * Then, the players take turns starting with the first player. In each turn, that player chooses - * a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of - * the chosen node (either the left child, right child, or parent of the chosen node.) - * - * If (and only if) a player cannot choose such a node in this way, they must pass their turn. If - * both players pass their turn, the game ends, and the winner is the player that colored more - * nodes. - * - * You are the second player. If it is possible to choose such a y to ensure you win the game, - * return true. If it is not possible, return false. - */ - -/** - * 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} n - * @param {number} x - * @return {boolean} - */ -var btreeGameWinningMove = function(root, n, x) { - let leftCount = 0; - let rightCount = 0; - - countNodes(root); - - const parentCount = n - leftCount - rightCount - 1; - const maxRegion = Math.max(parentCount, leftCount, rightCount); - - return maxRegion > n / 2; - - function countNodes(node) { - if (!node) return 0; - const left = countNodes(node.left); - const right = countNodes(node.right); - if (node.val === x) { - leftCount = left; - rightCount = right; - } - return left + right + 1; - } -}; diff --git a/solutions/1146-snapshot-array.js b/solutions/1146-snapshot-array.js deleted file mode 100644 index 1ceebcb6..00000000 --- a/solutions/1146-snapshot-array.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 1146. Snapshot Array - * https://leetcode.com/problems/snapshot-array/ - * Difficulty: Medium - * - * Implement a SnapshotArray that supports the following interface: - * - SnapshotArray(int length) initializes an array-like data structure with the given length. - * Initially, each element equals 0. - * - void set(index, val) sets the element at the given index to be equal to val. - * - int snap() takes a snapshot of the array and returns the snapId: the total number of times - * we called snap() minus 1. - * - int get(index, snapId) returns the value at the given index, at the time we took the - * snapshot with the given snapId - */ - -/** - * @param {number} length - */ -var SnapshotArray = function(length) { - this.history = new Map(); - this.snapshots = 0; - this.length = length; -}; - -/** - * @param {number} index - * @param {number} val - * @return {void} - */ -SnapshotArray.prototype.set = function(index, val) { - const current = this.history.get(this.snapshots) || new Map(); - current.set(index, val); - this.history.set(this.snapshots, current); -}; - -/** - * @return {number} - */ -SnapshotArray.prototype.snap = function() { - return this.snapshots++; -}; - -/** - * @param {number} index - * @param {number} snapId - * @return {number} - */ -SnapshotArray.prototype.get = function(index, snapId) { - for (let id = snapId; id >= 0; id--) { - const snapshot = this.history.get(id); - if (snapshot && snapshot.has(index)) { - return snapshot.get(index); - } - } - return 0; -}; diff --git a/solutions/1147-longest-chunked-palindrome-decomposition.js b/solutions/1147-longest-chunked-palindrome-decomposition.js deleted file mode 100644 index 47169c72..00000000 --- a/solutions/1147-longest-chunked-palindrome-decomposition.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1147. Longest Chunked Palindrome Decomposition - * https://leetcode.com/problems/longest-chunked-palindrome-decomposition/ - * Difficulty: Hard - * - * You are given a string text. You should split it to k substrings (subtext1, - * subtext2, ..., subtextk) such that: - * - subtexti is a non-empty string. - * - The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 - * + ... + subtextk == text). - * - subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k). - * - * Return the largest possible value of k. - */ - -/** - * @param {string} text - * @return {number} - */ -var longestDecomposition = function(text) { - return decompose(0, text.length - 1); - - function decompose(start, end) { - if (start > end) return 0; - if (start === end) return 1; - - const left = start; - const right = end; - let chunkSize = 0; - - while (left + chunkSize < right - chunkSize) { - chunkSize++; - if (text.slice(left, left + chunkSize) === text.slice(right - chunkSize + 1, right + 1)) { - return 2 + decompose(left + chunkSize, right - chunkSize); - } - } - - return 1; - } -}; diff --git a/solutions/1154-day-of-the-year.js b/solutions/1154-day-of-the-year.js deleted file mode 100644 index 4ce8d570..00000000 --- a/solutions/1154-day-of-the-year.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1154. Day of the Year - * https://leetcode.com/problems/day-of-the-year/ - * Difficulty: Easy - * - * Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, - * return the day number of the year. - */ - -/** - * @param {string} date - * @return {number} - */ -var dayOfYear = function(date) { - const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - const [year, month, day] = date.split('-').map(Number); - const isLeapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - if (isLeapYear) daysInMonth[1] = 29; - - let result = day; - for (let i = 0; i < month - 1; i++) { - result += daysInMonth[i]; - } - - return result; -}; diff --git a/solutions/1155-number-of-dice-rolls-with-target-sum.js b/solutions/1155-number-of-dice-rolls-with-target-sum.js deleted file mode 100644 index 39bc61a8..00000000 --- a/solutions/1155-number-of-dice-rolls-with-target-sum.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1155. Number of Dice Rolls With Target Sum - * https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/ - * Difficulty: Medium - * - * You have n dice, and each dice has k faces numbered from 1 to k. - * - * Given three integers n, k, and target, return the number of possible ways (out of the kn total - * ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may - * be too large, return it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} k - * @param {number} target - * @return {number} - */ -var numRollsToTarget = function(diceCount, faceCount, targetSum) { - const MOD = 1e9 + 7; - let dp = new Array(targetSum + 1).fill(0); - dp[0] = 1; - - for (let dice = 1; dice <= diceCount; dice++) { - const nextDp = new Array(targetSum + 1).fill(0); - for (let sum = 1; sum <= targetSum; sum++) { - for (let face = 1; face <= faceCount && face <= sum; face++) { - nextDp[sum] = (nextDp[sum] + dp[sum - face]) % MOD; - } - } - dp = nextDp; - } - - return dp[targetSum]; -}; diff --git a/solutions/1156-swap-for-longest-repeated-character-substring.js b/solutions/1156-swap-for-longest-repeated-character-substring.js deleted file mode 100644 index cdf4efe9..00000000 --- a/solutions/1156-swap-for-longest-repeated-character-substring.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1156. Swap For Longest Repeated Character Substring - * https://leetcode.com/problems/swap-for-longest-repeated-character-substring/ - * Difficulty: Medium - * - * You are given a string text. You can swap two of the characters in the text. - * - * Return the length of the longest substring with repeated characters. - */ - -/** - * @param {string} text - * @return {number} - */ -var maxRepOpt1 = function(text) { - const map = new Map(); - for (const char of text) { - map.set(char, (map.get(char) || 0) + 1); - } - - let result = 0; - for (let i = 0; i < text.length;) { - const currentChar = text[i]; - const segmentStart = i; - - while (i < text.length && text[i] === currentChar) i++; - const segmentLength = i - segmentStart; - - const totalAvailable = map.get(currentChar); - if (i < text.length && segmentLength < totalAvailable) { - const nextStart = i + 1; - let nextLength = 0; - while (nextStart + nextLength < text.length && text[nextStart + nextLength] === currentChar) { - nextLength++; - } - result = Math.max(result, Math.min(segmentLength + nextLength + 1, totalAvailable)); - } - result = Math.max(result, Math.min( - segmentLength + (totalAvailable > segmentLength ? 1 : 0), totalAvailable - )); - } - - return result; -}; diff --git a/solutions/1157-online-majority-element-in-subarray.js b/solutions/1157-online-majority-element-in-subarray.js deleted file mode 100644 index c982e650..00000000 --- a/solutions/1157-online-majority-element-in-subarray.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 1157. Online Majority Element In Subarray - * https://leetcode.com/problems/online-majority-element-in-subarray/ - * Difficulty: Hard - * - * Design a data structure that efficiently finds the majority element of a given subarray. - * - * The majority element of a subarray is an element that occurs threshold times or more in - * the subarray. - * - * Implementing the MajorityChecker class: - * - MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr. - * - int query(int left, int right, int threshold) returns the element in the subarray - * arr[left...right] that occurs at least threshold times, or -1 if no such element exists. - */ - -/** - * @param {number[]} arr - */ -var MajorityChecker = function(arr) { - this.positionMap = new Map(); - this.array = arr; - for (let i = 0; i < arr.length; i++) { - const positions = this.positionMap.get(arr[i]) || []; - positions.push(i); - this.positionMap.set(arr[i], positions); - } -}; - -/** - * @param {number} left - * @param {number} right - * @param {number} threshold - * @return {number} - */ -MajorityChecker.prototype.query = function(left, right, threshold) { - const maxAttempts = 20; - const rangeLength = right - left + 1; - - for (let attempt = 0; attempt < maxAttempts; attempt++) { - const candidate = this.array[left + Math.floor(Math.random() * rangeLength)]; - const positions = this.positionMap.get(candidate); - const count = countInRange(positions, left, right); - - if (count >= threshold) return candidate; - if (count + rangeLength - count < threshold) return -1; - } - return -1; -}; - -function countInRange(positions, left, right) { - const leftIndex = lowerBound(positions, left); - const rightIndex = upperBound(positions, right); - return rightIndex - leftIndex; -} - -function lowerBound(arr, target) { - let start = 0; - let end = arr.length; - while (start < end) { - const mid = Math.floor((start + end) / 2); - if (arr[mid] < target) start = mid + 1; - else end = mid; - } - return start; -} - -function upperBound(arr, target) { - let start = 0; - let end = arr.length; - while (start < end) { - const mid = Math.floor((start + end) / 2); - if (arr[mid] <= target) start = mid + 1; - else end = mid; - } - return start; -} diff --git a/solutions/1160-find-words-that-can-be-formed-by-characters.js b/solutions/1160-find-words-that-can-be-formed-by-characters.js deleted file mode 100644 index d2cdd24e..00000000 --- a/solutions/1160-find-words-that-can-be-formed-by-characters.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1160. Find Words That Can Be Formed by Characters - * https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/ - * Difficulty: Easy - * - * You are given an array of strings words and a string chars. - * - * A string is good if it can be formed by characters from chars (each character can only be - * used once). - * - * Return the sum of lengths of all good strings in words. - */ - -/** - * @param {string[]} words - * @param {string} chars - * @return {number} - */ -var countCharacters = function(words, availableChars) { - const charFrequency = new Map(); - for (const char of availableChars) { - charFrequency.set(char, (charFrequency.get(char) || 0) + 1); - } - - let result = 0; - for (const word of words) { - const tempFrequency = new Map(charFrequency); - let isValid = true; - - for (const char of word) { - if (!tempFrequency.has(char) || tempFrequency.get(char) === 0) { - isValid = false; - break; - } - tempFrequency.set(char, tempFrequency.get(char) - 1); - } - - if (isValid) result += word.length; - } - - return result; -}; diff --git a/solutions/1162-as-far-from-land-as-possible.js b/solutions/1162-as-far-from-land-as-possible.js deleted file mode 100644 index 57d80102..00000000 --- a/solutions/1162-as-far-from-land-as-possible.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 1162. As Far from Land as Possible - * https://leetcode.com/problems/as-far-from-land-as-possible/ - * Difficulty: Medium - * - * Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents - * land, find a water cell such that its distance to the nearest land cell is maximized, and return - * the distance. If no land or water exists in the grid, return -1. - * - * The distance used in this problem is the Manhattan distance: the distance between two cells - * (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var maxDistance = function(grid) { - const size = grid.length; - const queue = []; - let waterCount = 0; - - for (let row = 0; row < size; row++) { - for (let col = 0; col < size; col++) { - if (grid[row][col] === 1) { - queue.push([row, col]); - } else { - waterCount++; - } - } - } - - if (waterCount === 0 || queue.length === 0) return -1; - - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - let distance = -1; - - while (queue.length > 0) { - distance++; - const levelSize = queue.length; - for (let i = 0; i < levelSize; i++) { - const [currentRow, currentCol] = queue.shift(); - for (const [deltaRow, deltaCol] of directions) { - const newRow = currentRow + deltaRow; - const newCol = currentCol + deltaCol; - if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size - && grid[newRow][newCol] === 0) { - grid[newRow][newCol] = 1; - queue.push([newRow, newCol]); - } - } - } - } - - return distance === 0 ? -1 : distance; -}; diff --git a/solutions/1163-last-substring-in-lexicographical-order.js b/solutions/1163-last-substring-in-lexicographical-order.js deleted file mode 100644 index d3cbd638..00000000 --- a/solutions/1163-last-substring-in-lexicographical-order.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1163. Last Substring in Lexicographical Order - * https://leetcode.com/problems/last-substring-in-lexicographical-order/ - * Difficulty: Hard - * - * Given a string s, return the last substring of s in lexicographical order. - */ - -/** - * @param {string} s - * @return {string} - */ -var lastSubstring = function(s) { - let i = 0; - let j = 1; - let k = 0; - const n = s.length; - - while (j + k < n) { - if (s[i + k] === s[j + k]) { - k++; - } else if (s[i + k] < s[j + k]) { - i = Math.max(i + k + 1, j); - j = i + 1; - k = 0; - } else { - j += k + 1; - k = 0; - } - } - - return s.substring(i); -}; diff --git a/solutions/1169-invalid-transactions.js b/solutions/1169-invalid-transactions.js deleted file mode 100644 index 0dcab04a..00000000 --- a/solutions/1169-invalid-transactions.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1169. Invalid Transactions - * https://leetcode.com/problems/invalid-transactions/ - * Difficulty: Medium - * - * A transaction is possibly invalid if: - * - the amount exceeds $1000, or; - * - if it occurs within (and including) 60 minutes of another transaction with the same name in - * a different city. - * - * You are given an array of strings transaction where transactions[i] consists of comma-separated - * values representing the name, time (in minutes), amount, and city of the transaction. - * - * Return a list of transactions that are possibly invalid. You may return the answer in any order. - */ - -/** - * @param {string[]} transactions - * @return {string[]} - */ -var invalidTransactions = function(transactions) { - const parsed = transactions.map(t => { - const [name, time, amount, city] = t.split(','); - return { name, time: Number(time), amount: Number(amount), city }; - }); - - const invalid = new Set(); - - for (let i = 0; i < parsed.length; i++) { - const current = parsed[i]; - if (current.amount > 1000) { - invalid.add(i); - } - - for (let j = 0; j < parsed.length; j++) { - const other = parsed[j]; - if (i !== j && current.name === other.name - && Math.abs(current.time - other.time) <= 60 && current.city !== other.city) { - invalid.add(i); - invalid.add(j); - } - } - } - - return [...invalid].map(index => transactions[index]); -}; diff --git a/solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js b/solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js deleted file mode 100644 index 94791402..00000000 --- a/solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1170. Compare Strings by Frequency of the Smallest Character - * https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/ - * Difficulty: Medium - * - * Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty - * string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest - * character is 'c', which has a frequency of 2. - * - * You are given an array of strings words and another array of query strings queries. For each - * query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each - * W in words. - * - * Return an integer array answer, where each answer[i] is the answer to the ith query. - */ - -/** - * @param {string[]} queries - * @param {string[]} words - * @return {number[]} - */ -var numSmallerByFrequency = function(queries, words) { - const wordFrequencies = words.map(getMinCharFreq).sort((a, b) => a - b); - - return queries.map(query => { - const queryFreq = getMinCharFreq(query); - let left = 0; - let right = wordFrequencies.length; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (wordFrequencies[mid] <= queryFreq) { - left = mid + 1; - } else { - right = mid; - } - } - - return wordFrequencies.length - left; - }); - - function getMinCharFreq(str) { - let minChar = 'z'; - let freq = 0; - for (const char of str) { - if (char < minChar) { - minChar = char; - freq = 1; - } else if (char === minChar) { - freq++; - } - } - return freq; - } -}; diff --git a/solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js b/solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js deleted file mode 100644 index ca00d6d9..00000000 --- a/solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1171. Remove Zero Sum Consecutive Nodes from Linked List - * https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/ - * Difficulty: Medium - * - * Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to - * 0 until there are no such sequences. - * - * After doing so, return the head of the final linked list. You may return any such answer. - * - * (Note that in the examples below, all sequences are serializations of ListNode objects.) - */ - -/** - * 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 removeZeroSumSublists = function(head) { - const node = new ListNode(0, head); - const map = new Map(); - let prefixSum = 0; - - let current = node; - while (current) { - prefixSum += current.val; - map.set(prefixSum, current); - current = current.next; - } - - prefixSum = 0; - current = node; - while (current) { - prefixSum += current.val; - if (map.has(prefixSum) && map.get(prefixSum) !== current) { - current.next = map.get(prefixSum).next; - } - current = current.next; - } - - return node.next; -}; diff --git a/solutions/1172-dinner-plate-stacks.js b/solutions/1172-dinner-plate-stacks.js deleted file mode 100644 index f204e7bd..00000000 --- a/solutions/1172-dinner-plate-stacks.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * 1172. Dinner Plate Stacks - * https://leetcode.com/problems/dinner-plate-stacks/ - * Difficulty: Hard - * - * You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, - * each of the stacks has the same maximum capacity. - * - * Implement the DinnerPlates class: - * - DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks - * capacity. - * - void push(int val) Pushes the given integer val into the leftmost stack with a size less - * than capacity. - * - int pop() Returns the value at the top of the rightmost non-empty stack and removes it - * from that stack, and returns -1 if all the stacks are empty. - * - int popAtStack(int index) Returns the value at the top of the stack with the given index - * index and removes it from that stack or returns -1 if the stack with that given index is empty. - */ - -/** - * @param {number} capacity - */ -var DinnerPlates = function(capacity) { - this.maxCapacity = capacity; - this.plateStacks = []; - this.availableIndices = []; -}; - -/** - * @param {number} val - * @return {void} - */ -DinnerPlates.prototype.push = function(val) { - const targetIndex = this.availableIndices.length - ? this.availableIndices.pop() - : this.plateStacks.length - 1; - - if (!this.plateStacks[targetIndex] || this.plateStacks[targetIndex].length === this.maxCapacity) { - this.plateStacks.push([val]); - } else { - this.plateStacks[targetIndex].push(val); - } -}; - -/** - * @return {number} - */ -DinnerPlates.prototype.pop = function() { - while (this.plateStacks.length && !this.plateStacks.at(-1).length) { - while (this.plateStacks.length - 1 === this.availableIndices.at(-1)) { - this.availableIndices.pop(); - } - this.plateStacks.pop(); - } - - if (!this.plateStacks.length) { - return -1; - } - - const result = this.plateStacks.at(-1).pop() ?? -1; - - while (this.plateStacks.length && !this.plateStacks.at(-1).length) { - while (this.plateStacks.length - 1 === this.availableIndices.at(-1)) { - this.availableIndices.pop(); - } - this.plateStacks.pop(); - } - - return result; -}; - -/** - * @param {number} index - * @return {number} - */ -DinnerPlates.prototype.popAtStack = function(index) { - if (index >= this.plateStacks.length || !this.plateStacks[index].length) { - return -1; - } - - const result = this.plateStacks[index].pop(); - const temp = []; - - while (this.availableIndices.length && this.availableIndices.at(-1) < index) { - temp.push(this.availableIndices.pop()); - } - - this.availableIndices.push(index); - while (temp.length) { - this.availableIndices.push(temp.shift()); - } - - return result; -}; diff --git a/solutions/1175-prime-arrangements.js b/solutions/1175-prime-arrangements.js deleted file mode 100644 index 8dfd9eb1..00000000 --- a/solutions/1175-prime-arrangements.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1175. Prime Arrangements - * https://leetcode.com/problems/prime-arrangements/ - * Difficulty: Easy - * - * Return the number of permutations of 1 to n so that prime numbers are at prime - * indices (1-indexed.) - * - * (Recall that an integer is prime if and only if it is greater than 1, and cannot be written - * as a product of two positive integers both smaller than it.) - * - * Since the answer may be large, return the answer modulo 10^9 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -var numPrimeArrangements = function(n) { - let primeCount = 0; - for (let i = 1; i <= n; i++) { - if (isPrime(i)) primeCount++; - } - - const MOD = 1000000007n; - const nonPrimeCount = n - primeCount; - const primePermutations = factorial(primeCount); - const nonPrimePermutations = factorial(nonPrimeCount); - - return Number((primePermutations * nonPrimePermutations) % MOD); - - function isPrime(n) { - if (n < 2) return false; - for (let i = 2; i * i <= n; i++) { - if (n % i === 0) return false; - } - return true; - } - - function factorial(n) { - let product = 1n; - for (let i = 2; i <= n; i++) { - product *= BigInt(i); - } - return product; - } -}; diff --git a/solutions/1177-can-make-palindrome-from-substring.js b/solutions/1177-can-make-palindrome-from-substring.js deleted file mode 100644 index 4f807957..00000000 --- a/solutions/1177-can-make-palindrome-from-substring.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1177. Can Make Palindrome from Substring - * https://leetcode.com/problems/can-make-palindrome-from-substring/ - * Difficulty: Medium - * - * You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may - * rearrange the substring s[lefti...righti] for each query and then choose up to ki of them - * to replace with any lowercase English letter. - * - * If the substring is possible to be a palindrome string after the operations above, the - * result of the query is true. Otherwise, the result is false. - * - * Return a boolean array answer where answer[i] is the result of the ith query queries[i]. - * - * Note that each letter is counted individually for replacement, so if, for example - * s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note - * that no query modifies the initial string s. - */ - -/** - * @param {string} s - * @param {number[][]} queries - * @return {boolean[]} - */ -var canMakePaliQueries = function(s, queries) { - const prefixCounts = new Array(s.length + 1).fill().map(() => new Array(26).fill(0)); - - for (let i = 0; i < s.length; i++) { - prefixCounts[i + 1] = [...prefixCounts[i]]; - prefixCounts[i + 1][s.charCodeAt(i) - 97]++; - } - - const getOddCount = (left, right) => { - let odds = 0; - for (let j = 0; j < 26; j++) { - const count = prefixCounts[right + 1][j] - prefixCounts[left][j]; - odds += count % 2; - } - return odds; - }; - - const result = queries.map(([left, right, k]) => { - const oddCount = getOddCount(left, right); - return oddCount <= 2 * k + 1; - }); - - return result; -}; diff --git a/solutions/1178-number-of-valid-words-for-each-puzzle.js b/solutions/1178-number-of-valid-words-for-each-puzzle.js deleted file mode 100644 index 9db6e85e..00000000 --- a/solutions/1178-number-of-valid-words-for-each-puzzle.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1178. Number of Valid Words for Each Puzzle - * https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/ - * Difficulty: Hard - * - * With respect to a given puzzle string, a word is valid if both the following conditions - * are satisfied: - * - word contains the first letter of puzzle. - * - For each letter in word, that letter is in puzzle. - * - For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", - * and "baggage", while - * - invalid words are "beefed" (does not include 'a') and "based" (includes 's' which - * is not in the puzzle). - * - * Return an array answer, where answer[i] is the number of words in the given word list words - * that is valid with respect to the puzzle puzzles[i]. - */ - -/** - * @param {string[]} words - * @param {string[]} puzzles - * @return {number[]} - */ -var findNumOfValidWords = function(words, puzzles) { - const wordMasks = new Map(); - for (const word of words) { - const mask = getBitmask(word); - wordMasks.set(mask, (wordMasks.get(mask) || 0) + 1); - } - - const result = []; - for (const puzzle of puzzles) { - const puzzleMask = getBitmask(puzzle); - const firstCharBit = 1 << (puzzle.charCodeAt(0) - 97); - let count = 0; - - let submask = puzzleMask; - do { - if (submask & firstCharBit && wordMasks.has(submask)) { - count += wordMasks.get(submask); - } - submask = (submask - 1) & puzzleMask; - } while (submask); - - result.push(count); - } - - return result; - - function getBitmask(str) { - let mask = 0; - for (const char of str) { - mask |= 1 << (char.charCodeAt(0) - 97); - } - return mask; - } -}; diff --git a/solutions/1184-distance-between-bus-stops.js b/solutions/1184-distance-between-bus-stops.js deleted file mode 100644 index e63fe4f1..00000000 --- a/solutions/1184-distance-between-bus-stops.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1184. Distance Between Bus Stops - * https://leetcode.com/problems/distance-between-bus-stops/ - * Difficulty: Easy - * - * A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between - * all pairs of neighboring stops where distance[i] is the distance between the stops number - * i and (i + 1) % n. - * - * The bus goes along both directions i.e. clockwise and counterclockwise. - * - * Return the shortest distance between the given start and destination stops. - */ - -/** - * @param {number[]} distance - * @param {number} start - * @param {number} destination - * @return {number} - */ -var distanceBetweenBusStops = function(distance, start, destination) { - const normalizeIndices = (from, to) => from < to ? [from, to] : [to, from]; - - const [left, right] = normalizeIndices(start, destination); - const clockwiseDistance = distance.slice(left, right).reduce((sum, dist) => sum + dist, 0); - const totalDistance = distance.reduce((sum, dist) => sum + dist, 0); - const counterclockwiseDistance = totalDistance - clockwiseDistance; - - return Math.min(clockwiseDistance, counterclockwiseDistance); -}; diff --git a/solutions/1185-day-of-the-week.js b/solutions/1185-day-of-the-week.js deleted file mode 100644 index 97c71f96..00000000 --- a/solutions/1185-day-of-the-week.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1185. Day of the Week - * https://leetcode.com/problems/day-of-the-week/ - * Difficulty: Easy - * - * Given a date, return the corresponding day of the week for that date. - * - * The input is given as three integers representing the day, month and year respectively. - * - * Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", - * "Thursday", "Friday", "Saturday"}. - */ - -/** - * @param {number} day - * @param {number} month - * @param {number} year - * @return {string} - */ -var dayOfTheWeek = function(day, month, year) { - return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][ - new Date(year, month - 1, day).getDay() - ]; -}; diff --git a/solutions/1186-maximum-subarray-sum-with-one-deletion.js b/solutions/1186-maximum-subarray-sum-with-one-deletion.js deleted file mode 100644 index 41722f89..00000000 --- a/solutions/1186-maximum-subarray-sum-with-one-deletion.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1186. Maximum Subarray Sum with One Deletion - * https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/ - * Difficulty: Medium - * - * Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) - * with at most one element deletion. In other words, you want to choose a subarray and optionally - * delete one element from it so that there is still at least one element left and the sum of the - * remaining elements is maximum possible. - * - * Note that the subarray needs to be non-empty after deleting one element. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var maximumSum = function(arr) { - let maxNoDelete = arr[0]; - let maxOneDelete = 0; - let result = arr[0]; - - for (let i = 1; i < arr.length; i++) { - const prevMaxNoDelete = maxNoDelete; - maxNoDelete = Math.max(arr[i], maxNoDelete + arr[i]); - maxOneDelete = Math.max(prevMaxNoDelete, maxOneDelete + arr[i]); - result = Math.max(result, maxNoDelete, maxOneDelete); - } - - return result; -}; diff --git a/solutions/1187-make-array-strictly-increasing.js b/solutions/1187-make-array-strictly-increasing.js deleted file mode 100644 index 15701dcf..00000000 --- a/solutions/1187-make-array-strictly-increasing.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 1187. Make Array Strictly Increasing - * https://leetcode.com/problems/make-array-strictly-increasing/ - * Difficulty: Hard - * - * Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) - * needed to make arr1 strictly increasing. - * - * In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and - * do the assignment arr1[i] = arr2[j]. - * - * If there is no way to make arr1 strictly increasing, return -1. - */ - -/** - * @param {number[]} arr1 - * @param {number[]} arr2 - * @return {number} - */ -var makeArrayIncreasing = function(arr1, arr2) { - arr2 = [...new Set(arr2)].sort((a, b) => a - b); - let dp = new Map([[-Infinity, 0]]); - - for (let i = 0; i < arr1.length; i++) { - const nextDp = new Map(); - let minSteps = Infinity; - - for (const [prev, steps] of dp) { - if (steps >= minSteps) continue; - - if (arr1[i] > prev) { - updateMin(nextDp, arr1[i], steps); - minSteps = Math.min(minSteps, steps); - } - - const start = binarySearch(arr2, prev); - for (let j = start; j < arr2.length; j++) { - if (arr2[j] <= prev) continue; - updateMin(nextDp, arr2[j], steps + 1); - minSteps = Math.min(minSteps, steps + 1); - if (arr2[j] >= arr1[i]) break; - } - } - - if (nextDp.size === 0) return -1; - dp = pruneStates(nextDp); - } - - return Math.min(...dp.values()); -}; - -function updateMin(map, key, value) { - map.set(key, Math.min(value, map.get(key) ?? Infinity)); -} - -function binarySearch(arr, target) { - let left = 0; - let right = arr.length; - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (arr[mid] <= target) left = mid + 1; - else right = mid; - } - return left; -} - -function pruneStates(input) { - const map = new Map(); - let minSteps = Infinity; - for (const [val, steps] of [...input].sort((a, b) => a[0] - b[0])) { - if (steps < minSteps) { - map.set(val, steps); - minSteps = steps; - } - } - return map; -} diff --git a/solutions/1190-reverse-substrings-between-each-pair-of-parentheses.js b/solutions/1190-reverse-substrings-between-each-pair-of-parentheses.js deleted file mode 100644 index 3e2b5069..00000000 --- a/solutions/1190-reverse-substrings-between-each-pair-of-parentheses.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1190. Reverse Substrings Between Each Pair of Parentheses - * https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ - * Difficulty: Medium - * - * You are given a string s that consists of lower case English letters and brackets. - * - * Reverse the strings in each pair of matching parentheses, starting from the innermost one. - * - * Your result should not contain any brackets. - */ - -/** - * @param {string} s - * @return {string} - */ -var reverseParentheses = function(s) { - const stack = [[]]; - - for (const char of s) { - if (char === '(') { - stack.push([]); - } else if (char === ')') { - const reversed = stack.pop().reverse(); - stack[stack.length - 1].push(...reversed); - } else { - stack[stack.length - 1].push(char); - } - } - - return stack[0].join(''); -}; diff --git a/solutions/1191-k-concatenation-maximum-sum.js b/solutions/1191-k-concatenation-maximum-sum.js deleted file mode 100644 index 69cdcfac..00000000 --- a/solutions/1191-k-concatenation-maximum-sum.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1191. K-Concatenation Maximum Sum - * https://leetcode.com/problems/k-concatenation-maximum-sum/ - * Difficulty: Medium - * - * Given an integer array arr and an integer k, modify the array by repeating it k times. - * - * For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. - * - * Return the maximum sub-array sum in the modified array. Note that the length of the sub-array - * can be 0 and its sum in that case is 0. - * - * As the answer can be very large, return the answer modulo 109 + 7. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {number} - */ -var kConcatenationMaxSum = function(arr, k) { - const MOD = 1e9 + 7; - const arraySum = arr.reduce((sum, num) => sum + num, 0); - const maxSingle = helper(arr); - - if (k === 1) return maxSingle; - - const doubleArray = [...arr, ...arr]; - const maxDouble = helper(doubleArray); - - if (arraySum > 0) { - return Number((BigInt(maxDouble) + BigInt(arraySum) * BigInt(k - 2)) % BigInt(MOD)); - } - - return maxDouble; -}; - -function helper(arr) { - let maxSoFar = 0; - let maxEndingHere = 0; - - for (const num of arr) { - maxEndingHere = Math.max(0, maxEndingHere + num); - maxSoFar = Math.max(maxSoFar, maxEndingHere); - } - - return maxSoFar; -} diff --git a/solutions/1192-critical-connections-in-a-network.js b/solutions/1192-critical-connections-in-a-network.js deleted file mode 100644 index b45fc488..00000000 --- a/solutions/1192-critical-connections-in-a-network.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1192. Critical Connections in a Network - * https://leetcode.com/problems/critical-connections-in-a-network/ - * Difficulty: Hard - * - * There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections - * forming a network where connections[i] = [ai, bi] represents a connection between servers ai and - * bi. Any server can reach other servers directly or indirectly through the network. - * - * A critical connection is a connection that, if removed, will make some servers unable to reach - * some other server. - * - * Return all critical connections in the network in any order. - */ - -/** - * @param {number} n - * @param {number[][]} connections - * @return {number[][]} - */ -var criticalConnections = function(n, connections) { - const graph = Array.from({ length: n }, () => []); - const discoveryTimes = new Array(n).fill(-1); - const lowestReachableTimes = new Array(n).fill(-1); - const criticalEdges = []; - let time = 0; - - connections.forEach(([from, to]) => { - graph[from].push(to); - graph[to].push(from); - }); - - exploreNode(0, -1); - - return criticalEdges; - - function exploreNode(current, parent) { - discoveryTimes[current] = lowestReachableTimes[current] = time++; - - for (const neighbor of graph[current]) { - if (neighbor === parent) continue; - if (discoveryTimes[neighbor] === -1) { - exploreNode(neighbor, current); - lowestReachableTimes[current] = Math.min( - lowestReachableTimes[current], - lowestReachableTimes[neighbor] - ); - if (lowestReachableTimes[neighbor] > discoveryTimes[current]) { - criticalEdges.push([current, neighbor]); - } - } else { - lowestReachableTimes[current] = Math.min( - lowestReachableTimes[current], - discoveryTimes[neighbor] - ); - } - } - } -}; diff --git a/solutions/1201-ugly-number-iii.js b/solutions/1201-ugly-number-iii.js deleted file mode 100644 index 116dc652..00000000 --- a/solutions/1201-ugly-number-iii.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1201. Ugly Number III - * https://leetcode.com/problems/ugly-number-iii/ - * Difficulty: Medium - * - * An ugly number is a positive integer that is divisible by a, b, or c. - * - * Given four integers n, a, b, and c, return the nth ugly number. - */ - -/** - * @param {number} n - * @param {number} a - * @param {number} b - * @param {number} c - * @return {number} - */ -var nthUglyNumber = function(n, a, b, c) { - const ab = lcm(a, b); - const bc = lcm(b, c); - const ac = lcm(a, c); - const abc = lcm(ab, c); - let left = 1; - let right = 2 * 10**9; - - while (left < right) { - const mid = left + Math.floor((right - left) / 2); - if (countUgly(mid) < n) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; - - function lcm(x, y) { - return (x * y) / gcd(x, y); - } - - function gcd(x, y) { - return y === 0 ? x : gcd(y, x % y); - } - - function countUgly(num) { - return Math.floor(num / a) + Math.floor(num / b) + Math.floor(num / c) - - Math.floor(num / ab) - Math.floor(num / bc) - Math.floor(num / ac) - + Math.floor(num / abc); - } -}; diff --git a/solutions/1202-smallest-string-with-swaps.js b/solutions/1202-smallest-string-with-swaps.js deleted file mode 100644 index 57ae7209..00000000 --- a/solutions/1202-smallest-string-with-swaps.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1202. Smallest String With Swaps - * https://leetcode.com/problems/smallest-string-with-swaps/ - * Difficulty: Medium - * - * You are given a string s, and an array of pairs of indices in the string pairs where - * pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. - * - * You can swap the characters at any pair of indices in the given pairs any number of times. - * - * Return the lexicographically smallest string that s can be changed to after using the swaps. - */ - -/** - * @param {string} s - * @param {number[][]} pairs - * @return {string} - */ -var smallestStringWithSwaps = function(s, pairs) { - const parent = Array.from({ length: s.length }, (_, i) => i); - const rank = new Array(s.length).fill(0); - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - pairs.forEach(([x, y]) => union(x, y)); - - const components = new Map(); - for (let i = 0; i < s.length; i++) { - const root = find(i); - if (!components.has(root)) { - components.set(root, { indices: [], chars: [] }); - } - components.get(root).indices.push(i); - components.get(root).chars.push(s[i]); - } - - const result = new Array(s.length); - for (const { indices, chars } of components.values()) { - chars.sort((a, b) => b.localeCompare(a)); - indices.sort((a, b) => a - b); - indices.forEach((idx, i) => result[idx] = chars.pop()); - } - - return result.join(''); - - function union(x, y) { - const rootX = find(x); - const rootY = find(y); - if (rootX !== rootY) { - if (rank[rootX] < rank[rootY]) { - parent[rootX] = rootY; - } else if (rank[rootX] > rank[rootY]) { - parent[rootY] = rootX; - } else { - parent[rootY] = rootX; - rank[rootX]++; - } - } - } -}; diff --git a/solutions/1203-sort-items-by-groups-respecting-dependencies.js b/solutions/1203-sort-items-by-groups-respecting-dependencies.js deleted file mode 100644 index 429bd034..00000000 --- a/solutions/1203-sort-items-by-groups-respecting-dependencies.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * 1203. Sort Items by Groups Respecting Dependencies - * https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/ - * Difficulty: Hard - * - * There are n items each belonging to zero or one of m groups where group[i] is the group that - * the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items - * and the groups are zero indexed. A group can have no item belonging to it. - * - * Return a sorted list of the items such that: - * - The items that belong to the same group are next to each other in the sorted list. - * - There are some relations between these items where beforeItems[i] is a list containing all - * the items that should come before the i-th item in the sorted array (to the left of the i-th - * item). - * - * Return any solution if there is more than one solution and return an empty list if there is - * no solution. - */ - -/** - * @param {number} n - * @param {number} m - * @param {number[]} group - * @param {number[][]} beforeItems - * @return {number[]} - */ -var sortItems = function(n, m, group, beforeItems) { - const groupAdj = Array.from({ length: n + m }, () => []); - const itemAdj = Array.from({ length: n }, () => []); - const groupInDegree = new Array(n + m).fill(0); - const itemInDegree = new Array(n).fill(0); - let nextGroupId = m; - - assignGroupIds(); - buildGraphs(); - - const groupOrder = topologicalSort(groupAdj, groupInDegree, nextGroupId); - if (!groupOrder.length) return []; - - const itemOrder = topologicalSort(itemAdj, itemInDegree, n); - if (!itemOrder.length) return []; - - const groupToItems = new Map(); - itemOrder.forEach(item => { - if (!groupToItems.has(group[item])) { - groupToItems.set(group[item], []); - } - groupToItems.get(group[item]).push(item); - }); - - const result = []; - groupOrder.forEach(groupId => { - if (groupToItems.has(groupId)) { - result.push(...groupToItems.get(groupId)); - } - }); - - return result; - - function assignGroupIds() { - for (let i = 0; i < n; i++) { - if (group[i] === -1) { - group[i] = nextGroupId++; - } - } - } - - function buildGraphs() { - for (let i = 0; i < n; i++) { - for (const before of beforeItems[i]) { - if (group[before] !== group[i]) { - groupAdj[group[before]].push(group[i]); - groupInDegree[group[i]]++; - } else { - itemAdj[before].push(i); - itemInDegree[i]++; - } - } - } - } - - function topologicalSort(adjList, inDegree, size) { - const queue = []; - const order = []; - - for (let i = 0; i < size; i++) { - if (inDegree[i] === 0) queue.push(i); - } - - while (queue.length) { - const current = queue.shift(); - order.push(current); - for (const next of adjList[current]) { - inDegree[next]--; - if (inDegree[next] === 0) queue.push(next); - } - } - - return order.length === size ? order : []; - } -}; diff --git a/solutions/1209-remove-all-adjacent-duplicates-in-string-ii.js b/solutions/1209-remove-all-adjacent-duplicates-in-string-ii.js deleted file mode 100644 index 73df7788..00000000 --- a/solutions/1209-remove-all-adjacent-duplicates-in-string-ii.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1209. Remove All Adjacent Duplicates in String II - * https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/ - * Difficulty: Medium - * - * You are given a string s and an integer k, a k duplicate removal consists of choosing k - * adjacent and equal letters from s and removing them, causing the left and the right side - * of the deleted substring to concatenate together. - * - * We repeatedly make k duplicate removals on s until we no longer can. - * - * Return the final string after all such duplicate removals have been made. It is guaranteed - * that the answer is unique. - */ - -/** - * @param {string} s - * @param {number} k - * @return {string} - */ -var removeDuplicates = function(s, k) { - const stack = []; - - for (const char of s) { - if (stack.length && stack[stack.length - 1][0] === char) { - stack[stack.length - 1][1]++; - if (stack[stack.length - 1][1] === k) { - stack.pop(); - } - } else { - stack.push([char, 1]); - } - } - - return stack.reduce((result, [char, count]) => result + char.repeat(count), ''); -}; diff --git a/solutions/1210-minimum-moves-to-reach-target-with-rotations.js b/solutions/1210-minimum-moves-to-reach-target-with-rotations.js deleted file mode 100644 index b06cabf4..00000000 --- a/solutions/1210-minimum-moves-to-reach-target-with-rotations.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * 1210. Minimum Moves to Reach Target with Rotations - * https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/ - * Difficulty: Hard - * - * In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner - * at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented - * by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1). - * - * In one move the snake can: - * - Move one cell to the right if there are no blocked cells there. This move keeps the - * horizontal/vertical position of the snake as it is. - * - Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical - * position of the snake as it is. - * - Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. - * In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c). - * - Rotate counterclockwise if it's in a vertical position and the two cells to its right are both - * empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1). - * - * Return the minimum number of moves to reach the target. - * - * If there is no way to reach the target, return -1. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var minimumMoves = function(grid) { - const n = grid.length; - const queue = [[0, 0, 0, 1, 0]]; - const visited = new Set(['0,0,0,1']); - - while (queue.length) { - const [tailX, tailY, headX, headY, moves] = queue.shift(); - - if (tailX === n-1 && tailY === n-2 && headX === n-1 && headY === n-1) { - return moves; - } - - const isHorizontal = tailX === headX; - - if (isHorizontal) { - if (headY + 1 < n && isValid(tailX, tailY + 1) && isValid(headX, headY + 1)) { - const rightState = `${tailX},${tailY + 1},${headX},${headY + 1}`; - if (!visited.has(rightState)) { - visited.add(rightState); - queue.push([tailX, tailY + 1, headX, headY + 1, moves + 1]); - } - } - if (tailX + 1 < n && isValid(tailX + 1, tailY) && isValid(headX + 1, headY)) { - const downState = `${tailX + 1},${tailY},${headX + 1},${headY}`; - if (!visited.has(downState)) { - visited.add(downState); - queue.push([tailX + 1, tailY, headX + 1, headY, moves + 1]); - } - } - if (tailX + 1 < n && isValid(tailX + 1, tailY) && isValid(tailX + 1, tailY + 1)) { - const rotateState = `${tailX},${tailY},${tailX + 1},${tailY}`; - if (!visited.has(rotateState)) { - visited.add(rotateState); - queue.push([tailX, tailY, tailX + 1, tailY, moves + 1]); - } - } - } else { - if (headX + 1 < n && isValid(tailX + 1, tailY) && isValid(headX + 1, headY)) { - const downState = `${tailX + 1},${tailY},${headX + 1},${headY}`; - if (!visited.has(downState)) { - visited.add(downState); - queue.push([tailX + 1, tailY, headX + 1, headY, moves + 1]); - } - } - if (tailY + 1 < n && isValid(tailX, tailY + 1) && isValid(headX, tailY + 1)) { - const rightState = `${tailX},${tailY + 1},${headX},${tailY + 1}`; - if (!visited.has(rightState)) { - visited.add(rightState); - queue.push([tailX, tailY + 1, headX, tailY + 1, moves + 1]); - } - } - if (tailY + 1 < n && isValid(tailX, tailY + 1) && isValid(tailX + 1, tailY + 1)) { - const rotateState = `${tailX},${tailY},${tailX},${tailY + 1}`; - if (!visited.has(rotateState)) { - visited.add(rotateState); - queue.push([tailX, tailY, tailX, tailY + 1, moves + 1]); - } - } - } - } - - return -1; - - function isValid(x, y) { - return x >= 0 && x < n && y >= 0 && y < n && grid[x][y] === 0; - } -}; diff --git a/solutions/1218-longest-arithmetic-subsequence-of-given-difference.js b/solutions/1218-longest-arithmetic-subsequence-of-given-difference.js deleted file mode 100644 index e0031406..00000000 --- a/solutions/1218-longest-arithmetic-subsequence-of-given-difference.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1218. Longest Arithmetic Subsequence of Given Difference - * https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ - * Difficulty: Medium - * - * Given an integer array arr and an integer difference, return the length of the longest - * subsequence in arr which is an arithmetic sequence such that the difference between adjacent - * elements in the subsequence equals difference. - * - * A subsequence is a sequence that can be derived from arr by deleting some or no elements without - * changing the order of the remaining elements. - */ - -/** - * @param {number[]} arr - * @param {number} difference - * @return {number} - */ -var longestSubsequence = function(arr, difference) { - const sequenceLengths = new Map(); - let result = 0; - - for (const num of arr) { - const prevNum = num - difference; - const currentLength = (sequenceLengths.get(prevNum) || 0) + 1; - sequenceLengths.set(num, currentLength); - result = Math.max(result, currentLength); - } - - return result; -}; diff --git a/solutions/1219-path-with-maximum-gold.js b/solutions/1219-path-with-maximum-gold.js deleted file mode 100644 index 3d8c9c57..00000000 --- a/solutions/1219-path-with-maximum-gold.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 1219. Path with Maximum Gold - * https://leetcode.com/problems/path-with-maximum-gold/ - * Difficulty: Medium - * - * In a gold mine grid of size m x n, each cell in this mine has an integer representing the - * amount of gold in that cell, 0 if it is empty. - * - * Return the maximum amount of gold you can collect under the conditions: - * - Every time you are located in a cell you will collect all the gold in that cell. - * - From your position, you can walk one step to the left, right, up, or down. - * - You can't visit the same cell more than once. - * - Never visit a cell with 0 gold. - * - You can start and stop collecting gold from any position in the grid that has some gold. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var getMaximumGold = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - let maxGold = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j] !== 0) { - exploreGold(i, j, 0); - } - } - } - - return maxGold; - - function exploreGold(row, col, currentGold) { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] === 0) { - maxGold = Math.max(maxGold, currentGold); - return; - } - - const goldHere = grid[row][col]; - grid[row][col] = 0; - - exploreGold(row - 1, col, currentGold + goldHere); - exploreGold(row + 1, col, currentGold + goldHere); - exploreGold(row, col - 1, currentGold + goldHere); - exploreGold(row, col + 1, currentGold + goldHere); - - grid[row][col] = goldHere; - } -}; diff --git a/solutions/1220-count-vowels-permutation.js b/solutions/1220-count-vowels-permutation.js deleted file mode 100644 index 75c33416..00000000 --- a/solutions/1220-count-vowels-permutation.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1220. Count Vowels Permutation - * https://leetcode.com/problems/count-vowels-permutation/ - * Difficulty: Hard - * - * Given an integer n, your task is to count how many strings of length n can be formed under - * the following rules: - * - Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') - * - Each vowel 'a' may only be followed by an 'e'. - * - Each vowel 'e' may only be followed by an 'a' or an 'i'. - * - Each vowel 'i' may not be followed by another 'i'. - * - Each vowel 'o' may only be followed by an 'i' or a 'u'. - * - Each vowel 'u' may only be followed by an 'a'. - * - * Since the answer may be too large, return it modulo 10^9 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -var countVowelPermutation = function(n) { - const MOD = 1000000007n; - let aCount = 1n; - let eCount = 1n; - let iCount = 1n; - let oCount = 1n; - let uCount = 1n; - - for (let length = 2; length <= n; length++) { - const prevACount = aCount; - const prevECount = eCount; - const prevICount = iCount; - const prevOCount = oCount; - const prevUCount = uCount; - - aCount = (prevECount + prevICount + prevUCount) % MOD; - eCount = (prevACount + prevICount) % MOD; - iCount = (prevECount + prevOCount) % MOD; - oCount = (prevICount) % MOD; - uCount = (prevICount + prevOCount) % MOD; - } - - const total = aCount + eCount + iCount + oCount + uCount; - - return Number(total % MOD); -}; diff --git a/solutions/1221-split-a-string-in-balanced-strings.js b/solutions/1221-split-a-string-in-balanced-strings.js deleted file mode 100644 index aa0d2805..00000000 --- a/solutions/1221-split-a-string-in-balanced-strings.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1221. Split a String in Balanced Strings - * https://leetcode.com/problems/split-a-string-in-balanced-strings/ - * Difficulty: Easy - * - * Balanced strings are those that have an equal quantity of 'L' and 'R' characters. - * - * Given a balanced string s, split it into some number of substrings such that: - * - Each substring is balanced. - * - * Return the maximum number of balanced strings you can obtain. - */ - -/** - * @param {string} s - * @return {number} - */ -var balancedStringSplit = function(s) { - let result = 0; - let balance = 0; - - for (const char of s) { - if (char === 'R') balance++; - else balance--; - - if (balance === 0) result++; - } - - return result; -}; diff --git a/solutions/1222-queens-that-can-attack-the-king.js b/solutions/1222-queens-that-can-attack-the-king.js deleted file mode 100644 index 2544620e..00000000 --- a/solutions/1222-queens-that-can-attack-the-king.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1222. Queens That Can Attack the King - * https://leetcode.com/problems/queens-that-can-attack-the-king/ - * Difficulty: Medium - * - * On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king. - * - * You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the - * position of the ith black queen on the chessboard. You are also given an integer array king - * of length 2 where king = [xKing, yKing] represents the position of the white king. - * - * Return the coordinates of the black queens that can directly attack the king. You may return - * the answer in any order. - */ - -/** - * @param {number[][]} queens - * @param {number[]} king - * @return {number[][]} - */ -var queensAttacktheKing = function(queens, king) { - const [kingX, kingY] = king; - const queenSet = new Set(queens.map(([x, y]) => `${x},${y}`)); - const attackers = []; - const directions = [ - [-1, 0], [1, 0], [0, -1], [0, 1], - [-1, -1], [-1, 1], [1, -1], [1, 1] - ]; - - for (const [dx, dy] of directions) { - let x = kingX + dx; - let y = kingY + dy; - - while (x >= 0 && x < 8 && y >= 0 && y < 8) { - const pos = `${x},${y}`; - if (queenSet.has(pos)) { - attackers.push([x, y]); - break; - } - x += dx; - y += dy; - } - } - - return attackers; -}; diff --git a/solutions/1223-dice-roll-simulation.js b/solutions/1223-dice-roll-simulation.js deleted file mode 100644 index 9ef37654..00000000 --- a/solutions/1223-dice-roll-simulation.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1223. Dice Roll Simulation - * https://leetcode.com/problems/dice-roll-simulation/ - * Difficulty: Hard - * - * A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint - * to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) - * consecutive times. - * - * Given an array of integers rollMax and an integer n, return the number of distinct sequences - * that can be obtained with exact n rolls. Since the answer may be too large, return it modulo - * 1e9 + 7. - * - * Two sequences are considered different if at least one element differs from each other. - */ - -/** - * @param {number} n - * @param {number[]} rollMax - * @return {number} - */ -var dieSimulator = function(n, rollMax) { - const MOD = 1e9 + 7; - const faces = 6; - - const dp = new Array(n + 1).fill().map(() => new Array(faces).fill(0)); - for (let face = 0; face < faces; face++) { - dp[1][face] = 1; - } - - for (let rolls = 2; rolls <= n; rolls++) { - for (let face = 0; face < faces; face++) { - const maxConsecutive = Math.min(rolls, rollMax[face]); - let sequences = 0; - - for (let streak = 1; streak <= maxConsecutive; streak++) { - if (streak === rolls) { - sequences = (sequences + 1) % MOD; - } else { - let prevCombinations = 0; - for (let prevFace = 0; prevFace < faces; prevFace++) { - if (prevFace !== face) { - prevCombinations = (prevCombinations + dp[rolls - streak][prevFace]) % MOD; - } - } - sequences = (sequences + prevCombinations) % MOD; - } - } - dp[rolls][face] = sequences; - } - } - - let result = 0; - for (let face = 0; face < faces; face++) { - result = (result + dp[n][face]) % MOD; - } - - return result; -}; diff --git a/solutions/1224-maximum-equal-frequency.js b/solutions/1224-maximum-equal-frequency.js deleted file mode 100644 index cc7a888c..00000000 --- a/solutions/1224-maximum-equal-frequency.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1224. Maximum Equal Frequency - * https://leetcode.com/problems/maximum-equal-frequency/ - * Difficulty: Hard - * - * Given an array nums of positive integers, return the longest possible length of an array prefix - * of nums, such that it is possible to remove exactly one element from this prefix so that every - * number that has appeared in it will have the same number of occurrences. - * - * If after removing one element there are no remaining elements, it's still considered that every - * appeared number has the same number of ocurrences (0). - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxEqualFreq = function(nums) { - const countMap = new Map(); - const freqMap = new Map(); - let result = 0; - - for (let i = 0; i < nums.length; i++) { - const num = nums[i]; - const prevCount = countMap.get(num) || 0; - const newCount = prevCount + 1; - - countMap.set(num, newCount); - - if (prevCount > 0) { - freqMap.set(prevCount, (freqMap.get(prevCount) || 0) - 1); - if (freqMap.get(prevCount) === 0) freqMap.delete(prevCount); - } - freqMap.set(newCount, (freqMap.get(newCount) || 0) + 1); - - if (freqMap.size === 1) { - const [freq, occurrences] = [...freqMap.entries()][0]; - if (freq === 1 || occurrences === 1) result = i + 1; - } else if (freqMap.size === 2) { - const freqs = [...freqMap.keys()].sort((a, b) => a - b); - if (freqs[0] === 1 && freqMap.get(freqs[0]) === 1) result = i + 1; - if (freqs[1] === freqs[0] + 1 && freqMap.get(freqs[1]) === 1) result = i + 1; - } - } - - return result; -}; diff --git a/solutions/1227-airplane-seat-assignment-probability.js b/solutions/1227-airplane-seat-assignment-probability.js deleted file mode 100644 index c2e9dcde..00000000 --- a/solutions/1227-airplane-seat-assignment-probability.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * 1227. Airplane Seat Assignment Probability - * https://leetcode.com/problems/airplane-seat-assignment-probability/ - * Difficulty: Medium - * - * n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and - * picks a seat randomly. But after that, the rest of the passengers will: - * - Take their own seat if it is still available, and - * - Pick other seats randomly when they find their seat occupied - * - * Return the probability that the nth person gets his own seat. - */ - -/** - * @param {number} n - * @return {number} - */ -var nthPersonGetsNthSeat = function(n) { - return n === 1 ? 1 : 0.5; -}; diff --git a/solutions/1234-replace-the-substring-for-balanced-string.js b/solutions/1234-replace-the-substring-for-balanced-string.js deleted file mode 100644 index a8b585f7..00000000 --- a/solutions/1234-replace-the-substring-for-balanced-string.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1234. Replace the Substring for Balanced String - * https://leetcode.com/problems/replace-the-substring-for-balanced-string/ - * Difficulty: Medium - * - * You are given a string s of length n containing only four kinds of characters: - * 'Q', 'W', 'E', and 'R'. - * - * A string is said to be balanced if each of its characters appears n / 4 times where n is - * the length of the string. - * - * Return the minimum length of the substring that can be replaced with any other string of - * the same length to make s balanced. If s is already balanced, return 0. - */ - -/** - * @param {string} s - * @return {number} - */ -var balancedString = function(s) { - const target = s.length / 4; - const charCount = { Q: 0, W: 0, E: 0, R: 0 }; - - for (const char of s) { - charCount[char]++; - } - - if (Object.values(charCount).every(count => count === target)) return 0; - - let result = s.length; - let left = 0; - - for (let right = 0; right < s.length; right++) { - charCount[s[right]]--; - - while (left <= right && Object.values(charCount).every(count => count <= target)) { - result = Math.min(result, right - left + 1); - charCount[s[left]]++; - left++; - } - } - - return result; -}; diff --git a/solutions/1235-maximum-profit-in-job-scheduling.js b/solutions/1235-maximum-profit-in-job-scheduling.js deleted file mode 100644 index 264ce06b..00000000 --- a/solutions/1235-maximum-profit-in-job-scheduling.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1235. Maximum Profit in Job Scheduling - * https://leetcode.com/problems/maximum-profit-in-job-scheduling/ - * Difficulty: Hard - * - * We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], - * obtaining a profit of profit[i]. - * - * You're given the startTime, endTime and profit arrays, return the maximum profit you can - * take such that there are no two jobs in the subset with overlapping time range. - * - * If you choose a job that ends at time X you will be able to start another job that starts - * at time X. - */ - -/** - * @param {number[]} startTime - * @param {number[]} endTime - * @param {number[]} profit - * @return {number} - */ -var jobScheduling = function(startTime, endTime, profit) { - const jobCount = startTime.length; - const indices = Array.from({ length: jobCount }, (_, i) => i) - .sort((a, b) => startTime[a] - startTime[b]); - - const maxProfit = new Array(jobCount + 1).fill(0); - - for (let i = jobCount - 1; i >= 0; i--) { - let left = i + 1; - let right = jobCount - 1; - const currentEnd = endTime[indices[i]]; - - while (left <= right) { - const mid = left + right >> 1; - if (startTime[indices[mid]] < currentEnd) left = mid + 1; - else right = mid - 1; - } - - maxProfit[i] = Math.max(maxProfit[i + 1], profit[indices[i]] + maxProfit[left]); - } - - return maxProfit[0]; -}; diff --git a/solutions/1237-find-positive-integer-solution-for-a-given-equation.js b/solutions/1237-find-positive-integer-solution-for-a-given-equation.js deleted file mode 100644 index 8f658a4a..00000000 --- a/solutions/1237-find-positive-integer-solution-for-a-given-equation.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1237. Find Positive Integer Solution for a Given Equation - * https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/ - * Difficulty: Medium - * - * Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer - * the formula and return all positive integer pairs x and y where f(x,y) == z. You may - * return the pairs in any order. - * - * While the exact formula is hidden, the function is monotonically increasing, i.e.: - * - f(x, y) < f(x + 1, y) - * - f(x, y) < f(x, y + 1) - */ - -/** - * // This is the CustomFunction's API interface. - * // You should not implement it, or speculate about its implementation - * function CustomFunction() { - * @param {integer, integer} x, y - * @return {integer} - * this.f = function(x, y) { - * ... - * }; - * }; - */ - -/** - * @param {CustomFunction} customfunction - * @param {integer} z - * @return {integer[][]} - */ -function findSolution(customfunction, z) { - const pairs = []; - let left = 1; - let right = 1000; - - while (left <= 1000 && right >= 1) { - const value = customfunction.f(left, right); - if (value === z) { - pairs.push([left, right]); - left++; - right--; - } else if (value < z) { - left++; - } else { - right--; - } - } - - return pairs; -} diff --git a/solutions/1238-circular-permutation-in-binary-representation.js b/solutions/1238-circular-permutation-in-binary-representation.js deleted file mode 100644 index 88818a00..00000000 --- a/solutions/1238-circular-permutation-in-binary-representation.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1238. Circular Permutation in Binary Representation - * https://leetcode.com/problems/circular-permutation-in-binary-representation/ - * Difficulty: Medium - * - * Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) - * such that: - * - p[0] = start - * - p[i] and p[i+1] differ by only one bit in their binary representation. - * - p[0] and p[2^n -1] must also differ by only one bit in their binary representation. - */ - -/** - * @param {number} n - * @param {number} start - * @return {number[]} - */ -var circularPermutation = function(n, start) { - return helper(n).map(num => num ^ start); -}; - -function helper(n) { - const sequence = [0]; - for (let i = 0; i < n; i++) { - const mirror = sequence.slice().reverse(); - const power = 1 << i; - for (let j = 0; j < mirror.length; j++) { - sequence.push(mirror[j] + power); - } - } - return sequence; -} diff --git a/solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js b/solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js deleted file mode 100644 index 02e520cf..00000000 --- a/solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1239. Maximum Length of a Concatenated String with Unique Characters - * https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ - * Difficulty: Medium - * - * You are given an array of strings arr. A string s is formed by the concatenation of a subsequence - * of arr that has unique characters. - * - * Return the maximum possible length of s. - * - * 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 {string[]} arr - * @return {number} - */ -function maxLength(arr) { - let result = 0; - explore('', 0); - return result; - - function explore(current, index) { - result = Math.max(result, current.length); - for (let i = index; i < arr.length; i++) { - if (isUnique(current + arr[i])) { - explore(current + arr[i], i + 1); - } - } - } - - function isUnique(str) { - return new Set(str).size === str.length; - } -} diff --git a/solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js b/solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js deleted file mode 100644 index 8a423f4d..00000000 --- a/solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 1240. Tiling a Rectangle with the Fewest Squares - * https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/ - * Difficulty: Hard - * - * Given a rectangle of size n x m, return the minimum number of integer-sided squares that - * tile the rectangle. - */ - -/** - * @param {number} n - * @param {number} m - * @return {number} - */ -function tilingRectangle(n, m) { - let result = n * m; - const grid = new Array(n).fill().map(() => new Array(m).fill(false)); - explore(0); - return result; - - function canPlaceSquare(row, col, size) { - if (row + size > n || col + size > m) return false; - for (let i = row; i < row + size; i++) { - for (let j = col; j < col + size; j++) { - if (grid[i][j]) return false; - } - } - return true; - } - - function fillSquare(row, col, size, value) { - for (let i = row; i < row + size; i++) { - for (let j = col; j < col + size; j++) { - grid[i][j] = value; - } - } - } - - function explore(count) { - if (count >= result) return; - let row = -1; - let col = -1; - for (let i = 0; i < n && row === -1; i++) { - for (let j = 0; j < m; j++) { - if (!grid[i][j]) { - row = i; - col = j; - break; - } - } - } - if (row === -1) { - result = Math.min(result, count); - return; - } - for (let size = Math.min(n - row, m - col); size >= 1; size--) { - if (canPlaceSquare(row, col, size)) { - fillSquare(row, col, size, true); - explore(count + 1); - fillSquare(row, col, size, false); - } - } - } -} diff --git a/solutions/1247-minimum-swaps-to-make-strings-equal.js b/solutions/1247-minimum-swaps-to-make-strings-equal.js deleted file mode 100644 index d5ce1ec8..00000000 --- a/solutions/1247-minimum-swaps-to-make-strings-equal.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1247. Minimum Swaps to Make Strings Equal - * https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/ - * Difficulty: Medium - * - * You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. - * Your task is to make these two strings equal to each other. You can swap any two characters - * that belong to different strings, which means: swap s1[i] and s2[j]. - * - * Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is - * impossible to do so. - */ - -/** - * @param {string} s1 - * @param {string} s2 - * @return {number} - */ -function minimumSwap(s1, s2) { - let xyCount = 0; - let yxCount = 0; - - for (let i = 0; i < s1.length; i++) { - if (s1[i] === 'x' && s2[i] === 'y') xyCount++; - if (s1[i] === 'y' && s2[i] === 'x') yxCount++; - } - - if ((xyCount + yxCount) % 2 !== 0) return -1; - - return Math.floor(xyCount / 2) + Math.floor(yxCount / 2) + (xyCount % 2) * 2; -} diff --git a/solutions/1248-count-number-of-nice-subarrays.js b/solutions/1248-count-number-of-nice-subarrays.js deleted file mode 100644 index 915d6f8a..00000000 --- a/solutions/1248-count-number-of-nice-subarrays.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1248. Count Number of Nice Subarrays - * https://leetcode.com/problems/count-number-of-nice-subarrays/ - * Difficulty: Medium - * - * Given an array of integers nums and an integer k. A continuous subarray is called nice if there - * are k odd numbers on it. - * - * Return the number of nice sub-arrays. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var numberOfSubarrays = function(nums, k) { - const prefix = new Map([[0, 1]]); - let oddCount = 0; - let result = 0; - - for (const num of nums) { - oddCount += num % 2; - result += prefix.get(oddCount - k) || 0; - prefix.set(oddCount, (prefix.get(oddCount) || 0) + 1); - } - - return result; -}; diff --git a/solutions/1250-check-if-it-is-a-good-array.js b/solutions/1250-check-if-it-is-a-good-array.js deleted file mode 100644 index 3c599dac..00000000 --- a/solutions/1250-check-if-it-is-a-good-array.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1250. Check If It Is a Good Array - * https://leetcode.com/problems/check-if-it-is-a-good-array/ - * Difficulty: Hard - * - * Given an array nums of positive integers. Your task is to select some subset of nums, multiply - * each element by an integer and add all these numbers. The array is said to be good if you can - * obtain a sum of 1 from the array by any possible subset and multiplicand. - * - * Return True if the array is good otherwise return False. - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var isGoodArray = function(nums) { - let gcd = nums[0]; - - for (let num of nums) { - while (num !== 0) { - const temp = gcd % num; - gcd = num; - num = temp; - } - if (gcd === 1) return true; - } - - return gcd === 1; -}; diff --git a/solutions/1253-reconstruct-a-2-row-binary-matrix.js b/solutions/1253-reconstruct-a-2-row-binary-matrix.js deleted file mode 100644 index 39bbd47b..00000000 --- a/solutions/1253-reconstruct-a-2-row-binary-matrix.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 1253. Reconstruct a 2-Row Binary Matrix - * https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/ - * Difficulty: Medium - * - * Given the following details of a matrix with n columns and 2 rows: - * - The matrix is a binary matrix, which means each element in the matrix can be 0 or 1. - * - The sum of elements of the 0-th(upper) row is given as upper. - * - The sum of elements of the 1-st(lower) row is given as lower. - * - The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an - * integer array with length n. - * - * Your task is to reconstruct the matrix with upper, lower and colsum. - * Return it as a 2-D integer array. - * If there are more than one valid solution, any of them will be accepted. - * If no valid solution exists, return an empty 2-D array. - */ - -/** - * @param {number} upper - * @param {number} lower - * @param {number[]} colsum - * @return {number[][]} - */ -var reconstructMatrix = function(upper, lower, colsum) { - const n = colsum.length; - const matrix = [[], []]; - let upperLeft = upper; - let lowerLeft = lower; - - for (let i = 0; i < n; i++) { - if (colsum[i] === 2) { - matrix[0][i] = 1; - matrix[1][i] = 1; - upperLeft--; - lowerLeft--; - } else { - matrix[0][i] = 0; - matrix[1][i] = 0; - } - } - - if (upperLeft < 0 || lowerLeft < 0) return []; - - for (let i = 0; i < n; i++) { - if (colsum[i] === 1) { - if (upperLeft > 0) { - matrix[0][i] = 1; - matrix[1][i] = 0; - upperLeft--; - } else if (lowerLeft > 0) { - matrix[0][i] = 0; - matrix[1][i] = 1; - lowerLeft--; - } else { - return []; - } - } - } - - return upperLeft === 0 && lowerLeft === 0 ? matrix : []; -}; diff --git a/solutions/1254-number-of-closed-islands.js b/solutions/1254-number-of-closed-islands.js deleted file mode 100644 index 4eb1a187..00000000 --- a/solutions/1254-number-of-closed-islands.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1254. Number of Closed Islands - * https://leetcode.com/problems/number-of-closed-islands/ - * Difficulty: Medium - * - * Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally - * connected group of 0s and a closed island is an island totally (all left, top, right, bottom) - * surrounded by 1s. - * - * Return the number of closed islands. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var closedIsland = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - - for (let i = 0; i < rows; i++) { - markBorderConnected(i, 0); - markBorderConnected(i, cols - 1); - } - for (let j = 0; j < cols; j++) { - markBorderConnected(0, j); - markBorderConnected(rows - 1, j); - } - - let result = 0; - for (let i = 1; i < rows - 1; i++) { - for (let j = 1; j < cols - 1; j++) { - result += countClosed(i, j); - } - } - - return result; - - function markBorderConnected(row, col) { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 0) return; - grid[row][col] = 1; - markBorderConnected(row - 1, col); - markBorderConnected(row + 1, col); - markBorderConnected(row, col - 1); - markBorderConnected(row, col + 1); - } - - function countClosed(row, col) { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 0) return 0; - grid[row][col] = 1; - countClosed(row - 1, col); - countClosed(row + 1, col); - countClosed(row, col - 1); - countClosed(row, col + 1); - return 1; - } -}; diff --git a/solutions/1255-maximum-score-words-formed-by-letters.js b/solutions/1255-maximum-score-words-formed-by-letters.js deleted file mode 100644 index 139532c8..00000000 --- a/solutions/1255-maximum-score-words-formed-by-letters.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1255. Maximum Score Words Formed by Letters - * https://leetcode.com/problems/maximum-score-words-formed-by-letters/ - * Difficulty: Hard - * - * Given a list of words, list of single letters (might be repeating) and score of every character. - * - * Return the maximum score of any valid set of words formed by using the given letters (words[i] - * cannot be used two or more times). - * - * It is not necessary to use all characters in letters and each letter can only be used once. - * Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] - * respectively. - */ - -/** - * @param {string[]} words - * @param {character[]} letters - * @param {number[]} score - * @return {number} - */ -var maxScoreWords = function(words, letters, score) { - const letterCount = new Array(26).fill(0); - for (const letter of letters) { - letterCount[letter.charCodeAt(0) - 97]++; - } - return calculateMaxScore(0, letterCount); - - function calculateMaxScore(index, available) { - if (index === words.length) return 0; - - const skipScore = calculateMaxScore(index + 1, available); - const word = words[index]; - const tempCount = [...available]; - let canUse = true; - let wordScore = 0; - - for (const char of word) { - const charIndex = char.charCodeAt(0) - 97; - if (tempCount[charIndex] === 0) { - canUse = false; - break; - } - tempCount[charIndex]--; - wordScore += score[charIndex]; - } - - const useScore = canUse ? wordScore + calculateMaxScore(index + 1, tempCount) : 0; - return Math.max(skipScore, useScore); - } -}; diff --git a/solutions/1260-shift-2d-grid.js b/solutions/1260-shift-2d-grid.js deleted file mode 100644 index 933dc244..00000000 --- a/solutions/1260-shift-2d-grid.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1260. Shift 2D Grid - * https://leetcode.com/problems/shift-2d-grid/ - * Difficulty: Easy - * - * Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. - * - * In one shift operation: - * - Element at grid[i][j] moves to grid[i][j + 1]. - * - Element at grid[i][n - 1] moves to grid[i + 1][0]. - * - Element at grid[m - 1][n - 1] moves to grid[0][0]. - * - * Return the 2D grid after applying shift operation k times. - */ - -/** - * @param {number[][]} grid - * @param {number} k - * @return {number[][]} - */ -var shiftGrid = function(grid, k) { - const rows = grid.length; - const cols = grid[0].length; - const total = rows * cols; - - if (k === 0 || k % total === 0) return grid; - - const effectiveShifts = k % total; - const flat = grid.flat(); - const shifted = [...flat.slice(-effectiveShifts), ...flat.slice(0, -effectiveShifts)]; - const result = []; - for (let i = 0; i < rows; i++) { - result.push(shifted.slice(i * cols, (i + 1) * cols)); - } - - return result; -}; diff --git a/solutions/1262-greatest-sum-divisible-by-three.js b/solutions/1262-greatest-sum-divisible-by-three.js deleted file mode 100644 index 5f585cb3..00000000 --- a/solutions/1262-greatest-sum-divisible-by-three.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 1262. Greatest Sum Divisible by Three - * https://leetcode.com/problems/greatest-sum-divisible-by-three/ - * Difficulty: Medium - * - * Given an integer array nums, return the maximum possible sum of elements of the array such - * that it is divisible by three. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxSumDivThree = function(nums) { - const dp = [0, -Infinity, -Infinity]; - - for (const num of nums) { - const prev = [...dp]; - for (let remainder = 0; remainder < 3; remainder++) { - dp[(remainder + num) % 3] = Math.max(dp[(remainder + num) % 3], prev[remainder] + num); - } - } - - return dp[0]; -}; diff --git a/solutions/1263-minimum-moves-to-move-a-box-to-their-target-location.js b/solutions/1263-minimum-moves-to-move-a-box-to-their-target-location.js deleted file mode 100644 index c89f0307..00000000 --- a/solutions/1263-minimum-moves-to-move-a-box-to-their-target-location.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * 1263. Minimum Moves to Move a Box to Their Target Location - * https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/ - * Difficulty: Hard - * - * A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get - * them to target locations. - * - * The game is represented by an m x n grid of characters grid where each element is a wall, floor, - * or box. - * - * Your task is to move the box 'B' to the target position 'T' under the following rules: - * - The character 'S' represents the player. The player can move up, down, left, right in grid if - * it is a floor (empty cell). - * - The character '.' represents the floor which means a free cell to walk. - * - The character '#' represents the wall which means an obstacle (impossible to walk there). - * - There is only one box 'B' and one target cell 'T' in the grid. - * - The box can be moved to an adjacent free cell by standing next to the box and then moving in - * the direction of the box. This is a push. - * - The player cannot walk through the box. - * - * Return the minimum number of pushes to move the box to the target. If there is no way to reach - * the target, return -1. - */ - -/** - * @param {character[][]} grid - * @return {number} - */ -var minPushBox = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - let player; - let box; - let target; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j] === 'S') player = [i, j]; - if (grid[i][j] === 'B') box = [i, j]; - if (grid[i][j] === 'T') target = [i, j]; - } - } - - const queue = [[...box, ...player, 0]]; - const seen = new Set([`${box}-${player}`]); - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - - function canReach(src, dst, fixedBox) { - const visited = new Set(); - const stack = [src]; - - while (stack.length) { - const [r, c] = stack.pop(); - if (r === dst[0] && c === dst[1]) return true; - if (visited.has(`${r}-${c}`)) continue; - visited.add(`${r}-${c}`); - - for (const [dr, dc] of directions) { - const nr = r + dr; - const nc = c + dc; - if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc] === '#' - || (nr === fixedBox[0] && nc === fixedBox[1])) continue; - stack.push([nr, nc]); - } - } - return false; - } - - while (queue.length) { - const [boxRow, boxCol, playerRow, playerCol, pushes] = queue.shift(); - if (boxRow === target[0] && boxCol === target[1]) return pushes; - - for (const [dr, dc] of directions) { - const newBoxRow = boxRow + dr; - const newBoxCol = boxCol + dc; - const newPlayerRow = boxRow - dr; - const newPlayerCol = boxCol - dc; - - if (newBoxRow < 0 || newBoxRow >= rows || newBoxCol < 0 || newBoxCol >= cols - || grid[newBoxRow][newBoxCol] === '#') continue; - if (!canReach([playerRow, playerCol], [newPlayerRow, newPlayerCol], [boxRow, boxCol])) { - continue; - } - - const state = `${newBoxRow}-${newBoxCol}-${newPlayerRow}-${newPlayerCol}`; - if (seen.has(state)) continue; - - seen.add(state); - queue.push([newBoxRow, newBoxCol, newPlayerRow, newPlayerCol, pushes + 1]); - } - } - - return -1; -}; diff --git a/solutions/1266-minimum-time-visiting-all-points.js b/solutions/1266-minimum-time-visiting-all-points.js deleted file mode 100644 index 97eff7f6..00000000 --- a/solutions/1266-minimum-time-visiting-all-points.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 1266. Minimum Time Visiting All Points - * https://leetcode.com/problems/minimum-time-visiting-all-points/ - * Difficulty: Easy - * - * On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the - * minimum time in seconds to visit all the points in the order given by points. - * - * You can move according to these rules: - * - In 1 second, you can either: - * - move vertically by one unit, - * - move horizontally by one unit, or - * - move diagonally sqrt(2) units (in other words, move one unit vertically then one unit - * horizontally in 1 second). - * - You have to visit the points in the same order as they appear in the array. - * - You are allowed to pass through points that appear later in the order, but these do not - * count as visits. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var minTimeToVisitAllPoints = function(points) { - return points.reduce((steps, point, i) => steps + (!points[i + 1] ? 0 : Math.max( - Math.abs(point[0] - points[i + 1][0]), Math.abs(point[1] - points[i + 1][1]) - )), 0); -}; diff --git a/solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js b/solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js deleted file mode 100644 index c3334d3e..00000000 --- a/solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1269. Number of Ways to Stay in the Same Place After Some Steps - * https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/ - * Difficulty: Hard - * - * You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position - * to the left, 1 position to the right in the array, or stay in the same place (The pointer should - * not be placed outside the array at any time). - * - * Given two integers steps and arrLen, return the number of ways such that your pointer is still - * at index 0 after exactly steps steps. Since the answer may be too large, return it modulo - * 109 + 7. - */ - -/** - * @param {number} steps - * @param {number} arrLen - * @return {number} - */ -var numWays = function(steps, arrLen) { - const MOD = 1e9 + 7; - const maxPos = Math.min(steps, arrLen - 1); - let dp = new Array(maxPos + 1).fill(0); - dp[0] = 1; - - for (let step = 1; step <= steps; step++) { - const prev = dp; - dp = new Array(maxPos + 1).fill(0); - for (let pos = 0; pos <= maxPos; pos++) { - dp[pos] = prev[pos]; - if (pos > 0) dp[pos] = (dp[pos] + prev[pos - 1]) % MOD; - if (pos < maxPos) dp[pos] = (dp[pos] + prev[pos + 1]) % MOD; - } - } - - return dp[0]; -}; diff --git a/solutions/1275-find-winner-on-a-tic-tac-toe-game.js b/solutions/1275-find-winner-on-a-tic-tac-toe-game.js deleted file mode 100644 index 6a6e3cfc..00000000 --- a/solutions/1275-find-winner-on-a-tic-tac-toe-game.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1275. Find Winner on a Tic Tac Toe Game - * https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/ - * Difficulty: Easy - * - * Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: - * - Players take turns placing characters into empty squares ' '. - * - The first player A always places 'X' characters, while the second player B always places - * 'O' characters. - * - 'X' and 'O' characters are always placed into empty squares, never on filled ones. - * - The game ends when there are three of the same (non-empty) character filling any row, - * column, or diagonal. - * - The game also ends if all squares are non-empty. - * - No more moves can be played if the game is over. - * - * Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move - * will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). - * In case the game ends in a draw return "Draw". If there are still movements to play return - * "Pending". - * - * You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is - * initially empty, and A will play first. - */ - -/** - * @param {number[][]} moves - * @return {string} - */ -var tictactoe = function(moves) { - const rows = new Array(3).fill(0); - const cols = new Array(3).fill(0); - let diagonal = 0; - let antiDiagonal = 0; - - for (let i = 0; i < moves.length; i++) { - const value = i % 2 === 0 ? 1 : -1; - const [row, col] = moves[i]; - - rows[row] += value; - cols[col] += value; - if (row === col) diagonal += value; - if (row + col === 2) antiDiagonal += value; - - if ([rows[row], cols[col], diagonal, antiDiagonal].includes(3)) return 'A'; - if ([rows[row], cols[col], diagonal, antiDiagonal].includes(-3)) return 'B'; - } - - return moves.length === 9 ? 'Draw' : 'Pending'; -}; diff --git a/solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js b/solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js deleted file mode 100644 index 8213a3d2..00000000 --- a/solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1276. Number of Burgers with No Waste of Ingredients - * https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/ - * Difficulty: Medium - * - * Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are - * as follows: - * - Jumbo Burger: 4 tomato slices and 1 cheese slice. - * - Small Burger: 2 Tomato slices and 1 cheese slice. - * - * Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and - * the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining - * tomatoSlices and cheeseSlices equal to 0 return []. - */ - -/** - * @param {number} tomatoSlices - * @param {number} cheeseSlices - * @return {number[]} - */ -var numOfBurgers = function(tomatoSlices, cheeseSlices) { - const jumbo = Math.floor((tomatoSlices - 2 * cheeseSlices) / (4 - 2)); - const small = cheeseSlices - jumbo; - - if (jumbo < 0 || small < 0 || jumbo * 4 + small * 2 !== tomatoSlices) { - return []; - } - - return [jumbo, small]; -}; diff --git a/solutions/1277-count-square-submatrices-with-all-ones.js b/solutions/1277-count-square-submatrices-with-all-ones.js deleted file mode 100644 index b6788ab9..00000000 --- a/solutions/1277-count-square-submatrices-with-all-ones.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1277. Count Square Submatrices with All Ones - * https://leetcode.com/problems/count-square-submatrices-with-all-ones/ - * Difficulty: Medium - * - * Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. - */ - -/** - * @param {number[][]} matrix - * @return {number} - */ -var countSquares = function(matrix) { - const rows = matrix.length; - const cols = matrix[0].length; - const dp = Array.from({ length: rows }, () => new Array(cols).fill(0)); - let result = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (matrix[i][j] === 1) { - if (i === 0 || j === 0) { - dp[i][j] = 1; - } else { - dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1; - } - result += dp[i][j]; - } - } - } - - return result; -}; diff --git a/solutions/1278-palindrome-partitioning-iii.js b/solutions/1278-palindrome-partitioning-iii.js deleted file mode 100644 index 500e77db..00000000 --- a/solutions/1278-palindrome-partitioning-iii.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1278. Palindrome Partitioning III - * https://leetcode.com/problems/palindrome-partitioning-iii/ - * Difficulty: Hard - * - * You are given a string s containing lowercase letters and an integer k. You need to: - * - First, change some characters of s to other lowercase English letters. - * - Then divide s into k non-empty disjoint substrings such that each substring is a palindrome. - * - * Return the minimal number of characters that you need to change to divide the string. - */ - -/** - * @param {string} s - * @param {number} k - * @return {number} - */ -var palindromePartition = function(s, k) { - const n = s.length; - const cost = Array.from({ length: n }, () => new Array(n).fill(0)); - - for (let len = 2; len <= n; len++) { - for (let i = 0; i + len <= n; i++) { - const j = i + len - 1; - cost[i][j] = cost[i + 1][j - 1] + (s[i] === s[j] ? 0 : 1); - } - } - - const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(Infinity)); - dp[0][0] = 0; - - for (let i = 1; i <= n; i++) { - for (let j = 1; j <= Math.min(i, k); j++) { - for (let m = 0; m < i; m++) { - dp[i][j] = Math.min(dp[i][j], dp[m][j - 1] + cost[m][i - 1]); - } - } - } - - return dp[n][k]; -}; diff --git a/solutions/1281-subtract-the-product-and-sum-of-digits-of-an-integer.js b/solutions/1281-subtract-the-product-and-sum-of-digits-of-an-integer.js deleted file mode 100644 index 8854b93f..00000000 --- a/solutions/1281-subtract-the-product-and-sum-of-digits-of-an-integer.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1281. Subtract the Product and Sum of Digits of an Integer - * https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ - * Difficulty: Easy - * - * Given an integer number n, return the difference between the product of its digits and - * the sum of its digits. - */ - -/** - * @param {number} n - * @return {number} - */ -var subtractProductAndSum = function(n) { - let product = 1; - let sum = 0; - - while (n > 0) { - const digit = n % 10; - product *= digit; - sum += digit; - n = Math.floor(n / 10); - } - - return product - sum; -}; diff --git a/solutions/1282-group-the-people-given-the-group-size-they-belong-to.js b/solutions/1282-group-the-people-given-the-group-size-they-belong-to.js deleted file mode 100644 index 72a55368..00000000 --- a/solutions/1282-group-the-people-given-the-group-size-they-belong-to.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1282. Group the People Given the Group Size They Belong To - * https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/ - * Difficulty: Medium - * - * There are n people that are split into some unknown number of groups. Each person is labeled - * with a unique ID from 0 to n - 1. - * - * You are given an integer array groupSizes, where groupSizes[i] is the size of the group that - * person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3. - * - * Return a list of groups such that each person i is in a group of size groupSizes[i]. - * - * Each person should appear in exactly one group, and every person must be in a group. If there - * are multiple answers, return any of them. It is guaranteed that there will be at least one - * valid solution for the given input. - */ - -/** - * @param {number[]} groupSizes - * @return {number[][]} - */ -var groupThePeople = function(groupSizes) { - const map = new Map(); - const grouped = []; - - for (let i = 0; i < groupSizes.length; i++) { - const size = groupSizes[i]; - - map.set(size, map.has(size) ? [...map.get(size), i] : [i]); - - if (map.get(size).length === size) { - grouped.push(map.get(size)); - map.delete(size); - } - } - - return grouped; -}; diff --git a/solutions/1283-find-the-smallest-divisor-given-a-threshold.js b/solutions/1283-find-the-smallest-divisor-given-a-threshold.js deleted file mode 100644 index 12eb3776..00000000 --- a/solutions/1283-find-the-smallest-divisor-given-a-threshold.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1283. Find the Smallest Divisor Given a Threshold - * https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/ - * Difficulty: Medium - * - * Given an array of integers nums and an integer threshold, we will choose a positive integer - * divisor, divide all the array by it, and sum the division's result. Find the smallest divisor - * such that the result mentioned above is less than or equal to threshold. - * - * Each result of the division is rounded to the nearest integer greater than or equal to that - * element. (For example: 7/3 = 3 and 10/2 = 5). - * - * The test cases are generated so that there will be an answer. - */ - -/** - * @param {number[]} nums - * @param {number} threshold - * @return {number} - */ -var smallestDivisor = function(nums, threshold) { - let left = 1; - let right = Math.max(...nums); - - while (left < right) { - const mid = Math.floor((left + right) / 2); - const sum = nums.reduce((acc, num) => acc + Math.ceil(num / mid), 0); - - if (sum <= threshold) { - right = mid; - } else { - left = mid + 1; - } - } - - return left; -}; diff --git a/solutions/1284-minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.js b/solutions/1284-minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.js deleted file mode 100644 index dda02d8e..00000000 --- a/solutions/1284-minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix - * https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/ - * Difficulty: Hard - * - * Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the - * four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are - * called neighbors if they share one edge. - * - * Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. - * - * A binary matrix is a matrix with all cells equal to 0 or 1 only. - * - * A zero matrix is a matrix with all cells equal to 0. - */ - -/** - * @param {number[][]} mat - * @return {number} - */ -var minFlips = function(mat) { - const rows = mat.length; - const cols = mat[0].length; - const target = 0; - const start = mat.flat().reduce((acc, val, idx) => acc | (val << idx), 0); - const queue = [[start, 0]]; - const seen = new Set([start]); - const directions = [[0, 0], [0, 1], [0, -1], [1, 0], [-1, 0]]; - - while (queue.length) { - const [state, steps] = queue.shift(); - - if (state === target) return steps; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - let nextState = state; - for (const [di, dj] of directions) { - const ni = i + di; - const nj = j + dj; - if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { - const pos = ni * cols + nj; - nextState ^= (1 << pos); - } - } - if (!seen.has(nextState)) { - seen.add(nextState); - queue.push([nextState, steps + 1]); - } - } - } - } - - return -1; -}; diff --git a/solutions/1286-iterator-for-combination.js b/solutions/1286-iterator-for-combination.js deleted file mode 100644 index 2c55b90e..00000000 --- a/solutions/1286-iterator-for-combination.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1286. Iterator for Combination - * https://leetcode.com/problems/iterator-for-combination/ - * Difficulty: Medium - * - * Design the CombinationIterator class: - * - CombinationIterator(string characters, int combinationLength) Initializes the object with a - * string characters of sorted distinct lowercase English letters and a number combinationLength - * as arguments. - * - next() Returns the next combination of length combinationLength in lexicographical order. - * - hasNext() Returns true if and only if there exists a next combination. - */ - -/** - * @param {string} characters - * @param {number} combinationLength - */ -var CombinationIterator = function(characters, combinationLength) { - this.chars = characters; - this.length = combinationLength; - this.indices = new Array(combinationLength).fill(0).map((_, i) => i); - this.hasMore = true; -}; - -/** - * @return {string} - */ -CombinationIterator.prototype.next = function() { - const result = this.indices.map(i => this.chars[i]).join(''); - - this.hasMore = false; - for (let i = this.length - 1; i >= 0; i--) { - if (this.indices[i] < this.chars.length - (this.length - i)) { - this.indices[i]++; - for (let j = i + 1; j < this.length; j++) { - this.indices[j] = this.indices[j - 1] + 1; - } - this.hasMore = true; - break; - } - } - - return result; -}; - -/** - * @return {boolean} - */ -CombinationIterator.prototype.hasNext = function() { - return this.hasMore; -}; diff --git a/solutions/1288-remove-covered-intervals.js b/solutions/1288-remove-covered-intervals.js deleted file mode 100644 index 7c7713fa..00000000 --- a/solutions/1288-remove-covered-intervals.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1288. Remove Covered Intervals - * https://leetcode.com/problems/remove-covered-intervals/ - * Difficulty: Medium - * - * Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove - * all intervals that are covered by another interval in the list. - * - * The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d. - * - * Return the number of remaining intervals. - */ - -/** - * @param {number[][]} intervals - * @return {number} - */ -var removeCoveredIntervals = function(intervals) { - intervals.sort((a, b) => a[0] - b[0] || b[1] - a[1]); - - let result = 1; - let currentEnd = intervals[0][1]; - - for (let i = 1; i < intervals.length; i++) { - if (intervals[i][1] > currentEnd) { - result++; - currentEnd = intervals[i][1]; - } - } - - return result; -}; diff --git a/solutions/1289-minimum-falling-path-sum-ii.js b/solutions/1289-minimum-falling-path-sum-ii.js deleted file mode 100644 index 39cc6f24..00000000 --- a/solutions/1289-minimum-falling-path-sum-ii.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1289. Minimum Falling Path Sum II - * https://leetcode.com/problems/minimum-falling-path-sum-ii/ - * Difficulty: Hard - * - * Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero - * shifts. - * - * A falling path with non-zero shifts is a choice of exactly one element from each row of grid - * such that no two elements chosen in adjacent rows are in the same column. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var minFallingPathSum = function(grid) { - const n = grid.length; - let prevRow = [...grid[0]]; - - for (let row = 1; row < n; row++) { - const currRow = new Array(n); - for (let col = 0; col < n; col++) { - let minPrev = Infinity; - for (let prevCol = 0; prevCol < n; prevCol++) { - if (prevCol !== col) { - minPrev = Math.min(minPrev, prevRow[prevCol]); - } - } - currRow[col] = grid[row][col] + minPrev; - } - prevRow = currRow; - } - - return Math.min(...prevRow); -}; diff --git a/solutions/1293-shortest-path-in-a-grid-with-obstacles-elimination.js b/solutions/1293-shortest-path-in-a-grid-with-obstacles-elimination.js deleted file mode 100644 index b143e638..00000000 --- a/solutions/1293-shortest-path-in-a-grid-with-obstacles-elimination.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1293. Shortest Path in a Grid with Obstacles Elimination - * https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ - * Difficulty: Hard - * - * You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). - * You can move up, down, left, or right from and to an empty cell in one step. - * - * Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right - * corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to - * find such walk return -1. - */ - -function shortestPath(grid, k) { - const rows = grid.length; - const cols = grid[0].length; - if (rows === 1 && cols === 1) return 0; - - let steps = 1; - let queue = [[0, 0, k]]; - const visited = Array.from({ length: rows }, () => new Int16Array(cols).fill(-1)); - const directions = [0, -1, 0, 1, 0]; - - while (queue.length) { - const nextLevel = []; - for (const [row, col, obstaclesLeft] of queue) { - for (let i = 0; i < 4; i++) { - const newRow = row + directions[i]; - const newCol = col + directions[i + 1]; - - if (newRow < 0 || newRow === rows || newCol < 0 - || newCol === cols || visited[newRow][newCol] >= obstaclesLeft) continue; - - if (newRow === rows - 1 && newCol === cols - 1) return steps; - - const remainingObstacles = grid[newRow][newCol] ? obstaclesLeft - 1 : obstaclesLeft; - visited[newRow][newCol] = remainingObstacles; - nextLevel.push([newRow, newCol, remainingObstacles]); - } - } - steps++; - queue = nextLevel; - } - - return -1; -} diff --git a/solutions/1298-maximum-candies-you-can-get-from-boxes.js b/solutions/1298-maximum-candies-you-can-get-from-boxes.js deleted file mode 100644 index f273d470..00000000 --- a/solutions/1298-maximum-candies-you-can-get-from-boxes.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1298. Maximum Candies You Can Get from Boxes - * https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/ - * Difficulty: Hard - * - * You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and - * containedBoxes where: - * - status[i] is 1 if the ith box is open and 0 if the ith box is closed, - * - candies[i] is the number of candies in the ith box, - * - keys[i] is a list of the labels of the boxes you can open after opening the ith box. - * - containedBoxes[i] is a list of the boxes you found inside the ith box. - * - * You are given an integer array initialBoxes that contains the labels of the boxes you initially - * have. You can take all the candies in any open box and you can use the keys in it to open new - * boxes and you also can use the boxes you find in it. - * - * Return the maximum number of candies you can get following the rules above. - */ - -/** - * @param {number[]} status - * @param {number[]} candies - * @param {number[][]} keys - * @param {number[][]} containedBoxes - * @param {number[]} initialBoxes - * @return {number} - */ -var maxCandies = function(status, candies, keys, containedBoxes, initialBoxes) { - let totalCandies = 0; - const queue = [...initialBoxes]; - const availableKeys = new Set(); - const unopenedBoxes = new Set(); - - while (queue.length) { - const currentBox = queue.shift(); - - if (status[currentBox]) { - totalCandies += candies[currentBox]; - for (const key of keys[currentBox]) availableKeys.add(key); - for (const box of containedBoxes[currentBox]) queue.push(box); - } else { - unopenedBoxes.add(currentBox); - } - - for (const box of unopenedBoxes) { - if (availableKeys.has(box)) { - status[box] = 1; - unopenedBoxes.delete(box); - queue.push(box); - } - } - } - - return totalCandies; -}; diff --git a/solutions/1299-replace-elements-with-greatest-element-on-right-side.js b/solutions/1299-replace-elements-with-greatest-element-on-right-side.js deleted file mode 100644 index 50724b06..00000000 --- a/solutions/1299-replace-elements-with-greatest-element-on-right-side.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1299. Replace Elements with Greatest Element on Right Side - * https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ - * Difficulty: Easy - * - * Given an array arr, replace every element in that array with the greatest element among the - * elements to its right, and replace the last element with -1. - * - * After doing so, return the array. - */ - -/** - * @param {number[]} arr - * @return {number[]} - */ -var replaceElements = function(arr) { - let maxRight = -1; - for (let i = arr.length - 1; i >= 0; i--) { - const current = arr[i]; - arr[i] = maxRight; - maxRight = Math.max(maxRight, current); - } - return arr; -}; diff --git a/solutions/1300-sum-of-mutated-array-closest-to-target.js b/solutions/1300-sum-of-mutated-array-closest-to-target.js deleted file mode 100644 index e8e874fa..00000000 --- a/solutions/1300-sum-of-mutated-array-closest-to-target.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1300. Sum of Mutated Array Closest to Target - * https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/ - * Difficulty: Medium - * - * Given an integer array arr and a target value target, return the integer value such that when - * we change all the integers larger than value in the given array to be equal to value, the - * sum of the array gets as close as possible (in absolute difference) to target. - * - * In case of a tie, return the minimum such integer. - * - * Notice that the answer is not neccesarilly a number from arr. - */ - -/** - * @param {number[]} arr - * @param {number} target - * @return {number} - */ -var findBestValue = function(arr, target) { - arr.sort((a, b) => a - b); - let prefixSum = 0; - const length = arr.length; - - for (let i = 0; i < length; i++) { - const remaining = length - i; - const avg = (target - prefixSum) / remaining; - - if (avg <= arr[i]) { - const floorVal = Math.floor(avg); - const ceilVal = Math.ceil(avg); - const floorSum = prefixSum + floorVal * remaining; - const ceilSum = prefixSum + ceilVal * remaining; - - return Math.abs(floorSum - target) <= Math.abs(ceilSum - target) ? floorVal : ceilVal; - } - - prefixSum += arr[i]; - } - - return arr[length - 1]; -}; diff --git a/solutions/1301-number-of-paths-with-max-score.js b/solutions/1301-number-of-paths-with-max-score.js deleted file mode 100644 index ba34699c..00000000 --- a/solutions/1301-number-of-paths-with-max-score.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1301. Number of Paths with Max Score - * https://leetcode.com/problems/number-of-paths-with-max-score/ - * Difficulty: Hard - * - * You are given a square board of characters. You can move on the board starting at the bottom - * right square marked with the character 'S'. - * - * You need to reach the top left square marked with the character 'E'. The rest of the squares - * are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move - * you can go up, left or up-left (diagonally) only if there is no obstacle there. - * - * Return a list of two integers: the first integer is the maximum sum of numeric characters you - * can collect, and the second is the number of such paths that you can take to get that maximum - * sum, taken modulo 10^9 + 7. - * - * In case there is no path, return [0, 0]. - */ - -/** - * @param {string[]} board - * @return {number[]} - */ -var pathsWithMaxScore = function(board) { - const n = board.length; - const mod = 1000000007; - const dp = Array.from({ length: n }, () => - new Array(n).fill([-Infinity, 0]) - ); - - dp[n-1][n-1] = [0, 1]; - - for (let row = n-1; row >= 0; row--) { - for (let col = n-1; col >= 0; col--) { - if (board[row][col] === 'X') { - dp[row][col] = [-Infinity, 0]; - continue; - } - - if (row === n-1 && col === n-1) continue; - - const value = board[row][col] === 'E' ? 0 : Number(board[row][col]); - const directions = [[0, 1], [1, 0], [1, 1]]; - - for (const [dr, dc] of directions) { - const nextRow = row + dr; - const nextCol = col + dc; - - if (nextRow >= n || nextCol >= n) continue; - if (dp[nextRow][nextCol][1] === 0) continue; - - const score = dp[nextRow][nextCol][0] + value; - if (score > dp[row][col][0]) { - dp[row][col] = [score, dp[nextRow][nextCol][1]]; - } else if (score === dp[row][col][0]) { - dp[row][col][1] = (dp[row][col][1] + dp[nextRow][nextCol][1]) % mod; - } - } - } - } - - return dp[0][0][1] === 0 ? [0, 0] : dp[0][0]; -}; diff --git a/solutions/1302-deepest-leaves-sum.js b/solutions/1302-deepest-leaves-sum.js deleted file mode 100644 index 6d1b25d4..00000000 --- a/solutions/1302-deepest-leaves-sum.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1302. Deepest Leaves Sum - * https://leetcode.com/problems/deepest-leaves-sum/ - * Difficulty: Medium - * - * Given the root of a binary tree, return the sum of values of its deepest leaves. - */ - -/** - * 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 deepestLeavesSum = function(root) { - let maxDepth = 0; - let sumAtMaxDepth = 0; - - function traverse(node, depth) { - if (!node) return; - - if (depth > maxDepth) { - maxDepth = depth; - sumAtMaxDepth = node.val; - } else if (depth === maxDepth) { - sumAtMaxDepth += node.val; - } - - traverse(node.left, depth + 1); - traverse(node.right, depth + 1); - } - - traverse(root, 0); - return sumAtMaxDepth; -}; diff --git a/solutions/1305-all-elements-in-two-binary-search-trees.js b/solutions/1305-all-elements-in-two-binary-search-trees.js deleted file mode 100644 index d8307731..00000000 --- a/solutions/1305-all-elements-in-two-binary-search-trees.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1305. All Elements in Two Binary Search Trees - * https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ - * Difficulty: Medium - * - * Given two binary search trees root1 and root2, return a list containing all the integers from - * both trees sorted in ascending 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} root1 - * @param {TreeNode} root2 - * @return {number[]} - */ -var getAllElements = function(root1, root2) { - const values = []; - - inorder(root1); - inorder(root2); - - return values.sort((a, b) => a - b); - - function inorder(node) { - if (!node) return; - inorder(node.left); - values.push(node.val); - inorder(node.right); - } -}; diff --git a/solutions/1306-jump-game-iii.js b/solutions/1306-jump-game-iii.js deleted file mode 100644 index 46cd7fdf..00000000 --- a/solutions/1306-jump-game-iii.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1306. Jump Game III - * https://leetcode.com/problems/jump-game-iii/ - * Difficulty: Medium - * - * Given an array of non-negative integers arr, you are initially positioned at start index of - * the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you - * can reach any index with value 0. - * - * Notice that you can not jump outside of the array at any time. - */ - -/** - * @param {number[]} arr - * @param {number} start - * @return {boolean} - */ -var canReach = function(arr, start) { - const visited = new Set(); - const queue = [start]; - - while (queue.length) { - const current = queue.shift(); - - if (arr[current] === 0) return true; - if (visited.has(current)) continue; - - visited.add(current); - - const jump = arr[current]; - const nextRight = current + jump; - const nextLeft = current - jump; - - if (nextRight < arr.length) queue.push(nextRight); - if (nextLeft >= 0) queue.push(nextLeft); - } - - return false; -}; diff --git a/solutions/1307-verbal-arithmetic-puzzle.js b/solutions/1307-verbal-arithmetic-puzzle.js deleted file mode 100644 index 71b379ea..00000000 --- a/solutions/1307-verbal-arithmetic-puzzle.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 1307. Verbal Arithmetic Puzzle - * https://leetcode.com/problems/verbal-arithmetic-puzzle/ - * Difficulty: Hard - * - * Given an equation, represented by words on the left side and the result on the right side. - * - * You need to check if the equation is solvable under the following rules: - * - Each character is decoded as one digit (0 - 9). - * - No two characters can map to the same digit. - * - Each words[i] and result are decoded as one number without leading zeros. - * - Sum of numbers on the left side (words) will equal to the number on the right side (result). - * - * Return true if the equation is solvable, otherwise return false. - */ - -/** - * @param {string[]} words - * @param {string} result - * @return {boolean} - */ -var isSolvable = function(words, result) { - const charToDigit = new Map(); - const usedDigits = new Set(); - const leadingChars = new Set(); - - if (words.some(word => word.length > result.length)) return false; - - words.forEach(word => { - if (word.length > 1) leadingChars.add(word[0]); - }); - if (result.length > 1) leadingChars.add(result[0]); - - return solve(0, 0, 0); - - function solve(pos, wordIdx, carry) { - if (pos >= result.length) return carry === 0; - - if (wordIdx <= words.length - 1) { - const word = words[wordIdx]; - if (pos >= word.length) return solve(pos, wordIdx + 1, carry); - - const char = word[word.length - 1 - pos]; - if (charToDigit.has(char)) return solve(pos, wordIdx + 1, carry + charToDigit.get(char)); - - for (let digit = leadingChars.has(char) ? 1 : 0; digit <= 9; digit++) { - if (usedDigits.has(digit)) continue; - usedDigits.add(digit); - charToDigit.set(char, digit); - if (solve(pos, wordIdx + 1, carry + digit)) return true; - usedDigits.delete(digit); - charToDigit.delete(char); - } - return false; - } - - const sumDigit = carry % 10; - const resultChar = result[result.length - 1 - pos]; - - if (!charToDigit.has(resultChar)) { - if (usedDigits.has(sumDigit) || (pos === result.length - 1 && sumDigit === 0)) return false; - charToDigit.set(resultChar, sumDigit); - usedDigits.add(sumDigit); - const success = solve(pos + 1, 0, (carry - sumDigit) / 10); - charToDigit.delete(resultChar); - usedDigits.delete(sumDigit); - return success; - } - - return charToDigit.get(resultChar) === sumDigit && solve(pos + 1, 0, (carry - sumDigit) / 10); - } -}; diff --git a/solutions/1310-xor-queries-of-a-subarray.js b/solutions/1310-xor-queries-of-a-subarray.js deleted file mode 100644 index 9a61c298..00000000 --- a/solutions/1310-xor-queries-of-a-subarray.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1310. XOR Queries of a Subarray - * https://leetcode.com/problems/xor-queries-of-a-subarray/ - * Difficulty: Medium - * - * You are given an array arr of positive integers. You are also given the array queries where - * queries[i] = [lefti, righti]. - * - * For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR - * arr[lefti + 1] XOR ... XOR arr[righti]). - * - * Return an array answer where answer[i] is the answer to the ith query. - */ - -/** - * @param {number[]} arr - * @param {number[][]} queries - * @return {number[]} - */ -var xorQueries = function(arr, queries) { - const options = [0]; - arr.forEach((num, i) => options.push(options[i] ^ num)); - return queries.map(([left, right]) => options[right + 1] ^ options[left]); -}; diff --git a/solutions/1311-get-watched-videos-by-your-friends.js b/solutions/1311-get-watched-videos-by-your-friends.js deleted file mode 100644 index 5c7d5daf..00000000 --- a/solutions/1311-get-watched-videos-by-your-friends.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1311. Get Watched Videos by Your Friends - * https://leetcode.com/problems/get-watched-videos-by-your-friends/ - * Difficulty: Medium - * - * There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos - * and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the - * list of friends respectively for the person with id = i. - * - * Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched - * videos by the friends of your friends and so on. In general, the level k of videos are all - * watched videos by people with the shortest path exactly equal to k with you. Given your id - * and the level of videos, return the list of videos ordered by their frequencies (increasing). - * For videos with the same frequency order them alphabetically from least to greatest. - */ - -/** - * @param {string[][]} watchedVideos - * @param {number[][]} friends - * @param {number} id - * @param {number} level - * @return {string[]} - */ -var watchedVideosByFriends = function(watchedVideos, friends, id, level) { - const visited = new Set([id]); - let queue = [id]; - let currentLevel = 0; - - while (queue.length && currentLevel < level) { - const nextQueue = []; - queue.forEach(person => friends[person].forEach(friend => { - if (!visited.has(friend)) { - visited.add(friend); - nextQueue.push(friend); - } - })); - queue = nextQueue; - currentLevel++; - } - - const videoFrequency = new Map(); - queue.forEach(person => watchedVideos[person].forEach(video => { - return videoFrequency.set(video, (videoFrequency.get(video) || 0) + 1); - })); - - return [...videoFrequency.entries()] - .sort((a, b) => a[1] === b[1] ? a[0].localeCompare(b[0]) : a[1] - b[1]) - .map(([video]) => video); -}; diff --git a/solutions/1312-minimum-insertion-steps-to-make-a-string-palindrome.js b/solutions/1312-minimum-insertion-steps-to-make-a-string-palindrome.js deleted file mode 100644 index fd3d03fc..00000000 --- a/solutions/1312-minimum-insertion-steps-to-make-a-string-palindrome.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1312. Minimum Insertion Steps to Make a String Palindrome - * https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ - * Difficulty: Hard - * - * Given a string s. In one step you can insert any character at any index of the string. - * - * Return the minimum number of steps to make s palindrome. - * - * A Palindrome String is one that reads the same backward as well as forward. - */ - -/** - * @param {string} s - * @return {number} - */ -var minInsertions = function(s) { - const n = s.length; - const dp = new Array(n).fill().map(() => new Array(n).fill(0)); - - for (let len = 2; len <= n; len++) { - for (let start = 0; start + len <= n; start++) { - const end = start + len - 1; - dp[start][end] = s[start] === s[end] - ? dp[start + 1][end - 1] - : Math.min(dp[start + 1][end], dp[start][end - 1]) + 1; - } - } - - return dp[0][n - 1]; -}; diff --git a/solutions/1314-matrix-block-sum.js b/solutions/1314-matrix-block-sum.js deleted file mode 100644 index 03431961..00000000 --- a/solutions/1314-matrix-block-sum.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1314. Matrix Block Sum - * https://leetcode.com/problems/matrix-block-sum/ - * Difficulty: Medium - * - * Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] - * is the sum of all elements mat[r][c] for: - * - i - k <= r <= i + k, - * - j - k <= c <= j + k, and - * - (r, c) is a valid position in the matrix. - */ - -/** - * @param {number[][]} mat - * @param {number} k - * @return {number[][]} - */ -var matrixBlockSum = function(mat, k) { - const rows = mat.length; - const cols = mat[0].length; - const prefixSums = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0)); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - prefixSums[i + 1][j + 1] = prefixSums[i + 1][j] - + prefixSums[i][j + 1] - prefixSums[i][j] + mat[i][j]; - } - } - - const result = new Array(rows).fill().map(() => new Array(cols).fill(0)); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const top = Math.max(0, i - k); - const bottom = Math.min(rows - 1, i + k); - const left = Math.max(0, j - k); - const right = Math.min(cols - 1, j + k); - - result[i][j] = prefixSums[bottom + 1][right + 1] - - prefixSums[bottom + 1][left] - prefixSums[top][right + 1] + prefixSums[top][left]; - } - } - - return result; -}; diff --git a/solutions/1315-sum-of-nodes-with-even-valued-grandparent.js b/solutions/1315-sum-of-nodes-with-even-valued-grandparent.js deleted file mode 100644 index 3c7c4563..00000000 --- a/solutions/1315-sum-of-nodes-with-even-valued-grandparent.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1315. Sum of Nodes with Even-Valued Grandparent - * https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/ - * Difficulty: Medium - * - * Given the root of a binary tree, return the sum of values of nodes with an even-valued - * grandparent. If there are no nodes with an even-valued grandparent, return 0. - * - * A grandparent of a node is the parent of its parent if it exists. - */ - -/** - * 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 sumEvenGrandparent = function(root) { - let result = 0; - exploreTree(root, null, null); - return result; - - function exploreTree(current, parent, grandparent) { - if (!current) return; - - if (grandparent?.val % 2 === 0) { - result += current.val; - } - - exploreTree(current.left, current, parent); - exploreTree(current.right, current, parent); - } -}; diff --git a/solutions/1316-distinct-echo-substrings.js b/solutions/1316-distinct-echo-substrings.js deleted file mode 100644 index acdd22fe..00000000 --- a/solutions/1316-distinct-echo-substrings.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1316. Distinct Echo Substrings - * https://leetcode.com/problems/distinct-echo-substrings/ - * Difficulty: Hard - * - * Return the number of distinct non-empty substrings of text that can be written as the - * concatenation of some string with itself (i.e. it can be written as a + a where a is - * some string). - */ - -/** - * @param {string} text - * @return {number} - */ -var distinctEchoSubstrings = function(text) { - const set = new Set(); - - for (let size = 1; size <= text.length / 2; size++) { - let count = 0; - - for (let left = 0, right = size; right < text.length; left++, right++) { - if (text[left] === text[right]) { - count++; - } else { - count = 0; - } - - if (count === size) { - set.add(text.slice(left - size + 1, right + 1)); - count--; - } - } - } - - return set.size; -}; diff --git a/solutions/1320-minimum-distance-to-type-a-word-using-two-fingers.js b/solutions/1320-minimum-distance-to-type-a-word-using-two-fingers.js deleted file mode 100644 index 9ec26ff9..00000000 --- a/solutions/1320-minimum-distance-to-type-a-word-using-two-fingers.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 1320. Minimum Distance to Type a Word Using Two Fingers - * https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/ - * Difficulty: Hard - * - * You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter - * is located at some coordinate. - * - * For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at - * coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located - * at coordinate (4, 1). - * - * Given the string word, return the minimum total distance to type such string using only two - * fingers. - * - * The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. - * - * Note that the initial positions of your two fingers are considered free so do not count towards - * your total distance, also your two fingers do not have to start at the first letter or the first - * two letters. - */ - -/** - * @param {string} word - * @return {number} - */ -var minimumDistance = function(word) { - const memo = {}; - return dp(0, null, null); - - function dp(index, finger1, finger2) { - if (index === word.length) return 0; - - const key = `${index},${finger1},${finger2}`; - if (memo[key] !== undefined) return memo[key]; - - const nextChar = word[index]; - const moveFinger1 = distance(finger1, nextChar) + dp(index + 1, nextChar, finger2); - const moveFinger2 = distance(finger2, nextChar) + dp(index + 1, finger1, nextChar); - - memo[key] = Math.min(moveFinger1, moveFinger2); - return memo[key]; - } - - function getPosition(char) { - const code = char.charCodeAt(0) - 65; - return [Math.floor(code / 6), code % 6]; - } - - function distance(from, to) { - if (from === null) return 0; - const [x1, y1] = getPosition(from); - const [x2, y2] = getPosition(to); - return Math.abs(x1 - x2) + Math.abs(y1 - y2); - } -}; diff --git a/solutions/1325-delete-leaves-with-a-given-value.js b/solutions/1325-delete-leaves-with-a-given-value.js deleted file mode 100644 index d4a69f8f..00000000 --- a/solutions/1325-delete-leaves-with-a-given-value.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1325. Delete Leaves With a Given Value - * https://leetcode.com/problems/delete-leaves-with-a-given-value/ - * Difficulty: Medium - * - * Given a binary tree root and an integer target, delete all the leaf nodes with value target. - * - * Note that once you delete a leaf node with value target, if its parent node becomes a leaf - * node and has the value target, it should also be deleted (you need to continue doing that - * until you cannot). - */ - -/** - * 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} target - * @return {TreeNode} - */ -var removeLeafNodes = function(root, target) { - return pruneLeaves(root); - - function pruneLeaves(node) { - if (!node) return null; - - node.left = pruneLeaves(node.left); - node.right = pruneLeaves(node.right); - - if (!node.left && !node.right && node.val === target) { - return null; - } - - return node; - } -}; diff --git a/solutions/1326-minimum-number-of-taps-to-open-to-water-a-garden.js b/solutions/1326-minimum-number-of-taps-to-open-to-water-a-garden.js deleted file mode 100644 index 437a9a12..00000000 --- a/solutions/1326-minimum-number-of-taps-to-open-to-water-a-garden.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1326. Minimum Number of Taps to Open to Water a Garden - * https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/ - * Difficulty: Hard - * - * There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at - * the point n. (i.e., the length of the garden is n). - * - * There are n + 1 taps located at points [0, 1, ..., n] in the garden. - * - * Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means - * the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. - * - * Return the minimum number of taps that should be open to water the whole garden, If the garden - * cannot be watered return -1. - */ - -/** - * @param {number} n - * @param {number[]} ranges - * @return {number} - */ -var minTaps = function(n, ranges) { - const intervals = ranges.map((range, index) => [ - Math.max(0, index - range), - Math.min(n, index + range) - ]); - - intervals.sort((a, b) => a[0] - b[0] || b[1] - a[1]); - - let taps = 0; - let currentEnd = 0; - let nextEnd = 0; - let i = 0; - - while (i < intervals.length && currentEnd < n) { - taps++; - - while (i < intervals.length && intervals[i][0] <= currentEnd) { - nextEnd = Math.max(nextEnd, intervals[i][1]); - i++; - } - - if (currentEnd === nextEnd) return -1; - currentEnd = nextEnd; - } - - return currentEnd >= n ? taps : -1; -}; diff --git a/solutions/1328-break-a-palindrome.js b/solutions/1328-break-a-palindrome.js deleted file mode 100644 index 166d40c1..00000000 --- a/solutions/1328-break-a-palindrome.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1328. Break a Palindrome - * https://leetcode.com/problems/break-a-palindrome/ - * Difficulty: Medium - * - * Given a palindromic string of lowercase English letters palindrome, replace exactly one - * character with any lowercase English letter so that the resulting string is not a palindrome - * and that it is the lexicographically smallest one possible. - * - * Return the resulting string. If there is no way to replace a character to make it not a - * palindrome, return an empty string. - * - * A string a is lexicographically smaller than a string b (of the same length) if in the first - * position where a and b differ, a has a character strictly smaller than the corresponding - * character in b. For example, "abcc" is lexicographically smaller than "abcd" because the - * first position they differ is at the fourth character, and 'c' is smaller than 'd'. - */ - -/** - * @param {string} palindrome - * @return {string} - */ -var breakPalindrome = function(palindrome) { - if (palindrome.length === 1) return ''; - - const chars = palindrome.split(''); - - for (let i = 0; i < Math.floor(chars.length / 2); i++) { - if (chars[i] !== 'a') { - chars[i] = 'a'; - return chars.join(''); - } - } - - chars[chars.length - 1] = 'b'; - return chars.join(''); -}; diff --git a/solutions/1329-sort-the-matrix-diagonally.js b/solutions/1329-sort-the-matrix-diagonally.js deleted file mode 100644 index ff9694fd..00000000 --- a/solutions/1329-sort-the-matrix-diagonally.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1329. Sort the Matrix Diagonally - * https://leetcode.com/problems/sort-the-matrix-diagonally/ - * Difficulty: Medium - * - * A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost - * row or leftmost column and going in the bottom-right direction until reaching the matrix's - * end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, - * includes cells mat[2][0], mat[3][1], and mat[4][2]. - * - * Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return - * the resulting matrix. - */ - -/** - * @param {number[][]} mat - * @return {number[][]} - */ -var diagonalSort = function(mat) { - const rows = mat.length; - const cols = mat[0].length; - const diagonals = new Map(); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const diagonalKey = i - j; - if (!diagonals.has(diagonalKey)) { - diagonals.set(diagonalKey, []); - } - diagonals.get(diagonalKey).push(mat[i][j]); - } - } - - diagonals.forEach(values => values.sort((a, b) => a - b)); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const diagonalKey = i - j; - mat[i][j] = diagonals.get(diagonalKey).shift(); - } - } - - return mat; -}; diff --git a/solutions/1330-reverse-subarray-to-maximize-array-value.js b/solutions/1330-reverse-subarray-to-maximize-array-value.js deleted file mode 100644 index 6050cecd..00000000 --- a/solutions/1330-reverse-subarray-to-maximize-array-value.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1330. Reverse Subarray To Maximize Array Value - * https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/ - * Difficulty: Hard - * - * You are given an integer array nums. The value of this array is defined as the sum - * of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. - * - * You are allowed to select any subarray of the given array and reverse it. You can - * perform this operation only once. - * - * Find maximum possible value of the final array. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxValueAfterReverse = function(nums) { - let baseSum = 0; - let maxGain = 0; - let minPair = Infinity; - let maxPair = -Infinity; - const n = nums.length; - - for (let i = 0; i < n - 1; i++) { - baseSum += Math.abs(nums[i] - nums[i + 1]); - minPair = Math.min(minPair, Math.max(nums[i], nums[i + 1])); - maxPair = Math.max(maxPair, Math.min(nums[i], nums[i + 1])); - } - - maxGain = Math.max(0, 2 * (maxPair - minPair)); - - for (let i = 0; i < n - 1; i++) { - const left = i > 0 ? Math.abs(nums[0] - nums[i + 1]) - Math.abs(nums[i] - nums[i + 1]) : 0; - const right = i < n - 2 ? Math.abs(nums[n - 1] - nums[i]) - Math.abs(nums[i] - nums[i + 1]) : 0; - maxGain = Math.max(maxGain, left, right); - } - - return baseSum + maxGain; -}; diff --git a/solutions/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.js b/solutions/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.js deleted file mode 100644 index d42a5b58..00000000 --- a/solutions/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance - * https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/ - * Difficulty: Medium - * - * There are n cities numbered from 0 to n-1. Given the array edges where - * edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities - * fromi and toi, and given the integer distanceThreshold. - * - * Return the city with the smallest number of cities that are reachable through some path and whose - * distance is at most distanceThreshold, If there are multiple such cities, return the city with - * the greatest number. - * - * Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' - * weights along that path. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @param {number} distanceThreshold - * @return {number} - */ -var findTheCity = function(n, edges, distanceThreshold) { - const distances = Array.from({ length: n }, () => Array(n).fill(Infinity)); - - for (let i = 0; i < n; i++) { - distances[i][i] = 0; - } - - for (const [from, to, weight] of edges) { - distances[from][to] = weight; - distances[to][from] = weight; - } - - for (let k = 0; k < n; k++) { - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - distances[i][j] = Math.min(distances[i][j], distances[i][k] + distances[k][j]); - } - } - } - - let minNeighbors = n; - let result = 0; - - for (let i = 0; i < n; i++) { - const neighbors = distances[i].filter(dist => dist <= distanceThreshold).length - 1; - if (neighbors <= minNeighbors) { - minNeighbors = neighbors; - result = i; - } - } - - return result; -}; diff --git a/solutions/1335-minimum-difficulty-of-a-job-schedule.js b/solutions/1335-minimum-difficulty-of-a-job-schedule.js deleted file mode 100644 index f76a3d01..00000000 --- a/solutions/1335-minimum-difficulty-of-a-job-schedule.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1335. Minimum Difficulty of a Job Schedule - * https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/ - * Difficulty: Hard - * - * You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, - * you have to finish all the jobs j where 0 <= j < i). - * - * You have to finish at least one task every day. The difficulty of a job schedule is the sum of - * difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a - * job done on that day. - * - * You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job - * is jobDifficulty[i]. - * - * Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs - * return -1. - */ - -/** - * @param {number[]} jobDifficulty - * @param {number} d - * @return {number} - */ -var minDifficulty = function(jobDifficulty, d) { - const n = jobDifficulty.length; - if (n < d) return -1; - - const dp = new Array(d + 1).fill().map(() => new Array(n + 1).fill(Infinity)); - dp[0][0] = 0; - - for (let days = 1; days <= d; days++) { - for (let i = days; i <= n; i++) { - let maxDifficulty = 0; - for (let j = i - 1; j >= days - 1; j--) { - maxDifficulty = Math.max(maxDifficulty, jobDifficulty[j]); - dp[days][i] = Math.min(dp[days][i], dp[days - 1][j] + maxDifficulty); - } - } - } - - return dp[d][n] === Infinity ? -1 : dp[d][n]; -}; diff --git a/solutions/1337-the-k-weakest-rows-in-a-matrix.js b/solutions/1337-the-k-weakest-rows-in-a-matrix.js deleted file mode 100644 index 0fe90c5c..00000000 --- a/solutions/1337-the-k-weakest-rows-in-a-matrix.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 1337. The K Weakest Rows in a Matrix - * https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ - * Difficulty: Easy - * - * You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing - * civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will - * appear to the left of all the 0's in each row. - * - * A row i is weaker than a row j if one of the following is true: - * - The number of soldiers in row i is less than the number of soldiers in row j. - * - Both rows have the same number of soldiers and i < j. - * - * Return the indices of the k weakest rows in the matrix ordered from weakest to strongest. - */ - -/** - * @param {number[][]} mat - * @param {number} k - * @return {number[]} - */ -var kWeakestRows = function(mat, k) { - const soldierCounts = mat - .map((row, index) => [row.reduce((sum, val) => sum + val, 0), index]) - .sort((a, b) => a[0] - b[0] || a[1] - b[1]); - - return soldierCounts.slice(0, k).map(pair => pair[1]); -}; diff --git a/solutions/1338-reduce-array-size-to-the-half.js b/solutions/1338-reduce-array-size-to-the-half.js deleted file mode 100644 index e94fbd14..00000000 --- a/solutions/1338-reduce-array-size-to-the-half.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1338. Reduce Array Size to The Half - * https://leetcode.com/problems/reduce-array-size-to-the-half/ - * Difficulty: Medium - * - * You are given an integer array arr. You can choose a set of integers and remove all the - * occurrences of these integers in the array. - * - * Return the minimum size of the set so that at least half of the integers of the array - * are removed. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var minSetSize = function(arr) { - const map = new Map(); - const halfLength = arr.length / 2; - - arr.forEach(num => map.set(num, (map.get(num) || 0) + 1)); - - const frequencies = Array.from(map.values()).sort((a, b) => b - a); - - let removedCount = 0; - let result = 0; - - for (const freq of frequencies) { - removedCount += freq; - result++; - if (removedCount >= halfLength) break; - } - - return result; -}; diff --git a/solutions/1339-maximum-product-of-splitted-binary-tree.js b/solutions/1339-maximum-product-of-splitted-binary-tree.js deleted file mode 100644 index a79efcf5..00000000 --- a/solutions/1339-maximum-product-of-splitted-binary-tree.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1339. Maximum Product of Splitted Binary Tree - * https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/ - * Difficulty: Medium - * - * Given the root of a binary tree, split the binary tree into two subtrees by removing one edge - * such that the product of the sums of the subtrees is maximized. - * - * Return the maximum product of the sums of the two subtrees. Since the answer may be too large, - * return it modulo 109 + 7. - * - * Note that you need to maximize the answer before taking the mod and not after taking it. - */ - -/** - * 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 maxProduct = function(root) { - const sums = []; - const MOD = 1e9 + 7; - const total = calculateSum(root); - let maxProd = 0; - - for (const sum of sums) { - maxProd = Math.max(maxProd, sum * (total - sum)); - } - - return maxProd % MOD; - - function calculateSum(node) { - if (!node) return 0; - const leftSum = calculateSum(node.left); - const rightSum = calculateSum(node.right); - const totalSum = node.val + leftSum + rightSum; - sums.push(totalSum); - return totalSum; - } -}; diff --git a/solutions/1340-jump-game-v.js b/solutions/1340-jump-game-v.js deleted file mode 100644 index 6d9cc784..00000000 --- a/solutions/1340-jump-game-v.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 1340. Jump Game V - * https://leetcode.com/problems/jump-game-v/ - * Difficulty: Hard - * - * Given an array of integers arr and an integer d. In one step you can jump from index i to index: - * - i + x where: i + x < arr.length and 0 < x <= d. - * - i - x where: i - x >= 0 and 0 < x <= d. - * - * In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for - * all indices k between i and j (More formally min(i, j) < k < max(i, j)). - * - * You can choose any index of the array and start jumping. Return the maximum number of indices you - * can visit. - * - * Notice that you can not jump outside of the array at any time. - */ - -/** - * @param {number[]} arr - * @param {number} d - * @return {number} - */ -var maxJumps = function(arr, d) { - const n = arr.length; - const memo = new Array(n).fill(0); - let result = 1; - - for (let i = 0; i < n; i++) { - result = Math.max(result, exploreJumps(i)); - } - - return result; - - function exploreJumps(index) { - if (memo[index]) return memo[index]; - - let maxJumpsFromHere = 1; - - for (let offset = 1; offset <= d; offset++) { - const right = index + offset; - if (right < n && arr[index] > arr[right]) { - maxJumpsFromHere = Math.max(maxJumpsFromHere, 1 + exploreJumps(right)); - } else { - break; - } - } - - for (let offset = 1; offset <= d; offset++) { - const left = index - offset; - if (left >= 0 && arr[index] > arr[left]) { - maxJumpsFromHere = Math.max(maxJumpsFromHere, 1 + exploreJumps(left)); - } else { - break; - } - } - - memo[index] = maxJumpsFromHere; - return maxJumpsFromHere; - } -}; diff --git a/solutions/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js b/solutions/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js deleted file mode 100644 index ad308495..00000000 --- a/solutions/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold - * https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/ - * Difficulty: Medium - * - * Given an array of integers arr and two integers k and threshold, return the number of sub-arrays - * of size k and average greater than or equal to threshold. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @param {number} threshold - * @return {number} - */ -var numOfSubarrays = function(arr, k, threshold) { - let result = 0; - let windowSum = 0; - const minSum = k * threshold; - - for (let i = 0; i < k; i++) { - windowSum += arr[i]; - } - - if (windowSum >= minSum) result++; - - for (let i = k; i < arr.length; i++) { - windowSum += arr[i] - arr[i - k]; - if (windowSum >= minSum) result++; - } - - return result; -}; diff --git a/solutions/1344-angle-between-hands-of-a-clock.js b/solutions/1344-angle-between-hands-of-a-clock.js deleted file mode 100644 index 1101eaec..00000000 --- a/solutions/1344-angle-between-hands-of-a-clock.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 1344. Angle Between Hands of a Clock - * https://leetcode.com/problems/angle-between-hands-of-a-clock/ - * Difficulty: Medium - * - * Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the - * hour and the minute hand. - * - * Answers within 10-5 of the actual value will be accepted as correct. - */ - -/** - * @param {number} hour - * @param {number} minutes - * @return {number} - */ -var angleClock = function(hour, minutes) { - const hourAngle = (hour % 12 + minutes / 60) * 30; - const minuteAngle = minutes * 6; - const angle = Math.abs(hourAngle - minuteAngle); - return Math.min(angle, 360 - angle); -}; diff --git a/solutions/1345-jump-game-iv.js b/solutions/1345-jump-game-iv.js deleted file mode 100644 index 665edd7a..00000000 --- a/solutions/1345-jump-game-iv.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * 1345. Jump Game IV - * https://leetcode.com/problems/jump-game-iv/ - * Difficulty: Hard - * - * Given an array of integers arr, you are initially positioned at the first index of the array. - * - * In one step you can jump from index i to index: - * - i + 1 where: i + 1 < arr.length. - * - i - 1 where: i - 1 >= 0. - * - j where: arr[i] == arr[j] and i != j. - * - * Return the minimum number of steps to reach the last index of the array. - * - * Notice that you can not jump outside of the array at any time. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var minJumps = function(arr) { - const n = arr.length; - if (n <= 1) return 0; - - const valueToIndices = new Map(); - for (let i = 0; i < n; i++) { - if (!valueToIndices.has(arr[i])) { - valueToIndices.set(arr[i], []); - } - valueToIndices.get(arr[i]).push(i); - } - - const visited = new Set([0]); - let queue = [0]; - let result = 0; - - while (queue.length) { - const nextQueue = []; - - for (const current of queue) { - if (current === n - 1) return result; - - if (current + 1 < n && !visited.has(current + 1)) { - visited.add(current + 1); - nextQueue.push(current + 1); - } - - if (current - 1 >= 0 && !visited.has(current - 1)) { - visited.add(current - 1); - nextQueue.push(current - 1); - } - - for (const next of valueToIndices.get(arr[current]) || []) { - if (!visited.has(next)) { - visited.add(next); - nextQueue.push(next); - } - } - - valueToIndices.delete(arr[current]); - } - - queue = nextQueue; - result++; - } - - return result; -}; diff --git a/solutions/1346-check-if-n-and-its-double-exist.js b/solutions/1346-check-if-n-and-its-double-exist.js deleted file mode 100644 index 40984a56..00000000 --- a/solutions/1346-check-if-n-and-its-double-exist.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 1346. Check If N and Its Double Exist - * https://leetcode.com/problems/check-if-n-and-its-double-exist/ - * Difficulty: Easy - * - * Given an array arr of integers, check if there exist two indices i and j such that: - * - i != j - * - 0 <= i, j < arr.length - * - arr[i] == 2 * arr[j] - */ - -/** - * @param {number[]} arr - * @return {boolean} - */ -var checkIfExist = function(arr) { - const set = new Set(); - - for (const num of arr) { - if (set.has(num * 2) || set.has(num / 2)) { - return true; - } - set.add(num); - } - - return false; -}; diff --git a/solutions/1347-minimum-number-of-steps-to-make-two-strings-anagram.js b/solutions/1347-minimum-number-of-steps-to-make-two-strings-anagram.js deleted file mode 100644 index 8a2493a2..00000000 --- a/solutions/1347-minimum-number-of-steps-to-make-two-strings-anagram.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1347. Minimum Number of Steps to Make Two Strings Anagram - * https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/ - * Difficulty: Medium - * - * You are given two strings of the same length s and t. In one step you can choose any character - * of t and replace it with another character. - * - * Return the minimum number of steps to make t an anagram of s. - * - * An Anagram of a string is a string that contains the same characters with a different (or the - * same) ordering. - */ - -/** - * @param {string} s - * @param {string} t - * @return {number} - */ -var minSteps = function(s, t) { - const charCount = new Array(26).fill(0); - let result = 0; - - for (let i = 0; i < s.length; i++) { - charCount[s.charCodeAt(i) - 97]++; - charCount[t.charCodeAt(i) - 97]--; - } - - for (const count of charCount) { - if (count > 0) result += count; - } - - return result; -}; diff --git a/solutions/1348-tweet-counts-per-frequency.js b/solutions/1348-tweet-counts-per-frequency.js deleted file mode 100644 index e076628c..00000000 --- a/solutions/1348-tweet-counts-per-frequency.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 1348. Tweet Counts Per Frequency - * https://leetcode.com/problems/tweet-counts-per-frequency/ - * Difficulty: Medium - * - * A social media company is trying to monitor activity on their site by analyzing the number - * of tweets that occur in select periods of time. These periods can be partitioned into - * smaller time chunks based on a certain frequency (every minute, hour, or day). - * - * For example, the period [10, 10000] (in seconds) would be partitioned into the following - * time chunks with these frequencies: - * - Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000] - * - Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000] - * - Every day (86400-second chunks): [10,10000] - * - * Notice that the last chunk may be shorter than the specified frequency's chunk size and will - * always end with the end time of the period (10000 in the above example). - * - * Design and implement an API to help the company with their analysis. - * - * Implement the TweetCounts class: - * - TweetCounts() Initializes the TweetCounts object. - * - void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time - * (in seconds). - * - List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, - * int endTime) Returns a list of integers representing the number of tweets with tweetName - * in each time chunk for the given period of time [startTime, endTime] (in seconds) and - * frequency freq. - * - freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, - * or day respectively. - */ - -var TweetCounts = function() { - this.tweets = new Map(); -}; - -/** - * @param {string} tweetName - * @param {number} time - * @return {void} - */ -TweetCounts.prototype.recordTweet = function(tweetName, time) { - if (!this.tweets.has(tweetName)) { - this.tweets.set(tweetName, []); - } - this.tweets.get(tweetName).push(time); -}; - -/** - * @param {string} freq - * @param {string} tweetName - * @param {number} startTime - * @param {number} endTime - * @return {number[]} - */ -TweetCounts.prototype.getTweetCountsPerFrequency = function(freq, tweetName, startTime, endTime) { - let interval; - if (freq === 'minute') interval = 60; - else if (freq === 'hour') interval = 3600; - else interval = 86400; - - const count = Math.floor((endTime - startTime) / interval) + 1; - const result = new Array(count).fill(0); - - if (this.tweets.has(tweetName)) { - for (const time of this.tweets.get(tweetName)) { - if (time >= startTime && time <= endTime) { - const index = Math.floor((time - startTime) / interval); - result[index]++; - } - } - } - - return result; -}; diff --git a/solutions/1349-maximum-students-taking-exam.js b/solutions/1349-maximum-students-taking-exam.js deleted file mode 100644 index d8d1fce4..00000000 --- a/solutions/1349-maximum-students-taking-exam.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1349. Maximum Students Taking Exam - * https://leetcode.com/problems/maximum-students-taking-exam/ - * Difficulty: Hard - * - * Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is - * broken, it is denoted by '#' character otherwise it is denoted by a '.' character. - * - * Students can see the answers of those sitting next to the left, right, upper left and upper - * right, but he cannot see the answers of the student sitting directly in front or behind him. - * Return the maximum number of students that can take the exam together without any cheating - * being possible. - * - * Students must be placed in seats in good condition. - */ - -/** - * @param {character[][]} seats - * @return {number} - */ -var maxStudents = function(seats) { - const rows = seats.length; - const cols = seats[0].length; - const cache = new Map(); - - return countStudents(0, 0); - - function isValid(row, currMask, prevMask) { - for (let j = 0; j < cols; j++) { - if (!(currMask & (1 << j))) continue; - if (seats[row][j] === '#') return false; - if (j > 0 && (currMask & (1 << (j - 1)))) return false; - if (j < cols - 1 && (currMask & (1 << (j + 1)))) return false; - if (row > 0) { - if (j > 0 && (prevMask & (1 << (j - 1)))) return false; - if (j < cols - 1 && (prevMask & (1 << (j + 1)))) return false; - } - } - return true; - } - - function countStudents(row, prevMask) { - if (row === rows) return 0; - const key = `${row},${prevMask}`; - if (cache.has(key)) return cache.get(key); - - let maxCount = 0; - for (let currMask = 0; currMask < (1 << cols); currMask++) { - if (!isValid(row, currMask, prevMask)) continue; - const students = (currMask.toString(2).match(/1/g) || []).length; - maxCount = Math.max(maxCount, students + countStudents(row + 1, currMask)); - } - - cache.set(key, maxCount); - return maxCount; - } -}; diff --git a/solutions/1353-maximum-number-of-events-that-can-be-attended.js b/solutions/1353-maximum-number-of-events-that-can-be-attended.js deleted file mode 100644 index 94703b65..00000000 --- a/solutions/1353-maximum-number-of-events-that-can-be-attended.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * 1353. Maximum Number of Events That Can Be Attended - * https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ - * Difficulty: Medium - * - * You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts - * at startDayi and ends at endDayi. - * - * You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend - * one event at any time d. - * - * Return the maximum number of events you can attend. - */ - -/** - * @param {number[][]} events - * @return {number} - */ -var maxEvents = function(events) { - events.sort((a, b) => a[0] - b[0]); - const heap = []; - let result = 0; - let eventIndex = 0; - let currentDay = 1; - - while (eventIndex < events.length || heap.length) { - while (eventIndex < events.length && events[eventIndex][0] <= currentDay) { - heapPush(heap, events[eventIndex][1]); - eventIndex++; - } - - while (heap.length && heap[0] < currentDay) { - heapPop(heap); - } - - if (heap.length) { - heapPop(heap); - result++; - } - - currentDay++; - } - - function heapPush(arr, val) { - arr.push(val); - let i = arr.length - 1; - while (i > 0) { - const parent = Math.floor((i - 1) / 2); - if (arr[parent] <= arr[i]) break; - [arr[parent], arr[i]] = [arr[i], arr[parent]]; - i = parent; - } - } - - function heapPop(arr) { - const result = arr[0]; - arr[0] = arr[arr.length - 1]; - arr.pop(); - let i = 0; - while (true) { - const left = 2 * i + 1; - const right = 2 * i + 2; - let smallest = i; - if (left < arr.length && arr[left] < arr[smallest]) smallest = left; - if (right < arr.length && arr[right] < arr[smallest]) smallest = right; - if (smallest === i) break; - [arr[i], arr[smallest]] = [arr[smallest], arr[i]]; - i = smallest; - } - return result; - } - - return result; -}; diff --git a/solutions/1354-construct-target-array-with-multiple-sums.js b/solutions/1354-construct-target-array-with-multiple-sums.js deleted file mode 100644 index df914d7b..00000000 --- a/solutions/1354-construct-target-array-with-multiple-sums.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1354. Construct Target Array With Multiple Sums - * https://leetcode.com/problems/construct-target-array-with-multiple-sums/ - * Difficulty: Hard - * - * You are given an array target of n integers. From a starting array arr consisting of n 1's, - * you may perform the following procedure: - * - let x be the sum of all elements currently in your array. - * - choose index i, such that 0 <= i < n and set the value of arr at index i to x. - * - You may repeat this procedure as many times as needed. - * - * Return true if it is possible to construct the target array from arr, otherwise, return false. - */ - -/** - * @param {number[]} target - * @return {boolean} - */ -function isPossible(target) { - let totalSum = target.reduce((sum, num) => sum + num, 0); - const heap = [...target]; - - buildHeap(); - - while (heap[0] > 1) { - const largest = heap[0]; - totalSum -= largest; - if (totalSum < 1) return false; - const newValue = largest - Math.floor((largest - 1) / totalSum) * totalSum; - if (newValue === largest) return false; - totalSum += newValue; - heap[0] = newValue; - heapifyDown(0); - } - - return true; - - function heapifyDown(index) { - let largest = index; - const left = 2 * index + 1; - const right = 2 * index + 2; - if (left < heap.length && heap[left] > heap[largest]) largest = left; - if (right < heap.length && heap[right] > heap[largest]) largest = right; - if (largest !== index) { - [heap[index], heap[largest]] = [heap[largest], heap[index]]; - heapifyDown(largest); - } - } - - function buildHeap() { - for (let i = Math.floor(heap.length / 2) - 1; i >= 0; i--) { - heapifyDown(i); - } - } -} diff --git a/solutions/1357-apply-discount-every-n-orders.js b/solutions/1357-apply-discount-every-n-orders.js deleted file mode 100644 index a72d4ee5..00000000 --- a/solutions/1357-apply-discount-every-n-orders.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 1357. Apply Discount Every n Orders - * https://leetcode.com/problems/apply-discount-every-n-orders/ - * Difficulty: Medium - * - * There is a supermarket that is frequented by many customers. The products sold at the supermarket - * are represented as two parallel integer arrays products and prices, where the ith product has an - * ID of products[i] and a price of prices[i]. - * - * When a customer is paying, their bill is represented as two parallel integer arrays product and - * amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much - * of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price - * of the jth product). - * - * The supermarket decided to have a sale. Every nth customer paying for their groceries will be - * given a percentage discount. The discount amount is given by discount, where they will be given - * discount percent off their subtotal. More formally, if their subtotal is bill, then they would - * actually pay bill * ((100 - discount) / 100). - * - * Implement the Cashier class: - * - Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, - * the discount, and the products and their prices. - * - double getBill(int[] product, int[] amount) Returns the final total of the bill with the - * discount applied (if any). Answers within 10-5 of the actual value will be accepted. - */ - -/** - * @param {number} n - * @param {number} discount - * @param {number[]} products - * @param {number[]} prices - */ -var Cashier = function(n, discount, products, prices) { - this.customerCount = 0; - this.discountPercent = discount; - this.nthCustomer = n; - this.priceMap = new Map(); - for (let i = 0; i < products.length; i++) { - this.priceMap.set(products[i], prices[i]); - } -}; - -/** - * @param {number[]} product - * @param {number[]} amount - * @return {number} - */ -Cashier.prototype.getBill = function(product, amount) { - this.customerCount++; - let total = 0; - for (let i = 0; i < product.length; i++) { - total += this.priceMap.get(product[i]) * amount[i]; - } - if (this.customerCount % this.nthCustomer === 0) { - return total * (100 - this.discountPercent) / 100; - } - return total; -}; diff --git a/solutions/1358-number-of-substrings-containing-all-three-characters.js b/solutions/1358-number-of-substrings-containing-all-three-characters.js deleted file mode 100644 index 99459b80..00000000 --- a/solutions/1358-number-of-substrings-containing-all-three-characters.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1358. Number of Substrings Containing All Three Characters - * https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/ - * Difficulty: Medium - * - * Given a string s consisting only of characters a, b and c. - * - * Return the number of substrings containing at least one occurrence of all these - * characters a, b and c. - */ - -/** - * @param {string} s - * @return {number} - */ -var numberOfSubstrings = function(s) { - const count = [0, 0, 0]; - let result = 0; - let left = 0; - - for (let right = 0; right < s.length; right++) { - count[s[right].charCodeAt(0) - 97]++; - - while (count[0] > 0 && count[1] > 0 && count[2] > 0) { - result += s.length - right; - count[s[left].charCodeAt(0) - 97]--; - left++; - } - } - - return result; -}; diff --git a/solutions/1359-count-all-valid-pickup-and-delivery-options.js b/solutions/1359-count-all-valid-pickup-and-delivery-options.js deleted file mode 100644 index 2740ab36..00000000 --- a/solutions/1359-count-all-valid-pickup-and-delivery-options.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 1359. Count All Valid Pickup and Delivery Options - * https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ - * Difficulty: Hard - * - * Given n orders, each order consists of a pickup and a delivery service. - * - * Count all valid pickup/delivery possible sequences such that delivery(i) is always after - * of pickup(i). - * - * Since the answer may be too large, return it modulo 10^9 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -function countOrders(n) { - const MOD = 1e9 + 7; - let result = 1; - - for (let i = 1; i <= n; i++) { - result = (result * (2 * i - 1) * i) % MOD; - } - - return result; -} diff --git a/solutions/1361-validate-binary-tree-nodes.js b/solutions/1361-validate-binary-tree-nodes.js deleted file mode 100644 index 655d0735..00000000 --- a/solutions/1361-validate-binary-tree-nodes.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1361. Validate Binary Tree Nodes - * https://leetcode.com/problems/validate-binary-tree-nodes/ - * Difficulty: Medium - * - * You have n binary tree nodes numbered from 0 to n - 1 where node i has two children - * leftChild[i] and rightChild[i], return true if and only if all the given nodes form - * exactly one valid binary tree. - * - * If node i has no left child then leftChild[i] will equal -1, similarly for the right child. - * - * Note that the nodes have no values and that we only use the node numbers in this problem. - */ - -/** - * @param {number} n - * @param {number[]} leftChild - * @param {number[]} rightChild - * @return {boolean} - */ -var validateBinaryTreeNodes = function(n, leftChild, rightChild) { - const parentCount = new Array(n).fill(0); - let rootCandidate = -1; - - for (let i = 0; i < n; i++) { - if (leftChild[i] !== -1) parentCount[leftChild[i]]++; - if (rightChild[i] !== -1) parentCount[rightChild[i]]++; - } - - for (let i = 0; i < n; i++) { - if (parentCount[i] === 0) { - if (rootCandidate !== -1) return false; - rootCandidate = i; - } - if (parentCount[i] > 1) return false; - } - - if (rootCandidate === -1) return false; - - return countNodes(rootCandidate, new Set()) === n; - - function countNodes(node, visited) { - if (node === -1) return 0; - if (visited.has(node)) return -1; - visited.add(node); - const leftNodes = countNodes(leftChild[node], visited); - const rightNodes = countNodes(rightChild[node], visited); - if (leftNodes === -1 || rightNodes === -1) return -1; - return 1 + leftNodes + rightNodes; - } -}; diff --git a/solutions/1362-closest-divisors.js b/solutions/1362-closest-divisors.js deleted file mode 100644 index e3ab5bb2..00000000 --- a/solutions/1362-closest-divisors.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1362. Closest Divisors - * https://leetcode.com/problems/closest-divisors/ - * Difficulty: Medium - * - * Given an integer num, find the closest two integers in absolute difference whose product - * equals num + 1 or num + 2. - * - * Return the two integers in any order. - */ - -/** - * @param {number} num - * @return {number[]} - */ -function closestDivisors(num) { - const pair1 = findClosestPair(num + 1); - const pair2 = findClosestPair(num + 2); - - return Math.abs(pair1[1] - pair1[0]) <= Math.abs(pair2[1] - pair2[0]) ? pair1 : pair2; - - function findClosestPair(target) { - let minDifference = Infinity; - let pair = []; - - for (let divisor = 1; divisor <= Math.sqrt(target); divisor++) { - if (target % divisor === 0) { - const complement = target / divisor; - const difference = Math.abs(complement - divisor); - if (difference < minDifference) { - minDifference = difference; - pair = [divisor, complement]; - } - } - } - - return pair; - } -} diff --git a/solutions/1363-largest-multiple-of-three.js b/solutions/1363-largest-multiple-of-three.js deleted file mode 100644 index 37d535e9..00000000 --- a/solutions/1363-largest-multiple-of-three.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1363. Largest Multiple of Three - * https://leetcode.com/problems/largest-multiple-of-three/ - * Difficulty: Hard - * - * Given an array of digits digits, return the largest multiple of three that can be formed by - * concatenating some of the given digits in any order. If there is no answer return an empty - * string. - * - * Since the answer may not fit in an integer data type, return the answer as a string. Note - * that the returning answer must not contain unnecessary leading zeros. - */ - -/** - * @param {number[]} digits - * @return {string} - */ -var largestMultipleOfThree = function(digits) { - const counts = new Array(10).fill(0); - let sum = 0; - for (const digit of digits) { - counts[digit]++; - sum += digit; - } - - const remainder = sum % 3; - if (remainder === 0) { - return buildLargestNumber(counts, sum, 0); - } - - const sortedDigits = digits.slice().sort((a, b) => a - b); - for (const digit of sortedDigits) { - if (digit % 3 === remainder) { - counts[digit]--; - return buildLargestNumber(counts, sum - digit, 0); - } - } - - for (let i = 0; i < sortedDigits.length; i++) { - for (let j = i + 1; j < sortedDigits.length; j++) { - if ((sortedDigits[i] + sortedDigits[j]) % 3 === remainder) { - counts[sortedDigits[i]]--; - counts[sortedDigits[j]]--; - return buildLargestNumber(counts, sum - sortedDigits[i] - sortedDigits[j], 0); - } - } - } - - return ''; - - function buildLargestNumber(counts, total, modulo) { - let result = ''; - for (let digit = 9; digit >= 0; digit--) { - let count = counts[digit]; - while (count > 0 && total >= modulo) { - result += digit; - total -= digit; - count--; - } - } - return result.length > 0 && result[0] === '0' ? '0' : result; - } -}; diff --git a/solutions/1367-linked-list-in-binary-tree.js b/solutions/1367-linked-list-in-binary-tree.js deleted file mode 100644 index a95c1f45..00000000 --- a/solutions/1367-linked-list-in-binary-tree.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1367. Linked List in Binary Tree - * https://leetcode.com/problems/linked-list-in-binary-tree/ - * Difficulty: Medium - * - * Given a binary tree root and a linked list with head as the first node. - * - * Return True if all the elements in the linked list starting from the head correspond to some - * downward path connected in the binary tree otherwise return False. - * - * In this context downward path means a path that starts at some node and goes downwards. - */ - -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * 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 {ListNode} head - * @param {TreeNode} root - * @return {boolean} - */ -var isSubPath = function(head, root) { - if (!head) return true; - if (!root) return false; - return checkPath(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right); - - function checkPath(listNode, treeNode) { - if (!listNode) return true; - if (!treeNode) return false; - if (listNode.val !== treeNode.val) return false; - return checkPath(listNode.next, treeNode.left) || checkPath(listNode.next, treeNode.right); - } -}; diff --git a/solutions/1370-increasing-decreasing-string.js b/solutions/1370-increasing-decreasing-string.js deleted file mode 100644 index a654cc32..00000000 --- a/solutions/1370-increasing-decreasing-string.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1370. Increasing Decreasing String - * https://leetcode.com/problems/increasing-decreasing-string/ - * Difficulty: Easy - * - * You are given a string s. Reorder the string using the following algorithm: - * 1. Remove the smallest character from s and append it to the result. - * 2. Remove the smallest character from s that is greater than the last appended character, - * and append it to the result. - * 3. Repeat step 2 until no more characters can be removed. - * 4. Remove the largest character from s and append it to the result. - * 5. Remove the largest character from s that is smaller than the last appended character, - * and append it to the result. - * 6. Repeat step 5 until no more characters can be removed. - * 7. Repeat steps 1 through 6 until all characters from s have been removed. - * - * If the smallest or largest character appears more than once, you may choose any occurrence to - * append to the result. - * - * Return the resulting string after reordering s using this algorithm. - */ - -/** - * @param {string} s - * @return {string} - */ -var sortString = function(s) { - const charCounts = new Array(26).fill(0); - for (const char of s) { - charCounts[char.charCodeAt(0) - 97]++; - } - - let result = ''; - while (result.length < s.length) { - for (let i = 0; i < 26; i++) { - if (charCounts[i] > 0) { - result += String.fromCharCode(i + 97); - charCounts[i]--; - } - } - for (let i = 25; i >= 0; i--) { - if (charCounts[i] > 0) { - result += String.fromCharCode(i + 97); - charCounts[i]--; - } - } - } - - return result; -}; diff --git a/solutions/1371-find-the-longest-substring-containing-vowels-in-even-counts.js b/solutions/1371-find-the-longest-substring-containing-vowels-in-even-counts.js deleted file mode 100644 index 722c4847..00000000 --- a/solutions/1371-find-the-longest-substring-containing-vowels-in-even-counts.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1371. Find the Longest Substring Containing Vowels in Even Counts - * https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/ - * Difficulty: Medium - * - * Given the string s, return the size of the longest substring containing each vowel an even number - * of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. - */ - -/** - * @param {string} s - * @return {number} - */ -var findTheLongestSubstring = function(s) { - const vowelMap = new Map([['a', 0], ['e', 1], ['i', 2], ['o', 3], ['u', 4]]); - const stateToIndex = new Map([[0, -1]]); - let state = 0; - let result = 0; - - for (let i = 0; i < s.length; i++) { - if (vowelMap.has(s[i])) { - state ^= 1 << vowelMap.get(s[i]); - } - if (stateToIndex.has(state)) { - result = Math.max(result, i - stateToIndex.get(state)); - } else { - stateToIndex.set(state, i); - } - } - - return result; -}; diff --git a/solutions/1373-maximum-sum-bst-in-binary-tree.js b/solutions/1373-maximum-sum-bst-in-binary-tree.js deleted file mode 100644 index 1277a4e4..00000000 --- a/solutions/1373-maximum-sum-bst-in-binary-tree.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1373. Maximum Sum BST in Binary Tree - * https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/ - * Difficulty: Hard - * - * Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a - * Binary Search Tree (BST). - * - * Assume a 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 {number} - */ -var maxSumBST = function(root) { - let result = 0; - traverse(root); - return result; - - function traverse(node) { - if (!node) return { isBST: true, min: Infinity, max: -Infinity, sum: 0 }; - - const left = traverse(node.left); - const right = traverse(node.right); - - if (left.isBST && right.isBST && node.val > left.max && node.val < right.min) { - const currentSum = node.val + left.sum + right.sum; - result = Math.max(result, currentSum); - return { - isBST: true, - min: Math.min(node.val, left.min), - max: Math.max(node.val, right.max), - sum: currentSum - }; - } - - return { isBST: false, min: 0, max: 0, sum: 0 }; - } -}; diff --git a/solutions/1375-number-of-times-binary-string-is-prefix-aligned.js b/solutions/1375-number-of-times-binary-string-is-prefix-aligned.js deleted file mode 100644 index 728e9657..00000000 --- a/solutions/1375-number-of-times-binary-string-is-prefix-aligned.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1375. Number of Times Binary String Is Prefix-Aligned - * https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/ - * Difficulty: Medium - * - * You have a 1-indexed binary string of length n where all the bits are 0 initially. We will - * flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are - * given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will - * be flipped in the ith step. - * - * A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range - * [1, i] are ones and all the other bits are zeros. - * - * Return the number of times the binary string is prefix-aligned during the flipping process. - */ - -/** - * @param {number[]} light - * @return {number} - */ -var numTimesAllBlue = function(flips) { - let maxFlipped = 0; - let result = 0; - - flips.forEach((position, step) => { - maxFlipped = Math.max(maxFlipped, position); - if (maxFlipped === step + 1) result++; - }); - - return result; -}; diff --git a/solutions/1376-time-needed-to-inform-all-employees.js b/solutions/1376-time-needed-to-inform-all-employees.js deleted file mode 100644 index ffe9a6ff..00000000 --- a/solutions/1376-time-needed-to-inform-all-employees.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1376. Time Needed to Inform All Employees - * https://leetcode.com/problems/time-needed-to-inform-all-employees/ - * Difficulty: Medium - * - * A company has n employees with a unique ID for each employee from 0 to n - 1. The head - * of the company is the one with headID. - * - * Each employee has one direct manager given in the manager array where manager[i] is the - * direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that - * the subordination relationships have a tree structure. - * - * The head of the company wants to inform all the company employees of an urgent piece of - * news. He will inform his direct subordinates, and they will inform their subordinates, - * and so on until all employees know about the urgent news. - * - * The i-th employee needs informTime[i] minutes to inform all of his direct subordinates - * (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). - * - * Return the number of minutes needed to inform all the employees about the urgent news. - */ - -/** - * @param {number} n - * @param {number} headID - * @param {number[]} manager - * @param {number[]} informTime - * @return {number} - */ -var numOfMinutes = function(n, headID, manager, informTime) { - const adjacencyList = Array.from({ length: n }, () => []); - - for (let i = 0; i < n; i++) { - if (manager[i] !== -1) { - adjacencyList[manager[i]].push(i); - } - } - - return calculateTime(headID); - - function calculateTime(employee) { - let maxSubordinateTime = 0; - - for (const subordinate of adjacencyList[employee]) { - maxSubordinateTime = Math.max(maxSubordinateTime, calculateTime(subordinate)); - } - - return informTime[employee] + maxSubordinateTime; - } -}; diff --git a/solutions/1377-frog-position-after-t-seconds.js b/solutions/1377-frog-position-after-t-seconds.js deleted file mode 100644 index a1a90370..00000000 --- a/solutions/1377-frog-position-after-t-seconds.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1377. Frog Position After T Seconds - * https://leetcode.com/problems/frog-position-after-t-seconds/ - * Difficulty: Hard - * - * Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts - * jumping from vertex 1. In one second, the frog jumps from its current vertex to another - * unvisited vertex if they are directly connected. The frog can not jump back to a visited - * vertex. In case the frog can jump to several vertices, it jumps randomly to one of them - * with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, - * it jumps forever on the same 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. - * - * Return the probability that after t seconds the frog is on the vertex target. Answers - * within 10-5 of the actual answer will be accepted. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @param {number} t - * @param {number} target - * @return {number} - */ -var frogPosition = function(n, edges, t, target) { - const adjacencyList = Array.from({ length: n + 1 }, () => []); - for (const [a, b] of edges) { - adjacencyList[a].push(b); - adjacencyList[b].push(a); - } - - return explore(1, 0, 1, new Set()); - - function explore(vertex, time, probability, visited) { - if (time > t) return 0; - if (vertex === target && time === t) return probability; - if (vertex === target && adjacencyList[vertex].every(v => visited.has(v))) return probability; - - const unvisitedNeighbors = adjacencyList[vertex].filter(v => !visited.has(v)); - if (unvisitedNeighbors.length === 0) return 0; - - const nextProbability = probability / unvisitedNeighbors.length; - visited.add(vertex); - - for (const neighbor of unvisitedNeighbors) { - const result = explore(neighbor, time + 1, nextProbability, visited); - if (result > 0) return result; - } - - return 0; - } -}; diff --git a/solutions/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.js b/solutions/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.js deleted file mode 100644 index 388c5f3e..00000000 --- a/solutions/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree - * https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ - * Difficulty: Easy - * - * Given two binary trees original and cloned and given a reference to a node target in the original - * tree. - * - * The cloned tree is a copy of the original tree. - * - * Return a reference to the same node in the cloned tree. - * - * Note that you are not allowed to change any of the two trees or the target node and the answer - * must be a reference to a node in the cloned tree. - */ - -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} original - * @param {TreeNode} cloned - * @param {TreeNode} target - * @return {TreeNode} - */ -var getTargetCopy = function(original, cloned, target) { - return traverse(original, cloned); - - function traverse(originalNode, clonedNode) { - if (!originalNode) return null; - if (originalNode === target) return clonedNode; - - const leftResult = traverse(originalNode.left, clonedNode.left); - if (leftResult) return leftResult; - - return traverse(originalNode.right, clonedNode.right); - } -}; diff --git a/solutions/1381-design-a-stack-with-increment-operation.js b/solutions/1381-design-a-stack-with-increment-operation.js deleted file mode 100644 index 5aa9f52d..00000000 --- a/solutions/1381-design-a-stack-with-increment-operation.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 1381. Design a Stack With Increment Operation - * https://leetcode.com/problems/design-a-stack-with-increment-operation/ - * Difficulty: Medium - * - * Design a stack that supports increment operations on its elements. - * - * Implement the CustomStack class: - * - CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number - * of elements in the stack. - * - void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize. - * - int pop() Pops and returns the top of the stack or -1 if the stack is empty. - * - void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are - * less than k elements in the stack, increment all the elements in the stack. - */ - -/** - * @param {number} maxSize - */ -var CustomStack = function(maxSize) { - this.elements = []; - this.capacity = maxSize; -}; - -/** - * @param {number} x - * @return {void} - */ -CustomStack.prototype.push = function(x) { - if (this.elements.length < this.capacity) { - this.elements.push(x); - } -}; - -/** - * @return {number} - */ -CustomStack.prototype.pop = function() { - return this.elements.length ? this.elements.pop() : -1; -}; - -/** - * @param {number} k - * @param {number} val - * @return {void} - */ -CustomStack.prototype.increment = function(k, val) { - const limit = Math.min(k, this.elements.length); - for (let i = 0; i < limit; i++) { - this.elements[i] += val; - } -}; diff --git a/solutions/1382-balance-a-binary-search-tree.js b/solutions/1382-balance-a-binary-search-tree.js deleted file mode 100644 index 1c0a0035..00000000 --- a/solutions/1382-balance-a-binary-search-tree.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1382. Balance a Binary Search Tree - * https://leetcode.com/problems/balance-a-binary-search-tree/ - * Difficulty: Medium - * - * Given the root of a binary search tree, return a balanced binary search tree with the same - * node values. If there is more than one answer, return any of them. - * - * A binary search tree is balanced if the depth of the two subtrees of every node never differs - * by more than 1. - */ - -/** - * 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 {TreeNode} - */ -var balanceBST = function(root) { - const nodes = []; - collectInOrder(root); - return buildBalancedTree(0, nodes.length - 1); - - function collectInOrder(node) { - if (!node) return; - collectInOrder(node.left); - nodes.push(node.val); - collectInOrder(node.right); - } - - function buildBalancedTree(start, end) { - if (start > end) return null; - const mid = Math.floor((start + end) / 2); - const node = new TreeNode(nodes[mid]); - node.left = buildBalancedTree(start, mid - 1); - node.right = buildBalancedTree(mid + 1, end); - return node; - } -}; diff --git a/solutions/1383-maximum-performance-of-a-team.js b/solutions/1383-maximum-performance-of-a-team.js deleted file mode 100644 index d7fd5ec5..00000000 --- a/solutions/1383-maximum-performance-of-a-team.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 1383. Maximum Performance of a Team - * https://leetcode.com/problems/maximum-performance-of-a-team/ - * Difficulty: Hard - * - * You are given two integers n and k and two integer arrays speed and efficiency both of length n. - * There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and - * efficiency of the ith engineer respectively. - * - * Choose at most k different engineers out of the n engineers to form a team with the maximum - * performance. - * - * The performance of a team is the sum of its engineers' speeds multiplied by the minimum - * efficiency among its engineers. - * - * Return the maximum performance of this team. Since the answer can be a huge number, return it - * modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number[]} speed - * @param {number[]} efficiency - * @param {number} k - * @return {number} - */ -var maxPerformance = function(n, speed, efficiency, k) { - const engineers = Array.from({ length: n }, (_, i) => [efficiency[i], speed[i]]) - .sort((a, b) => b[0] - a[0]); - const speedHeap = []; - let totalSpeed = 0n; - let maxPerf = 0n; - const MOD = 1000000007n; - - function insertSpeed(val) { - speedHeap.push(val); - let i = speedHeap.length - 1; - while (i > 0) { - const parent = Math.floor((i - 1) / 2); - if (speedHeap[parent] <= speedHeap[i]) break; - [speedHeap[i], speedHeap[parent]] = [speedHeap[parent], speedHeap[i]]; - i = parent; - } - } - - function removeMinSpeed() { - const min = speedHeap[0]; - speedHeap[0] = speedHeap.pop(); - let i = 0; - while (true) { - const left = 2 * i + 1; - const right = 2 * i + 2; - let smallest = i; - if (left < speedHeap.length && speedHeap[left] < speedHeap[smallest]) { - smallest = left; - } - if (right < speedHeap.length && speedHeap[right] < speedHeap[smallest]) { - smallest = right; - } - if (smallest === i) break; - [speedHeap[i], speedHeap[smallest]] = [speedHeap[smallest], speedHeap[i]]; - i = smallest; - } - return min; - } - - for (const [eff, spd] of engineers) { - insertSpeed(spd); - totalSpeed += BigInt(spd); - - if (speedHeap.length > k) { - totalSpeed -= BigInt(removeMinSpeed()); - } - - maxPerf = maxPerf > totalSpeed * BigInt(eff) ? maxPerf : totalSpeed * BigInt(eff); - } - - return Number(maxPerf % MOD); -}; diff --git a/solutions/1385-find-the-distance-value-between-two-arrays.js b/solutions/1385-find-the-distance-value-between-two-arrays.js deleted file mode 100644 index 6e777127..00000000 --- a/solutions/1385-find-the-distance-value-between-two-arrays.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1385. Find the Distance Value Between Two Arrays - * https://leetcode.com/problems/find-the-distance-value-between-two-arrays/ - * Difficulty: Easy - * - * Given two integer arrays arr1 and arr2, and the integer d, return the distance value between - * the two arrays. - * - * The distance value is defined as the number of elements arr1[i] such that there is not any - * element arr2[j] where |arr1[i]-arr2[j]| <= d. - */ - -/** - * @param {number[]} arr1 - * @param {number[]} arr2 - * @param {number} d - * @return {number} - */ -var findTheDistanceValue = function(arr1, arr2, d) { - let result = 0; - - for (const num1 of arr1) { - let isValid = true; - for (const num2 of arr2) { - if (Math.abs(num1 - num2) <= d) { - isValid = false; - break; - } - } - if (isValid) result++; - } - - return result; -}; diff --git a/solutions/1386-cinema-seat-allocation.js b/solutions/1386-cinema-seat-allocation.js deleted file mode 100644 index 0862016d..00000000 --- a/solutions/1386-cinema-seat-allocation.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 1386. Cinema Seat Allocation - * https://leetcode.com/problems/cinema-seat-allocation/ - * Difficulty: Medium - * - * A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled - * from 1 to 10 as shown in the figure above. - * - * Given the array reservedSeats containing the numbers of seats already reserved, for example, - * reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. - * - * Return the maximum number of four-person groups you can assign on the cinema seats. A four-person - * group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and - * [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle - * split a four-person group, in that case, the aisle split a four-person group in the middle, which - * means to have two people on each side. - */ - -/** - * @param {number} n - * @param {number[][]} reservedSeats - * @return {number} - */ -var maxNumberOfFamilies = function(n, reservedSeats) { - const rowReservations = new Map(); - - for (const [row, seat] of reservedSeats) { - if (!rowReservations.has(row)) { - rowReservations.set(row, new Set()); - } - rowReservations.get(row).add(seat); - } - - let result = 2 * (n - rowReservations.size); - - for (const seats of rowReservations.values()) { - let canPlaceGroup = false; - - if (!seats.has(2) && !seats.has(3) && !seats.has(4) && !seats.has(5)) { - result++; - canPlaceGroup = true; - } - if (!seats.has(6) && !seats.has(7) && !seats.has(8) && !seats.has(9)) { - result++; - canPlaceGroup = true; - } - if (!canPlaceGroup && !seats.has(4) && !seats.has(5) && !seats.has(6) && !seats.has(7)) { - result++; - } - } - - return result; -}; diff --git a/solutions/1387-sort-integers-by-the-power-value.js b/solutions/1387-sort-integers-by-the-power-value.js deleted file mode 100644 index 6b16f51a..00000000 --- a/solutions/1387-sort-integers-by-the-power-value.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 1387. Sort Integers by The Power Value - * https://leetcode.com/problems/sort-integers-by-the-power-value/ - * Difficulty: Medium - * - * The power of an integer x is defined as the number of steps needed to transform x into - * 1 using the following steps: - * - if x is even then x = x / 2 - * - if x is odd then x = 3 * x + 1 - * - * For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 - * (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). - * - * Given three integers lo, hi and k. The task is to sort all integers in the interval - * [lo, hi] by the power value in ascending order, if two or more integers have the same - * power value sort them by ascending order. - * - * Return the kth integer in the range [lo, hi] sorted by the power value. - * - * Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform - * into 1 using these steps and that the power of x is will fit in a 32-bit signed integer. - */ - -/** - * @param {number} lo - * @param {number} hi - * @param {number} k - * @return {number} - */ -var getKth = function(lo, hi, k) { - const powerValues = new Map(); - const numbers = Array.from({ length: hi - lo + 1 }, (_, i) => lo + i); - - numbers.sort((a, b) => { - const powerA = getPower(a); - const powerB = getPower(b); - return powerA === powerB ? a - b : powerA - powerB; - }); - - return numbers[k - 1]; - - function calculatePower(num) { - let steps = 0; - while (num !== 1) { - if (num % 2 === 0) { - num = num / 2; - } else { - num = 3 * num + 1; - } - steps++; - } - return steps; - } - - function getPower(num) { - if (!powerValues.has(num)) { - powerValues.set(num, calculatePower(num)); - } - return powerValues.get(num); - } -}; diff --git a/solutions/1388-pizza-with-3n-slices.js b/solutions/1388-pizza-with-3n-slices.js deleted file mode 100644 index bcd22a17..00000000 --- a/solutions/1388-pizza-with-3n-slices.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1388. Pizza With 3n Slices - * https://leetcode.com/problems/pizza-with-3n-slices/ - * Difficulty: Hard - * - * There is a pizza with 3n slices of varying size, you and your friends will take slices - * of pizza as follows: - * - You will pick any pizza slice. - * - Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. - * - Your friend Bob will pick the next slice in the clockwise direction of your pick. - * - Repeat until there are no more slices of pizzas. - * - * Given an integer array slices that represent the sizes of the pizza slices in a clockwise - * direction, return the maximum possible sum of slice sizes that you can pick. - */ - -/** - * @param {number[]} slices - * @return {number} - */ -var maxSizeSlices = function(slices) { - const n = slices.length; - const count = n / 3; - const case1 = selectMaxSum(slices, count - 1, 2, n - 2); - const case2 = selectMaxSum(slices, count, 1, n - 1); - - return Math.max(slices[0] + case1, case2); - - function selectMaxSum(arr, count, start, end, memo = new Map()) { - const key = `${count},${start},${end}`; - if (count === 0 || start > end) return 0; - if (memo.has(key)) return memo.get(key); - - const includeFirst = arr[start] + selectMaxSum(arr, count - 1, start + 2, end, memo); - const excludeFirst = selectMaxSum(arr, count, start + 1, end, memo); - const result = Math.max(includeFirst, excludeFirst); - - memo.set(key, result); - return result; - } -}; diff --git a/solutions/1390-four-divisors.js b/solutions/1390-four-divisors.js deleted file mode 100644 index 4642349b..00000000 --- a/solutions/1390-four-divisors.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1390. Four Divisors - * https://leetcode.com/problems/four-divisors/ - * Difficulty: Medium - * - * Given an integer array nums, return the sum of divisors of the integers in that array - * that have exactly four divisors. If there is no such integer in the array, return 0. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var sumFourDivisors = function(nums) { - function countDivisors(num) { - const divisors = new Set(); - for (let i = 1; i * i <= num; i++) { - if (num % i === 0) { - divisors.add(i); - divisors.add(num / i); - } - } - return divisors; - } - - let result = 0; - for (const num of nums) { - const divisors = countDivisors(num); - if (divisors.size === 4) { - const sum = [...divisors].reduce((acc, val) => acc + val, 0); - result += sum; - } - } - - return result; -}; diff --git a/solutions/1391-check-if-there-is-a-valid-path-in-a-grid.js b/solutions/1391-check-if-there-is-a-valid-path-in-a-grid.js deleted file mode 100644 index bf558817..00000000 --- a/solutions/1391-check-if-there-is-a-valid-path-in-a-grid.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1391. Check if There is a Valid Path in a Grid - * https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ - * Difficulty: Medium - * - * You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] - * can be: - * - 1 which means a street connecting the left cell and the right cell. - * - 2 which means a street connecting the upper cell and the lower cell. - * - 3 which means a street connecting the left cell and the lower cell. - * - 4 which means a street connecting the right cell and the lower cell. - * - 5 which means a street connecting the left cell and the upper cell. - * - 6 which means a street connecting the right cell and the upper cell. - * - * You will initially start at the street of the upper-left cell (0, 0). A valid path in the - * grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right - * cell (m - 1, n - 1). The path should only follow the streets. - * - * Notice that you are not allowed to change any street. - * - * Return true if there is a valid path in the grid or false otherwise. - */ - -/** - * @param {number[][]} grid - * @return {boolean} - */ -var hasValidPath = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const directions = { - 1: [[0, -1, [1, 4, 6]], [0, 1, [1, 3, 5]]], - 2: [[-1, 0, [2, 3, 4]], [1, 0, [2, 5, 6]]], - 3: [[0, -1, [1, 4, 6]], [1, 0, [2, 5, 6]]], - 4: [[0, 1, [1, 3, 5]], [1, 0, [2, 5, 6]]], - 5: [[0, -1, [1, 4, 6]], [-1, 0, [2, 3, 4]]], - 6: [[0, 1, [1, 3, 5]], [-1, 0, [2, 3, 4]]] - }; - - return explorePath(0, 0); - - function isValid(x, y) { - return x >= 0 && x < rows && y >= 0 && y < cols; - } - - function explorePath(x, y, visited = new Set()) { - if (!isValid(x, y) || visited.has(`${x},${y}`)) return false; - if (x === rows - 1 && y === cols - 1) return true; - - visited.add(`${x},${y}`); - const street = grid[x][y]; - - for (const [dx, dy, validStreets] of directions[street]) { - const newX = x + dx; - const newY = y + dy; - if (isValid(newX, newY) && validStreets.includes(grid[newX][newY])) { - if (explorePath(newX, newY, visited)) return true; - } - } - - return false; - } -}; diff --git a/solutions/1392-longest-happy-prefix.js b/solutions/1392-longest-happy-prefix.js deleted file mode 100644 index bc2f9cd3..00000000 --- a/solutions/1392-longest-happy-prefix.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1392. Longest Happy Prefix - * https://leetcode.com/problems/longest-happy-prefix/ - * Difficulty: Hard - * - * A string is called a happy prefix if is a non-empty prefix which is also a suffix - * (excluding itself). - * - * Given a string s, return the longest happy prefix of s. Return an empty string "" - * if no such prefix exists. - */ - -/** - * @param {string} s - * @return {string} - */ -var longestPrefix = function(s) { - let prefixLength = 0; - const prefixHash = new Array(s.length).fill(0); - - for (let i = 1; i < s.length; i++) { - while (prefixLength > 0 && s[i] !== s[prefixLength]) { - prefixLength = prefixHash[prefixLength - 1]; - } - if (s[i] === s[prefixLength]) { - prefixLength++; - } - prefixHash[i] = prefixLength; - } - - return s.slice(0, prefixHash[s.length - 1]); -}; diff --git a/solutions/1394-find-lucky-integer-in-an-array.js b/solutions/1394-find-lucky-integer-in-an-array.js deleted file mode 100644 index 737140d9..00000000 --- a/solutions/1394-find-lucky-integer-in-an-array.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1394. Find Lucky Integer in an Array - * https://leetcode.com/problems/find-lucky-integer-in-an-array/ - * Difficulty: Easy - * - * Given an array of integers arr, a lucky integer is an integer that has a frequency - * in the array equal to its value. - * - * Return the largest lucky integer in the array. If there is no lucky integer return -1. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var findLucky = function(arr) { - const frequencyMap = new Map(); - let result = -1; - - for (const num of arr) { - frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1); - } - for (const [num, count] of frequencyMap) { - if (num === count && num > result) { - result = num; - } - } - - return result; -}; diff --git a/solutions/1395-count-number-of-teams.js b/solutions/1395-count-number-of-teams.js deleted file mode 100644 index 1e3a0f0b..00000000 --- a/solutions/1395-count-number-of-teams.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1395. Count Number of Teams - * https://leetcode.com/problems/count-number-of-teams/ - * Difficulty: Medium - * - * There are n soldiers standing in a line. Each soldier is assigned a unique rating value. - * - * You have to form a team of 3 soldiers amongst them under the following rules: - * - Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). - * - A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) - * where (0 <= i < j < k < n). - * - * Return the number of teams you can form given the conditions. (soldiers can be part of - * multiple teams). - */ - -/** - * @param {number[]} rating - * @return {number} - */ -var numTeams = function(rating) { - let result = 0; - const n = rating.length; - - for (let j = 1; j < n - 1; j++) { - let leftLess = 0; - let leftGreater = 0; - let rightLess = 0; - let rightGreater = 0; - - for (let i = 0; i < j; i++) { - if (rating[i] < rating[j]) leftLess++; - else leftGreater++; - } - - for (let k = j + 1; k < n; k++) { - if (rating[k] < rating[j]) rightLess++; - else rightGreater++; - } - - result += leftLess * rightGreater + leftGreater * rightLess; - } - - return result; -}; diff --git a/solutions/1396-design-underground-system.js b/solutions/1396-design-underground-system.js deleted file mode 100644 index 9572c5d7..00000000 --- a/solutions/1396-design-underground-system.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * 1396. Design Underground System - * https://leetcode.com/problems/design-underground-system/ - * Difficulty: Medium - * - * An underground railway system is keeping track of customer travel times between different - * stations. They are using this data to calculate the average time it takes to travel from - * one station to another. - * - * Implement the UndergroundSystem class: - * - void checkIn(int id, string stationName, int t) - * - A customer with a card ID equal to id, checks in at the station stationName at time t. - * - A customer can only be checked into one place at a time. - * - void checkOut(int id, string stationName, int t) - * - A customer with a card ID equal to id, checks out from the station stationName at time t. - * - double getAverageTime(string startStation, string endStation) - * - Returns the average time it takes to travel from startStation to endStation. - * - The average time is computed from all the previous traveling times from startStation to - * endStation that happened directly, meaning a check in at startStation followed by a check - * out from endStation. - * - The time it takes to travel from startStation to endStation may be different from the - * time it takes to travel from endStation to startStation. - * - * There will be at least one customer that has traveled from startStation to endStation before - * getAverageTime is called. - * You may assume all calls to the checkIn and checkOut methods are consistent. If a customer - * checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in - * chronological order. - */ - - -var UndergroundSystem = function() { - this.travels = new Map(); - this.averages = new Map(); -}; - -/** - * @param {number} id - * @param {string} stationName - * @param {number} t - * @return {void} - */ -UndergroundSystem.prototype.checkIn = function(id, stationName, t) { - this.travels.set(id, { startStation: stationName, startTime: t }); -}; - -/** - * @param {number} id - * @param {string} stationName - * @param {number} t - * @return {void} - */ -UndergroundSystem.prototype.checkOut = function(id, stationName, t) { - const { startStation, startTime } = this.travels.get(id); - const route = `${startStation}-${stationName}`; - const duration = t - startTime; - - if (!this.averages.has(route)) { - this.averages.set(route, { totalTime: 0, count: 0 }); - } - - const record = this.averages.get(route); - record.totalTime += duration; - record.count += 1; - - this.travels.delete(id); -}; - -/** - * @param {string} startStation - * @param {string} endStation - * @return {number} - */ -UndergroundSystem.prototype.getAverageTime = function(startStation, endStation) { - const route = `${startStation}-${endStation}`; - const { totalTime, count } = this.averages.get(route); - return totalTime / count; -}; diff --git a/solutions/1397-find-all-good-strings.js b/solutions/1397-find-all-good-strings.js deleted file mode 100644 index 73b3b207..00000000 --- a/solutions/1397-find-all-good-strings.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 1397. Find All Good Strings - * https://leetcode.com/problems/find-all-good-strings/ - * Difficulty: Hard - * - * Given the strings s1 and s2 of size n and the string evil, return the number of good strings. - * - * A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically - * smaller than or equal to s2, and it does not contain the string evil as a substring. Since the - * answer can be a huge number, return this modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {string} s1 - * @param {string} s2 - * @param {string} evil - * @return {number} - */ -var findGoodStrings = function(n, s1, s2, evil) { - const MOD = 1e9 + 7; - const memo = new Map(); - const evilLPS = computeLPS(evil); - - function computeLPS(pattern) { - const lps = new Array(pattern.length).fill(0); - let length = 0; - let i = 1; - while (i < pattern.length) { - if (pattern[i] === pattern[length]) { - length++; - lps[i] = length; - i++; - } else { - if (length !== 0) { - length = lps[length - 1]; - } else { - lps[i] = 0; - i++; - } - } - } - return lps; - } - - function countValid(pos, evilMatched, bound1, bound2, str1, str2, evilStr, lps) { - if (evilMatched === evilStr.length) return 0; - if (pos === n) return 1; - - const key = `${pos}:${evilMatched}:${bound1}:${bound2}`; - if (memo.has(key)) return memo.get(key); - - let result = 0; - const start = bound1 ? str1[pos] : 'a'; - const end = bound2 ? str2[pos] : 'z'; - - for (let c = start; c <= end; c = String.fromCharCode(c.charCodeAt(0) + 1)) { - let newEvilMatched = evilMatched; - while (newEvilMatched > 0 && c !== evilStr[newEvilMatched]) { - newEvilMatched = lps[newEvilMatched - 1]; - } - if (c === evilStr[newEvilMatched]) { - newEvilMatched++; - } - - const newBound1 = bound1 && c === str1[pos]; - const newBound2 = bound2 && c === str2[pos]; - - result = (result + countValid( - pos + 1, newEvilMatched, newBound1, newBound2, str1, str2, evilStr, lps - )) % MOD; - } - - memo.set(key, result); - return result; - } - - return countValid(0, 0, true, true, s1, s2, evil, evilLPS); -}; diff --git a/solutions/1399-count-largest-group.js b/solutions/1399-count-largest-group.js deleted file mode 100644 index caf7c44f..00000000 --- a/solutions/1399-count-largest-group.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1399. Count Largest Group - * https://leetcode.com/problems/count-largest-group/ - * Difficulty: Easy - * - * You are given an integer n. - * - * Each number from 1 to n is grouped according to the sum of its digits. - * - * Return the number of groups that have the largest size. - */ - -/** - * @param {number} n - * @return {number} - */ -var countLargestGroup = function(n) { - const map = new Map(); - let maxSize = 0; - - for (let num = 1; num <= n; num++) { - const digitSum = calculateDigitSum(num); - const size = (map.get(digitSum) || 0) + 1; - map.set(digitSum, size); - maxSize = Math.max(maxSize, size); - } - - let result = 0; - for (const size of map.values()) { - if (size === maxSize) result++; - } - - return result; -}; - -function calculateDigitSum(num) { - let sum = 0; - while (num > 0) { - sum += num % 10; - num = Math.floor(num / 10); - } - return sum; -} diff --git a/solutions/1401-circle-and-rectangle-overlapping.js b/solutions/1401-circle-and-rectangle-overlapping.js deleted file mode 100644 index 719a9be1..00000000 --- a/solutions/1401-circle-and-rectangle-overlapping.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1401. Circle and Rectangle Overlapping - * https://leetcode.com/problems/circle-and-rectangle-overlapping/ - * Difficulty: Medium - * - * You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle - * represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, - * and (x2, y2) are the coordinates of the top-right corner of the rectangle. - * - * Return true if the circle and rectangle are overlapped otherwise return false. In other words, - * check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same - * time. - */ - -/** - * @param {number} radius - * @param {number} xCenter - * @param {number} yCenter - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @return {boolean} - */ -var checkOverlap = function(radius, xCenter, yCenter, x1, y1, x2, y2) { - const closestX = Math.max(x1, Math.min(x2, xCenter)); - const closestY = Math.max(y1, Math.min(y2, yCenter)); - - return ((xCenter - closestX) ** 2 + (yCenter - closestY) ** 2) <= radius ** 2; -}; diff --git a/solutions/1403-minimum-subsequence-in-non-increasing-order.js b/solutions/1403-minimum-subsequence-in-non-increasing-order.js deleted file mode 100644 index 2c2ffb5b..00000000 --- a/solutions/1403-minimum-subsequence-in-non-increasing-order.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1403. Minimum Subsequence in Non-Increasing Order - * https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/ - * Difficulty: Easy - * - * Given the array nums, obtain a subsequence of the array whose sum of elements is strictly - * greater than the sum of the non included elements in such subsequence. - * - * If there are multiple solutions, return the subsequence with minimum size and if there still - * exist multiple solutions, return the subsequence with the maximum total sum of all its elements. - * A subsequence of an array can be obtained by erasing some (possibly zero) elements from the - * array. - * - * Note that the solution with the given constraints is guaranteed to be unique. Also return the - * answer sorted in non-increasing order. - */ - -/** - * @param {number[]} nums - * @return {number[]} - */ -var minSubsequence = function(nums) { - const sorted = nums.sort((a, b) => b - a); - const totalSum = sorted.reduce((sum, num) => sum + num, 0); - const result = []; - let currentSum = 0; - - for (const num of sorted) { - currentSum += num; - result.push(num); - if (currentSum > totalSum - currentSum) break; - } - - return result; -}; diff --git a/solutions/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.js b/solutions/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.js deleted file mode 100644 index 15b554f2..00000000 --- a/solutions/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1404. Number of Steps to Reduce a Number in Binary Representation to One - * https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ - * Difficulty: Medium - * - * Given the binary representation of an integer as a string s, return the number of steps to reduce - * it to 1 under the following rules: - * - If the current number is even, you have to divide it by 2. - * - If the current number is odd, you have to add 1 to it. - * - * It is guaranteed that you can always reach one for all test cases. - */ - -/** - * @param {string} s - * @return {number} - */ -var numSteps = function(s) { - let num = BigInt(`0b${s}`); - let steps = 0; - - while (num !== 1n) { - if (num % 2n === 0n) { - num /= 2n; - } else { - num += 1n; - } - steps++; - } - - return steps; -}; diff --git a/solutions/1405-longest-happy-string.js b/solutions/1405-longest-happy-string.js deleted file mode 100644 index c1ad3fea..00000000 --- a/solutions/1405-longest-happy-string.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1405. Longest Happy String - * https://leetcode.com/problems/longest-happy-string/ - * Difficulty: Medium - * - * A string s is called happy if it satisfies the following conditions: - * - s only contains the letters 'a', 'b', and 'c'. - * - s does not contain any of "aaa", "bbb", or "ccc" as a substring. - * - s contains at most a occurrences of the letter 'a'. - * - s contains at most b occurrences of the letter 'b'. - * - s contains at most c occurrences of the letter 'c'. - * - * Given three integers a, b, and c, return the longest possible happy string. If there are - * multiple longest happy strings, return any of them. If there is no such string, return - * the empty string "". - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {number} a - * @param {number} b - * @param {number} c - * @return {string} - */ -var longestDiverseString = function(a, b, c) { - const counts = [ - { char: 'a', count: a }, - { char: 'b', count: b }, - { char: 'c', count: c } - ]; - const result = []; - - while (true) { - counts.sort((x, y) => y.count - x.count); - - let added = false; - for (let i = 0; i < 3; i++) { - const { char, count } = counts[i]; - if (count === 0) continue; - - const total = result.length; - if (total >= 2 && result[total - 1] === char && result[total - 2] === char) { - continue; - } - - result.push(char); - counts[i].count--; - added = true; - break; - } - - if (!added) break; - } - - return result.join(''); -}; diff --git a/solutions/1406-stone-game-iii.js b/solutions/1406-stone-game-iii.js deleted file mode 100644 index 007d61ea..00000000 --- a/solutions/1406-stone-game-iii.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1406. Stone Game III - * https://leetcode.com/problems/stone-game-iii/ - * Difficulty: Hard - * - * Alice and Bob continue their games with piles of stones. There are several stones arranged - * in a row, and each stone has an associated value which is an integer given in the array - * stoneValue. - * - * Alice and Bob take turns, with Alice starting first. On each player's turn, that player can - * take 1, 2, or 3 stones from the first remaining stones in the row. - * - * The score of each player is the sum of the values of the stones taken. The score of each - * player is 0 initially. - * - * The objective of the game is to end with the highest score, and the winner is the player - * with the highest score and there could be a tie. The game continues until all the stones - * have been taken. - * - * Assume Alice and Bob play optimally. - * - * Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game - * with the same score. - */ - -/** - * @param {number[]} stoneValue - * @return {string} - */ -var stoneGameIII = function(stoneValue) { - const n = stoneValue.length; - const cache = new Array(n + 1).fill(null); - - function findOptimalScore(index) { - if (index >= n) return 0; - if (cache[index] !== null) return cache[index]; - - let maxScore = -Infinity; - let currentSum = 0; - - for (let stones = 1; stones <= 3 && index + stones - 1 < n; stones++) { - currentSum += stoneValue[index + stones - 1]; - const opponentScore = findOptimalScore(index + stones); - maxScore = Math.max(maxScore, currentSum + (index + stones < n ? -opponentScore : 0)); - } - - cache[index] = maxScore; - return maxScore; - } - - const aliceScore = findOptimalScore(0); - if (aliceScore > 0) return 'Alice'; - if (aliceScore < 0) return 'Bob'; - return 'Tie'; -}; diff --git a/solutions/1409-queries-on-a-permutation-with-key.js b/solutions/1409-queries-on-a-permutation-with-key.js deleted file mode 100644 index 518312a8..00000000 --- a/solutions/1409-queries-on-a-permutation-with-key.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1409. Queries on a Permutation With Key - * https://leetcode.com/problems/queries-on-a-permutation-with-key/ - * Difficulty: Medium - * - * Given the array queries of positive integers between 1 and m, you have to process all - * queries[i] (from i=0 to i=queries.length-1) according to the following rules: - * - In the beginning, you have the permutation P=[1,2,3,...,m]. - * - For the current i, find the position of queries[i] in the permutation P (indexing from 0) - * and then move this at the beginning of the permutation P. Notice that the position of - * queries[i] in P is the result for queries[i]. - * - * Return an array containing the result for the given queries. - */ - -/** - * @param {number[]} queries - * @param {number} m - * @return {number[]} - */ -var processQueries = function(queries, m) { - const permutation = Array.from({ length: m }, (_, i) => i + 1); - const result = []; - - for (const query of queries) { - const position = permutation.indexOf(query); - result.push(position); - permutation.splice(position, 1); - permutation.unshift(query); - } - - return result; -}; diff --git a/solutions/1411-number-of-ways-to-paint-n-3-grid.js b/solutions/1411-number-of-ways-to-paint-n-3-grid.js deleted file mode 100644 index e64c367b..00000000 --- a/solutions/1411-number-of-ways-to-paint-n-3-grid.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1411. Number of Ways to Paint N × 3 Grid - * https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/ - * Difficulty: Hard - * - * You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of - * the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the - * same color (i.e., no two cells that share vertical or horizontal sides have the same color). - * - * Given n the number of rows of the grid, return the number of ways you can paint this grid. - * As the answer may grow large, the answer must be computed modulo 109 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -var numOfWays = function(n) { - const MOD = 1000000007n; - let pattern121 = 6n; - let pattern123 = 6n; - - for (let row = 2; row <= n; row++) { - const nextPattern121 = (3n * pattern121 + 2n * pattern123) % MOD; - const nextPattern123 = (2n * pattern121 + 2n * pattern123) % MOD; - pattern121 = nextPattern121; - pattern123 = nextPattern123; - } - - return Number((pattern121 + pattern123) % MOD); -}; diff --git a/solutions/1413-minimum-value-to-get-positive-step-by-step-sum.js b/solutions/1413-minimum-value-to-get-positive-step-by-step-sum.js deleted file mode 100644 index fb8d9b57..00000000 --- a/solutions/1413-minimum-value-to-get-positive-step-by-step-sum.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1413. Minimum Value to Get Positive Step by Step Sum - * https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/ - * Difficulty: Easy - * - * Given an array of integers nums, you start with an initial positive value startValue. - * - * In each iteration, you calculate the step by step sum of startValue plus elements in - * nums (from left to right). - * - * Return the minimum positive value of startValue such that the step by step sum is never - * less than 1. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minStartValue = function(nums) { - let minSum = 0; - let currentSum = 0; - - for (const num of nums) { - currentSum += num; - minSum = Math.min(minSum, currentSum); - } - - return Math.max(1, 1 - minSum); -}; diff --git a/solutions/1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.js b/solutions/1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.js deleted file mode 100644 index b4d4908a..00000000 --- a/solutions/1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K - * https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/ - * Difficulty: Medium - * - * Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. - * The same Fibonacci number can be used multiple times. - * - * The Fibonacci numbers are defined as: - * - F1 = 1 - * - F2 = 1 - * - Fn = Fn-1 + Fn-2 for n > 2. - * - * It is guaranteed that for the given constraints we can always find such Fibonacci numbers - * that sum up to k. - */ - -/** - * @param {number} k - * @return {number} - */ -var findMinFibonacciNumbers = function(k) { - const fibonacci = [1, 1]; - while (fibonacci[fibonacci.length - 1] <= k) { - fibonacci.push(fibonacci[fibonacci.length - 1] + fibonacci[fibonacci.length - 2]); - } - - let count = 0; - let remaining = k; - - for (let i = fibonacci.length - 1; i >= 0 && remaining > 0; i--) { - while (fibonacci[i] <= remaining) { - remaining -= fibonacci[i]; - count++; - } - } - - return count; -}; diff --git a/solutions/1416-restore-the-array.js b/solutions/1416-restore-the-array.js deleted file mode 100644 index 890117d3..00000000 --- a/solutions/1416-restore-the-array.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1416. Restore The Array - * https://leetcode.com/problems/restore-the-array/ - * Difficulty: Hard - * - * A program was supposed to print an array of integers. The program forgot to print whitespaces - * and the array is printed as a string of digits s and all we know is that all integers in the - * array were in the range [1, k] and there are no leading zeros in the array. - * - * Given the string s and the integer k, return the number of the possible arrays that can be - * printed as s using the mentioned program. Since the answer may be very large, return it modulo - * 109 + 7. - */ - -/** - * @param {string} s - * @param {number} k - * @return {number} - */ -function numberOfArrays(s, k) { - const MOD = 1e9 + 7; - const dp = new Array(s.length + 1).fill(0); - dp[0] = 1; - - for (let i = 1; i <= s.length; i++) { - let num = 0; - for (let j = i - 1; j >= Math.max(0, i - String(k).length); j--) { - if (j < 0) break; - num = Number(s[j]) * Math.pow(10, i - j - 1) + num; - if (num <= k && (s[j] !== '0')) { - dp[i] = (dp[i] + dp[j]) % MOD; - } - } - } - - return dp[s.length]; -} diff --git a/solutions/1417-reformat-the-string.js b/solutions/1417-reformat-the-string.js deleted file mode 100644 index 521a4a87..00000000 --- a/solutions/1417-reformat-the-string.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1417. Reformat The String - * https://leetcode.com/problems/reformat-the-string/ - * Difficulty: Easy - * - * You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase - * English letters and digits). - * - * You have to find a permutation of the string where no letter is followed by another letter and - * no digit is followed by another digit. That is, no two adjacent characters have the same type. - * - * Return the reformatted string or return an empty string if it is impossible to reformat the - * string. - */ - -/** - * @param {string} s - * @return {string} - */ -var reformat = function(s) { - const letters = []; - const digits = []; - for (const char of s) { - if (isNaN(char)) { - letters.push(char); - } else { - digits.push(char); - } - } - if (Math.abs(letters.length - digits.length) > 1) { - return ''; - } - const result = []; - const longer = letters.length >= digits.length ? letters : digits; - const shorter = longer === letters ? digits : letters; - for (let i = 0; i < longer.length; i++) { - result.push(longer[i]); - if (i < shorter.length) { - result.push(shorter[i]); - } - } - return result.join(''); -}; diff --git a/solutions/1418-display-table-of-food-orders-in-a-restaurant.js b/solutions/1418-display-table-of-food-orders-in-a-restaurant.js deleted file mode 100644 index 2ce33465..00000000 --- a/solutions/1418-display-table-of-food-orders-in-a-restaurant.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1418. Display Table of Food Orders in a Restaurant - * https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/ - * Difficulty: Medium - * - * Given the array orders, which represents the orders that customers have done in a restaurant. - * More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the - * name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item - * customer orders. - * - * Return the restaurant's “display table”. The “display table” is a table whose row entries - * denote how many of each food item each table ordered. The first column is the table number - * and the remaining columns correspond to each food item in alphabetical order. The first row - * should be a header whose first column is “Table”, followed by the names of the food items. - * Note that the customer names are not part of the table. Additionally, the rows should be - * sorted in numerically increasing order. - */ - -/** - * @param {string[][]} orders - * @return {string[][]} - */ -var displayTable = function(orders) { - const foodItems = new Set(); - const tableOrders = new Map(); - - for (const [, table, item] of orders) { - foodItems.add(item); - const tableMap = tableOrders.get(table) || new Map(); - tableMap.set(item, (tableMap.get(item) || 0) + 1); - tableOrders.set(table, tableMap); - } - - const sortedItems = [...foodItems].sort(); - const header = ['Table', ...sortedItems]; - const result = [header]; - - for (const table of [...tableOrders.keys()].sort((a, b) => a - b)) { - const row = [table]; - const items = tableOrders.get(table); - for (const item of sortedItems) { - row.push(String(items.get(item) || 0)); - } - result.push(row); - } - - return result; -}; diff --git a/solutions/1419-minimum-number-of-frogs-croaking.js b/solutions/1419-minimum-number-of-frogs-croaking.js deleted file mode 100644 index a1b00e6f..00000000 --- a/solutions/1419-minimum-number-of-frogs-croaking.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1419. Minimum Number of Frogs Croaking - * https://leetcode.com/problems/minimum-number-of-frogs-croaking/ - * Difficulty: Medium - * - * You are given the string croakOfFrogs, which represents a combination of the string "croak" - * from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" - * are mixed. - * - * Return the minimum number of different frogs to finish all the croaks in the given string. - * - * A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. - * The frogs have to print all five letters to finish a croak. If the given string is not a - * combination of a valid "croak" return -1. - */ - -/** - * @param {string} croakOfFrogs - * @return {number} - */ -var minNumberOfFrogs = function(croakOfFrogs) { - let activeFrogs = 0; - let maxFrogs = 0; - const counts = { c: 0, r: 0, o: 0, a: 0, k: 0 }; - const order = 'croak'; - - for (const char of croakOfFrogs) { - if (!order.includes(char)) return -1; - counts[char]++; - - if (char === 'c') { - activeFrogs++; - maxFrogs = Math.max(maxFrogs, activeFrogs); - } else if (char === 'k') { - activeFrogs--; - } - - for (let i = 1; i < order.length; i++) { - if (counts[order[i]] > counts[order[i - 1]]) return -1; - } - } - - return activeFrogs === 0 && counts.c === counts.k ? maxFrogs : -1; -}; diff --git a/solutions/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.js b/solutions/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.js deleted file mode 100644 index 405e1b18..00000000 --- a/solutions/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons - * https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/ - * Difficulty: Hard - * - * You are given three integers n, m and k. Consider the following algorithm to find the maximum - * element of an array of positive integers. - * - * You should build the array arr which has the following properties: - * - arr has exactly n integers. - * - 1 <= arr[i] <= m where (0 <= i < n). - * - After applying the mentioned algorithm to arr, the value search_cost is equal to k. - * - * Return the number of ways to build the array arr under the mentioned conditions. As the answer - * may grow large, the answer must be computed modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} m - * @param {number} k - * @return {number} - */ -function numOfArrays(length, maxValue, searchCost) { - const MOD = 1e9 + 7; - const cache = Array.from({ length: length + 1 }, () => - Array.from({ length: maxValue + 1 }, () => - Array(searchCost + 1).fill(-1) - ) - ); - - function computeArrays(pos, currentMax, remainingCost) { - if (pos === length) return remainingCost === 0 ? 1 : 0; - if (remainingCost < 0) return 0; - if (cache[pos][currentMax][remainingCost] !== -1) { - return cache[pos][currentMax][remainingCost]; - } - - let total = 0; - for (let value = 1; value <= currentMax; value++) { - total = (total + computeArrays(pos + 1, currentMax, remainingCost)) % MOD; - } - - if (remainingCost > 0) { - for (let value = currentMax + 1; value <= maxValue; value++) { - total = (total + computeArrays(pos + 1, value, remainingCost - 1)) % MOD; - } - } - - return cache[pos][currentMax][remainingCost] = total; - } - - let result = 0; - for (let value = 1; value <= maxValue; value++) { - result = (result + computeArrays(1, value, searchCost - 1)) % MOD; - } - - return result; -} diff --git a/solutions/1422-maximum-score-after-splitting-a-string.js b/solutions/1422-maximum-score-after-splitting-a-string.js deleted file mode 100644 index 412ea64f..00000000 --- a/solutions/1422-maximum-score-after-splitting-a-string.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1422. Maximum Score After Splitting a String - * https://leetcode.com/problems/maximum-score-after-splitting-a-string/ - * Difficulty: Easy - * - * Given a string s of zeros and ones, return the maximum score after splitting the string into - * two non-empty substrings (i.e. left substring and right substring). - * - * The score after splitting a string is the number of zeros in the left substring plus the number - * of ones in the right substring. - */ - -/** - * @param {string} s - * @return {number} - */ -var maxScore = function(s) { - let rightOnes = s.split('').reduce((count, char) => count + (char === '1'), 0); - let leftZeros = 0; - let result = 0; - - for (let i = 0; i < s.length - 1; i++) { - leftZeros += s[i] === '0'; - rightOnes -= s[i] === '1'; - result = Math.max(result, leftZeros + rightOnes); - } - - return result; -}; diff --git a/solutions/1423-maximum-points-you-can-obtain-from-cards.js b/solutions/1423-maximum-points-you-can-obtain-from-cards.js deleted file mode 100644 index d9f781f3..00000000 --- a/solutions/1423-maximum-points-you-can-obtain-from-cards.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1423. Maximum Points You Can Obtain from Cards - * https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ - * Difficulty: Medium - * - * There are several cards arranged in a row, and each card has an associated number of - * points. The points are given in the integer array cardPoints. - * - * In one step, you can take one card from the beginning or from the end of the row. - * You have to take exactly k cards. - * - * Your score is the sum of the points of the cards you have taken. - * - * Given the integer array cardPoints and the integer k, return the maximum score you can obtain. - */ - -/** - * @param {number[]} cardPoints - * @param {number} k - * @return {number} - */ -var maxScore = function(cardPoints, k) { - const totalLength = cardPoints.length; - const windowSize = totalLength - k; - let windowSum = cardPoints.slice(0, windowSize).reduce((sum, num) => sum + num, 0); - let minWindowSum = windowSum; - const totalSum = cardPoints.reduce((sum, num) => sum + num, 0); - - for (let i = windowSize; i < totalLength; i++) { - windowSum = windowSum + cardPoints[i] - cardPoints[i - windowSize]; - minWindowSum = Math.min(minWindowSum, windowSum); - } - - return totalSum - minWindowSum; -}; diff --git a/solutions/1424-diagonal-traverse-ii.js b/solutions/1424-diagonal-traverse-ii.js deleted file mode 100644 index b7942133..00000000 --- a/solutions/1424-diagonal-traverse-ii.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1424. Diagonal Traverse II - * https://leetcode.com/problems/diagonal-traverse-ii/ - * Difficulty: Medium - * - * Given a 2D integer array nums, return all elements of nums in diagonal order as shown - * in the below images. - */ - -/** - * @param {number[][]} nums - * @return {number[]} - */ -var findDiagonalOrder = function(nums) { - const diagonalGroups = []; - - for (let row = 0; row < nums.length; row++) { - for (let col = 0; col < nums[row].length; col++) { - const sum = row + col; - if (!diagonalGroups[sum]) { - diagonalGroups[sum] = []; - } - diagonalGroups[sum].push(nums[row][col]); - } - } - - const result = []; - for (const group of diagonalGroups) { - if (group) { - result.push(...group.reverse()); - } - } - - return result; -}; diff --git a/solutions/1425-constrained-subsequence-sum.js b/solutions/1425-constrained-subsequence-sum.js deleted file mode 100644 index 7938b2c2..00000000 --- a/solutions/1425-constrained-subsequence-sum.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1425. Constrained Subsequence Sum - * https://leetcode.com/problems/constrained-subsequence-sum/ - * Difficulty: Hard - * - * Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence - * of that array such that for every two consecutive integers in the subsequence, nums[i] and - * nums[j], where i < j, the condition j - i <= k is satisfied. - * - * A subsequence of an array is obtained by deleting some number of elements (can be zero) from the - * array, leaving the remaining elements in their original order. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var constrainedSubsetSum = function(nums, k) { - const maxSums = [...nums]; - const deque = []; - let result = nums[0]; - - for (let i = 0; i < nums.length; i++) { - while (deque.length && deque[0] < i - k) { - deque.shift(); - } - - if (deque.length) { - maxSums[i] = Math.max(maxSums[i], maxSums[deque[0]] + nums[i]); - } - - while (deque.length && maxSums[deque[deque.length - 1]] <= maxSums[i]) { - deque.pop(); - } - - deque.push(i); - result = Math.max(result, maxSums[i]); - } - - return result; -}; diff --git a/solutions/1432-max-difference-you-can-get-from-changing-an-integer.js b/solutions/1432-max-difference-you-can-get-from-changing-an-integer.js deleted file mode 100644 index 0ceef117..00000000 --- a/solutions/1432-max-difference-you-can-get-from-changing-an-integer.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 1432. Max Difference You Can Get From Changing an Integer - * https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/ - * Difficulty: Medium - * - * You are given an integer num. You will apply the following steps exactly two times: - * - Pick a digit x (0 <= x <= 9). - * - Pick another digit y (0 <= y <= 9). The digit y can be equal to x. - * - Replace all the occurrences of x in the decimal representation of num by y. - * - The new integer cannot have any leading zeros, also the new integer cannot be 0. - * - * Let a and b be the results of applying the operations to num the first and second times, - * respectively. - * - * Return the max difference between a and b. - */ - -/** - * @param {number} num - * @return {number} - */ -var maxDiff = function(num) { - const digits = num.toString().split(''); - - const maxNum = digits.slice(); - for (let i = 0; i < maxNum.length; i++) { - if (maxNum[i] !== '9') { - const target = maxNum[i]; - for (let j = i; j < maxNum.length; j++) { - if (maxNum[j] === target) { - maxNum[j] = '9'; - } - } - break; - } - } - - const minNum = digits.slice(); - if (minNum[0] !== '1') { - const target = minNum[0]; - for (let j = 0; j < minNum.length; j++) { - if (minNum[j] === target) { - minNum[j] = '1'; - } - } - } else { - for (let i = 1; i < minNum.length; i++) { - if (minNum[i] !== '0' && minNum[i] !== '1') { - const target = minNum[i]; - for (let j = i; j < minNum.length; j++) { - if (minNum[j] === target) { - minNum[j] = '0'; - } - } - break; - } - } - } - - return parseInt(maxNum.join('')) - parseInt(minNum.join('')); -}; diff --git a/solutions/1433-check-if-a-string-can-break-another-string.js b/solutions/1433-check-if-a-string-can-break-another-string.js deleted file mode 100644 index c045db4f..00000000 --- a/solutions/1433-check-if-a-string-can-break-another-string.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1433. Check If a String Can Break Another String - * https://leetcode.com/problems/check-if-a-string-can-break-another-string/ - * Difficulty: Medium - * - * Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can - * break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. - * - * A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all - * i between 0 and n-1. - */ - -/** - * @param {string} s1 - * @param {string} s2 - * @return {boolean} - */ -var checkIfCanBreak = function(s1, s2) { - const sorted1 = s1.split('').sort(); - const sorted2 = s2.split('').sort(); - - let canBreak1 = true; - let canBreak2 = true; - - for (let i = 0; i < s1.length; i++) { - if (sorted1[i] < sorted2[i]) { - canBreak1 = false; - } - if (sorted2[i] < sorted1[i]) { - canBreak2 = false; - } - } - - return canBreak1 || canBreak2; -}; diff --git a/solutions/1434-number-of-ways-to-wear-different-hats-to-each-other.js b/solutions/1434-number-of-ways-to-wear-different-hats-to-each-other.js deleted file mode 100644 index 70f70a1c..00000000 --- a/solutions/1434-number-of-ways-to-wear-different-hats-to-each-other.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 1434. Number of Ways to Wear Different Hats to Each Other - * https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/ - * Difficulty: Hard - * - * There are n people and 40 types of hats labeled from 1 to 40. - * - * Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person. - * - * Return the number of ways that n people can wear different hats from each other. - * - * Since the answer may be too large, return it modulo 109 + 7. - */ - -/** - * @param {number[][]} hats - * @return {number} - */ -var numberWays = function(hats) { - const MOD = 1e9 + 7; - const hatToPeople = Array(41).fill().map(() => []); - const cache = new Map(); - - for (let person = 0; person < hats.length; person++) { - for (const hat of hats[person]) { - hatToPeople[hat].push(person); - } - } - - function assignHats(hat, usedMask) { - if (hat > 40) { - return usedMask === (1 << hats.length) - 1 ? 1 : 0; - } - - const key = `${hat}:${usedMask}`; - if (cache.has(key)) { - return cache.get(key); - } - - let ways = assignHats(hat + 1, usedMask); - - for (const person of hatToPeople[hat]) { - if (!(usedMask & (1 << person))) { - ways = (ways + assignHats(hat + 1, usedMask | (1 << person))) % MOD; - } - } - - cache.set(key, ways); - return ways; - } - - return assignHats(1, 0); -}; diff --git a/solutions/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js b/solutions/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js deleted file mode 100644 index dd9aeb73..00000000 --- a/solutions/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit - * https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ - * Difficulty: Medium - * - * Given an array of integers nums and an integer limit, return the size of the longest non-empty - * subarray such that the absolute difference between any two elements of this subarray is less than - * or equal to limit. - */ - -/** - * @param {number[]} nums - * @param {number} limit - * @return {number} - */ -var longestSubarray = function(nums, limit) { - const maxDeque = []; - const minDeque = []; - let result = 0; - let left = 0; - - for (let right = 0; right < nums.length; right++) { - while (maxDeque.length && nums[maxDeque[maxDeque.length - 1]] <= nums[right]) { - maxDeque.pop(); - } - maxDeque.push(right); - - while (minDeque.length && nums[minDeque[minDeque.length - 1]] >= nums[right]) { - minDeque.pop(); - } - minDeque.push(right); - - while (nums[maxDeque[0]] - nums[minDeque[0]] > limit) { - if (maxDeque[0] < minDeque[0]) { - left = maxDeque.shift() + 1; - } else { - left = minDeque.shift() + 1; - } - } - - result = Math.max(result, right - left + 1); - } - - return result; -}; diff --git a/solutions/1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.js b/solutions/1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.js deleted file mode 100644 index 79b54852..00000000 --- a/solutions/1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows - * https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/ - * Difficulty: Hard - * - * You are given an m x n matrix mat that has its rows sorted in non-decreasing order and - * an integer k. - * - * You are allowed to choose exactly one element from each row to form an array. - * - * Return the kth smallest array sum among all possible arrays. - */ - -/** - * @param {number[][]} mat - * @param {number} k - * @return {number} - */ -var kthSmallest = function(mat, k) { - let sums = [0]; - const rows = mat.length; - - for (let row = 0; row < rows; row++) { - const nextSums = []; - for (const prevSum of sums) { - for (const num of mat[row]) { - nextSums.push(prevSum + num); - } - } - sums = nextSums.sort((a, b) => a - b).slice(0, Math.min(k, nextSums.length)); - } - - return sums[k - 1]; -}; diff --git a/solutions/1441-build-an-array-with-stack-operations.js b/solutions/1441-build-an-array-with-stack-operations.js deleted file mode 100644 index f961b9be..00000000 --- a/solutions/1441-build-an-array-with-stack-operations.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1441. Build an Array With Stack Operations - * https://leetcode.com/problems/build-an-array-with-stack-operations/ - * Difficulty: Medium - * - * You are given an integer array target and an integer n. - * - * You have an empty stack with the two following operations: - * - "Push": pushes an integer to the top of the stack. - * - "Pop": removes the integer on the top of the stack. - * - * You also have a stream of the integers in the range [1, n]. - * - * Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal - * to target. You should follow the following rules: - * - If the stream of the integers is not empty, pick the next integer from the stream and push it - * to the top of the stack. - * - If the stack is not empty, pop the integer at the top of the stack. - * - If, at any moment, the elements in the stack (from the bottom to the top) are equal to target, - * do not read new integers from the stream and do not do more operations on the stack. - * - * Return the stack operations needed to build target following the mentioned rules. If there are - * multiple valid answers, return any of them. - */ - -/** - * @param {number[]} target - * @param {number} n - * @return {string[]} - */ -var buildArray = function(target, n) { - const result = []; - let current = 1; - - for (const num of target) { - while (current < num) { - result.push('Push'); - result.push('Pop'); - current++; - } - result.push('Push'); - current++; - } - - return result; -}; diff --git a/solutions/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.js b/solutions/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.js deleted file mode 100644 index 2ff05e2b..00000000 --- a/solutions/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1442. Count Triplets That Can Form Two Arrays of Equal XOR - * https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/ - * Difficulty: Medium - * - * Given an array of integers arr. - * - * We want to select three indices i, j and k where (0 <= i < j <= k < arr.length). - * - * Let's define a and b as follows: - * - a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1] - * - b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k] - * - * Note that ^ denotes the bitwise-xor operation. - * - * Return the number of triplets (i, j and k) Where a == b. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var countTriplets = function(arr) { - const prefixXor = [0]; - let result = 0; - - for (const num of arr) { - prefixXor.push(prefixXor[prefixXor.length - 1] ^ num); - } - - for (let i = 0; i < arr.length; i++) { - for (let k = i + 1; k < arr.length; k++) { - if ((prefixXor[k + 1] ^ prefixXor[i]) === 0) { - result += k - i; - } - } - } - - return result; -}; diff --git a/solutions/1444-number-of-ways-of-cutting-a-pizza.js b/solutions/1444-number-of-ways-of-cutting-a-pizza.js deleted file mode 100644 index 6ccd96bf..00000000 --- a/solutions/1444-number-of-ways-of-cutting-a-pizza.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 1444. Number of Ways of Cutting a Pizza - * https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ - * Difficulty: Hard - * - * Given a rectangular pizza represented as a rows x cols matrix containing the following - * characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut - * the pizza into k pieces using k-1 cuts. - * - * For each cut you choose the direction: vertical or horizontal, then you choose a cut - * position at the cell boundary and cut the pizza into two pieces. If you cut the pizza - * vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, - * give the upper part of the pizza to a person. Give the last piece of pizza to the last person. - * - * Return the number of ways of cutting the pizza such that each piece contains at least one apple. - * Since the answer can be a huge number, return this modulo 10^9 + 7. - */ - -/** - * @param {string[]} pizza - * @param {number} k - * @return {number} - */ -var ways = function(pizza, k) { - const MOD = 1e9 + 7; - const rows = pizza.length; - const cols = pizza[0].length; - const appleCount = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0)); - const dpCache = new Array(rows + 1).fill().map(() => - new Array(cols + 1).fill().map(() => new Array(k + 1).fill(-1)) - ); - - for (let i = rows - 1; i >= 0; i--) { - for (let j = cols - 1; j >= 0; j--) { - appleCount[i][j] = (pizza[i][j] === 'A' ? 1 : 0) - + appleCount[i + 1][j] + appleCount[i][j + 1] - appleCount[i + 1][j + 1]; - } - } - - return countWays(0, 0, k - 1); - - function countWays(row, col, cutsLeft) { - if (appleCount[row][col] === 0) return 0; - if (cutsLeft === 0) return 1; - if (dpCache[row][col][cutsLeft] !== -1) return dpCache[row][col][cutsLeft]; - - let result = 0; - - for (let i = row + 1; i < rows; i++) { - if (appleCount[row][col] - appleCount[i][col] > 0) { - result = (result + countWays(i, col, cutsLeft - 1)) % MOD; - } - } - - for (let j = col + 1; j < cols; j++) { - if (appleCount[row][col] - appleCount[row][j] > 0) { - result = (result + countWays(row, j, cutsLeft - 1)) % MOD; - } - } - - dpCache[row][col][cutsLeft] = result; - return result; - } -}; diff --git a/solutions/1449-form-largest-integer-with-digits-that-add-up-to-target.js b/solutions/1449-form-largest-integer-with-digits-that-add-up-to-target.js deleted file mode 100644 index 03ad2db3..00000000 --- a/solutions/1449-form-largest-integer-with-digits-that-add-up-to-target.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1449. Form Largest Integer With Digits That Add up to Target - * https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/ - * Difficulty: Hard - * - * Given an array of integers cost and an integer target, return the maximum integer you can - * paint under the following rules: - * - The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). - * - The total cost used must be equal to target. - * - The integer does not have 0 digits. - * - * Since the answer may be very large, return it as a string. If there is no way to paint any - * integer given the condition, return "0". - */ - -/** - * @param {number[]} cost - * @param {number} target - * @return {string} - */ -var largestNumber = function(cost, target) { - const maxDigits = new Array(target + 1).fill('0'); - maxDigits[0] = ''; - - for (let current = 1; current <= target; current++) { - for (let digit = 1; digit <= 9; digit++) { - const prev = current - cost[digit - 1]; - if (prev >= 0 && maxDigits[prev] !== '0') { - const candidate = digit + maxDigits[prev]; - if (candidate.length > maxDigits[current].length - || (candidate.length === maxDigits[current].length && candidate > maxDigits[current])) { - maxDigits[current] = candidate; - } - } - } - } - - return maxDigits[target]; -}; diff --git a/solutions/1452-people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list.js b/solutions/1452-people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list.js deleted file mode 100644 index 26391c94..00000000 --- a/solutions/1452-people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1452. People Whose List of Favorite Companies Is Not a Subset of Another List - * https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/ - * Difficulty: Medium - * - * Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies - * for the ith person (indexed from 0). - * - * Return the indices of people whose list of favorite companies is not a subset of any other list - * of favorites companies. You must return the indices in increasing order. - */ - -/** - * @param {string[][]} favoriteCompanies - * @return {number[]} - */ -var peopleIndexes = function(favoriteCompanies) { - const companySets = favoriteCompanies.map(companies => new Set(companies)); - const result = []; - - for (let i = 0; i < favoriteCompanies.length; i++) { - let isSubset = false; - for (let j = 0; j < favoriteCompanies.length; j++) { - if (i !== j && isSubsetOf(companySets[i], companySets[j])) { - isSubset = true; - break; - } - } - if (!isSubset) { - result.push(i); - } - } - - return result; - - function isSubsetOf(setA, setB) { - if (setA.size > setB.size) return false; - for (const item of setA) { - if (!setB.has(item)) return false; - } - return true; - } -}; diff --git a/solutions/1453-maximum-number-of-darts-inside-of-a-circular-dartboard.js b/solutions/1453-maximum-number-of-darts-inside-of-a-circular-dartboard.js deleted file mode 100644 index 02becdec..00000000 --- a/solutions/1453-maximum-number-of-darts-inside-of-a-circular-dartboard.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1453. Maximum Number of Darts Inside of a Circular Dartboard - * https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/ - * Difficulty: Hard - * - * Alice is throwing n darts on a very large wall. You are given an array darts where - * darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. - * - * Bob knows the positions of the n darts on the wall. He wants to place a dartboard of - * radius r on the wall so that the maximum number of darts that Alice throws lie on the - * dartboard. - * - * Given the integer r, return the maximum number of darts that can lie on the dartboard. - */ - -/** - * @param {number[][]} darts - * @param {number} r - * @return {number} - */ -var numPoints = function(darts, r) { - let maxDarts = 1; - const n = darts.length; - const radiusSquared = r * r; - - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - const dx = darts[j][0] - darts[i][0]; - const dy = darts[j][1] - darts[i][1]; - const distSquared = dx * dx + dy * dy; - - if (distSquared > 4 * radiusSquared + 1e-8) continue; - - const midX = (darts[i][0] + darts[j][0]) / 2; - const midY = (darts[i][1] + darts[j][1]) / 2; - - if (distSquared < 1e-8) continue; - - const dist = Math.sqrt(distSquared) / 2; - const height = Math.sqrt(radiusSquared - dist * dist); - - let perpX = -dy; - let perpY = dx; - const norm = Math.sqrt(perpX * perpX + perpY * perpY); - perpX /= norm; - perpY /= norm; - - const count1 = countDartsInCircle(darts, midX + height * perpX, midY + height * perpY, r); - const count2 = countDartsInCircle(darts, midX - height * perpX, midY - height * perpY, r); - - maxDarts = Math.max(maxDarts, count1, count2); - } - } - - return maxDarts; - - function countDartsInCircle(darts, centerX, centerY, r) { - let count = 0; - const radiusSquared = r * r; - - for (const dart of darts) { - const dx = dart[0] - centerX; - const dy = dart[1] - centerY; - if (dx * dx + dy * dy <= radiusSquared + 1e-8) { - count++; - } - } - - return count; - } -}; diff --git a/solutions/1457-pseudo-palindromic-paths-in-a-binary-tree.js b/solutions/1457-pseudo-palindromic-paths-in-a-binary-tree.js deleted file mode 100644 index f6836e69..00000000 --- a/solutions/1457-pseudo-palindromic-paths-in-a-binary-tree.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1457. Pseudo-Palindromic Paths in a Binary Tree - * https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/ - * Difficulty: Medium - * - * Given a binary tree where node values are digits from 1 to 9. A path in the binary tree - * is said to be pseudo-palindromic if at least one permutation of the node values in the - * path is a palindrome. - * - * Return the number of pseudo-palindromic paths going from the root node to leaf nodes. - */ - -/** - * 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 pseudoPalindromicPaths = function(root) { - const frequency = new Array(10).fill(0); - let count = 0; - - traverse(root); - - return count; - - function traverse(node) { - if (!node) return; - - frequency[node.val]++; - - if (!node.left && !node.right) { - let oddCount = 0; - for (let i = 1; i <= 9; i++) { - if (frequency[i] % 2 !== 0) oddCount++; - } - if (oddCount <= 1) count++; - } - - traverse(node.left); - traverse(node.right); - - frequency[node.val]--; - } -}; diff --git a/solutions/1458-max-dot-product-of-two-subsequences.js b/solutions/1458-max-dot-product-of-two-subsequences.js deleted file mode 100644 index b3669b44..00000000 --- a/solutions/1458-max-dot-product-of-two-subsequences.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1458. Max Dot Product of Two Subsequences - * https://leetcode.com/problems/max-dot-product-of-two-subsequences/ - * Difficulty: Hard - * - * Given two arrays nums1 and nums2. - * - * Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the - * same length. - * - * A subsequence of a array is a new array which is formed from the original array by deleting - * some (can be none) of the characters without disturbing the relative positions of the remaining - * characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var maxDotProduct = function(nums1, nums2) { - const m = nums1.length; - const n = nums2.length; - const dp = new Array(m + 1).fill().map(() => new Array(n + 1).fill(-Infinity)); - - let result = -Infinity; - for (let i = 1; i <= m; i++) { - for (let j = 1; j <= n; j++) { - result = Math.max(result, computeMax(i, j)); - } - } - - return result; - - function computeMax(i, j) { - if (i === 0 || j === 0) return -Infinity; - if (dp[i][j] !== -Infinity) return dp[i][j]; - - dp[i][j] = nums1[i - 1] * nums2[j - 1]; - dp[i][j] = Math.max( - dp[i][j], - dp[i][j] + computeMax(i - 1, j - 1), - computeMax(i - 1, j), - computeMax(i, j - 1) - ); - - return dp[i][j]; - } -}; diff --git a/solutions/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js b/solutions/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js deleted file mode 100644 index bf12f5b1..00000000 --- a/solutions/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 1461. Check If a String Contains All Binary Codes of Size K - * https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ - * Difficulty: Medium - * - * Given a binary string s and an integer k, return true if every binary code of length k is a - * substring of s. Otherwise, return false. - */ - -/** - * @param {string} s - * @param {number} k - * @return {boolean} - */ -var hasAllCodes = function(s, k) { - const requiredCount = 1 << k; - const seenCodes = new Set(); - - for (let i = 0; i <= s.length - k; i++) { - seenCodes.add(s.slice(i, i + k)); - if (seenCodes.size === requiredCount) return true; - } - - return false; -}; diff --git a/solutions/1463-cherry-pickup-ii.js b/solutions/1463-cherry-pickup-ii.js deleted file mode 100644 index 498decc9..00000000 --- a/solutions/1463-cherry-pickup-ii.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1463. Cherry Pickup II - * https://leetcode.com/problems/cherry-pickup-ii/ - * Difficulty: Hard - * - * You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] - * represents the number of cherries that you can collect from the (i, j) cell. - * - * You have two robots that can collect cherries for you: - * - Robot #1 is located at the top-left corner (0, 0), and - * - Robot #2 is located at the top-right corner (0, cols - 1). - * - * Return the maximum number of cherries collection using both robots by following the rules below: - * - From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1). - * - When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty - * cell. - * - When both robots stay in the same cell, only one takes the cherries. - * - Both robots cannot move outside of the grid at any moment. - * - Both robots should reach the bottom row in grid. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var cherryPickup = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const cache = new Array(rows).fill().map(() => { - return new Array(cols).fill().map(() => new Array(cols).fill(-1)); - }); - - return Math.max(0, findMaxCherries(0, 0, cols - 1)); - - function findMaxCherries(row, col1, col2) { - if (row === rows || col1 < 0 || col1 >= cols || col2 < 0 || col2 >= cols) { - return -Infinity; - } - if (cache[row][col1][col2] !== -1) { - return cache[row][col1][col2]; - } - - const cherries = col1 === col2 ? grid[row][col1] : grid[row][col1] + grid[row][col2]; - - if (row === rows - 1) { - return cherries; - } - - let maxCherries = -Infinity; - for (const nextCol1 of [col1 - 1, col1, col1 + 1]) { - for (const nextCol2 of [col2 - 1, col2, col2 + 1]) { - maxCherries = Math.max(maxCherries, findMaxCherries(row + 1, nextCol1, nextCol2)); - } - } - - cache[row][col1][col2] = cherries + maxCherries; - return cache[row][col1][col2]; - } -}; diff --git a/solutions/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.js b/solutions/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.js deleted file mode 100644 index 2bfc7f78..00000000 --- a/solutions/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts - * https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/ - * Difficulty: Medium - * - * You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and - * verticalCuts where: - * - horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal - * cut and similarly, and - * - verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut. - * - * Return the maximum area of a piece of cake after you cut at each horizontal and vertical position - * provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, - * return this modulo 109 + 7. - */ - -/** - * @param {number} h - * @param {number} w - * @param {number[]} horizontalCuts - * @param {number[]} verticalCuts - * @return {number} - */ -var maxArea = function(h, w, horizontalCuts, verticalCuts) { - horizontalCuts.sort((a, b) => a - b); - verticalCuts.sort((a, b) => a - b); - - let maxHeight = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length - 1]); - let maxWidth = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length - 1]); - - for (let i = 1; i < horizontalCuts.length; i++) { - maxHeight = Math.max(maxHeight, horizontalCuts[i] - horizontalCuts[i - 1]); - } - for (let i = 1; i < verticalCuts.length; i++) { - maxWidth = Math.max(maxWidth, verticalCuts[i] - verticalCuts[i - 1]); - } - - return Number((BigInt(maxHeight) * BigInt(maxWidth)) % BigInt(1000000007)); -}; diff --git a/solutions/1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls.js b/solutions/1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls.js deleted file mode 100644 index a3a3be00..00000000 --- a/solutions/1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls - * https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/ - * Difficulty: Hard - * - * Given 2n balls of k distinct colors. You will be given an integer array balls of size k where - * balls[i] is the number of balls of color i. - * - * All the balls will be shuffled uniformly at random, then we will distribute the first n balls to - * the first box and the remaining n balls to the other box (Please read the explanation of the - * second example carefully). - * - * Please note that the two boxes are considered different. For example, if we have two balls of - * colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different - * than the distribution [b] (a) (Please read the explanation of the first example carefully). - * - * Return the probability that the two boxes have the same number of distinct balls. Answers - * within 10-5 of the actual value will be accepted as correct. - */ - -/** - * @param {number[]} balls - * @return {number} - */ -var getProbability = function(balls) { - const totalBalls = balls.reduce((sum, count) => sum + count, 0); - const halfBalls = totalBalls / 2; - let validCombinations = 0; - let totalCombinations = 0; - - calculateCombinations(0, new Array(balls.length).fill(0), halfBalls, 0); - return validCombinations / totalCombinations; - - function countDistinct(config) { - return config.filter(count => count > 0).length; - } - - function calculateCombinations(index, config, remaining, firstBoxCount) { - if (index === balls.length) { - if (firstBoxCount === halfBalls) { - const secondBox = balls.map((count, i) => count - config[i]); - if (countDistinct(config) === countDistinct(secondBox)) { - validCombinations += combinatorialProduct(config) * combinatorialProduct(secondBox); - } - totalCombinations += combinatorialProduct(config) * combinatorialProduct(secondBox); - } - return; - } - - for (let i = 0; i <= balls[index] && firstBoxCount + i <= halfBalls; i++) { - if (remaining >= i) { - config[index] = i; - calculateCombinations(index + 1, config, remaining - i, firstBoxCount + i); - config[index] = 0; - } - } - } - - function combinatorialProduct(config) { - const numerator = factorial(halfBalls); - let denominator = 1; - for (const count of config) { - denominator *= factorial(count); - } - return numerator / denominator; - } - - function factorial(n) { - let result = 1; - for (let i = 2; i <= n; i++) { - result *= i; - } - return result; - } -}; diff --git a/solutions/1471-the-k-strongest-values-in-an-array.js b/solutions/1471-the-k-strongest-values-in-an-array.js deleted file mode 100644 index b7128df9..00000000 --- a/solutions/1471-the-k-strongest-values-in-an-array.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1471. The k Strongest Values in an Array - * https://leetcode.com/problems/the-k-strongest-values-in-an-array/ - * Difficulty: Medium - * - * Given an array of integers arr and an integer k. - * - * A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| - * where m is the centre of the array. - * - * If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] - * if arr[i] > arr[j]. - * - * Return a list of the strongest k values in the array. return the answer in any arbitrary order. - * - * The centre is the middle value in an ordered integer list. More formally, if the length of the - * list is n, the centre is the element in position ((n - 1) / 2) in the sorted list (0-indexed). - * - For arr = [6, -3, 7, 2, 11], n = 5 and the centre is obtained by sorting the array - * arr = [-3, 2, 6, 7, 11] and the centre is arr[m] where m = ((5 - 1) / 2) = 2. The centre is 6. - * - For arr = [-7, 22, 17, 3], n = 4 and the centre is obtained by sorting the array - * arr = [-7, 3, 17, 22] and the centre is arr[m] where m = ((4 - 1) / 2) = 1. The centre is 3. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {number[]} - */ -var getStrongest = function(arr, k) { - const sorted = arr.slice().sort((a, b) => a - b); - const centre = sorted[Math.floor((sorted.length - 1) / 2)]; - - return arr.sort((a, b) => { - const diffA = Math.abs(a - centre); - const diffB = Math.abs(b - centre); - return diffA === diffB ? b - a : diffB - diffA; - }).slice(0, k); -}; diff --git a/solutions/1473-paint-house-iii.js b/solutions/1473-paint-house-iii.js deleted file mode 100644 index 272cf274..00000000 --- a/solutions/1473-paint-house-iii.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1473. Paint House III - * https://leetcode.com/problems/paint-house-iii/ - * Difficulty: Hard - * - * There is a row of m houses in a small city, each house must be painted with one of the n - * colors (labeled from 1 to n), some houses that have been painted last summer should not - * be painted again. - * - * A neighborhood is a maximal group of continuous houses that are painted with the same color. - * - * For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. - * - * Given an array houses, an m x n matrix cost and an integer target where: - * - houses[i]: is the color of the house i, and 0 if the house is not painted yet. - * - cost[i][j]: is the cost of paint the house i with the color j + 1. - * - * Return the minimum cost of painting all the remaining houses in such a way that there are exactly - * target neighborhoods. If it is not possible, return -1. - */ - -/** - * @param {number[]} houses - * @param {number[][]} cost - * @param {number} m - * @param {number} n - * @param {number} target - * @return {number} - */ -var minCost = function(houses, cost, m, n, target) { - const cache = new Map(); - const result = findMinCost(0, 0, 0); - return result === Infinity ? -1 : result; - - function findMinCost(index, prevColor, neighborhoods) { - if (index === m) return neighborhoods === target ? 0 : Infinity; - if (neighborhoods > target) return Infinity; - - const key = `${index}:${prevColor}:${neighborhoods}`; - if (cache.has(key)) return cache.get(key); - - let minCost = Infinity; - const currentColor = houses[index]; - - if (currentColor !== 0) { - const newNeighborhoods = prevColor === currentColor ? neighborhoods : neighborhoods + 1; - minCost = findMinCost(index + 1, currentColor, newNeighborhoods); - } else { - for (let color = 1; color <= n; color++) { - const newNeighborhoods = prevColor === color ? neighborhoods : neighborhoods + 1; - const currentCost = cost[index][color - 1] - + findMinCost(index + 1, color, newNeighborhoods); - minCost = Math.min(minCost, currentCost); - } - } - - cache.set(key, minCost); - return minCost; - } -}; diff --git a/solutions/1476-subrectangle-queries.js b/solutions/1476-subrectangle-queries.js deleted file mode 100644 index 732d42a4..00000000 --- a/solutions/1476-subrectangle-queries.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1476. Subrectangle Queries - * https://leetcode.com/problems/subrectangle-queries/ - * Difficulty: Medium - * - * Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix - * of integers in the constructor and supports two methods: - * 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) - * - Updates all values with newValue in the subrectangle whose upper left coordinate is - * (row1,col1) and bottom right coordinate is (row2,col2). - * 2. getValue(int row, int col) - * - * Returns the current value of the coordinate (row,col) from the rectangle. - */ - -/** - * @param {number[][]} rectangle - */ -var SubrectangleQueries = function(rectangle) { - this.grid = rectangle.map(row => [...row]); -}; - -/** - * @param {number} row1 - * @param {number} col1 - * @param {number} row2 - * @param {number} col2 - * @param {number} newValue - * @return {void} - */ -SubrectangleQueries.prototype.updateSubrectangle = function(row1, col1, row2, col2, newValue) { - for (let i = row1; i <= row2; i++) { - for (let j = col1; j <= col2; j++) { - this.grid[i][j] = newValue; - } - } -}; - -/** - * @param {number} row - * @param {number} col - * @return {number} - */ -SubrectangleQueries.prototype.getValue = function(row, col) { - return this.grid[row][col]; -}; diff --git a/solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js b/solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js deleted file mode 100644 index da521439..00000000 --- a/solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum - * https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/ - * Difficulty: Medium - * - * You are given an array of integers arr and an integer target. - * - * You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There - * can be multiple answers so you have to find an answer where the sum of the lengths of the - * two sub-arrays is minimum. - * - * Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you - * cannot find such two sub-arrays. - */ - -/** - * @param {number[]} arr - * @param {number} target - * @return {number} - */ -var minSumOfLengths = function(arr, target) { - const prefixSums = new Map([[0, -1]]); - let currentSum = 0; - let minLength = Infinity; - const minLengths = new Array(arr.length).fill(Infinity); - let result = Infinity; - - for (let i = 0; i < arr.length; i++) { - currentSum += arr[i]; - if (prefixSums.has(currentSum - target)) { - const start = prefixSums.get(currentSum - target); - const length = i - start; - minLength = Math.min(minLength, length); - if (start >= 0 && minLengths[start] !== Infinity) { - result = Math.min(result, length + minLengths[start]); - } - } - minLengths[i] = minLength; - prefixSums.set(currentSum, i); - } - - return result === Infinity ? -1 : result; -}; diff --git a/solutions/1478-allocate-mailboxes.js b/solutions/1478-allocate-mailboxes.js deleted file mode 100644 index 105a5506..00000000 --- a/solutions/1478-allocate-mailboxes.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1478. Allocate Mailboxes - * https://leetcode.com/problems/allocate-mailboxes/ - * Difficulty: Hard - * - * Given the array houses where houses[i] is the location of the ith house along a street and - * an integer k, allocate k mailboxes in the street. - * - * Return the minimum total distance between each house and its nearest mailbox. - * - * The test cases are generated so that the answer fits in a 32-bit integer. - */ - -/** - * @param {number[]} houses - * @param {number} k - * @return {number} - */ -var minDistance = function(houses, k) { - houses.sort((a, b) => a - b); - const n = houses.length; - const cache = new Map(); - - return findMinDistance(0, k); - - function medianDistance(start, end) { - let sum = 0; - const mid = Math.floor((start + end) / 2); - for (let i = start; i <= end; i++) { - sum += Math.abs(houses[i] - houses[mid]); - } - return sum; - } - - function findMinDistance(index, mailboxes) { - if (index === n) return mailboxes === 0 ? 0 : Infinity; - if (mailboxes === 0) return Infinity; - - const key = `${index}:${mailboxes}`; - if (cache.has(key)) return cache.get(key); - - let minDist = Infinity; - for (let j = index; j < n && n - j >= mailboxes; j++) { - const distance = medianDistance(index, j) + findMinDistance(j + 1, mailboxes - 1); - minDist = Math.min(minDist, distance); - } - - cache.set(key, minDist); - return minDist; - } -}; diff --git a/solutions/1482-minimum-number-of-days-to-make-m-bouquets.js b/solutions/1482-minimum-number-of-days-to-make-m-bouquets.js deleted file mode 100644 index e91f509f..00000000 --- a/solutions/1482-minimum-number-of-days-to-make-m-bouquets.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1482. Minimum Number of Days to Make m Bouquets - * https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/ - * Difficulty: Medium - * - * You are given an integer array bloomDay, an integer m and an integer k. - * - * You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the - * garden. - * - * The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be - * used in exactly one bouquet. - * - * Return the minimum number of days you need to wait to be able to make m bouquets from the garden. - * If it is impossible to make m bouquets return -1. - */ - -/** - * @param {number[]} bloomDay - * @param {number} m - * @param {number} k - * @return {number} - */ -var minDays = function(bloomDay, m, k) { - if (m * k > bloomDay.length) return -1; - - let left = 1; - let right = Math.max(...bloomDay); - let result = -1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (canMakeBouquets(mid)) { - result = mid; - right = mid - 1; - } else { - left = mid + 1; - } - } - - return result; - - function canMakeBouquets(days) { - let bouquets = 0; - let flowers = 0; - for (const bloom of bloomDay) { - if (bloom <= days) { - flowers++; - if (flowers === k) { - bouquets++; - flowers = 0; - } - } else { - flowers = 0; - } - } - return bouquets >= m; - } -}; diff --git a/solutions/1483-kth-ancestor-of-a-tree-node.js b/solutions/1483-kth-ancestor-of-a-tree-node.js deleted file mode 100644 index 55a281ca..00000000 --- a/solutions/1483-kth-ancestor-of-a-tree-node.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 1483. Kth Ancestor of a Tree Node - * https://leetcode.com/problems/kth-ancestor-of-a-tree-node/ - * Difficulty: Hard - * - * You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array - * parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the - * kth ancestor of a given node. - * - * The kth ancestor of a tree node is the kth node in the path from that node to the root node. - * - * Implement the TreeAncestor class: - * - TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree - * and the parent array. - * - int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there - * is no such ancestor, return -1. - */ - -/** - * @param {number} n - * @param {number[]} parent - */ -var TreeAncestor = function(n, parent) { - const maxDepth = Math.ceil(Math.log2(n)); - this.ancestors = Array.from({ length: n }, () => new Array(maxDepth + 1).fill(-1)); - - for (let i = 0; i < n; i++) { - this.ancestors[i][0] = parent[i]; - } - - for (let j = 1; j <= maxDepth; j++) { - for (let i = 0; i < n; i++) { - if (this.ancestors[i][j - 1] !== -1) { - this.ancestors[i][j] = this.ancestors[this.ancestors[i][j - 1]][j - 1]; - } - } - } -}; - -/** - * @param {number} node - * @param {number} k - * @return {number} - */ -TreeAncestor.prototype.getKthAncestor = function(node, k) { - let current = node; - for (let j = 0; k > 0 && current !== -1; j++, k >>= 1) { - if (k & 1) { - current = this.ancestors[current][j]; - } - } - return current; -}; diff --git a/solutions/1487-making-file-names-unique.js b/solutions/1487-making-file-names-unique.js deleted file mode 100644 index 9ac5746f..00000000 --- a/solutions/1487-making-file-names-unique.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1487. Making File Names Unique - * https://leetcode.com/problems/making-file-names-unique/ - * Difficulty: Medium - * - * Given an array of strings names of size n. You will create n folders in your file system such - * that, at the ith minute, you will create a folder with the name names[i]. - * - * Since two files cannot have the same name, if you enter a folder name that was previously used, - * the system will have a suffix addition to its name in the form of (k), where, k is the smallest - * positive integer such that the obtained name remains unique. - * - * Return an array of strings of length n where ans[i] is the actual name the system will assign - * to the ith folder when you create it. - */ - -/** - * @param {string[]} names - * @return {string[]} - */ -var getFolderNames = function(names) { - const map = new Map(); - const result = []; - - for (const name of names) { - if (!map.has(name)) { - result.push(name); - map.set(name, 1); - } else { - let suffix = map.get(name); - let newName = `${name}(${suffix})`; - while (map.has(newName)) { - suffix++; - newName = `${name}(${suffix})`; - } - result.push(newName); - map.set(name, suffix + 1); - map.set(newName, 1); - } - } - - return result; -}; diff --git a/solutions/1488-avoid-flood-in-the-city.js b/solutions/1488-avoid-flood-in-the-city.js deleted file mode 100644 index e433b2c0..00000000 --- a/solutions/1488-avoid-flood-in-the-city.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 1488. Avoid Flood in The City - * https://leetcode.com/problems/avoid-flood-in-the-city/ - * Difficulty: Medium - * - * Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it - * rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is - * full of water, there will be a flood. Your goal is to avoid floods in any lake. - * - * Given an integer array rains where: - * - rains[i] > 0 means there will be rains over the rains[i] lake. - * - rains[i] == 0 means there are no rains this day and you can choose one lake this day and - * dry it. - * - * Return an array ans where: - * - ans.length == rains.length - * - ans[i] == -1 if rains[i] > 0. - * - ans[i] is the lake you choose to dry in the ith day if rains[i] == 0. - * - * If there are multiple valid answers return any of them. If it is impossible to avoid flood return - * an empty array. - * - * Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty - * lake, nothing changes. - */ - -/** - * @param {number[]} rains - * @return {number[]} - */ -var avoidFlood = function(rains) { - const fullLakes = new Map(); - const dryDays = []; - const result = new Array(rains.length).fill(-1); - - for (let i = 0; i < rains.length; i++) { - if (rains[i] === 0) { - dryDays.push(i); - } else { - if (fullLakes.has(rains[i])) { - const lastRain = fullLakes.get(rains[i]); - let found = false; - for (let j = 0; j < dryDays.length; j++) { - if (dryDays[j] > lastRain) { - result[dryDays[j]] = rains[i]; - dryDays.splice(j, 1); - found = true; - break; - } - } - if (!found) return []; - } - fullLakes.set(rains[i], i); - } - } - - for (const dryDay of dryDays) { - result[dryDay] = 1; - } - - return result; -}; diff --git a/solutions/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.js b/solutions/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.js deleted file mode 100644 index 9fad786f..00000000 --- a/solutions/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree - * https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/ - * Difficulty: Hard - * - * Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an - * array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge - * between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that - * connects all vertices without cycles and with the minimum possible total edge weight. - * - * Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree - * (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is - * called a critical edge. On the other hand, a pseudo-critical edge is that which can appear - * in some MSTs but not all. - * - * Note that you can return the indices of the edges in any order. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number[][]} - */ -var findCriticalAndPseudoCriticalEdges = function(n, edges) { - const indexedEdges = edges.map((edge, i) => [...edge, i]); - indexedEdges.sort((a, b) => a[2] - b[2]); - - const minWeight = getMSTWeight(); - const critical = []; - const pseudoCritical = []; - - for (let i = 0; i < edges.length; i++) { - if (getMSTWeight(i) > minWeight) { - critical.push(indexedEdges[i][3]); - } else if (getMSTWeight(-1, i) === minWeight) { - pseudoCritical.push(indexedEdges[i][3]); - } - } - - return [critical, pseudoCritical]; - - function findParent(parents, x) { - if (parents[x] !== x) parents[x] = findParent(parents, parents[x]); - return parents[x]; - } - - function union(parents, ranks, x, y) { - const px = findParent(parents, x); - const py = findParent(parents, y); - if (px === py) return false; - if (ranks[px] < ranks[py]) { - parents[px] = py; - } else if (ranks[px] > ranks[py]) { - parents[py] = px; - } else { - parents[py] = px; - ranks[px]++; - } - return true; - } - - function getMSTWeight(exclude = -1, include = -1) { - const parents = Array.from({ length: n }, (_, i) => i); - const ranks = new Array(n).fill(0); - let weight = 0; - let edgesUsed = 0; - - if (include !== -1) { - const [u, v, w] = indexedEdges[include]; - if (union(parents, ranks, u, v)) { - weight += w; - edgesUsed++; - } - } - - for (let i = 0; i < indexedEdges.length; i++) { - if (i === exclude || i === include) continue; - const [u, v, w] = indexedEdges[i]; - if (union(parents, ranks, u, v)) { - weight += w; - edgesUsed++; - } - } - - return edgesUsed === n - 1 ? weight : Infinity; - } -}; diff --git a/solutions/1493-longest-subarray-of-1s-after-deleting-one-element.js b/solutions/1493-longest-subarray-of-1s-after-deleting-one-element.js deleted file mode 100644 index c1a11255..00000000 --- a/solutions/1493-longest-subarray-of-1s-after-deleting-one-element.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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/solutions/1494-parallel-courses-ii.js b/solutions/1494-parallel-courses-ii.js deleted file mode 100644 index 8bb21f82..00000000 --- a/solutions/1494-parallel-courses-ii.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * 1494. Parallel Courses II - * https://leetcode.com/problems/parallel-courses-ii/ - * Difficulty: Hard - * - * You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are - * also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a - * prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei - * has to be taken before course nextCoursei. Also, you are given the integer k. - * - * In one semester, you can take at most k courses as long as you have taken all the prerequisites - * in the previous semesters for the courses you are taking. - * - * Return the minimum number of semesters needed to take all courses. The testcases will be - * generated such that it is possible to take every course. - */ - -/** - * @param {number} n - * @param {number[][]} relations - * @param {number} k - * @return {number} - */ -var minNumberOfSemesters = function(n, relations, k) { - const prerequisites = new Array(n).fill(0); - for (const [prev, next] of relations) { - prerequisites[next - 1] |= 1 << (prev - 1); - } - - const cache = new Array(1 << n).fill(-1); - - return findMinSemesters(0); - - function findMinSemesters(courses) { - if (courses === (1 << n) - 1) return 0; - if (cache[courses] !== -1) return cache[courses]; - - let available = 0; - for (let i = 0; i < n; i++) { - if (!(courses & (1 << i)) && (courses & prerequisites[i]) === prerequisites[i]) { - available |= 1 << i; - } - } - - let minSemesters = n + 1; - const combinations = function(pos, count, selected) { - if (count === 0 || pos === n) { - if (selected) { - minSemesters = Math.min( - minSemesters, - 1 + findMinSemesters(courses | selected) - ); - } - return; - } - if (!(available & (1 << pos))) return combinations(pos + 1, count, selected); - combinations(pos + 1, count - 1, selected | (1 << pos)); - combinations(pos + 1, count, selected); - }; - - combinations(0, Math.min(k, bitCount(available)), 0); - cache[courses] = minSemesters; - return minSemesters; - } - - function bitCount(num) { - let count = 0; - while (num) { - count += num & 1; - num >>= 1; - } - return count; - } -}; diff --git a/solutions/1497-check-if-array-pairs-are-divisible-by-k.js b/solutions/1497-check-if-array-pairs-are-divisible-by-k.js deleted file mode 100644 index 1322a96f..00000000 --- a/solutions/1497-check-if-array-pairs-are-divisible-by-k.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1497. Check If Array Pairs Are Divisible by k - * https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/ - * Difficulty: Medium - * - * Given an array of integers arr of even length n and an integer k. - * - * We want to divide the array into exactly n / 2 pairs such that the sum of each pair is - * divisible by k. - * - * Return true If you can find a way to do that or false otherwise. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {boolean} - */ -var canArrange = function(arr, k) { - const remainders = new Array(k).fill(0); - - for (const num of arr) { - const remainder = ((num % k) + k) % k; - remainders[remainder]++; - } - - for (let i = 0; i <= Math.floor(k / 2); i++) { - if (i === 0 || i * 2 === k) { - if (remainders[i] % 2 !== 0) return false; - } else if (remainders[i] !== remainders[k - i]) { - return false; - } - } - - return true; -}; diff --git a/solutions/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.js b/solutions/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.js deleted file mode 100644 index 661a1465..00000000 --- a/solutions/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1498. Number of Subsequences That Satisfy the Given Sum Condition - * https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/ - * Difficulty: Medium - * - * You are given an array of integers nums and an integer target. - * - * Return the number of non-empty subsequences of nums such that the sum of the minimum and - * maximum element on it is less or equal to target. Since the answer may be too large, - * return it modulo 109 + 7. - */ - -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var numSubseq = function(nums, target) { - const MOD = 1e9 + 7; - const sortedNums = nums.sort((a, b) => a - b); - const length = nums.length; - let result = 0; - const powers = new Array(length).fill(1); - - for (let i = 1; i < length; i++) { - powers[i] = (powers[i - 1] * 2) % MOD; - } - - let left = 0; - let right = length - 1; - - while (left <= right) { - if (sortedNums[left] + sortedNums[right] <= target) { - result = (result + powers[right - left]) % MOD; - left++; - } else { - right--; - } - } - - return result; -}; diff --git a/solutions/1499-max-value-of-equation.js b/solutions/1499-max-value-of-equation.js deleted file mode 100644 index d8801769..00000000 --- a/solutions/1499-max-value-of-equation.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1499. Max Value of Equation - * https://leetcode.com/problems/max-value-of-equation/ - * Difficulty: Hard - * - * You are given an array points containing the coordinates of points on a 2D plane, - * sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all - * 1 <= i < j <= points.length. You are also given an integer k. - * - * Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k - * and 1 <= i < j <= points.length. - * - * It is guaranteed that there exists at least one pair of points that satisfy the - * constraint |xi - xj| <= k. - */ - -/** - * @param {number[][]} points - * @param {number} k - * @return {number} - */ -var findMaxValueOfEquation = function(points, k) { - let result = -Infinity; - const q = []; - - for (let j = 0; j < points.length; j++) { - const [xj, yj] = points[j]; - - while (q.length && xj - points[q[0]][0] > k) { - q.shift(); - } - - if (q.length) { - const [xi, yi] = points[q[0]]; - result = Math.max(result, yi + yj + xj - xi); - } - - while (q.length && yj - xj >= points[q[q.length - 1]][1] - points[q[q.length - 1]][0]) { - q.pop(); - } - - q.push(j); - } - - return result; -}; diff --git a/solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js b/solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js deleted file mode 100644 index 73792d35..00000000 --- a/solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1503. Last Moment Before All Ants Fall Out of a Plank - * https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/ - * Difficulty: Medium - * - * We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves - * with a speed of 1 unit per second. Some of the ants move to the left, the other move to the - * right. - * - * When two ants moving in two different directions meet at some point, they change their directions - * and continue moving again. Assume changing directions does not take any additional time. - * - * When an ant reaches one end of the plank at a time t, it falls out of the plank immediately. - * - * Given an integer n and two integer arrays left and right, the positions of the ants moving to the - * left and the right, return the moment when the last ant(s) fall out of the plank. - */ - -/** - * @param {number} n - * @param {number[]} left - * @param {number[]} right - * @return {number} - */ -var getLastMoment = function(n, left, right) { - let result = 0; - - for (const pos of left) { - result = Math.max(result, pos); - } - for (const pos of right) { - result = Math.max(result, n - pos); - } - - return result; -}; diff --git a/solutions/1504-count-submatrices-with-all-ones.js b/solutions/1504-count-submatrices-with-all-ones.js deleted file mode 100644 index f045ea39..00000000 --- a/solutions/1504-count-submatrices-with-all-ones.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1504. Count Submatrices With All Ones - * https://leetcode.com/problems/count-submatrices-with-all-ones/ - * Difficulty: Medium - * - * Given an m x n binary matrix mat, return the number of submatrices that have all ones. - */ - -/** - * @param {number[][]} mat - * @return {number} - */ -var numSubmat = function(mat) { - const rows = mat.length; - const cols = mat[0].length; - const heights = new Array(cols).fill(0); - let result = 0; - - for (let i = 0; i < rows; i++) { - const stack = []; - for (let j = 0; j < cols; j++) { - heights[j] = mat[i][j] === 1 ? heights[j] + 1 : 0; - - while (stack.length && heights[j] <= heights[stack[stack.length - 1]]) { - stack.pop(); - } - - stack.push(j); - - for (let k = 0; k < stack.length; k++) { - const height = heights[stack[k]]; - const width = k === 0 ? stack[k] + 1 : stack[k] - stack[k - 1]; - result += height * width; - } - } - } - - return result; -}; diff --git a/solutions/1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js b/solutions/1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js deleted file mode 100644 index 99bf831a..00000000 --- a/solutions/1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits - * https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/ - * Difficulty: Hard - * - * You are given a string num representing the digits of a very large integer and an integer k. You - * are allowed to swap any two adjacent digits of the integer at most k times. - * - * Return the minimum integer you can obtain also as a string. - */ - -/** - * @param {string} num - * @param {number} k - * @return {string} - */ -var minInteger = function(num, k) { - const digits = num.split(''); - const n = digits.length; - const fenwick = new Array(n + 1).fill(0); - const digitQueues = Array.from({ length: 10 }, () => []); - const result = []; - - for (let i = 0; i < n; i++) { - digitQueues[digits[i]].push(i); - } - - for (let i = 0; i < n; i++) { - for (let digit = 0; digit <= 9; digit++) { - if (digitQueues[digit].length === 0) continue; - const pos = digitQueues[digit][0]; - const swapsNeeded = pos - fetchValue(pos); - if (swapsNeeded <= k) { - k -= swapsNeeded; - result.push(digit); - update(pos); - digitQueues[digit].shift(); - break; - } - } - } - - return result.join(''); - - function update(index) { - for (let i = index + 1; i <= n; i += i & -i) { - fenwick[i]++; - } - } - - function fetchValue(index) { - let sum = 0; - for (let i = index + 1; i > 0; i -= i & -i) { - sum += fenwick[i]; - } - return sum; - } -}; diff --git a/solutions/1508-range-sum-of-sorted-subarray-sums.js b/solutions/1508-range-sum-of-sorted-subarray-sums.js deleted file mode 100644 index 611b82da..00000000 --- a/solutions/1508-range-sum-of-sorted-subarray-sums.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1508. Range Sum of Sorted Subarray Sums - * https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/ - * Difficulty: Medium - * - * You are given the array nums consisting of n positive integers. You computed the sum of all - * non-empty continuous subarrays from the array and then sorted them in non-decreasing order, - * creating a new array of n * (n + 1) / 2 numbers. - * - * Return the sum of the numbers from index left to index right (indexed from 1), inclusive, - * in the new array. Since the answer can be a huge number return it modulo 109 + 7. - */ - -/** - * @param {number[]} nums - * @param {number} n - * @param {number} left - * @param {number} right - * @return {number} - */ -var rangeSum = function(nums, n, left, right) { - const MOD = 1e9 + 7; - const sums = []; - - for (let start = 0; start < n; start++) { - let currentSum = 0; - for (let end = start; end < n; end++) { - currentSum += nums[end]; - sums.push(currentSum); - } - } - - sums.sort((a, b) => a - b); - - let result = 0; - for (let i = left - 1; i < right; i++) { - result = (result + sums[i]) % MOD; - } - - return result; -}; diff --git a/solutions/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.js b/solutions/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.js deleted file mode 100644 index ea4a397d..00000000 --- a/solutions/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1509. Minimum Difference Between Largest and Smallest Value in Three Moves - * https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/ - * Difficulty: Medium - * - * You are given an integer array nums. - * - * In one move, you can choose one element of nums and change it to any value. - * - * Return the minimum difference between the largest and smallest value of nums after performing at - * most three moves. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minDifference = function(nums) { - if (nums.length <= 4) return 0; - - nums.sort((a, b) => a - b); - - const n = nums.length; - let result = Infinity; - - result = Math.min(result, nums[n - 1] - nums[3]); - result = Math.min(result, nums[n - 2] - nums[2]); - result = Math.min(result, nums[n - 3] - nums[1]); - result = Math.min(result, nums[n - 4] - nums[0]); - - return result; -}; diff --git a/solutions/1510-stone-game-iv.js b/solutions/1510-stone-game-iv.js deleted file mode 100644 index 51282ddd..00000000 --- a/solutions/1510-stone-game-iv.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1510. Stone Game IV - * https://leetcode.com/problems/stone-game-iv/ - * Difficulty: Hard - * - * Alice and Bob take turns playing a game, with Alice starting first. - * - * Initially, there are n stones in a pile. On each player's turn, that player makes a move - * consisting of removing any non-zero square number of stones in the pile. - * - * Also, if a player cannot make a move, he/she loses the game. - * - * Given a positive integer n, return true if and only if Alice wins the game otherwise return - * false, assuming both players play optimally. - */ - -/** - * @param {number} n - * @return {boolean} - */ -var winnerSquareGame = function(n) { - const dp = new Array(n + 1).fill(false); - - for (let stones = 1; stones <= n; stones++) { - for (let square = 1; square * square <= stones; square++) { - if (!dp[stones - square * square]) { - dp[stones] = true; - break; - } - } - } - - return dp[n]; -}; diff --git a/solutions/1513-number-of-substrings-with-only-1s.js b/solutions/1513-number-of-substrings-with-only-1s.js deleted file mode 100644 index 5052a65d..00000000 --- a/solutions/1513-number-of-substrings-with-only-1s.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1513. Number of Substrings With Only 1s - * https://leetcode.com/problems/number-of-substrings-with-only-1s/ - * Difficulty: Medium - * - * Given a binary string s, return the number of substrings with all characters 1's. Since the - * answer may be too large, return it modulo 109 + 7. - */ - -/** - * @param {string} s - * @return {number} - */ -var numSub = function(s) { - const MOD = 1e9 + 7; - let result = 0; - let consecutiveOnes = 0; - - for (const char of s) { - if (char === '1') { - consecutiveOnes++; - result = (result + consecutiveOnes) % MOD; - } else { - consecutiveOnes = 0; - } - } - - return result; -}; diff --git a/solutions/1514-path-with-maximum-probability.js b/solutions/1514-path-with-maximum-probability.js deleted file mode 100644 index aba75224..00000000 --- a/solutions/1514-path-with-maximum-probability.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1514. Path with Maximum Probability - * https://leetcode.com/problems/path-with-maximum-probability/ - * Difficulty: Medium - * - * You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list - * where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability - * of success of traversing that edge succProb[i]. - * - * Given two nodes start and end, find the path with the maximum probability of success to go from - * start to end and return its success probability. - * - * If there is no path from start to end, return 0. Your answer will be accepted if it differs from - * the correct answer by at most 1e-5. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @param {number[]} succProb - * @param {number} startNode - * @param {number} endNode - * @return {number} - */ -var maxProbability = function(n, edges, succProb, startNode, endNode) { - const maxProbs = new Array(n).fill(0); - maxProbs[startNode] = 1; - - const graph = Array.from({ length: n }, () => []); - edges.forEach(([a, b], i) => { - graph[a].push([b, succProb[i]]); - graph[b].push([a, succProb[i]]); - }); - - const queue = [startNode]; - while (queue.length) { - const current = queue.shift(); - for (const [next, prob] of graph[current]) { - const newProb = maxProbs[current] * prob; - if (newProb > maxProbs[next]) { - maxProbs[next] = newProb; - queue.push(next); - } - } - } - - return maxProbs[endNode]; -}; diff --git a/solutions/1515-best-position-for-a-service-centre.js b/solutions/1515-best-position-for-a-service-centre.js deleted file mode 100644 index baee8eba..00000000 --- a/solutions/1515-best-position-for-a-service-centre.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 1515. Best Position for a Service Centre - * https://leetcode.com/problems/best-position-for-a-service-centre/ - * Difficulty: Hard - * - * A delivery company wants to build a new service center in a new city. The company knows the - * positions of all the customers in this city on a 2D-Map and wants to build the new center in - * a position such that the sum of the euclidean distances to all customers is minimum. - * - * Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on - * the map, return the minimum sum of the euclidean distances to all customers. - * - * In other words, you need to choose the position of the service center [xcentre, ycentre] such - * that the following formula is minimized: - * - Answers within 10-5 of the actual value will be accepted. - */ - -/** - * @param {number[][]} positions - * @return {number} - */ -var getMinDistSum = function(positions) { - const n = positions.length; - let xSum = 0; - let ySum = 0; - - for (const [x, y] of positions) { - xSum += x; - ySum += y; - } - - let xCenter = xSum / n; - let yCenter = ySum / n; - const epsilon = 1e-7; - const maxIterations = 1000; - - for (let iter = 0; iter < maxIterations; iter++) { - let xNumerator = 0; - let yNumerator = 0; - let denominator = 0; - - for (const [x, y] of positions) { - const dx = xCenter - x; - const dy = yCenter - y; - const dist = Math.sqrt(dx * dx + dy * dy); - if (dist < epsilon) continue; - const weight = 1 / dist; - xNumerator += x * weight; - yNumerator += y * weight; - denominator += weight; - } - - if (denominator < epsilon) break; - - const newX = xNumerator / denominator; - const newY = yNumerator / denominator; - - if (Math.abs(newX - xCenter) < epsilon && Math.abs(newY - yCenter) < epsilon) { - break; - } - - xCenter = newX; - yCenter = newY; - } - - let sumDist = 0; - for (const [x, y] of positions) { - sumDist += Math.sqrt((xCenter - x) ** 2 + (yCenter - y) ** 2); - } - - return sumDist; -}; diff --git a/solutions/1518-water-bottles.js b/solutions/1518-water-bottles.js deleted file mode 100644 index fe7ce020..00000000 --- a/solutions/1518-water-bottles.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1518. Water Bottles - * https://leetcode.com/problems/water-bottles/ - * Difficulty: Easy - * - * There are numBottles water bottles that are initially full of water. You can exchange numExchange - * empty water bottles from the market with one full water bottle. - * - * The operation of drinking a full water bottle turns it into an empty bottle. - * - * Given the two integers numBottles and numExchange, return the maximum number of water bottles you - * can drink. - */ - -/** - * @param {number} numBottles - * @param {number} numExchange - * @return {number} - */ -var numWaterBottles = function(numBottles, numExchange) { - let result = numBottles; - let emptyBottles = numBottles; - - while (emptyBottles >= numExchange) { - const newBottles = Math.floor(emptyBottles / numExchange); - result += newBottles; - emptyBottles = newBottles + (emptyBottles % numExchange); - } - - return result; -}; diff --git a/solutions/1520-maximum-number-of-non-overlapping-substrings.js b/solutions/1520-maximum-number-of-non-overlapping-substrings.js deleted file mode 100644 index 91f48d51..00000000 --- a/solutions/1520-maximum-number-of-non-overlapping-substrings.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1520. Maximum Number of Non-Overlapping Substrings - * https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/ - * Difficulty: Hard - * - * Given a string s of lowercase letters, you need to find the maximum number of non-empty - * substrings of s that meet the following conditions: - * 1. The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], - * either j < x or i > y is true. - * 2. A substring that contains a certain character c must also contain all occurrences of c. - * - * Find the maximum number of substrings that meet the above conditions. If there are multiple - * solutions with the same number of substrings, return the one with minimum total length. It - * can be shown that there exists a unique solution of minimum total length. - * - * Notice that you can return the substrings in any order. - */ - -/** - * @param {string} s - * @return {string[]} - */ -var maxNumOfSubstrings = function(s) { - const charRange = new Array(26).fill().map(() => [Infinity, -Infinity]); - - for (let i = 0; i < s.length; i++) { - const charIndex = s.charCodeAt(i) - 97; - charRange[charIndex][0] = Math.min(charRange[charIndex][0], i); - charRange[charIndex][1] = Math.max(charRange[charIndex][1], i); - } - - const intervals = []; - for (let c = 0; c < 26; c++) { - if (charRange[c][0] === Infinity) continue; - const start = charRange[c][0]; - let end = charRange[c][1]; - let valid = true; - - for (let i = start; i <= end; i++) { - const charIndex = s.charCodeAt(i) - 97; - if (charRange[charIndex][0] < start) { - valid = false; - break; - } - end = Math.max(end, charRange[charIndex][1]); - } - - if (valid) { - intervals.push([start, end]); - } - } - - intervals.sort((a, b) => a[1] - b[1] || a[0] - b[0]); - - const result = []; - let lastEnd = -1; - - for (const [start, end] of intervals) { - if (start > lastEnd) { - result.push(s.slice(start, end + 1)); - lastEnd = end; - } - } - - return result; -}; diff --git a/solutions/1521-find-a-value-of-a-mysterious-function-closest-to-target.js b/solutions/1521-find-a-value-of-a-mysterious-function-closest-to-target.js deleted file mode 100644 index 20f2b679..00000000 --- a/solutions/1521-find-a-value-of-a-mysterious-function-closest-to-target.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1521. Find a Value of a Mysterious Function Closest to Target - * https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target/ - * Difficulty: Hard - * - * Winston was given the above mysterious function func. He has an integer array arr and an integer - * target and he wants to find the values l and r that make the value |func(arr, l, r) - target| - * minimum possible. - * - * Return the minimum possible value of |func(arr, l, r) - target|. - * - * Notice that func should be called with the values l and r where 0 <= l, r < arr.length. - */ - -/** - * @param {number[]} arr - * @param {number} target - * @return {number} - */ -var closestToTarget = function(arr, target) { - let result = Infinity; - let seen = new Set(); - - for (let right = 0; right < arr.length; right++) { - const current = new Set([arr[right]]); - result = Math.min(result, Math.abs(arr[right] - target)); - - for (const previous of seen) { - const currentAnd = previous & arr[right]; - current.add(currentAnd); - result = Math.min(result, Math.abs(currentAnd - target)); - } - - seen = current; - } - - return result; -}; diff --git a/solutions/1523-count-odd-numbers-in-an-interval-range.js b/solutions/1523-count-odd-numbers-in-an-interval-range.js deleted file mode 100644 index 40e853a0..00000000 --- a/solutions/1523-count-odd-numbers-in-an-interval-range.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 1523. Count Odd Numbers in an Interval Range - * https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ - * Difficulty: Easy - * - * Given two non-negative integers low and high. Return the count of odd numbers between low - * and high (inclusive). - */ - -/** - * @param {number} low - * @param {number} high - * @return {number} - */ -var countOdds = function(low, high) { - const range = high - low + 1; - - if (low % 2 !== 0 && high % 2 !== 0) { - return Math.floor(range / 2) + 1; - } - - return Math.floor(range / 2); -}; diff --git a/solutions/1525-number-of-good-ways-to-split-a-string.js b/solutions/1525-number-of-good-ways-to-split-a-string.js deleted file mode 100644 index 2d24d3ce..00000000 --- a/solutions/1525-number-of-good-ways-to-split-a-string.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1525. Number of Good Ways to Split a String - * https://leetcode.com/problems/number-of-good-ways-to-split-a-string/ - * Difficulty: Medium - * - * You are given a string s. - * - * A split is called good if you can split s into two non-empty strings sleft and sright where - * their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters - * in sleft and sright is the same. - * - * Return the number of good splits you can make in s. - */ - -/** - * @param {string} s - * @return {number} - */ -var numSplits = function(s) { - const leftDistinct = new Map(); - const rightDistinct = new Map(); - let result = 0; - - for (const char of s) { - rightDistinct.set(char, (rightDistinct.get(char) || 0) + 1); - } - - for (let i = 0; i < s.length - 1; i++) { - const char = s[i]; - leftDistinct.set(char, (leftDistinct.get(char) || 0) + 1); - - if (rightDistinct.get(char) === 1) { - rightDistinct.delete(char); - } else { - rightDistinct.set(char, rightDistinct.get(char) - 1); - } - - if (leftDistinct.size === rightDistinct.size) { - result++; - } - } - - return result; -}; diff --git a/solutions/1526-minimum-number-of-increments-on-subarrays-to-form-a-target-array.js b/solutions/1526-minimum-number-of-increments-on-subarrays-to-form-a-target-array.js deleted file mode 100644 index 4271112a..00000000 --- a/solutions/1526-minimum-number-of-increments-on-subarrays-to-form-a-target-array.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 1526. Minimum Number of Increments on Subarrays to Form a Target Array - * https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/ - * Difficulty: Hard - * - * You are given an integer array target. You have an integer array initial of the same size as - * target with all elements initially zeros. - * - * In one operation you can choose any subarray from initial and increment each value by one. - * - * Return the minimum number of operations to form a target array from initial. - * - * The test cases are generated so that the answer fits in a 32-bit integer. - */ - -/** - * @param {number[]} target - * @return {number} - */ -var minNumberOperations = function(target) { - let operations = target[0]; - for (let i = 1; i < target.length; i++) { - if (target[i] > target[i - 1]) { - operations += target[i] - target[i - 1]; - } - } - return operations; -}; diff --git a/solutions/1529-minimum-suffix-flips.js b/solutions/1529-minimum-suffix-flips.js deleted file mode 100644 index bf497b9c..00000000 --- a/solutions/1529-minimum-suffix-flips.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1529. Minimum Suffix Flips - * https://leetcode.com/problems/minimum-suffix-flips/ - * Difficulty: Medium - * - * You are given a 0-indexed binary string target of length n. You have another binary string s - * of length n that is initially set to all zeros. You want to make s equal to target. - * - * In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive - * range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'. - * - * Return the minimum number of operations needed to make s equal to target. - */ - -/** - * @param {string} target - * @return {number} - */ -var minFlips = function(target) { - let current = '0'; - let result = 0; - - for (const bit of target) { - if (bit !== current) { - result++; - current = bit; - } - } - - return result; -}; diff --git a/solutions/1530-number-of-good-leaf-nodes-pairs.js b/solutions/1530-number-of-good-leaf-nodes-pairs.js deleted file mode 100644 index a5364874..00000000 --- a/solutions/1530-number-of-good-leaf-nodes-pairs.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1530. Number of Good Leaf Nodes Pairs - * https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/ - * Difficulty: Medium - * - * You are given the root of a binary tree and an integer distance. A pair of two different leaf - * nodes of a binary tree is said to be good if the length of the shortest path between them is - * less than or equal to distance. - * - * Return the number of good leaf node pairs in the tree. - */ - -/** - * 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} distance - * @return {number} - */ -var countPairs = function(root, distance) { - let result = 0; - traverseTree(root); - return result; - - function traverseTree(node) { - if (!node) return []; - if (!node.left && !node.right) return [1]; - - const leftDistances = traverseTree(node.left); - const rightDistances = traverseTree(node.right); - - for (const left of leftDistances) { - for (const right of rightDistances) { - if (left + right <= distance) result++; - } - } - - const allDistances = []; - for (const dist of leftDistances.concat(rightDistances)) { - if (dist + 1 <= distance) allDistances.push(dist + 1); - } - - return allDistances; - } -}; diff --git a/solutions/1531-string-compression-ii.js b/solutions/1531-string-compression-ii.js deleted file mode 100644 index 099d1eb7..00000000 --- a/solutions/1531-string-compression-ii.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1531. String Compression II - * https://leetcode.com/problems/string-compression-ii/ - * Difficulty: Hard - * - * Run-length encoding is a string compression method that works by replacing consecutive - * identical characters (repeated 2 or more times) with the concatenation of the character - * and the number marking the count of the characters (length of the run). For example, - * to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus - * the compressed string becomes "a2bc3". - * - * Notice that in this problem, we are not adding '1' after single characters. - * - * Given a string s and an integer k. You need to delete at most k characters from s such that - * the run-length encoded version of s has minimum length. - * - * Find the minimum length of the run-length encoded version of s after deleting at most - * k characters. - */ - -/** - * @param {string} s - * @param {number} k - * @return {number} - */ -var getLengthOfOptimalCompression = function(s, k) { - const n = s.length; - const dp = new Array(n + 1).fill().map(() => new Array(k + 1).fill(9999)); - dp[0][0] = 0; - - for (let i = 1; i <= n; i++) { - for (let j = 0; j <= k; j++) { - let count = 0; - let deletions = 0; - - for (let m = i; m >= 1; m--) { - if (s[m - 1] === s[i - 1]) count++; - else deletions++; - - if (j - deletions >= 0) { - dp[i][j] = Math.min( - dp[i][j], - dp[m - 1][j - deletions] + calculateEncodedLength(count) - ); - } - } - - if (j > 0) { - dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]); - } - } - } - - return dp[n][k]; - - function calculateEncodedLength(count) { - if (count === 0) return 0; - if (count === 1) return 1; - if (count < 10) return 2; - if (count < 100) return 3; - return 4; - } -}; diff --git a/solutions/1534-count-good-triplets.js b/solutions/1534-count-good-triplets.js deleted file mode 100644 index ab56b726..00000000 --- a/solutions/1534-count-good-triplets.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1534. Count Good Triplets - * https://leetcode.com/problems/count-good-triplets/ - * Difficulty: Easy - * - * Given an array of integers arr, and three integers a, b and c. You need to find the number - * of good triplets. - * - * A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: - * - 0 <= i < j < k < arr.length - * - |arr[i] - arr[j]| <= a - * - |arr[j] - arr[k]| <= b - * - |arr[i] - arr[k]| <= c - * - * Where |x| denotes the absolute value of x. - * - * Return the number of good triplets. - */ - -function countGoodTriplets(arr, a, b, c) { - const length = arr.length; - let result = 0; - - for (let i = 0; i < length - 2; i++) { - for (let j = i + 1; j < length - 1; j++) { - if (Math.abs(arr[i] - arr[j]) <= a) { - for (let k = j + 1; k < length; k++) { - if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { - result++; - } - } - } - } - } - - return result; -} diff --git a/solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js b/solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js deleted file mode 100644 index c479ed57..00000000 --- a/solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 1536. Minimum Swaps to Arrange a Binary Grid - * https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/ - * Difficulty: Medium - * - * Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and - * swap them. - * - * A grid is said to be valid if all the cells above the main diagonal are zeros. - * - * Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot - * be valid. - * - * The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n). - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var minSwaps = function(grid) { - const n = grid.length; - const trailingZeros = new Array(n).fill(0); - - for (let i = 0; i < n; i++) { - trailingZeros[i] = countTrailingZeros(i); - } - - let swaps = 0; - for (let i = 0; i < n - 1; i++) { - const requiredZeros = n - i - 1; - let found = false; - - for (let j = i; j < n; j++) { - if (trailingZeros[j] >= requiredZeros) { - found = true; - for (let k = j; k > i; k--) { - [trailingZeros[k], trailingZeros[k - 1]] = [trailingZeros[k - 1], trailingZeros[k]]; - swaps++; - } - break; - } - } - - if (!found) return -1; - } - - return swaps; - - function countTrailingZeros(row) { - let count = 0; - for (let j = n - 1; j >= 0; j--) { - if (grid[row][j] === 0) count++; - else break; - } - return count; - } -}; diff --git a/solutions/1537-get-the-maximum-score.js b/solutions/1537-get-the-maximum-score.js deleted file mode 100644 index b4be118c..00000000 --- a/solutions/1537-get-the-maximum-score.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1537. Get the Maximum Score - * https://leetcode.com/problems/get-the-maximum-score/ - * Difficulty: Hard - * - * You are given two sorted arrays of distinct integers nums1 and nums2. - * - * A valid path is defined as follows: - * - Choose array nums1 or nums2 to traverse (from index-0). - * - Traverse the current array from left to right. - * - If you are reading any value that is present in nums1 and nums2 you are allowed to change - * your path to the other array. (Only one repeated value is considered in the valid path). - * - * The score is defined as the sum of unique values in a valid path. - * - * Return the maximum score you can obtain of all possible valid paths. Since the answer may be - * too large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var maxSum = function(nums1, nums2) { - const MOD = 1e9 + 7; - const m = nums1.length; - const n = nums2.length; - let i = 0; - let j = 0; - let sum1 = 0; - let sum2 = 0; - - while (i < m && j < n) { - if (nums1[i] < nums2[j]) { - sum1 += nums1[i++]; - } else if (nums1[i] > nums2[j]) { - sum2 += nums2[j++]; - } else { - sum1 = sum2 = Math.max(sum1, sum2) + nums1[i]; - i++; - j++; - } - } - - while (i < m) { - sum1 += nums1[i++]; - } - - while (j < n) { - sum2 += nums2[j++]; - } - - return Math.max(sum1, sum2) % MOD; -}; diff --git a/solutions/1539-kth-missing-positive-number.js b/solutions/1539-kth-missing-positive-number.js deleted file mode 100644 index 2f89676b..00000000 --- a/solutions/1539-kth-missing-positive-number.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1539. Kth Missing Positive Number - * https://leetcode.com/problems/kth-missing-positive-number/ - * Difficulty: Easy - * - * Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. - * - * Return the kth positive integer that is missing from this array. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {number} - */ -var findKthPositive = function(arr, k) { - let left = 0; - let right = arr.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const count = arr[mid] - mid - 1; - - if (count < k) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return left + k; -}; diff --git a/solutions/1540-can-convert-string-in-k-moves.js b/solutions/1540-can-convert-string-in-k-moves.js deleted file mode 100644 index 3bc55397..00000000 --- a/solutions/1540-can-convert-string-in-k-moves.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1540. Can Convert String in K Moves - * https://leetcode.com/problems/can-convert-string-in-k-moves/ - * Difficulty: Medium - * - * Given two strings s and t, your goal is to convert s into t in k moves or less. - * - * During the ith (1 <= i <= k) move you can: - * - Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen - * in any previous move, and shift the character at that index i times. - * - Do nothing. - * - * Shifting a character means replacing it by the next letter in the alphabet (wrapping around so - * that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times. - * - * Remember that any index j can be picked at most once. - * - * Return true if it's possible to convert s into t in no more than k moves, otherwise return false. - */ - -/** - * @param {string} s - * @param {string} t - * @param {number} k - * @return {boolean} - */ -var canConvertString = function(source, target, maxMoves) { - if (source.length !== target.length) return false; - const shiftCounts = new Array(26).fill(0); - - for (let i = 0; i < source.length; i++) { - const shiftNeeded = (target.charCodeAt(i) - source.charCodeAt(i) + 26) % 26; - if (shiftNeeded > 0) { - shiftCounts[shiftNeeded]++; - } - } - - for (let shift = 1; shift < 26; shift++) { - if (shiftCounts[shift] === 0) continue; - const totalMoves = shift + 26 * (shiftCounts[shift] - 1); - if (totalMoves > maxMoves) return false; - } - - return true; -}; diff --git a/solutions/1541-minimum-insertions-to-balance-a-parentheses-string.js b/solutions/1541-minimum-insertions-to-balance-a-parentheses-string.js deleted file mode 100644 index 83dbd166..00000000 --- a/solutions/1541-minimum-insertions-to-balance-a-parentheses-string.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1541. Minimum Insertions to Balance a Parentheses String - * https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/ - * Difficulty: Medium - * - * Given a parentheses string s containing only the characters '(' and ')'. A parentheses string - * is balanced if: - * - Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. - * - Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'. - * - * In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. - * - For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are - * not balanced. - * - * You can insert the characters '(' and ')' at any position of the string to balance it if needed. - * - * Return the minimum number of insertions needed to make s balanced. - */ - -/** - * @param {string} s - * @return {number} - */ -var minInsertions = function(s) { - let result = 0; - let openCount = 0; - - for (let i = 0; i < s.length; i++) { - if (s[i] === '(') { - openCount++; - } else { - if (i + 1 < s.length && s[i + 1] === ')') { - i++; - } else { - result++; - } - if (openCount > 0) { - openCount--; - } else { - result++; - } - } - } - - result += openCount * 2; - - return result; -}; diff --git a/solutions/1542-find-longest-awesome-substring.js b/solutions/1542-find-longest-awesome-substring.js deleted file mode 100644 index 45c349a1..00000000 --- a/solutions/1542-find-longest-awesome-substring.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1542. Find Longest Awesome Substring - * https://leetcode.com/problems/find-longest-awesome-substring/ - * Difficulty: Hard - * - * You are given a string s. An awesome substring is a non-empty substring of s such that we - * can make any number of swaps in order to make it a palindrome. - * - * Return the length of the maximum length awesome substring of s. - */ - -/** - * @param {string} s - * @return {number} - */ -var longestAwesome = function(s) { - let result = 0; - let prefixMask = 0; - const digitMasks = new Map(); - digitMasks.set(0, -1); - - for (let i = 0; i < s.length; i++) { - const digit = s.charCodeAt(i) - '0'.charCodeAt(0); - prefixMask ^= (1 << digit); - - if (digitMasks.has(prefixMask)) { - result = Math.max(result, i - digitMasks.get(prefixMask)); - } else { - digitMasks.set(prefixMask, i); - } - - for (let j = 0; j < 10; j++) { - const oddMask = prefixMask ^ (1 << j); - if (digitMasks.has(oddMask)) { - result = Math.max(result, i - digitMasks.get(oddMask)); - } - } - } - - return result; -}; diff --git a/solutions/1544-make-the-string-great.js b/solutions/1544-make-the-string-great.js deleted file mode 100644 index edcaeed9..00000000 --- a/solutions/1544-make-the-string-great.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1544. Make The String Great - * https://leetcode.com/problems/make-the-string-great/ - * Difficulty: Easy - * - * Given a string s of lower and upper case English letters. - * - * A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: - * - 0 <= i <= s.length - 2 - * - s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. - * - * To make the string good, you can choose two adjacent characters that make the string bad and - * remove them. You can keep doing this until the string becomes good. - * - * Return the string after making it good. The answer is guaranteed to be unique under the given - * constraints. - * - * Notice that an empty string is also good. - */ - -/** - * @param {string} s - * @return {string} - */ -var makeGood = function(s) { - const stack = []; - - for (const char of s) { - const lastChar = stack[stack.length - 1]; - if (lastChar && ((char.toLowerCase() === lastChar.toLowerCase()) && (char !== lastChar))) { - stack.pop(); - } else { - stack.push(char); - } - } - - return stack.join(''); -}; diff --git a/solutions/1545-find-kth-bit-in-nth-binary-string.js b/solutions/1545-find-kth-bit-in-nth-binary-string.js deleted file mode 100644 index d2cee786..00000000 --- a/solutions/1545-find-kth-bit-in-nth-binary-string.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1545. Find Kth Bit in Nth Binary String - * https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/ - * Difficulty: Medium - * - * Given two positive integers n and k, the binary string Sn is formed as follows: - * - S1 = "0" - * - Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1 - * - * Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and - * invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). - * - * For example, the first four strings in the above sequence are: - * - S1 = "0" - * - S2 = "011" - * - S3 = "0111001" - * - S4 = "011100110110001" - * - * Return the kth bit in Sn. It is guaranteed that k is valid for the given n. - */ - -/** - * @param {number} n - * @param {number} k - * @return {character} - */ -var findKthBit = function(n, k) { - let position = k - 1; - let invertCount = 0; - let length = (1 << n) - 1; - - while (position !== 0) { - const mid = length >> 1; - - if (position === mid) { - return invertCount % 2 === 0 ? '1' : '0'; - } - - if (position > mid) { - position = length - position - 1; - invertCount++; - } else { - length = mid; - } - } - - return invertCount % 2 === 0 ? '0' : '1'; -}; diff --git a/solutions/1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.js b/solutions/1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.js deleted file mode 100644 index 094e3d53..00000000 --- a/solutions/1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target - * https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/ - * Difficulty: Medium - * - * Given an array nums and an integer target, return the maximum number of non-empty non-overlapping - * subarrays such that the sum of values in each subarray is equal to target. - */ - -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var maxNonOverlapping = function(nums, target) { - const prefixSums = new Map(); - let currentSum = 0; - let result = 0; - prefixSums.set(0, 0); - - for (let i = 0; i < nums.length; i++) { - currentSum += nums[i]; - - if (prefixSums.has(currentSum - target)) { - result++; - prefixSums.clear(); - prefixSums.set(0, i + 1); - currentSum = 0; - } else { - prefixSums.set(currentSum, i + 1); - } - } - - return result; -}; diff --git a/solutions/1547-minimum-cost-to-cut-a-stick.js b/solutions/1547-minimum-cost-to-cut-a-stick.js deleted file mode 100644 index f7b0cf36..00000000 --- a/solutions/1547-minimum-cost-to-cut-a-stick.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1547. Minimum Cost to Cut a Stick - * https://leetcode.com/problems/minimum-cost-to-cut-a-stick/ - * Difficulty: Hard - * - * Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a - * stick of length 6 is labelled as follows. - * - * Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. - * - * You should perform the cuts in order, you can change the order of the cuts as you wish. - * - * The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs - * of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of - * their lengths is the length of the stick before the cut). Please refer to the first example - * for a better explanation. - * - * Return the minimum total cost of the cuts. - */ - -/** - * @param {number} n - * @param {number[]} cuts - * @return {number} - */ -var minCost = function(n, cuts) { - cuts.push(0, n); - cuts.sort((a, b) => a - b); - - const memo = new Map(); - - return computeMinCost(0, cuts.length - 1); - - function computeMinCost(left, right) { - if (right - left <= 1) return 0; - - const key = `${left},${right}`; - if (memo.has(key)) return memo.get(key); - - let minCost = Infinity; - for (let i = left + 1; i < right; i++) { - const cost = (cuts[right] - cuts[left]) + computeMinCost(left, i) + computeMinCost(i, right); - minCost = Math.min(minCost, cost); - } - - memo.set(key, minCost); - return minCost; - } -}; diff --git a/solutions/1552-magnetic-force-between-two-balls.js b/solutions/1552-magnetic-force-between-two-balls.js deleted file mode 100644 index ef15f17b..00000000 --- a/solutions/1552-magnetic-force-between-two-balls.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 1552. Magnetic Force Between Two Balls - * https://leetcode.com/problems/magnetic-force-between-two-balls/ - * Difficulty: Medium - * - * In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls - * if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at - * position[i], Morty has m balls and needs to distribute the balls into the baskets such that - * the minimum magnetic force between any two balls is maximum. - * - * Rick stated that magnetic force between two different balls at positions x and y is |x - y|. - * - * Given the integer array position and the integer m. Return the required force. - */ - -/** - * @param {number[]} position - * @param {number} m - * @return {number} - */ -var maxDistance = function(position, m) { - position.sort((a, b) => a - b); - - let left = 1; - let right = position[position.length - 1] - position[0]; - let result = 0; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (canPlaceBalls(mid)) { - result = mid; - left = mid + 1; - } else { - right = mid - 1; - } - } - - return result; - - function canPlaceBalls(minForce) { - let count = 1; - let lastPos = position[0]; - - for (let i = 1; i < position.length; i++) { - if (position[i] - lastPos >= minForce) { - count++; - lastPos = position[i]; - } - } - - return count >= m; - } -}; diff --git a/solutions/1553-minimum-number-of-days-to-eat-n-oranges.js b/solutions/1553-minimum-number-of-days-to-eat-n-oranges.js deleted file mode 100644 index 7ef834bc..00000000 --- a/solutions/1553-minimum-number-of-days-to-eat-n-oranges.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1553. Minimum Number of Days to Eat N Oranges - * https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/ - * Difficulty: Hard - * - * There are n oranges in the kitchen and you decided to eat some of these oranges every day as - * follows: - * - Eat one orange. - * - If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges. - * - If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges. - * - * You can only choose one of the actions per day. - * - * Given the integer n, return the minimum number of days to eat n oranges. - */ - -/** - * @param {number} n - * @return {number} - */ -var minDays = function(n) { - const memo = new Map(); - return computeMinDays(n); - - function computeMinDays(oranges) { - if (oranges <= 1) return oranges; - if (memo.has(oranges)) return memo.get(oranges); - - const eatHalf = computeMinDays(Math.floor(oranges / 2)) + (oranges % 2) + 1; - const eatTwoThirds = computeMinDays(Math.floor(oranges / 3)) + (oranges % 3) + 1; - const minDays = Math.min(eatHalf, eatTwoThirds); - memo.set(oranges, minDays); - return minDays; - } -}; diff --git a/solutions/1556-thousand-separator.js b/solutions/1556-thousand-separator.js deleted file mode 100644 index c9e078cd..00000000 --- a/solutions/1556-thousand-separator.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1556. Thousand Separator - * https://leetcode.com/problems/thousand-separator/ - * Difficulty: Easy - * - * Given an integer n, add a dot (".") as the thousands separator and return it in string format. - */ - -/** - * @param {number} n - * @return {string} - */ -var thousandSeparator = function(n) { - const digits = n.toString().split(''); - const result = []; - - while (digits.length > 0) { - const group = digits.splice(-3).join(''); - result.unshift(group); - if (digits.length > 0) { - result.unshift('.'); - } - } - - return result.join(''); -}; diff --git a/solutions/1557-minimum-number-of-vertices-to-reach-all-nodes.js b/solutions/1557-minimum-number-of-vertices-to-reach-all-nodes.js deleted file mode 100644 index 2c36e0bc..00000000 --- a/solutions/1557-minimum-number-of-vertices-to-reach-all-nodes.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1557. Minimum Number of Vertices to Reach All Nodes - * https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ - * Difficulty: Medium - * - * Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges - * where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. - * - * Find the smallest set of vertices from which all nodes in the graph are reachable. It's - * guaranteed that a unique solution exists. - * - * Notice that you can return the vertices in any order. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number[]} - */ -var findSmallestSetOfVertices = function(n, edges) { - const hasIncomingEdge = new Array(n).fill(false); - for (const [_, to] of edges) { - hasIncomingEdge[to] = true; - } - - const result = []; - for (let i = 0; i < n; i++) { - if (!hasIncomingEdge[i]) { - result.push(i); - } - } - - return result; -}; diff --git a/solutions/1558-minimum-numbers-of-function-calls-to-make-target-array.js b/solutions/1558-minimum-numbers-of-function-calls-to-make-target-array.js deleted file mode 100644 index 25086640..00000000 --- a/solutions/1558-minimum-numbers-of-function-calls-to-make-target-array.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1558. Minimum Numbers of Function Calls to Make Target Array - * https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/ - * Difficulty: Medium - * - * You are given an integer array nums. You have an integer array arr of the same length with all - * values set to 0 initially. You also have the following modify function. - * - * You want to use the modify function to convert arr to nums using the minimum number of calls. - * - * Return the minimum number of function calls to make nums from arr. - * - * The test cases are generated so that the answer fits in a 32-bit signed integer. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minOperations = function(nums) { - let totalOperations = 0; - let maxDivisions = 0; - - for (let num of nums) { - let currentDivisions = 0; - let increments = 0; - - while (num > 0) { - if (num % 2 === 1) { - increments++; - num--; - } else { - currentDivisions++; - num /= 2; - } - } - - totalOperations += increments; - maxDivisions = Math.max(maxDivisions, currentDivisions); - } - - return totalOperations + maxDivisions; -}; diff --git a/solutions/1559-detect-cycles-in-2d-grid.js b/solutions/1559-detect-cycles-in-2d-grid.js deleted file mode 100644 index 486155dd..00000000 --- a/solutions/1559-detect-cycles-in-2d-grid.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 1559. Detect Cycles in 2D Grid - * https://leetcode.com/problems/detect-cycles-in-2d-grid/ - * Difficulty: Medium - * - * Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle - * consisting of the same value in grid. - * - * A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From - * a given cell, you can move to one of the cells adjacent to it - in one of the four directions - * (up, down, left, or right), if it has the same value of the current cell. - * - * Also, you cannot move to the cell that you visited in your last move. For example, the cycle - * (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last - * visited cell. - * - * Return true if any cycle of the same value exists in grid, otherwise, return false. - */ - -/** - * @param {character[][]} grid - * @return {boolean} - */ -var containsCycle = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const visited = new Set(); - - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - if (!visited.has(`${row},${col}`)) { - if (explorePath(row, col, -1, -1, grid[row][col])) return true; - } - } - } - - return false; - - function explorePath(row, col, prevRow, prevCol, char) { - const key = `${row},${col}`; - if (visited.has(key)) return true; - visited.add(key); - - const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - for (const [dx, dy] of directions) { - const newRow = row + dx; - const newCol = col + dy; - - if (newRow === prevRow && newCol === prevCol) continue; - if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue; - if (grid[newRow][newCol] !== char) continue; - - if (explorePath(newRow, newCol, row, col, char)) return true; - } - - return false; - } -}; diff --git a/solutions/1560-most-visited-sector-in-a-circular-track.js b/solutions/1560-most-visited-sector-in-a-circular-track.js deleted file mode 100644 index 4c561b2d..00000000 --- a/solutions/1560-most-visited-sector-in-a-circular-track.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1560. Most Visited Sector in a Circular Track - * https://leetcode.com/problems/most-visited-sector-in-a-circular-track/ - * Difficulty: Easy - * - * Given an integer n and an integer array rounds. We have a circular track which consists of n - * sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of - * m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For - * example, round 1 starts at sector rounds[0] and ends at sector rounds[1] - * - * Return an array of the most visited sectors sorted in ascending order. - * - * Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise - * direction (See the first example). - */ - -/** - * @param {number} n - * @param {number[]} rounds - * @return {number[]} - */ -var mostVisited = function(n, rounds) { - const sectorVisits = new Array(n + 1).fill(0); - let maxVisits = 0; - - for (let i = 1; i < rounds.length; i++) { - let start = rounds[i - 1]; - const end = rounds[i]; - - while (start !== end) { - sectorVisits[start]++; - maxVisits = Math.max(maxVisits, sectorVisits[start]); - start = start === n ? 1 : start + 1; - } - } - - sectorVisits[rounds[rounds.length - 1]]++; - maxVisits = Math.max(maxVisits, sectorVisits[rounds[rounds.length - 1]]); - - const result = []; - for (let i = 1; i <= n; i++) { - if (sectorVisits[i] === maxVisits) { - result.push(i); - } - } - - return result; -}; diff --git a/solutions/1561-maximum-number-of-coins-you-can-get.js b/solutions/1561-maximum-number-of-coins-you-can-get.js deleted file mode 100644 index 7643b7bd..00000000 --- a/solutions/1561-maximum-number-of-coins-you-can-get.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1561. Maximum Number of Coins You Can Get - * https://leetcode.com/problems/maximum-number-of-coins-you-can-get/ - * Difficulty: Medium - * - * There are 3n piles of coins of varying size, you and your friends will take piles of coins as - * follows: - * - In each step, you will choose any 3 piles of coins (not necessarily consecutive). - * - Of your choice, Alice will pick the pile with the maximum number of coins. - * - You will pick the next pile with the maximum number of coins. - * - Your friend Bob will pick the last pile. - * - Repeat until there are no more piles of coins. - * - * Given an array of integers piles where piles[i] is the number of coins in the ith pile. - * - * Return the maximum number of coins that you can have. - */ - -/** - * @param {number[]} piles - * @return {number} - */ -var maxCoins = function(piles) { - piles.sort((a, b) => b - a); - let result = 0; - const rounds = piles.length / 3; - - for (let i = 1; i < piles.length - rounds; i += 2) { - result += piles[i]; - } - - return result; -}; diff --git a/solutions/1562-find-latest-group-of-size-m.js b/solutions/1562-find-latest-group-of-size-m.js deleted file mode 100644 index e4d2b3b2..00000000 --- a/solutions/1562-find-latest-group-of-size-m.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1562. Find Latest Group of Size M - * https://leetcode.com/problems/find-latest-group-of-size-m/ - * Difficulty: Medium - * - * Given an array arr that represents a permutation of numbers from 1 to n. - * - * You have a binary string of size n that initially has all its bits set to zero. At each step - * i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position - * arr[i] is set to 1. - * - * You are also given an integer m. Find the latest step at which there exists a group of ones - * of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended - * in either direction. - * - * Return the latest step at which there exists a group of ones of length exactly m. If no such - * group exists, return -1. - */ - -/** - * @param {number[]} arr - * @param {number} m - * @return {number} - */ -var findLatestStep = function(arr, m) { - const lengths = new Array(arr.length + 2).fill(0); - const count = new Map(); - let result = -1; - - for (let step = 0; step < arr.length; step++) { - const pos = arr[step]; - const left = lengths[pos - 1]; - const right = lengths[pos + 1]; - const newLength = left + right + 1; - - lengths[pos - left] = newLength; - lengths[pos + right] = newLength; - lengths[pos] = newLength; - - count.set(left, (count.get(left) || 0) - 1); - count.set(right, (count.get(right) || 0) - 1); - count.set(newLength, (count.get(newLength) || 0) + 1); - - if (count.get(m) > 0) result = step + 1; - } - - return result; -}; diff --git a/solutions/1563-stone-game-v.js b/solutions/1563-stone-game-v.js deleted file mode 100644 index e07864b4..00000000 --- a/solutions/1563-stone-game-v.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1563. Stone Game V - * https://leetcode.com/problems/stone-game-v/ - * Difficulty: Hard - * - * There are several stones arranged in a row, and each stone has an associated value which - * is an integer given in the array stoneValue. - * - * In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and - * right row), then Bob calculates the value of each row which is the sum of the values of all - * the stones in this row. Bob throws away the row which has the maximum value, and Alice's - * score increases by the value of the remaining row. If the value of the two rows are equal, - * Bob lets Alice decide which row will be thrown away. The next round starts with the remaining - * row. - * - * The game ends when there is only one stone remaining. Alice's is initially zero. - * - * Return the maximum score that Alice can obtain. - */ - -/** - * @param {number[]} stoneValue - * @return {number} - */ -var stoneGameV = function(stoneValue) { - const n = stoneValue.length; - const prefixScore = Array.from({ length: n + 1 }, () => 0); - const dp = Array.from({ length: n }, () => new Array(n).fill(-1)); - - for (let index = 1; index <= n; index++) { - prefixScore[index] = prefixScore[index - 1] + stoneValue[index - 1]; - } - - return getMaxScore(0, n - 1); - - function getMaxScore(left, right) { - if (left >= right) return 0; - if (dp[left][right] !== -1) return dp[left][right]; - let result = 0; - - for (let index = left; index < right; index++) { - const heap1 = prefixScore[index + 1] - prefixScore[left]; - const heap2 = prefixScore[right + 1] - prefixScore[index + 1]; - - if (heap1 > heap2) { - const score = heap2 + getMaxScore(index + 1, right); - - result = Math.max(score, result); - } else if (heap1 < heap2) { - const score = heap1 + getMaxScore(left, index); - - result = Math.max(score, result); - } else { - const score1 = heap2 + getMaxScore(index + 1, right); - const score2 = heap1 + getMaxScore(left, index); - - result = Math.max(result, score1, score2); - } - } - - dp[left][right] = result; - - return result; - } -}; diff --git a/solutions/1567-maximum-length-of-subarray-with-positive-product.js b/solutions/1567-maximum-length-of-subarray-with-positive-product.js deleted file mode 100644 index b36a1866..00000000 --- a/solutions/1567-maximum-length-of-subarray-with-positive-product.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1567. Maximum Length of Subarray With Positive Product - * https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/ - * Difficulty: Medium - * - * Given an array of integers nums, find the maximum length of a subarray where the product of - * all its elements is positive. - * - * A subarray of an array is a consecutive sequence of zero or more values taken out of that array. - * - * Return the maximum length of a subarray with positive product. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var getMaxLen = function(nums) { - let result = 0; - let positiveCount = 0; - let negativeCount = 0; - let firstNegativeIndex = -1; - - for (let i = 0; i < nums.length; i++) { - if (nums[i] === 0) { - positiveCount = 0; - negativeCount = 0; - firstNegativeIndex = -1; - continue; - } - - if (nums[i] > 0) { - positiveCount++; - } else { - negativeCount++; - if (firstNegativeIndex === -1) { - firstNegativeIndex = i; - } - } - - if (negativeCount % 2 === 0) { - result = Math.max(result, positiveCount + negativeCount); - } else { - result = Math.max(result, i - firstNegativeIndex); - } - } - - return result; -}; diff --git a/solutions/1568-minimum-number-of-days-to-disconnect-island.js b/solutions/1568-minimum-number-of-days-to-disconnect-island.js deleted file mode 100644 index b7183dd1..00000000 --- a/solutions/1568-minimum-number-of-days-to-disconnect-island.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 1568. Minimum Number of Days to Disconnect Island - * https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/ - * Difficulty: Hard - * - * You are given an m x n binary grid grid where 1 represents land and 0 represents water. An - * island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. - * - * The grid is said to be connected if we have exactly one island, otherwise is said disconnected. - * - * In one day, we are allowed to change any single land cell (1) into a water cell (0). - * - * Return the minimum number of days to disconnect the grid. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var minDays = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - - if (countIslands() !== 1) return 0; - - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (grid[r][c] === 1) { - grid[r][c] = 0; - if (countIslands() !== 1) return 1; - grid[r][c] = 1; - } - } - } - - return 2; - - function countIslands() { - const visited = Array(rows).fill().map(() => Array(cols).fill(false)); - let islands = 0; - - function dfs(row, col) { - if (row < 0 || row >= rows || col < 0 || col >= cols - || visited[row][col] || grid[row][col] === 0) { - return; - } - visited[row][col] = true; - dfs(row + 1, col); - dfs(row - 1, col); - dfs(row, col + 1); - dfs(row, col - 1); - } - - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (grid[r][c] === 1 && !visited[r][c]) { - islands++; - dfs(r, c); - } - } - } - return islands; - } -}; diff --git a/solutions/1569-number-of-ways-to-reorder-array-to-get-same-bst.js b/solutions/1569-number-of-ways-to-reorder-array-to-get-same-bst.js deleted file mode 100644 index b28dc600..00000000 --- a/solutions/1569-number-of-ways-to-reorder-array-to-get-same-bst.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1569. Number of Ways to Reorder Array to Get Same BST - * https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/ - * Difficulty: Hard - * - * Given an array nums that represents a permutation of integers from 1 to n. We are going to - * construct a binary search tree (BST) by inserting the elements of nums in order into an - * initially empty BST. Find the number of different ways to reorder nums so that the constructed - * BST is identical to that formed from the original array nums. - * - * For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a - * right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST. - * - * Return the number of ways to reorder nums such that the BST formed is identical to the original - * BST formed from nums. - * - * Since the answer may be very large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var numOfWays = function(nums) { - const MOD = BigInt(10 ** 9 + 7); - const factorialCache = Array(nums.length).fill(null); - factorialCache[0] = 1n; - - function calculatePermutations(arr) { - if (arr.length < 3) return 1n; - - const root = arr[0]; - const leftSubtree = []; - const rightSubtree = []; - - for (let i = 1; i < arr.length; i++) { - if (arr[i] < root) { - leftSubtree.push(arr[i]); - } else { - rightSubtree.push(arr[i]); - } - } - - const leftPermutations = calculatePermutations(leftSubtree); - const rightPermutations = calculatePermutations(rightSubtree); - const totalNodes = BigInt(arr.length - 1); - const leftNodes = BigInt(leftSubtree.length); - - return (helper(totalNodes, leftNodes) * leftPermutations * rightPermutations) % MOD; - } - - function helper(n, k) { - factorialCache[n] = computeFactorial(n); - factorialCache[n - k] = computeFactorial(n - k); - factorialCache[k] = computeFactorial(k); - return factorialCache[n] / (factorialCache[k] * factorialCache[n - k]); - } - - function computeFactorial(n) { - if (factorialCache[n]) return factorialCache[n]; - return n * computeFactorial(n - 1n); - } - - return Number((calculatePermutations(nums) - 1n) % MOD); -}; diff --git a/solutions/1572-matrix-diagonal-sum.js b/solutions/1572-matrix-diagonal-sum.js deleted file mode 100644 index 0eb5ac63..00000000 --- a/solutions/1572-matrix-diagonal-sum.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1572. Matrix Diagonal Sum - * https://leetcode.com/problems/matrix-diagonal-sum/ - * Difficulty: Easy - * - * Given a square matrix mat, return the sum of the matrix diagonals. - * - * Only include the sum of all the elements on the primary diagonal and all the elements on the - * secondary diagonal that are not part of the primary diagonal. - */ - -/** - * @param {number[][]} mat - * @return {number} - */ -var diagonalSum = function(mat) { - const n = mat.length; - let sum = 0; - - for (let i = 0; i < n; i++) { - sum += mat[i][i]; - sum += mat[i][n - 1 - i]; - } - - if (n % 2 === 1) { - sum -= mat[Math.floor(n / 2)][Math.floor(n / 2)]; - } - - return sum; -}; diff --git a/solutions/1573-number-of-ways-to-split-a-string.js b/solutions/1573-number-of-ways-to-split-a-string.js deleted file mode 100644 index 0ce0e198..00000000 --- a/solutions/1573-number-of-ways-to-split-a-string.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1573. Number of Ways to Split a String - * https://leetcode.com/problems/number-of-ways-to-split-a-string/ - * Difficulty: Medium - * - * Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 - * where s1 + s2 + s3 = s. - * - * Return the number of ways s can be split such that the number of ones is the same in s1, - * s2, and s3. Since the answer may be too large, return it modulo 109 + 7. - */ - -/** - * @param {string} s - * @return {number} - */ -var numWays = function(s) { - const MOD = 1e9 + 7; - let ones = 0; - - for (const char of s) { - if (char === '1') ones++; - } - - if (ones % 3 !== 0) return 0; - if (ones === 0) { - return Number((BigInt(s.length - 1) * BigInt(s.length - 2) / 2n) % BigInt(MOD)); - } - - const targetOnes = ones / 3; - let firstCount = 0; - let secondCount = 0; - let currentOnes = 0; - - for (let i = 0; i < s.length; i++) { - if (s[i] === '1') currentOnes++; - if (currentOnes === targetOnes) firstCount++; - else if (currentOnes === 2 * targetOnes) secondCount++; - } - - return Number((BigInt(firstCount) * BigInt(secondCount)) % BigInt(MOD)); -}; diff --git a/solutions/1574-shortest-subarray-to-be-removed-to-make-array-sorted.js b/solutions/1574-shortest-subarray-to-be-removed-to-make-array-sorted.js deleted file mode 100644 index db657500..00000000 --- a/solutions/1574-shortest-subarray-to-be-removed-to-make-array-sorted.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1574. Shortest Subarray to be Removed to Make Array Sorted - * https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/ - * Difficulty: Medium - * - * Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining - * elements in arr are non-decreasing. - * - * Return the length of the shortest subarray to remove. - * - * A subarray is a contiguous subsequence of the array. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var findLengthOfShortestSubarray = function(arr) { - const n = arr.length; - let left = 0; - - while (left < n - 1 && arr[left] <= arr[left + 1]) { - left++; - } - - if (left === n - 1) return 0; - - let right = n - 1; - while (right > 0 && arr[right - 1] <= arr[right]) { - right--; - } - - let minLength = Math.min(n - left - 1, right); - - for (let i = 0, j = right; i <= left && j < n; i++) { - while (j < n && arr[i] > arr[j]) { - j++; - } - minLength = Math.min(minLength, j - i - 1); - } - - return minLength; -}; diff --git a/solutions/1575-count-all-possible-routes.js b/solutions/1575-count-all-possible-routes.js deleted file mode 100644 index b71afee0..00000000 --- a/solutions/1575-count-all-possible-routes.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1575. Count All Possible Routes - * https://leetcode.com/problems/count-all-possible-routes/ - * Difficulty: Hard - * - * You are given an array of distinct positive integers locations where locations[i] represents - * the position of city i. You are also given integers start, finish and fuel representing the - * starting city, ending city, and the initial amount of fuel you have, respectively. - * - * At each step, if you are at city i, you can pick any city j such that j != i and - * 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the - * amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes - * the absolute value of x. - * - * Notice that fuel cannot become negative at any point in time, and that you are allowed to visit - * any city more than once (including start and finish). - * - * Return the count of all possible routes from start to finish. Since the answer may be too large, - * return it modulo 109 + 7. - */ - -/** - * @param {number[]} locations - * @param {number} start - * @param {number} finish - * @param {number} fuel - * @return {number} - */ -var countRoutes = function(locations, start, finish, fuel) { - const MOD = 1e9 + 7; - const memo = new Array(locations.length).fill().map(() => new Array(fuel + 1).fill(-1)); - - function calculateRoutes(currentCity, remainingFuel) { - if (remainingFuel < 0) return 0; - if (memo[currentCity][remainingFuel] !== -1) return memo[currentCity][remainingFuel]; - - let routes = currentCity === finish ? 1 : 0; - - for (let nextCity = 0; nextCity < locations.length; nextCity++) { - if (nextCity !== currentCity) { - const fuelCost = Math.abs(locations[currentCity] - locations[nextCity]); - routes = (routes + calculateRoutes(nextCity, remainingFuel - fuelCost)) % MOD; - } - } - - memo[currentCity][remainingFuel] = routes; - return routes; - } - - return calculateRoutes(start, fuel); -}; diff --git a/solutions/1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.js b/solutions/1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.js deleted file mode 100644 index 78972574..00000000 --- a/solutions/1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers - * https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/ - * Difficulty: Medium - * - * Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and - * type 2) under the following rules: - * - Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length - * and 0 <= j < k < nums2.length. - * - Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length - * and 0 <= j < k < nums1.length. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var numTriplets = function(nums1, nums2) { - return countTriplets(nums1, nums2) + countTriplets(nums2, nums1); - - function countTriplets(arr1, arr2) { - const productMap = new Map(); - let count = 0; - - for (let i = 0; i < arr2.length; i++) { - for (let j = i + 1; j < arr2.length; j++) { - const product = BigInt(arr2[i]) * BigInt(arr2[j]); - productMap.set(product, (productMap.get(product) || 0) + 1); - } - } - - for (const num of arr1) { - const square = BigInt(num) * BigInt(num); - if (productMap.has(square)) { - count += productMap.get(square); - } - } - - return count; - } -}; diff --git a/solutions/1578-minimum-time-to-make-rope-colorful.js b/solutions/1578-minimum-time-to-make-rope-colorful.js deleted file mode 100644 index 8c787a32..00000000 --- a/solutions/1578-minimum-time-to-make-rope-colorful.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1578. Minimum Time to Make Rope Colorful - * https://leetcode.com/problems/minimum-time-to-make-rope-colorful/ - * Difficulty: Medium - * - * Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] - * is the color of the ith balloon. - * - * Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same - * color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. - * You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) - * that Bob needs to remove the ith balloon from the rope. - * - * Return the minimum time Bob needs to make the rope colorful. - */ - -/** - * @param {string} colors - * @param {number[]} neededTime - * @return {number} - */ -var minCost = function(colors, neededTime) { - let result = 0; - let i = 0; - - while (i < colors.length - 1) { - if (colors[i] === colors[i + 1]) { - let maxTime = neededTime[i]; - let sumTime = neededTime[i]; - let j = i + 1; - - while (j < colors.length && colors[j] === colors[i]) { - maxTime = Math.max(maxTime, neededTime[j]); - sumTime += neededTime[j]; - j++; - } - - result += sumTime - maxTime; - i = j; - } else { - i++; - } - } - - return result; -}; diff --git a/solutions/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js b/solutions/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js deleted file mode 100644 index 3a4cf256..00000000 --- a/solutions/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 1579. Remove Max Number of Edges to Keep Graph Fully Traversable - * https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/ - * Difficulty: Hard - * - * Alice and Bob have an undirected graph of n nodes and three types of edges: - * - Type 1: Can be traversed by Alice only. - * - Type 2: Can be traversed by Bob only. - * - Type 3: Can be traversed by both Alice and Bob. - * - * Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type - * typei between nodes ui and vi, find the maximum number of edges you can remove so that after - * removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph - * is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. - * - * Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully - * traverse the graph. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number} - */ -var maxNumEdgesToRemove = function(n, edges) { - const alice = new UnionFind(n + 1); - const bob = new UnionFind(n + 1); - let removableEdges = 0; - - for (const [type, u, v] of edges) { - if (type === 3) { - const usedAlice = alice.union(u, v); - const usedBob = bob.union(u, v); - if (!usedAlice && !usedBob) { - removableEdges++; - } - } - } - - for (const [type, u, v] of edges) { - if (type === 1) { - if (!alice.union(u, v)) { - removableEdges++; - } - } else if (type === 2) { - if (!bob.union(u, v)) { - removableEdges++; - } - } - } - - return alice.components === 2 && bob.components === 2 ? removableEdges : -1; -}; - -class UnionFind { - constructor(size) { - this.parent = Array(size).fill().map((_, i) => i); - this.rank = Array(size).fill(0); - this.components = size; - } - - find(x) { - if (this.parent[x] !== x) { - this.parent[x] = this.find(this.parent[x]); - } - return this.parent[x]; - } - - union(x, y) { - const rootX = this.find(x); - const rootY = this.find(y); - if (rootX === rootY) return false; - if (this.rank[rootX] < this.rank[rootY]) { - this.parent[rootX] = rootY; - } else if (this.rank[rootX] > this.rank[rootY]) { - this.parent[rootY] = rootX; - } else { - this.parent[rootY] = rootX; - this.rank[rootX]++; - } - this.components--; - return true; - } -} diff --git a/solutions/1582-special-positions-in-a-binary-matrix.js b/solutions/1582-special-positions-in-a-binary-matrix.js deleted file mode 100644 index ea2e1db8..00000000 --- a/solutions/1582-special-positions-in-a-binary-matrix.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1582. Special Positions in a Binary Matrix - * https://leetcode.com/problems/special-positions-in-a-binary-matrix/ - * Difficulty: Easy - * - * Given an m x n binary matrix mat, return the number of special positions in mat. - * - * A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and - * column j are 0 (rows and columns are 0-indexed). - */ - -/** - * @param {number[][]} mat - * @return {number} - */ -var numSpecial = function(mat) { - const rows = mat.length; - const cols = mat[0].length; - const rowSums = new Array(rows).fill(0); - const colSums = new Array(cols).fill(0); - let result = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (mat[i][j] === 1) { - rowSums[i]++; - colSums[j]++; - } - } - } - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (mat[i][j] === 1 && rowSums[i] === 1 && colSums[j] === 1) { - result++; - } - } - } - - return result; -}; diff --git a/solutions/1583-count-unhappy-friends.js b/solutions/1583-count-unhappy-friends.js deleted file mode 100644 index 428d7112..00000000 --- a/solutions/1583-count-unhappy-friends.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 1583. Count Unhappy Friends - * https://leetcode.com/problems/count-unhappy-friends/ - * Difficulty: Medium - * - * You are given a list of preferences for n friends, where n is always even. - * - * For each person i, preferences[i] contains a list of friends sorted in the order of preference. - * In other words, a friend earlier in the list is more preferred than a friend later in the list. - * Friends in each list are denoted by integers from 0 to n-1. - * - * All the friends are divided into pairs. The pairings are given in a list pairs, where - * pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi. - * - * However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x - * is paired with y and there exists a friend u who is paired with v but: - * - x prefers u over y, and - * - u prefers x over v. - * - * Return the number of unhappy friends. - */ - -/** - * @param {number} n - * @param {number[][]} preferences - * @param {number[][]} pairs - * @return {number} - */ -var unhappyFriends = function(n, preferences, pairs) { - const rank = Array.from({ length: n }, () => new Array(n).fill(0)); - const pairMap = new Array(n).fill(0); - let result = 0; - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n - 1; j++) { - rank[i][preferences[i][j]] = j; - } - } - - for (const [x, y] of pairs) { - pairMap[x] = y; - pairMap[y] = x; - } - - for (let x = 0; x < n; x++) { - const y = pairMap[x]; - for (const u of preferences[x]) { - if (u === y) break; - const v = pairMap[u]; - if (rank[u][x] < rank[u][v]) { - result++; - break; - } - } - } - - return result; -}; diff --git a/solutions/1584-min-cost-to-connect-all-points.js b/solutions/1584-min-cost-to-connect-all-points.js deleted file mode 100644 index 64cd86dc..00000000 --- a/solutions/1584-min-cost-to-connect-all-points.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1584. Min Cost to Connect All Points - * https://leetcode.com/problems/min-cost-to-connect-all-points/ - * Difficulty: Medium - * - * You are given an array points representing integer coordinates of some points on a 2D-plane, - * where points[i] = [xi, yi]. - * - * The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between - * them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. - * - * Return the minimum cost to make all points connected. All points are connected if there is - * exactly one simple path between any two points. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var minCostConnectPoints = function(points) { - const n = points.length; - const minCost = Array(n).fill(Infinity); - const visited = new Set(); - let result = 0; - - minCost[0] = 0; - - for (let i = 0; i < n; i++) { - let minIdx = -1; - let minVal = Infinity; - - for (let j = 0; j < n; j++) { - if (!visited.has(j) && minCost[j] < minVal) { - minVal = minCost[j]; - minIdx = j; - } - } - - if (minIdx === -1) break; - - visited.add(minIdx); - result += minVal; - - for (let j = 0; j < n; j++) { - if (!visited.has(j)) { - const cost = Math.abs(points[minIdx][0] - points[j][0]) - + Math.abs(points[minIdx][1] - points[j][1]); - minCost[j] = Math.min(minCost[j], cost); - } - } - } - - return result; -}; diff --git a/solutions/1585-check-if-string-is-transformable-with-substring-sort-operations.js b/solutions/1585-check-if-string-is-transformable-with-substring-sort-operations.js deleted file mode 100644 index 181bccb0..00000000 --- a/solutions/1585-check-if-string-is-transformable-with-substring-sort-operations.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1585. Check If String Is Transformable With Substring Sort Operations - * https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/ - * Difficulty: Hard - * - * Given two strings s and t, transform string s into string t using the following operation any - * number of times: - * - Choose a non-empty substring in s and sort it in place so the characters are in ascending - * order. - * - For example, applying the operation on the underlined substring in "14234" results - * in "12344". - * - * Return true if it is possible to transform s into t. Otherwise, return false. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} s - * @param {string} t - * @return {boolean} - */ -var isTransformable = function(source, target) { - const digitPositions = Array.from({ length: 10 }, () => []); - for (let index = 0; index < source.length; index++) { - digitPositions[source[index]].push(index); - } - - const currentIndices = new Array(10).fill(0); - - for (const digit of target) { - const digitValue = parseInt(digit, 10); - if (currentIndices[digitValue] >= digitPositions[digitValue].length) { - return false; - } - - const position = digitPositions[digitValue][currentIndices[digitValue]]; - for (let smallerDigit = 0; smallerDigit < digitValue; smallerDigit++) { - if (currentIndices[smallerDigit] < digitPositions[smallerDigit].length - && digitPositions[smallerDigit][currentIndices[smallerDigit]] < position) { - return false; - } - } - - currentIndices[digitValue]++; - } - - return true; -}; diff --git a/solutions/1588-sum-of-all-odd-length-subarrays.js b/solutions/1588-sum-of-all-odd-length-subarrays.js deleted file mode 100644 index 2121c748..00000000 --- a/solutions/1588-sum-of-all-odd-length-subarrays.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1588. Sum of All Odd Length Subarrays - * https://leetcode.com/problems/sum-of-all-odd-length-subarrays/ - * Difficulty: Easy - * - * Given an array of positive integers arr, return the sum of all possible odd-length - * subarrays of arr. - * - * A subarray is a contiguous subsequence of the array. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var sumOddLengthSubarrays = function(arr) { - let result = 0; - - for (let index = 0; index < arr.length; index++) { - result += arr[index] * Math.ceil(((index + 1) * (arr.length - index)) / 2); - } - - return result; -}; diff --git a/solutions/1589-maximum-sum-obtained-of-any-permutation.js b/solutions/1589-maximum-sum-obtained-of-any-permutation.js deleted file mode 100644 index 69acb0f6..00000000 --- a/solutions/1589-maximum-sum-obtained-of-any-permutation.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1589. Maximum Sum Obtained of Any Permutation - * https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/ - * Difficulty: Medium - * - * We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. - * The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] - * + nums[endi]. Both starti and endi are 0-indexed. - * - * Return the maximum total sum of all requests among all permutations of nums. - * - * Since the answer may be too large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} nums - * @param {number[][]} requests - * @return {number} - */ -var maxSumRangeQuery = function(nums, requests) { - const MOD = 1e9 + 7; - const n = nums.length; - const freq = new Array(n + 1).fill(0); - - for (const [start, end] of requests) { - freq[start]++; - freq[end + 1]--; - } - - const count = new Array(n).fill(0); - let current = 0; - for (let i = 0; i < n; i++) { - current += freq[i]; - count[i] = current; - } - - count.sort((a, b) => b - a); - nums.sort((a, b) => b - a); - - let total = 0; - for (let i = 0; i < n; i++) { - total = (total + nums[i] * count[i]) % MOD; - } - - return total; -}; diff --git a/solutions/1590-make-sum-divisible-by-p.js b/solutions/1590-make-sum-divisible-by-p.js deleted file mode 100644 index f4ab73cf..00000000 --- a/solutions/1590-make-sum-divisible-by-p.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1590. Make Sum Divisible by P - * https://leetcode.com/problems/make-sum-divisible-by-p/ - * Difficulty: Medium - * - * Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that - * the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. - * - * Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. - * - * A subarray is defined as a contiguous block of elements in the array. - */ - -/** - * @param {number[]} nums - * @param {number} p - * @return {number} - */ -var minSubarray = function(nums, p) { - const totalSum = nums.reduce((sum, num) => sum + num, 0); - const remainder = totalSum % p; - - if (remainder === 0) return 0; - - const prefixSums = new Map([[0, -1]]); - let currentSum = 0; - let minLength = nums.length; - - for (let i = 0; i < nums.length; i++) { - currentSum = (currentSum + nums[i]) % p; - const target = (currentSum - remainder + p) % p; - - if (prefixSums.has(target)) { - minLength = Math.min(minLength, i - prefixSums.get(target)); - } - - prefixSums.set(currentSum, i); - } - - return minLength < nums.length ? minLength : -1; -}; diff --git a/solutions/1591-strange-printer-ii.js b/solutions/1591-strange-printer-ii.js deleted file mode 100644 index 40aa1509..00000000 --- a/solutions/1591-strange-printer-ii.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * 1591. Strange Printer II - * https://leetcode.com/problems/strange-printer-ii/ - * Difficulty: Hard - * - * There is a strange printer with the following two special requirements: - * - On each turn, the printer will print a solid rectangular pattern of a single color on the - * grid. This will cover up the existing colors in the rectangle. - * - Once the printer has used a color for the above operation, the same color cannot be used again. - * - * You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position - * (row, col) of the grid. - * - * Return true if it is possible to print the matrix targetGrid, otherwise, return false. - */ - -/** - * @param {number[][]} targetGrid - * @return {boolean} - */ -var isPrintable = function(targetGrid) { - const rows = targetGrid.length; - const cols = targetGrid[0].length; - const colorBounds = new Map(); - - for (let color = 1; color <= 60; color++) { - let minRow = rows; - let maxRow = -1; - let minCol = cols; - let maxCol = -1; - - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (targetGrid[r][c] === color) { - minRow = Math.min(minRow, r); - maxRow = Math.max(maxRow, r); - minCol = Math.min(minCol, c); - maxCol = Math.max(maxCol, c); - } - } - } - if (maxRow >= 0) { - colorBounds.set(color, [minRow, maxRow, minCol, maxCol]); - } - } - - const dependencies = new Map(); - for (const [color, [minRow, maxRow, minCol, maxCol]] of colorBounds) { - const deps = new Set(); - for (let r = minRow; r <= maxRow; r++) { - for (let c = minCol; c <= maxCol; c++) { - if (targetGrid[r][c] !== color) { - deps.add(targetGrid[r][c]); - } - } - } - dependencies.set(color, deps); - } - - const visited = new Set(); - const recStack = new Set(); - - function hasCycle(color) { - if (recStack.has(color)) return true; - if (visited.has(color)) return false; - - visited.add(color); - recStack.add(color); - - for (const dep of dependencies.get(color) || []) { - if (hasCycle(dep)) return true; - } - - recStack.delete(color); - return false; - } - - for (const color of colorBounds.keys()) { - if (hasCycle(color)) return false; - } - - return true; -}; diff --git a/solutions/1592-rearrange-spaces-between-words.js b/solutions/1592-rearrange-spaces-between-words.js deleted file mode 100644 index b6b8b786..00000000 --- a/solutions/1592-rearrange-spaces-between-words.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1592. Rearrange Spaces Between Words - * https://leetcode.com/problems/rearrange-spaces-between-words/ - * Difficulty: Easy - * - * You are given a string text of words that are placed among some number of spaces. Each word - * consists of one or more lowercase English letters and are separated by at least one space. - * It's guaranteed that text contains at least one word. - * - * Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent - * words and that number is maximized. If you cannot redistribute all the spaces equally, place - * the extra spaces at the end, meaning the returned string should be the same length as text. - * - * Return the string after rearranging the spaces. - */ - -/** - * @param {string} text - * @return {string} - */ -var reorderSpaces = function(text) { - const words = text.trim().split(/\s+/); - const spaceCount = text.length - words.join('').length; - const wordCount = words.length; - - if (wordCount === 1) return words[0] + ' '.repeat(spaceCount); - - const spacesBetween = Math.floor(spaceCount / (wordCount - 1)); - const extraSpaces = spaceCount % (wordCount - 1); - - return words.join(' '.repeat(spacesBetween)) + ' '.repeat(extraSpaces); -}; diff --git a/solutions/1593-split-a-string-into-the-max-number-of-unique-substrings.js b/solutions/1593-split-a-string-into-the-max-number-of-unique-substrings.js deleted file mode 100644 index d5f32602..00000000 --- a/solutions/1593-split-a-string-into-the-max-number-of-unique-substrings.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1593. Split a String Into the Max Number of Unique Substrings - * https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/ - * Difficulty: Medium - * - * Given a string s, return the maximum number of unique substrings that the given string can - * be split into. - * - * You can split string s into any list of non-empty substrings, where the concatenation of - * the substrings forms the original string. However, you must split the substrings such that - * all of them are unique. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} s - * @return {number} - */ -var maxUniqueSplit = function(s) { - return backtrack(0, new Set()); - - function backtrack(start, seen) { - if (start === s.length) return seen.size; - - let maxSplits = 0; - for (let end = start + 1; end <= s.length; end++) { - const substring = s.slice(start, end); - if (!seen.has(substring)) { - seen.add(substring); - maxSplits = Math.max(maxSplits, backtrack(end, seen)); - seen.delete(substring); - } - } - - return maxSplits; - } -}; diff --git a/solutions/1594-maximum-non-negative-product-in-a-matrix.js b/solutions/1594-maximum-non-negative-product-in-a-matrix.js deleted file mode 100644 index ec7d75f3..00000000 --- a/solutions/1594-maximum-non-negative-product-in-a-matrix.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1594. Maximum Non Negative Product in a Matrix - * https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/ - * Difficulty: Medium - * - * You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), - * and in each step, you can only move right or down in the matrix. - * - * Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right - * corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a - * path is the product of all integers in the grid cells visited along the path. - * - * Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, - * return -1. - * - * Notice that the modulo is performed after getting the maximum product. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var maxProductPath = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const dp = Array.from({ length: rows }, () => - Array.from({ length: cols }, () => [1, 1]) - ); - - dp[0][0] = [grid[0][0], grid[0][0]]; - - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - if (row === 0 && col === 0) continue; - - let minProduct = Infinity; - let maxProduct = -Infinity; - - if (row > 0) { - minProduct = Math.min( - minProduct, - dp[row - 1][col][0] * grid[row][col], - dp[row - 1][col][1] * grid[row][col] - ); - maxProduct = Math.max( - maxProduct, - dp[row - 1][col][0] * grid[row][col], - dp[row - 1][col][1] * grid[row][col] - ); - } - - if (col > 0) { - minProduct = Math.min( - minProduct, - dp[row][col - 1][0] * grid[row][col], - dp[row][col - 1][1] * grid[row][col] - ); - maxProduct = Math.max( - maxProduct, - dp[row][col - 1][0] * grid[row][col], - dp[row][col - 1][1] * grid[row][col] - ); - } - - dp[row][col] = [minProduct, maxProduct]; - } - } - - const maxResult = dp[rows - 1][cols - 1][1]; - return maxResult < 0 ? -1 : maxResult % (10 ** 9 + 7); -}; diff --git a/solutions/1595-minimum-cost-to-connect-two-groups-of-points.js b/solutions/1595-minimum-cost-to-connect-two-groups-of-points.js deleted file mode 100644 index cd610a08..00000000 --- a/solutions/1595-minimum-cost-to-connect-two-groups-of-points.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1595. Minimum Cost to Connect Two Groups of Points - * https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/ - * Difficulty: Hard - * - * You are given two groups of points where the first group has size1 points, the second group - * has size2 points, and size1 >= size2. - * - * The cost of the connection between any two points are given in an size1 x size2 matrix where - * cost[i][j] is the cost of connecting point i of the first group and point j of the second group. - * The groups are connected if each point in both groups is connected to one or more points in the - * opposite group. In other words, each point in the first group must be connected to at least one - * point in the second group, and each point in the second group must be connected to at least one - * point in the first group. - * - * Return the minimum cost it takes to connect the two groups. - */ - -/** -* @param {number[][]} cost -* @return {number} -*/ -var connectTwoGroups = function(cost) { - const size1 = cost.length; - const size2 = cost[0].length; - - const minCostGroup2 = new Array(size2).fill(Infinity); - for (let j = 0; j < size2; j++) { - for (let i = 0; i < size1; i++) { - minCostGroup2[j] = Math.min(minCostGroup2[j], cost[i][j]); - } - } - - const memo = new Array(size1).fill(0).map(() => new Array(1 << size2).fill(-1)); - - return dfs(0, 0); - - function dfs(i, mask) { - if (i === size1) { - let remainingCost = 0; - for (let j = 0; j < size2; j++) { - if ((mask & (1 << j)) === 0) { - remainingCost += minCostGroup2[j]; - } - } - return remainingCost; - } - - if (memo[i][mask] !== -1) return memo[i][mask]; - - let minCost = Infinity; - - for (let j = 0; j < size2; j++) { - minCost = Math.min( - minCost, - cost[i][j] + dfs(i + 1, mask | (1 << j)) - ); - } - - memo[i][mask] = minCost; - return minCost; - } -}; diff --git a/solutions/1599-maximum-profit-of-operating-a-centennial-wheel.js b/solutions/1599-maximum-profit-of-operating-a-centennial-wheel.js deleted file mode 100644 index 46911193..00000000 --- a/solutions/1599-maximum-profit-of-operating-a-centennial-wheel.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 1599. Maximum Profit of Operating a Centennial Wheel - * https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/ - * Difficulty: Medium - * - * You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for - * up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you - * runningCost dollars. - * - * You are given an array customers of length n where customers[i] is the number of new customers - * arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times - * before the customers[i] customers arrive. You cannot make customers wait if there is room in the - * gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the - * ground and will exit once that gondola reaches the ground again. - * - * You can stop the wheel at any time, including before serving all customers. If you decide to stop - * serving customers, all subsequent rotations are free in order to get all the customers down - * safely. Note that if there are currently more than four customers waiting at the wheel, only - * four will board the gondola, and the rest will wait for the next rotation. - * - * Return the minimum number of rotations you need to perform to maximize your profit. If there is - * no scenario where the profit is positive, return -1. - */ - -/** - * @param {number[]} customers - * @param {number} boardingCost - * @param {number} runningCost - * @return {number} - */ -var minOperationsMaxProfit = function(customers, boardingCost, runningCost) { - let waitingCustomers = 0; - let totalBoarded = 0; - let maxProfit = -Infinity; - let rotationAtMaxProfit = -1; - let currentProfit = 0; - let rotations = 0; - - const gondolaCapacity = 4; - - for (let i = 0; i < customers.length || waitingCustomers > 0; i++) { - rotations++; - - if (i < customers.length) { - waitingCustomers += customers[i]; - } - - const boarding = Math.min(waitingCustomers, gondolaCapacity); - waitingCustomers -= boarding; - totalBoarded += boarding; - - currentProfit = totalBoarded * boardingCost - rotations * runningCost; - - if (currentProfit > maxProfit) { - maxProfit = currentProfit; - rotationAtMaxProfit = rotations; - } - } - - return maxProfit > 0 ? rotationAtMaxProfit : -1; -}; diff --git a/solutions/1600-throne-inheritance.js b/solutions/1600-throne-inheritance.js deleted file mode 100644 index 6d1f6f4e..00000000 --- a/solutions/1600-throne-inheritance.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * 1600. Throne Inheritance - * https://leetcode.com/problems/throne-inheritance/ - * Difficulty: Medium - * - * A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, - * someone in the family dies or a child is born. - * - * The kingdom has a well-defined order of inheritance that consists of the king as the first - * member. Let's define the recursive function Successor(x, curOrder), which given a person x and - * the inheritance order so far, returns who should be the next person after x in the order of - * inheritance. - * - * For example, assume we have a kingdom that consists of the king, his children Alice and Bob - * (Alice is older than Bob), and finally Alice's son Jack. - * - * 1. In the beginning, curOrder will be ["king"]. - * 2. Calling Successor(king, curOrder) will return Alice, so we append to curOrder to - * get ["king", "Alice"]. - * 3. Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to - * get ["king", "Alice", "Jack"]. - * 4. Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to - * get ["king", "Alice", "Jack", "Bob"]. - * 5. Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance - * will be ["king", "Alice", "Jack", "Bob"]. - * - * Using the above function, we can always obtain a unique order of inheritance. - * - * Implement the ThroneInheritance class: - * - ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. - * The name of the king is given as part of the constructor. - * - void birth(string parentName, string childName) Indicates that parentName gave birth - * to childName. - * - void death(string name) Indicates the death of name. The death of the person doesn't - * affect the Successor function nor the current inheritance order. You can treat it as - * just marking the person as dead. - * - string[] getInheritanceOrder() Returns a list representing the current order of inheritance - * excluding dead people. - */ - -/** - * @param {string} kingName - */ -var ThroneInheritance = function(kingName) { - this.king = kingName; - this.familyTree = new Map(); - this.deceased = new Set(); -}; - -/** - * @param {string} parentName - * @param {string} childName - * @return {void} - */ -ThroneInheritance.prototype.birth = function(parentName, childName) { - if (!this.familyTree.has(parentName)) { - this.familyTree.set(parentName, []); - } - this.familyTree.get(parentName).push(childName); -}; - -/** - * @param {string} name - * @return {void} - */ -ThroneInheritance.prototype.death = function(name) { - this.deceased.add(name); -}; - -/** - * @return {string[]} - */ -ThroneInheritance.prototype.getInheritanceOrder = function() { - const result = []; - const traverse = (person) => { - if (!this.deceased.has(person)) { - result.push(person); - } - const children = this.familyTree.get(person) || []; - for (const child of children) { - traverse(child); - } - }; - traverse(this.king); - return result; -}; diff --git a/solutions/1601-maximum-number-of-achievable-transfer-requests.js b/solutions/1601-maximum-number-of-achievable-transfer-requests.js deleted file mode 100644 index d1da07b1..00000000 --- a/solutions/1601-maximum-number-of-achievable-transfer-requests.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1601. Maximum Number of Achievable Transfer Requests - * https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/ - * Difficulty: Hard - * - * We have n buildings numbered from 0 to n - 1. Each building has a number of employees. - * It's transfer season, and some employees want to change the building they reside in. - * - * You are given an array requests where requests[i] = [fromi, toi] represents an employee's - * request to transfer from building fromi to building toi. - * - * All buildings are full, so a list of requests is achievable only if for each building, the - * net change in employee transfers is zero. This means the number of employees leaving is - * equal to the number of employees moving in. For example if n = 3 and two employees are - * leaving building 0, one is leaving building 1, and one is leaving building 2, there should - * be two employees moving to building 0, one employee moving to building 1, and one employee - * moving to building 2. - * - * Return the maximum number of achievable requests. - */ - -/** - * @param {number} n - * @param {number[][]} requests - * @return {number} - */ -var maximumRequests = function(n, requests) { - let maxAchievable = 0; - tryCombination(0, 0, new Array(n).fill(0)); - return maxAchievable; - - function tryCombination(index, count, balance) { - if (index === requests.length) { - if (balance.every(val => val === 0)) { - maxAchievable = Math.max(maxAchievable, count); - } - return; - } - - const [from, to] = requests[index]; - balance[from]--; - balance[to]++; - tryCombination(index + 1, count + 1, balance); - balance[from]++; - balance[to]--; - - tryCombination(index + 1, count, balance); - } -}; diff --git a/solutions/1603-design-parking-system.js b/solutions/1603-design-parking-system.js deleted file mode 100644 index 040c764d..00000000 --- a/solutions/1603-design-parking-system.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1603. Design Parking System - * https://leetcode.com/problems/design-parking-system/ - * Difficulty: Easy - * - * Design a parking system for a parking lot. The parking lot has three kinds of parking - * spaces: big, medium, and small, with a fixed number of slots for each size. - * - * Implement the ParkingSystem class: - * - ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. - * The number of slots for each parking space are given as part of the constructor. - * - bool addCar(int carType) Checks whether there is a parking space of carType for the car that - * wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which - * are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its - * carType. If there is no space available, return false, else park the car in that size space - * and return true. - */ - -/** - * @param {number} big - * @param {number} medium - * @param {number} small - */ -var ParkingSystem = function(big, medium, small) { - this.spaces = { 1: big, 2: medium, 3: small }; -}; - -/** - * @param {number} carType - * @return {boolean} - */ -ParkingSystem.prototype.addCar = function(carType) { - if (this.spaces[carType] > 0) { - this.spaces[carType]--; - return true; - } - return false; -}; diff --git a/solutions/1604-alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.js b/solutions/1604-alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.js deleted file mode 100644 index 439bb8a2..00000000 --- a/solutions/1604-alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period - * https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/ - * Difficulty: Medium - * - * LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their - * key-card, the security system saves the worker's name and the time when it was used. The system - * emits an alert if any worker uses the key-card three or more times in a one-hour period. - * - * You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds - * to a person's name and the time when their key-card was used in a single day. - * - * Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49". - * - * Return a list of unique worker names who received an alert for frequent keycard use. Sort the - * names in ascending order alphabetically. - * - * Notice that "10:00" - "11:00" is considered to be within a one-hour period, while - * "22:51" - "23:52" is not considered to be within a one-hour period. - */ - -/** - * @param {string[]} keyName - * @param {string[]} keyTime - * @return {string[]} - */ -var alertNames = function(keyName, keyTime) { - const usageMap = new Map(); - for (let i = 0; i < keyName.length; i++) { - if (!usageMap.has(keyName[i])) { - usageMap.set(keyName[i], []); - } - usageMap.get(keyName[i]).push(timeToMinutes(keyTime[i])); - } - - const result = []; - for (const [name, times] of usageMap) { - times.sort((a, b) => a - b); - for (let i = 2; i < times.length; i++) { - if (times[i] - times[i - 2] <= 60) { - result.push(name); - break; - } - } - } - - return result.sort(); - - function timeToMinutes(time) { - const [hours, minutes] = time.split(':').map(Number); - return hours * 60 + minutes; - } -}; diff --git a/solutions/1605-find-valid-matrix-given-row-and-column-sums.js b/solutions/1605-find-valid-matrix-given-row-and-column-sums.js deleted file mode 100644 index 4e24c533..00000000 --- a/solutions/1605-find-valid-matrix-given-row-and-column-sums.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1605. Find Valid Matrix Given Row and Column Sums - * https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/ - * Difficulty: Medium - * - * You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum - * of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a - * 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums - * of each row and column. - * - * Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies - * the rowSum and colSum requirements. - * - * Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that - * at least one matrix that fulfills the requirements exists. - */ - -/** - * @param {number[]} rowSum - * @param {number[]} colSum - * @return {number[][]} - */ -var restoreMatrix = function(rowSum, colSum) { - const rows = rowSum.length; - const cols = colSum.length; - const matrix = Array.from({ length: rows }, () => Array(cols).fill(0)); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const value = Math.min(rowSum[i], colSum[j]); - matrix[i][j] = value; - rowSum[i] -= value; - colSum[j] -= value; - } - } - - return matrix; -}; diff --git a/solutions/1606-find-servers-that-handled-most-number-of-requests.js b/solutions/1606-find-servers-that-handled-most-number-of-requests.js deleted file mode 100644 index 07ecad21..00000000 --- a/solutions/1606-find-servers-that-handled-most-number-of-requests.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * 1606. Find Servers That Handled Most Number of Requests - * https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/ - * Difficulty: Hard - * - * You have k servers numbered from 0 to k-1 that are being used to handle multiple requests - * simultaneously. Each server has infinite computational capacity but cannot handle more than - * one request at a time. The requests are assigned to servers according to a specific algorithm: - * - The ith (0-indexed) request arrives. - * - If all servers are busy, the request is dropped (not handled at all). - * - If the (i % k)th server is available, assign the request to that server. - * - Otherwise, assign the request to the next available server (wrapping around the list of servers - * and starting from 0 if necessary). For example, if the ith server is busy, try to assign the - * request to the (i+1)th server, then the (i+2)th server, and so on. - * - * You are given a strictly increasing array arrival of positive integers, where arrival[i] - * represents the arrival time of the ith request, and another array load, where load[i] represents - * the load of the ith request (the time it takes to complete). Your goal is to find the busiest - * server(s). A server is considered busiest if it handled the most number of requests successfully - * among all the servers. - * - * Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs - * in any order. - */ - -/** - * @param {number} k - * @param {number[]} arrival - * @param {number[]} load - * @return {number[]} - */ -var busiestServers = function(k, arrival, load) { - const requests = new Array(k).fill(0); - const busy = new PriorityQueue((a, b) => a[0] - b[0]); - const right = Array.from({length: k}, (_, i) => i); - let left = []; - - for (let i = 0; i < arrival.length; i++) { - const time = arrival[i]; - const target = i % k; - - while (!busy.isEmpty() && busy.front()[0] <= time) { - const serverId = busy.dequeue()[1]; - (serverId >= target) ? binaryInsert(right, serverId) : binaryInsert(left, serverId); - } - - let assigned = -1; - - if (right.length > 0) { - const index = binarySearch(right, target); - if (index < right.length) { - assigned = right[index]; - right.splice(index, 1); - } - } - - if (assigned === -1 && left.length > 0) { - assigned = left[0]; - left.shift(); - } - - if (assigned !== -1) { - requests[assigned]++; - busy.enqueue([time + load[i], assigned]); - } - - if ((i + 1) % k === 0) { - right.push(...left); - right.sort((a, b) => a - b); - left = []; - } - } - - const maxRequests = Math.max(...requests); - return requests.reduce((result, count, index) => { - if (count === maxRequests) result.push(index); - return result; - }, []); -}; - -function binarySearch(arr, target) { - let left = 0; - let right = arr.length - 1; - let result = arr.length; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (arr[mid] >= target) { - result = mid; - right = mid - 1; - } else { - left = mid + 1; - } - } - - return result; -} - -function binaryInsert(arr, val) { - arr.splice(binarySearch(arr, val), 0, val); -} diff --git a/solutions/1608-special-array-with-x-elements-greater-than-or-equal-x.js b/solutions/1608-special-array-with-x-elements-greater-than-or-equal-x.js deleted file mode 100644 index 1d19e657..00000000 --- a/solutions/1608-special-array-with-x-elements-greater-than-or-equal-x.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1608. Special Array With X Elements Greater Than or Equal X - * https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ - * Difficulty: Easy - * - * You are given an array nums of non-negative integers. nums is considered special if there exists - * a number x such that there are exactly x numbers in nums that are greater than or equal to x. - * - * Notice that x does not have to be an element in nums. - * - * Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, - * the value for x is unique. - */ - -/** - * @param {number[]} nums - * @param {number} start - * @param {number} end - * @return {number} - */ -function specialArray(numbers) { - numbers.sort((a, b) => b - a); - let left = 0; - let right = numbers.length; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (mid === 0 || numbers[mid - 1] >= mid) { - if (mid === numbers.length || numbers[mid] < mid) { - return mid; - } - left = mid + 1; - } else { - right = mid - 1; - } - } - - return -1; -} diff --git a/solutions/1609-even-odd-tree.js b/solutions/1609-even-odd-tree.js deleted file mode 100644 index 43196719..00000000 --- a/solutions/1609-even-odd-tree.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1609. Even Odd Tree - * https://leetcode.com/problems/even-odd-tree/ - * Difficulty: Medium - * - * A binary tree is named Even-Odd if it meets the following conditions: - * - The root of the binary tree is at level index 0, its children are at level index 1, their - * children are at level index 2, etc. - * - For every even-indexed level, all nodes at the level have odd integer values in strictly - * increasing order (from left to right). - * - For every odd-indexed level, all nodes at the level have even integer values in strictly - * decreasing order (from left to right). - * - * Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise - * return false. - */ - -/** - * 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 isEvenOddTree = function(root) { - let queue = [root]; - let level = 0; - - while (queue.length) { - const levelSize = queue.length; - let prevValue = level % 2 === 0 ? -Infinity : Infinity; - const newQueue = []; - - for (let i = 0; i < levelSize; i++) { - const node = queue[i]; - const isEvenLevel = level % 2 === 0; - const isOddValue = node.val % 2 === 1; - - if (isEvenLevel && (!isOddValue || node.val <= prevValue)) return false; - if (!isEvenLevel && (isOddValue || node.val >= prevValue)) return false; - - prevValue = node.val; - if (node.left) newQueue.push(node.left); - if (node.right) newQueue.push(node.right); - } - - queue = newQueue; - level++; - } - - return true; -}; diff --git a/solutions/1610-maximum-number-of-visible-points.js b/solutions/1610-maximum-number-of-visible-points.js deleted file mode 100644 index 057119b3..00000000 --- a/solutions/1610-maximum-number-of-visible-points.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1610. Maximum Number of Visible Points - * https://leetcode.com/problems/maximum-number-of-visible-points/ - * Difficulty: Hard - * - * You are given an array points, an integer angle, and your location, where location = [posx, posy] - * and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. - * - * Initially, you are facing directly east from your position. You cannot move from your position, - * but you can rotate. In other words, posx and posy cannot be changed. Your field of view in - * degrees is represented by angle, determining how wide you can see from any given view direction. - * Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the - * inclusive range of angles [d - angle/2, d + angle/2]. - * - * You can see some set of points if, for each point, the angle formed by the point, your position, - * and the immediate east direction from your position is in your field of view. - * - * There can be multiple points at one coordinate. There may be points at your location, and you - * can always see these points regardless of your rotation. Points do not obstruct your vision to - * other points. - * - * Return the maximum number of points you can see. - */ - -/** - * @param {number[][]} points - * @param {number} angle - * @param {number[]} location - * @return {number} - */ -var visiblePoints = function(points, angle, location) { - const angles = []; - let originPoints = 0; - const [x0, y0] = location; - - for (const [x, y] of points) { - if (x === x0 && y === y0) { - originPoints++; - continue; - } - const radian = Math.atan2(y - y0, x - x0); - const degree = (radian * 180) / Math.PI; - angles.push(degree); - angles.push(degree + 360); - } - - angles.sort((a, b) => a - b); - const threshold = angle; - let maxVisible = 0; - let left = 0; - - for (let right = 0; right < angles.length; right++) { - while (angles[right] - angles[left] > threshold) { - left++; - } - maxVisible = Math.max(maxVisible, right - left + 1); - } - - return maxVisible + originPoints; -}; diff --git a/solutions/1611-minimum-one-bit-operations-to-make-integers-zero.js b/solutions/1611-minimum-one-bit-operations-to-make-integers-zero.js deleted file mode 100644 index 5358ed7a..00000000 --- a/solutions/1611-minimum-one-bit-operations-to-make-integers-zero.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1611. Minimum One Bit Operations to Make Integers Zero - * https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/ - * Difficulty: Hard - * - * Given an integer n, you must transform it into 0 using the following operations any number - * of times: - * - Change the rightmost (0th) bit in the binary representation of n. - * - Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the - * (i-2)th through 0th bits are set to 0. - * - * Return the minimum number of operations to transform n into 0. - */ - -/** - * @param {number} n - * @return {number} - */ -var minimumOneBitOperations = function(n) { - if (n === 0) return 0; - - let result = 0; - let bit = 1; - while (bit <= n) { - if (n & bit) { - result = (1 << (bit.toString(2).length)) - 1 - result; - } - bit <<= 1; - } - - return result; -}; diff --git a/solutions/1614-maximum-nesting-depth-of-the-parentheses.js b/solutions/1614-maximum-nesting-depth-of-the-parentheses.js deleted file mode 100644 index 84e76888..00000000 --- a/solutions/1614-maximum-nesting-depth-of-the-parentheses.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 1614. Maximum Nesting Depth of the Parentheses - * https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/ - * Difficulty: Easy - * - * Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the - * maximum number of nested parentheses. - */ - -/** - * @param {string} s - * @return {number} - */ -var maxDepth = function(s) { - let currentDepth = 0; - let maxDepth = 0; - - for (const char of s) { - if (char === '(') { - currentDepth++; - maxDepth = Math.max(maxDepth, currentDepth); - } else if (char === ')') { - currentDepth--; - } - } - - return maxDepth; -}; diff --git a/solutions/1615-maximal-network-rank.js b/solutions/1615-maximal-network-rank.js deleted file mode 100644 index 63992bb7..00000000 --- a/solutions/1615-maximal-network-rank.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1615. Maximal Network Rank - * https://leetcode.com/problems/maximal-network-rank/ - * Difficulty: Medium - * - * There is an infrastructure of n cities with some number of roads connecting these cities. - * Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. - * - * The network rank of two different cities is defined as the total number of directly connected - * roads to either city. If a road is directly connected to both cities, it is only counted once. - * - * The maximal network rank of the infrastructure is the maximum network rank of all pairs of - * different cities. - * - * Given the integer n and the array roads, return the maximal network rank of the entire - * infrastructure. - */ - -/** - * @param {number} n - * @param {number[][]} roads - * @return {number} - */ -var maximalNetworkRank = function(n, citiesConnections) { - const cityRoadCounts = new Array(n).fill(0); - const directConnections = new Set(); - - for (const [cityA, cityB] of citiesConnections) { - cityRoadCounts[cityA]++; - cityRoadCounts[cityB]++; - directConnections.add(`${Math.min(cityA, cityB)}-${Math.max(cityA, cityB)}`); - } - - let maxNetworkRank = 0; - - for (let cityA = 0; cityA < n; cityA++) { - for (let cityB = cityA + 1; cityB < n; cityB++) { - let networkRank = cityRoadCounts[cityA] + cityRoadCounts[cityB]; - if (directConnections.has(`${cityA}-${cityB}`) - || directConnections.has(`${cityB}-${cityA}`)) { - networkRank--; - } - maxNetworkRank = Math.max(maxNetworkRank, networkRank); - } - } - - return maxNetworkRank; -}; diff --git a/solutions/1616-split-two-strings-to-make-palindrome.js b/solutions/1616-split-two-strings-to-make-palindrome.js deleted file mode 100644 index 757d8bb2..00000000 --- a/solutions/1616-split-two-strings-to-make-palindrome.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1616. Split Two Strings to Make Palindrome - * https://leetcode.com/problems/split-two-strings-to-make-palindrome/ - * Difficulty: Medium - * - * You are given two strings a and b of the same length. Choose an index and split both strings at - * the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, - * and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if - * aprefix + bsuffix or bprefix + asuffix forms a palindrome. - * - * When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be - * empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are - * valid splits. - * - * Return true if it is possible to form a palindrome string, otherwise return false. - * - * Notice that x + y denotes the concatenation of strings x and y. - */ - -/** - * @param {string} a - * @param {string} b - * @return {boolean} - */ -var checkPalindromeFormation = function(a, b) { - return check(a, b) || check(b, a); - - function isPalindrome(str, left, right) { - while (left < right) { - if (str[left++] !== str[right--]) return false; - } - return true; - } - - function check(str1, str2) { - let left = 0; - let right = str1.length - 1; - - while (left < right && str1[left] === str2[right]) { - left++; - right--; - } - - return isPalindrome(str1, left, right) || isPalindrome(str2, left, right); - } -}; diff --git a/solutions/1617-count-subtrees-with-max-distance-between-cities.js b/solutions/1617-count-subtrees-with-max-distance-between-cities.js deleted file mode 100644 index d4a4f7cd..00000000 --- a/solutions/1617-count-subtrees-with-max-distance-between-cities.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * 1617. Count Subtrees With Max Distance Between Cities - * https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/ - * Difficulty: Hard - * - * There are n cities numbered from 1 to n. You are given an array edges of size n-1, where - * edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists - * a unique path between each pair of cities. In other words, the cities form a tree. - * - * A subtree is a subset of cities where every city is reachable from every other city in the - * subset, where the path between each pair passes through only the cities from the subset. - * Two subtrees are different if there is a city in one subtree that is not present in the other. - * - * For each d from 1 to n-1, find the number of subtrees in which the maximum distance between - * any two cities in the subtree is equal to d. - * - * Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in - * which the maximum distance between any two cities is equal to d. - * - * Notice that the distance between the two cities is the number of edges in the path between them. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number[]} - */ -var countSubgraphsForEachDiameter = function(n, connections) { - const adjacencyList = Array.from({ length: n }, () => []); - for (const [u, v] of connections) { - adjacencyList[u - 1].push(v - 1); - adjacencyList[v - 1].push(u - 1); - } - - const diameterCounts = new Array(n - 1).fill(0); - - for (let mask = 1; mask < 1 << n; mask++) { - const selectedNodes = Array(n).fill(0); - let nodeCount = 0; - for (let i = 0; i < n; i++) { - if (mask & (1 << i)) { - selectedNodes[i] = 1; - nodeCount++; - } - } - - if (nodeCount < 2) continue; - - const start = selectedNodes.findIndex(bit => bit); - const { maxDist: dist1, farthestNode, distances } = findMaxDistance(selectedNodes, start); - - if (distances.some((d, i) => selectedNodes[i] && d === -1)) continue; - - const { maxDist: dist2 } = findMaxDistance(selectedNodes, farthestNode); - - if (dist2 > 0) { - diameterCounts[dist2 - 1]++; - } - } - - return diameterCounts; - - function findMaxDistance(nodes, start) { - const distances = new Array(n).fill(-1); - const queue = [start]; - distances[start] = 0; - let maxDist = 0; - let farthestNode = start; - - while (queue.length) { - const current = queue.shift(); - for (const neighbor of adjacencyList[current]) { - if (nodes[neighbor] && distances[neighbor] === -1) { - distances[neighbor] = distances[current] + 1; - if (distances[neighbor] > maxDist) { - maxDist = distances[neighbor]; - farthestNode = neighbor; - } - queue.push(neighbor); - } - } - } - - return { maxDist, farthestNode, distances }; - } -}; diff --git a/solutions/1619-mean-of-array-after-removing-some-elements.js b/solutions/1619-mean-of-array-after-removing-some-elements.js deleted file mode 100644 index d7c37100..00000000 --- a/solutions/1619-mean-of-array-after-removing-some-elements.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 1619. Mean of Array After Removing Some Elements - * https://leetcode.com/problems/mean-of-array-after-removing-some-elements/ - * Difficulty: Easy - * - * Given an integer array arr, return the mean of the remaining integers after removing the - * smallest 5% and the largest 5% of the elements. - * - * Answers within 10-5 of the actual answer will be considered accepted. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var trimMean = function(numbers) { - const sortedNumbers = numbers.sort((a, b) => a - b); - const trimSize = numbers.length * 0.05; - const trimmedNumbers = sortedNumbers.slice(trimSize, -trimSize); - const sum = trimmedNumbers.reduce((acc, num) => acc + num, 0); - - return sum / trimmedNumbers.length; -}; diff --git a/solutions/1620-coordinate-with-maximum-network-quality.js b/solutions/1620-coordinate-with-maximum-network-quality.js deleted file mode 100644 index 24c01103..00000000 --- a/solutions/1620-coordinate-with-maximum-network-quality.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1620. Coordinate With Maximum Network Quality - * https://leetcode.com/problems/coordinate-with-maximum-network-quality/ - * Difficulty: Medium - * - * You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the - * ith network tower with location (xi, yi) and quality factor qi. All the coordinates are - * integral coordinates on the X-Y plane, and the distance between the two coordinates is the - * Euclidean distance. - * - * You are also given an integer radius where a tower is reachable if the distance is less than - * or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not - * reachable. - * - * The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula - * ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network - * quality at a coordinate is the sum of the signal qualities from all the reachable towers. - * - * Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network - * quality is maximum. If there are multiple coordinates with the same network quality, return - * the lexicographically minimum non-negative coordinate. - * - * Note: - * - A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: - * - x1 < x2, or - * - x1 == x2 and y1 < y2. - * - ⌊val⌋ is the greatest integer less than or equal to val (the floor function). - */ - -/** - * @param {number[][]} towers - * @param {number} radius - * @return {number[]} - */ -var bestCoordinate = function(towers, radius) { - let maxQuality = 0; - let optimalCoord = [0, 0]; - - for (let x = 0; x <= 50; x++) { - for (let y = 0; y <= 50; y++) { - let currentQuality = 0; - - for (const [towerX, towerY, quality] of towers) { - const distance = calculateDistance(x, y, towerX, towerY); - if (distance <= radius) { - currentQuality += Math.floor(quality / (1 + distance)); - } - } - - if (currentQuality > maxQuality) { - maxQuality = currentQuality; - optimalCoord = [x, y]; - } else if (currentQuality === maxQuality && currentQuality > 0) { - if (x < optimalCoord[0] || (x === optimalCoord[0] && y < optimalCoord[1])) { - optimalCoord = [x, y]; - } - } - } - } - - return optimalCoord; - - function calculateDistance(x1, y1, x2, y2) { - return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); - } -}; diff --git a/solutions/1621-number-of-sets-of-k-non-overlapping-line-segments.js b/solutions/1621-number-of-sets-of-k-non-overlapping-line-segments.js deleted file mode 100644 index de32d068..00000000 --- a/solutions/1621-number-of-sets-of-k-non-overlapping-line-segments.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1621. Number of Sets of K Non-Overlapping Line Segments - * https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/ - * Difficulty: Medium - * - * Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number - * of ways we can draw exactly k non-overlapping line segments such that each segment covers two - * or more points. The endpoints of each segment must have integral coordinates. The k line segments - * do not have to cover all n points, and they are allowed to share endpoints. - * - * Return the number of ways we can draw k non-overlapping line segments. Since this number can be - * huge, return it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var numberOfSets = function(n, k) { - const MOD = 1e9 + 7; - const comb = Array.from({ length: n + k }, () => Array(n + k).fill(0)); - - for (let i = 0; i < n + k; i++) { - comb[i][0] = 1; - for (let j = 1; j <= i; j++) { - comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % MOD; - } - } - - return comb[n + k - 1][2 * k]; -}; diff --git a/solutions/1622-fancy-sequence.js b/solutions/1622-fancy-sequence.js deleted file mode 100644 index 16864595..00000000 --- a/solutions/1622-fancy-sequence.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * 1622. Fancy Sequence - * https://leetcode.com/problems/fancy-sequence/ - * Difficulty: Hard - * - * Write an API that generates fancy sequences using the append, addAll, and multAll operations. - * - * Implement the Fancy class: - * - Fancy() Initializes the object with an empty sequence. - * - void append(val) Appends an integer val to the end of the sequence. - * - void addAll(inc) Increments all existing values in the sequence by an integer inc. - * - void multAll(m) Multiplies all existing values in the sequence by an integer m. - * - int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo - * 109 + 7. If the index is greater or equal than the length of the sequence, return -1. - */ - -var Fancy = function() { - this.sequence = []; - this.additive = 0n; - this.multiplicative = 1n; - this.MOD = 1000000007n; -}; - -/** - * @param {number} val - * @return {void} - */ -Fancy.prototype.append = function(val) { - const valBig = BigInt(val); - const inverse = this.modInverse(this.multiplicative); - const adjustedVal = ((valBig - this.additive + this.MOD) * inverse) % this.MOD; - this.sequence.push(adjustedVal); -}; - -/** - * @param {number} inc - * @return {void} - */ -Fancy.prototype.addAll = function(inc) { - this.additive = (this.additive + BigInt(inc)) % this.MOD; -}; - -/** - * @param {number} m - * @return {void} - */ -Fancy.prototype.multAll = function(m) { - const mBig = BigInt(m); - this.additive = (this.additive * mBig) % this.MOD; - this.multiplicative = (this.multiplicative * mBig) % this.MOD; -}; - -/** - * @param {number} idx - * @return {number} - */ -Fancy.prototype.getIndex = function(idx) { - if (idx >= this.sequence.length) return -1; - return Number((this.sequence[idx] * this.multiplicative + this.additive) % this.MOD); -}; - -/** - * @param {number} a - * @return {number} - */ -Fancy.prototype.modInverse = function(a) { - let m = this.MOD; - const m0 = m; - let x = 1n; - let y = 0n; - - a = a % m; - while (a > 1n) { - const q = a / m; - [a, m] = [m, a % m]; - [x, y] = [y, x - q * y]; - } - - return x < 0n ? x + m0 : x; -}; diff --git a/solutions/1624-largest-substring-between-two-equal-characters.js b/solutions/1624-largest-substring-between-two-equal-characters.js deleted file mode 100644 index 84a2a15c..00000000 --- a/solutions/1624-largest-substring-between-two-equal-characters.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1624. Largest Substring Between Two Equal Characters - * https://leetcode.com/problems/largest-substring-between-two-equal-characters/ - * Difficulty: Easy - * - * Given a string s, return the length of the longest substring between two equal characters, - * excluding the two characters. If there is no such substring return -1. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} s - * @return {number} - */ -var maxLengthBetweenEqualCharacters = function(s) { - const charFirstIndex = new Map(); - let maxLength = -1; - - for (let i = 0; i < s.length; i++) { - const char = s[i]; - if (charFirstIndex.has(char)) { - maxLength = Math.max(maxLength, i - charFirstIndex.get(char) - 1); - } else { - charFirstIndex.set(char, i); - } - } - - return maxLength; -}; diff --git a/solutions/1625-lexicographically-smallest-string-after-applying-operations.js b/solutions/1625-lexicographically-smallest-string-after-applying-operations.js deleted file mode 100644 index 64e4490d..00000000 --- a/solutions/1625-lexicographically-smallest-string-after-applying-operations.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1625. Lexicographically Smallest String After Applying Operations - * https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/ - * Difficulty: Medium - * - * You are given a string s of even length consisting of digits from 0 to 9, and two integers a - * and b. - * - * You can apply either of the following two operations any number of times and in any order on s: - * - Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, - * if s = "3456" and a = 5, s becomes "3951". - * - Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345". - * - * Return the lexicographically smallest string you can obtain by applying the above operations any - * number of times on s. - * - * A string a is lexicographically smaller than a string b (of the same length) if in the first - * position where a and b differ, string a has a letter that appears earlier in the alphabet than - * the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" - * because the first position they differ is at the third letter, and '5' comes before '9'. - */ - -/** - * @param {string} s - * @param {number} a - * @param {number} b - * @return {string} - */ -var findLexSmallestString = function(s, a, b) { - const visited = new Set(); - let smallestString = s; - const queue = [s]; - - const addOperation = str => { - const chars = str.split(''); - for (let i = 1; i < str.length; i += 2) { - chars[i] = String((parseInt(chars[i]) + a) % 10); - } - return chars.join(''); - }; - - const rotateOperation = str => { - return str.slice(-b) + str.slice(0, -b); - }; - - while (queue.length) { - const current = queue.shift(); - if (visited.has(current)) continue; - visited.add(current); - if (current < smallestString) smallestString = current; - - const added = addOperation(current); - const rotated = rotateOperation(current); - - queue.push(added); - queue.push(rotated); - } - - return smallestString; -}; diff --git a/solutions/1626-best-team-with-no-conflicts.js b/solutions/1626-best-team-with-no-conflicts.js deleted file mode 100644 index c862c5a3..00000000 --- a/solutions/1626-best-team-with-no-conflicts.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1626. Best Team With No Conflicts - * https://leetcode.com/problems/best-team-with-no-conflicts/ - * Difficulty: Medium - * - * You are the manager of a basketball team. For the upcoming tournament, you want to choose the - * team with the highest overall score. The score of the team is the sum of scores of all the - * players in the team. - * - * However, the basketball team is not allowed to have conflicts. A conflict exists if a younger - * player has a strictly higher score than an older player. A conflict does not occur between - * players of the same age. - * - * Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and - * age of the ith player, respectively, return the highest overall score of all possible basketball - * teams. - */ - -/** - * @param {number[]} scores - * @param {number[]} ages - * @return {number} - */ -var bestTeamScore = function(scores, ages) { - const players = ages.map((age, index) => ({ age, score: scores[index] })); - players.sort((a, b) => a.age - b.age || a.score - b.score); - - const maxScores = new Array(players.length).fill(0); - let highestScore = 0; - - for (let current = 0; current < players.length; current++) { - maxScores[current] = players[current].score; - for (let previous = 0; previous < current; previous++) { - if (players[previous].score <= players[current].score) { - maxScores[current] = Math.max( - maxScores[current], - maxScores[previous] + players[current].score - ); - } - } - highestScore = Math.max(highestScore, maxScores[current]); - } - - return highestScore; -}; diff --git a/solutions/1627-graph-connectivity-with-threshold.js b/solutions/1627-graph-connectivity-with-threshold.js deleted file mode 100644 index ce6c554b..00000000 --- a/solutions/1627-graph-connectivity-with-threshold.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1627. Graph Connectivity With Threshold - * https://leetcode.com/problems/graph-connectivity-with-threshold/ - * Difficulty: Hard - * - * We have n cities labeled from 1 to n. Two different cities with labels x and y are directly - * connected by a bidirectional road if and only if x and y share a common divisor strictly - * greater than some threshold. More formally, cities with labels x and y have a road between - * them if there exists an integer z such that all of the following are true: - * - x % z == 0, - * - y % z == 0, and - * - z > threshold. - * - * Given the two integers, n and threshold, and an array of queries, you must determine for each - * queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there - * is some path between them). - * - * Return an array answer, where answer.length == queries.length and answer[i] is true if for - * the ith query, there is a path between ai and bi, or answer[i] is false if there is no path. - */ - -/** - * @param {number} n - * @param {number} threshold - * @param {number[][]} queries - * @return {boolean[]} - */ -var areConnected = function(n, threshold, queries) { - const parent = new Array(n + 1).fill().map((_, i) => i); - - for (let z = threshold + 1; z <= n; z++) { - for (let x = z; x <= n; x += z) { - union(x, z); - } - } - - return queries.map(([a, b]) => find(a) === find(b)); - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - parent[find(x)] = find(y); - } -}; diff --git a/solutions/1629-slowest-key.js b/solutions/1629-slowest-key.js deleted file mode 100644 index 849c3862..00000000 --- a/solutions/1629-slowest-key.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1629. Slowest Key - * https://leetcode.com/problems/slowest-key/ - * Difficulty: Easy - * - * A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. - * - * You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in - * the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the - * ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and - * every subsequent key was pressed at the exact time the previous key was released. - * - * The tester wants to know the key of the keypress that had the longest duration. The ith keypress - * had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of - * releaseTimes[0]. - * - * Note that the same key could have been pressed multiple times during the test, and these multiple - * presses of the same key may not have had the same duration. - * - * Return the key of the keypress that had the longest duration. If there are multiple such - * keypresses, return the lexicographically largest key of the keypresses. - */ - -/** - * @param {number[]} releaseTimes - * @param {string} keysPressed - * @return {character} - */ -var slowestKey = function(releaseTimes, keysPressed) { - let maxDuration = releaseTimes[0]; - let result = keysPressed[0]; - - for (let i = 1; i < releaseTimes.length; i++) { - const duration = releaseTimes[i] - releaseTimes[i - 1]; - if (duration > maxDuration || (duration === maxDuration && keysPressed[i] > result)) { - maxDuration = duration; - result = keysPressed[i]; - } - } - - return result; -}; diff --git a/solutions/1630-arithmetic-subarrays.js b/solutions/1630-arithmetic-subarrays.js deleted file mode 100644 index b56f5709..00000000 --- a/solutions/1630-arithmetic-subarrays.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1630. Arithmetic Subarrays - * https://leetcode.com/problems/arithmetic-subarrays/ - * Difficulty: Medium - * - * A sequence of numbers is called arithmetic if it consists of at least two elements, and the - * difference between every two consecutive elements is the same. More formally, a sequence s - * is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. - * - * For example, these are arithmetic sequences: - * - 1, 3, 5, 7, 9 - * - 7, 7, 7, 7 - * - 3, -1, -5, -9 - * - * The following sequence is not arithmetic: - * - 1, 1, 2, 5, 7 - * - * You are given an array of n integers, nums, and two arrays of m integers each, l and r, - * representing the m range queries, where the ith query is the range [l[i], r[i]]. All the - * arrays are 0-indexed. - * - * Return a list of boolean elements answer, where answer[i] is true if the subarray - * nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic - * sequence, and false otherwise. - */ - -/** - * @param {number[]} nums - * @param {number[]} l - * @param {number[]} r - * @return {boolean[]} - */ -var checkArithmeticSubarrays = function(nums, l, r) { - return l.map((start, index) => { - const end = r[index]; - const subarray = nums.slice(start, end + 1); - return isArithmetic(subarray); - }); - - function isArithmetic(subarray) { - if (subarray.length < 2) return false; - subarray.sort((a, b) => a - b); - const diff = subarray[1] - subarray[0]; - for (let i = 2; i < subarray.length; i++) { - if (subarray[i] - subarray[i - 1] !== diff) return false; - } - return true; - } -}; diff --git a/solutions/1631-path-with-minimum-effort.js b/solutions/1631-path-with-minimum-effort.js deleted file mode 100644 index 75fe9c85..00000000 --- a/solutions/1631-path-with-minimum-effort.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * 1631. Path With Minimum Effort - * https://leetcode.com/problems/path-with-minimum-effort/ - * Difficulty: Medium - * - * You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size - * rows x columns, where heights[row][col] represents the height of cell (row, col). You are - * situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, - * (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish - * to find a route that requires the minimum effort. - * - * A route's effort is the maximum absolute difference in heights between two consecutive - * cells of the route. - * - * Return the minimum effort required to travel from the top-left cell to the bottom-right cell. - */ - -/** - * @param {number[][]} heights - * @return {number} - */ -var minimumEffortPath = function(heights) { - const rows = heights.length; - const cols = heights[0].length; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - - function canReach(maxEffort) { - const visited = Array.from({ length: rows }, () => Array(cols).fill(false)); - const queue = [[0, 0]]; - visited[0][0] = true; - - while (queue.length) { - const [row, col] = queue.shift(); - if (row === rows - 1 && col === cols - 1) return true; - - for (const [dr, dc] of directions) { - const newRow = row + dr; - const newCol = col + dc; - - if (newRow >= 0 && newRow < rows && newCol >= 0 - && newCol < cols && !visited[newRow][newCol]) { - const effort = Math.abs(heights[newRow][newCol] - heights[row][col]); - if (effort <= maxEffort) { - visited[newRow][newCol] = true; - queue.push([newRow, newCol]); - } - } - } - } - return false; - } - - let left = 0; - let right = 1000000; - let result = right; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (canReach(mid)) { - result = mid; - right = mid - 1; - } else { - left = mid + 1; - } - } - - return result; -}; diff --git a/solutions/1632-rank-transform-of-a-matrix.js b/solutions/1632-rank-transform-of-a-matrix.js deleted file mode 100644 index 50caf43e..00000000 --- a/solutions/1632-rank-transform-of-a-matrix.js +++ /dev/null @@ -1,129 +0,0 @@ -/** - * 1632. Rank Transform of a Matrix - * https://leetcode.com/problems/rank-transform-of-a-matrix/ - * Difficulty: Hard - * - * Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of - * matrix[row][col]. - * - * The rank is an integer that represents how large an element is compared to other elements. - * It is calculated using the following rules: - * - The rank is an integer starting from 1. - * - If two elements p and q are in the same row or column, then: - * - If p < q then rank(p) < rank(q) - * - If p == q then rank(p) == rank(q) - * - If p > q then rank(p) > rank(q) - * - The rank should be as small as possible. - * - * The test cases are generated so that answer is unique under the given rules. - */ - -/** - * @param {number[][]} matrix - * @return {number[][]} - */ -var matrixRankTransform = function(matrix) { - const rows = matrix.length; - const cols = matrix[0].length; - const result = Array.from({ length: rows }, () => new Array(cols).fill(0)); - const parent = new Array(rows * cols).fill(-1); - const elements = []; - - for (let row = 0; row < rows; row++) { - const valueToCoords = new Map(); - for (let col = 0; col < cols; col++) { - const value = matrix[row][col]; - if (!valueToCoords.has(value)) valueToCoords.set(value, []); - valueToCoords.get(value).push([row, col]); - } - for (const coords of valueToCoords.values()) { - for (let i = 1; i < coords.length; i++) { - const [r1, c1] = coords[0]; - const [r2, c2] = coords[i]; - union(r1 * cols + c1, r2 * cols + c2); - } - } - } - - for (let col = 0; col < cols; col++) { - const valueToCoords = new Map(); - for (let row = 0; row < rows; row++) { - const value = matrix[row][col]; - if (!valueToCoords.has(value)) valueToCoords.set(value, []); - valueToCoords.get(value).push([row, col]); - } - for (const coords of valueToCoords.values()) { - for (let i = 1; i < coords.length; i++) { - const [r1, c1] = coords[0]; - const [r2, c2] = coords[i]; - union(r1 * cols + c1, r2 * cols + c2); - } - } - } - - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - elements.push([matrix[row][col], row, col]); - } - } - elements.sort((a, b) => a[0] - b[0]); - - const rowMaxRank = new Array(rows).fill(0); - const colMaxRank = new Array(cols).fill(0); - const groups = new Map(); - - for (let i = 0; i < elements.length; i++) { - const [value, row, col] = elements[i]; - const root = find(row * cols + col); - if (!groups.has(root)) groups.set(root, []); - groups.get(root).push([row, col]); - } - - let i = 0; - while (i < elements.length) { - const value = elements[i][0]; - const currentGroups = new Map(); - while (i < elements.length && elements[i][0] === value) { - const [, row, col] = elements[i]; - const root = find(row * cols + col); - if (!currentGroups.has(root)) currentGroups.set(root, []); - currentGroups.get(root).push([row, col]); - i++; - } - - for (const [root, coords] of currentGroups) { - let maxRank = 0; - for (const [row, col] of coords) { - maxRank = Math.max(maxRank, rowMaxRank[row], colMaxRank[col]); - } - const rank = maxRank + 1; - for (const [row, col] of coords) { - result[row][col] = rank; - rowMaxRank[row] = rank; - colMaxRank[col] = rank; - } - } - } - - return result; - - function find(x) { - if (parent[x] < 0) return x; - return parent[x] = find(parent[x]); - } - - function union(x, y) { - const px = find(x); - const py = find(y); - - if (px !== py) { - if (parent[px] < parent[py]) { - parent[px] += parent[py]; - parent[py] = px; - } else { - parent[py] += parent[px]; - parent[px] = py; - } - } - } -}; diff --git a/solutions/1636-sort-array-by-increasing-frequency.js b/solutions/1636-sort-array-by-increasing-frequency.js deleted file mode 100644 index 25dd28e8..00000000 --- a/solutions/1636-sort-array-by-increasing-frequency.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 1636. Sort Array by Increasing Frequency - * https://leetcode.com/problems/sort-array-by-increasing-frequency/ - * Difficulty: Easy - * - * Given an array of integers nums, sort the array in increasing order based on the frequency - * of the values. If multiple values have the same frequency, sort them in decreasing order. - * - * Return the sorted array. - */ - -/** - * @param {number[]} nums - * @return {number[]} - */ -var frequencySort = function(nums) { - const map = new Map(); - nums.forEach(num => map.set(num, (map.get(num) || 0) + 1)); - - return nums.sort((a, b) => { - const freqA = map.get(a); - const freqB = map.get(b); - return freqA === freqB ? b - a : freqA - freqB; - }); -}; diff --git a/solutions/1637-widest-vertical-area-between-two-points-containing-no-points.js b/solutions/1637-widest-vertical-area-between-two-points-containing-no-points.js deleted file mode 100644 index 8e41dc36..00000000 --- a/solutions/1637-widest-vertical-area-between-two-points-containing-no-points.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1637. Widest Vertical Area Between Two Points Containing No Points - * https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/ - * Difficulty: Easy - * - * Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between - * two points such that no points are inside the area. - * - * A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite - * height). The widest vertical area is the one with the maximum width. - * - * Note that points on the edge of a vertical area are not considered included in the area. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var maxWidthOfVerticalArea = function(points) { - points.sort((a, b) => a[0] - b[0]); - let result = 0; - for (let i = 1; i < points.length; i++) { - result = Math.max(result, points[i][0] - points[i - 1][0]); - } - return result; -}; diff --git a/solutions/1638-count-substrings-that-differ-by-one-character.js b/solutions/1638-count-substrings-that-differ-by-one-character.js deleted file mode 100644 index 030b847f..00000000 --- a/solutions/1638-count-substrings-that-differ-by-one-character.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1638. Count Substrings That Differ by One Character - * https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ - * Difficulty: Medium - * - * Given two strings s and t, find the number of ways you can choose a non-empty substring of s - * and replace a single character by a different character such that the resulting substring is - * a substring of t. In other words, find the number of substrings in s that differ from some - * substring in t by exactly one character. - * - * For example, the underlined substrings in "computer" and "computation" only differ by the - * 'e'/'a', so this is a valid way. - * - * Return the number of substrings that satisfy the condition above. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} s - * @param {string} t - * @return {number} - */ -var countSubstrings = function(s, t) { - let result = 0; - - for (let i = 0; i < s.length; i++) { - for (let j = 0; j < t.length; j++) { - let diffCount = 0; - for (let k = 0; i + k < s.length && j + k < t.length; k++) { - if (s[i + k] !== t[j + k]) diffCount++; - if (diffCount === 1) result++; - if (diffCount > 1) break; - } - } - } - - return result; -}; diff --git a/solutions/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.js b/solutions/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.js deleted file mode 100644 index 45ccd6a8..00000000 --- a/solutions/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1639. Number of Ways to Form a Target String Given a Dictionary - * https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/ - * Difficulty: Hard - * - * You are given a list of strings of the same length words and a string target. - * - * Your task is to form target using the given words under the following rules: - * - target should be formed from left to right. - * - To form the ith character (0-indexed) of target, you can choose the kth character of the jth - * string in words if target[i] = words[j][k]. - * - Once you use the kth character of the jth string of words, you can no longer use the xth - * character of any string in words where x <= k. In other words, all characters to the left of - * or at index k become unusuable for every string. - * - Repeat the process until you form the string target. - * - * Notice that you can use multiple characters from the same string in words provided the - * conditions above are met. - * - * Return the number of ways to form target from words. Since the answer may be too large, return - * it modulo 109 + 7. - */ - -/** - * @param {string[]} words - * @param {string} target - * @return {number} - */ -var numWays = function(words, target) { - const MOD = 1e9 + 7; - const wordLength = words[0].length; - const targetLength = target.length; - const charCounts = Array(wordLength).fill().map(() => Array(26).fill(0)); - - for (const word of words) { - for (let i = 0; i < wordLength; i++) { - charCounts[i][word.charCodeAt(i) - 97]++; - } - } - - const dp = Array(targetLength + 1).fill().map(() => Array(wordLength + 1).fill(0)); - dp[0][0] = 1; - - for (let i = 0; i <= targetLength; i++) { - for (let j = 0; j < wordLength; j++) { - if (i < targetLength) { - const charIndex = target.charCodeAt(i) - 97; - dp[i + 1][j + 1] = (dp[i + 1][j + 1] + dp[i][j] * charCounts[j][charIndex]) % MOD; - } - dp[i][j + 1] = (dp[i][j + 1] + dp[i][j]) % MOD; - } - } - - return dp[targetLength][wordLength]; -}; diff --git a/solutions/1640-check-array-formation-through-concatenation.js b/solutions/1640-check-array-formation-through-concatenation.js deleted file mode 100644 index eabb17a6..00000000 --- a/solutions/1640-check-array-formation-through-concatenation.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1640. Check Array Formation Through Concatenation - * https://leetcode.com/problems/check-array-formation-through-concatenation/ - * Difficulty: Easy - * - * You are given an array of distinct integers arr and an array of integer arrays pieces, - * where the integers in pieces are distinct. Your goal is to form arr by concatenating - * the arrays in pieces in any order. However, you are not allowed to reorder the integers - * in each array pieces[i]. - * - * Return true if it is possible to form the array arr from pieces. Otherwise, return false. - */ - -/** - * @param {number[]} arr - * @param {number[][]} pieces - * @return {boolean} - */ -var canFormArray = function(arr, pieces) { - const numberToPiece = new Map(); - for (const piece of pieces) { - numberToPiece.set(piece[0], piece); - } - - let index = 0; - while (index < arr.length) { - const currentNumber = arr[index]; - if (!numberToPiece.has(currentNumber)) { - return false; - } - const piece = numberToPiece.get(currentNumber); - for (const num of piece) { - if (arr[index] !== num) { - return false; - } - index++; - } - } - - return true; -}; diff --git a/solutions/1641-count-sorted-vowel-strings.js b/solutions/1641-count-sorted-vowel-strings.js deleted file mode 100644 index 2e8915b0..00000000 --- a/solutions/1641-count-sorted-vowel-strings.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 1641. Count Sorted Vowel Strings - * https://leetcode.com/problems/count-sorted-vowel-strings/ - * Difficulty: Medium - * - * Given an integer n, return the number of strings of length n that consist only of vowels - * (a, e, i, o, u) and are lexicographically sorted. - * - * A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes - * before s[i+1] in the alphabet. - */ - -/** - * @param {number} n - * @return {number} - */ -var countVowelStrings = function(n) { - const vowelCounts = [1, 1, 1, 1, 1]; - - for (let i = 1; i < n; i++) { - for (let j = 3; j >= 0; j--) { - vowelCounts[j] += vowelCounts[j + 1]; - } - } - - return vowelCounts.reduce((sum, count) => sum + count, 0); -}; diff --git a/solutions/1642-furthest-building-you-can-reach.js b/solutions/1642-furthest-building-you-can-reach.js deleted file mode 100644 index 0aaebdee..00000000 --- a/solutions/1642-furthest-building-you-can-reach.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1642. Furthest Building You Can Reach - * https://leetcode.com/problems/furthest-building-you-can-reach/ - * Difficulty: Medium - * - * You are given an integer array heights representing the heights of buildings, some bricks, - * and some ladders. - * - * You start your journey from building 0 and move to the next building by possibly using - * bricks or ladders. - * - * While moving from building i to building i+1 (0-indexed): - * - If the current building's height is greater than or equal to the next building's height, - * you do not need a ladder or bricks. - * - If the current building's height is less than the next building's height, you can either - * use one ladder or (h[i+1] - h[i]) bricks. - * - * Return the furthest building index (0-indexed) you can reach if you use the given ladders - * and bricks optimally. - */ - -/** - * @param {number[]} heights - * @param {number} bricks - * @param {number} ladders - * @return {number} - */ -var furthestBuilding = function(heights, bricks, ladders) { - const minHeap = new MinPriorityQueue(); - - for (let i = 0; i < heights.length - 1; i++) { - const climb = heights[i + 1] - heights[i]; - if (climb > 0) { - minHeap.push(climb); - if (minHeap.size() > ladders) { - bricks -= minHeap.pop(); - if (bricks < 0) { - return i; - } - } - } - } - - return heights.length - 1; -}; - diff --git a/solutions/1643-kth-smallest-instructions.js b/solutions/1643-kth-smallest-instructions.js deleted file mode 100644 index e7bd79fd..00000000 --- a/solutions/1643-kth-smallest-instructions.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1643. Kth Smallest Instructions - * https://leetcode.com/problems/kth-smallest-instructions/ - * Difficulty: Hard - * - * Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only - * travel right and down. You are going to help Bob by providing instructions for him to reach - * destination. - * - * The instructions are represented as a string, where each character is either: - * - 'H', meaning move horizontally (go right), or - * - 'V', meaning move vertically (go down). - * - * Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), - * both "HHHVV" and "HVHVH" are valid instructions. - * - * However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically - * smallest instructions that will lead him to destination. k is 1-indexed. - * - * Given an integer array destination and an integer k, return the kth lexicographically - * smallest instructions that will take Bob to destination. - */ - -/** - * @param {number[]} destination - * @param {number} k - * @return {string} - */ -var kthSmallestPath = function(destination, k) { - let verticalMoves = destination[0]; - let horizontalMoves = destination[1]; - const totalMoves = verticalMoves + horizontalMoves; - let path = ''; - - for (let i = 0; i < totalMoves; i++) { - if (horizontalMoves === 0) { - path += 'V'; - verticalMoves--; - continue; - } - const combinations = calculateCombinations( - verticalMoves + horizontalMoves - 1, - horizontalMoves - 1 - ); - if (k <= combinations) { - path += 'H'; - horizontalMoves--; - } else { - path += 'V'; - verticalMoves--; - k -= combinations; - } - } - - return path; -}; - -function calculateCombinations(n, r) { - if (r < 0 || r > n) return 0; - let result = 1; - for (let i = 1; i <= r; i++) { - result = result * (n - i + 1) / i; - } - return Math.floor(result); -} diff --git a/solutions/1646-get-maximum-in-generated-array.js b/solutions/1646-get-maximum-in-generated-array.js deleted file mode 100644 index 4c4ae686..00000000 --- a/solutions/1646-get-maximum-in-generated-array.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1646. Get Maximum in Generated Array - * https://leetcode.com/problems/get-maximum-in-generated-array/ - * Difficulty: Easy - * - * You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated - * in the following way: - * - nums[0] = 0 - * - nums[1] = 1 - * - nums[2 * i] = nums[i] when 2 <= 2 * i <= n - * - nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n - * - * Return the maximum integer in the array nums. - */ - -/** - * @param {number} n - * @return {number} - */ -var getMaximumGenerated = function(n) { - if (n === 0) return 0; - - const generatedArray = new Array(n + 1).fill(0); - generatedArray[1] = 1; - let maximumValue = 1; - - for (let i = 1; i <= Math.floor(n / 2); i++) { - if (2 * i <= n) { - generatedArray[2 * i] = generatedArray[i]; - maximumValue = Math.max(maximumValue, generatedArray[2 * i]); - } - if (2 * i + 1 <= n) { - generatedArray[2 * i + 1] = generatedArray[i] + generatedArray[i + 1]; - maximumValue = Math.max(maximumValue, generatedArray[2 * i + 1]); - } - } - - return maximumValue; -}; diff --git a/solutions/1647-minimum-deletions-to-make-character-frequencies-unique.js b/solutions/1647-minimum-deletions-to-make-character-frequencies-unique.js deleted file mode 100644 index 22568c4c..00000000 --- a/solutions/1647-minimum-deletions-to-make-character-frequencies-unique.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1647. Minimum Deletions to Make Character Frequencies Unique - * https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/ - * Difficulty: Medium - * - * A string s is called good if there are no two different characters in s that have the - * same frequency. - * - * Given a string s, return the minimum number of characters you need to delete to make s good. - * - * The frequency of a character in a string is the number of times it appears in the string. - * For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. - */ - -/** - * @param {string} s - * @return {number} - */ -var minDeletions = function(s) { - const charFrequencies = new Array(26).fill(0); - for (const char of s) { - charFrequencies[char.charCodeAt(0) - 97]++; - } - - charFrequencies.sort((a, b) => b - a); - let result = 0; - const usedFrequencies = new Set(); - - for (const freq of charFrequencies) { - if (freq === 0) break; - let currentFreq = freq; - while (usedFrequencies.has(currentFreq) && currentFreq > 0) { - currentFreq--; - result++; - } - usedFrequencies.add(currentFreq); - } - - return result; -}; diff --git a/solutions/1648-sell-diminishing-valued-colored-balls.js b/solutions/1648-sell-diminishing-valued-colored-balls.js deleted file mode 100644 index 15594e62..00000000 --- a/solutions/1648-sell-diminishing-valued-colored-balls.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1648. Sell Diminishing-Valued Colored Balls - * https://leetcode.com/problems/sell-diminishing-valued-colored-balls/ - * Difficulty: Medium - * - * You have an inventory of different colored balls, and there is a customer that wants orders - * balls of any color. - * - * The customer weirdly values the colored balls. Each colored ball's value is the number of balls - * of that color you currently have in your inventory. For example, if you own 6 yellow balls, - * the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 - * yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls - * decreases as you sell more to the customer). - * - * You are given an integer array, inventory, where inventory[i] represents the number of balls of - * the ith color that you initially own. You are also given an integer orders, which represents - * the total number of balls that the customer wants. You can sell the balls in any order. - * - * Return the maximum total value that you can attain after selling orders colored balls. As the - * answer may be too large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} inventory - * @param {number} orders - * @return {number} - */ -var maxProfit = function(inventory, orders) { - const MOD = 1e9 + 7; - inventory.sort((a, b) => b - a); - inventory.push(0); - - let totalProfit = 0; - let currentColor = 0; - let ballsSold = 0; - - while (ballsSold < orders) { - const currentCount = inventory[currentColor]; - const nextCount = inventory[currentColor + 1]; - const colors = currentColor + 1; - const ballsToSell = Math.min( - orders - ballsSold, - colors * (currentCount - nextCount) - ); - - const fullSets = Math.floor(ballsToSell / colors); - const remainder = ballsToSell % colors; - - if (fullSets > 0) { - const endValue = currentCount - fullSets + 1; - let sequenceSum = (BigInt(colors) * BigInt(fullSets) % BigInt(MOD)) - * (BigInt(currentCount) + BigInt(endValue)) % BigInt(MOD); - sequenceSum = (sequenceSum * BigInt(500000004)) % BigInt(MOD); - totalProfit = (totalProfit + Number(sequenceSum)) % MOD; - } - - if (remainder > 0) { - totalProfit = (totalProfit + (remainder * (currentCount - fullSets)) % MOD) % MOD; - } - - ballsSold += ballsToSell; - currentColor++; - } - - return totalProfit; -}; diff --git a/solutions/1649-create-sorted-array-through-instructions.js b/solutions/1649-create-sorted-array-through-instructions.js deleted file mode 100644 index 6e3937c7..00000000 --- a/solutions/1649-create-sorted-array-through-instructions.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 1649. Create Sorted Array through Instructions - * https://leetcode.com/problems/create-sorted-array-through-instructions/ - * Difficulty: Hard - * - * Given an integer array instructions, you are asked to create a sorted array from the elements in - * instructions. You start with an empty container nums. For each element from left to right in - * instructions, insert it into nums. The cost of each insertion is the minimum of the following: - * - The number of elements currently in nums that are strictly less than instructions[i]. - * - The number of elements currently in nums that are strictly greater than instructions[i]. - * - * For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) - * (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. - * - * Return the total cost to insert all elements from instructions into nums. Since the answer may - * be large, return it modulo 109 + 7 - */ - -/** - * @param {number[]} instructions - * @return {number} - */ -var createSortedArray = function(instructions) { - const MOD = 1e9 + 7; - const maxValue = Math.max(...instructions); - const fenwickTree = new Array(maxValue + 1).fill(0); - let totalCost = 0; - - for (let i = 0; i < instructions.length; i++) { - const value = instructions[i]; - const lessCount = query(value - 1); - const greaterCount = i - query(value); - totalCost = (totalCost + Math.min(lessCount, greaterCount)) % MOD; - update(value); - } - - return totalCost; - - function update(index) { - for (let i = index; i <= maxValue; i += i & -i) { - fenwickTree[i]++; - } - } - - function query(index) { - let sum = 0; - for (let i = index; i > 0; i -= i & -i) { - sum += fenwickTree[i]; - } - return sum; - } -}; diff --git a/solutions/1652-defuse-the-bomb.js b/solutions/1652-defuse-the-bomb.js deleted file mode 100644 index 69b7a74b..00000000 --- a/solutions/1652-defuse-the-bomb.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1652. Defuse the Bomb - * https://leetcode.com/problems/defuse-the-bomb/ - * Difficulty: Easy - * - * You have a bomb to defuse, and your time is running out! Your informer will provide you with - * a circular array code of length of n and a key k. - * - * To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. - * - If k > 0, replace the ith number with the sum of the next k numbers. - * - If k < 0, replace the ith number with the sum of the previous k numbers. - * - If k == 0, replace the ith number with 0. - * - * As code is circular, the next element of code[n-1] is code[0], and the previous element of - * code[0] is code[n-1]. - * - * Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! - */ - -/** - * @param {number[]} code - * @param {number} k - * @return {number[]} - */ -var decrypt = function(code, k) { - const n = code.length; - const result = new Array(n).fill(0); - - if (k === 0) return result; - - const isPositive = k > 0; - const steps = Math.abs(k); - - for (let i = 0; i < n; i++) { - let sum = 0; - for (let j = 1; j <= steps; j++) { - const index = isPositive ? (i + j) % n : (i - j + n) % n; - sum += code[index]; - } - result[i] = sum; - } - - return result; -}; diff --git a/solutions/1653-minimum-deletions-to-make-string-balanced.js b/solutions/1653-minimum-deletions-to-make-string-balanced.js deleted file mode 100644 index 12ae2c7b..00000000 --- a/solutions/1653-minimum-deletions-to-make-string-balanced.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1653. Minimum Deletions to Make String Balanced - * https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/ - * Difficulty: Medium - * - * You are given a string s consisting only of characters 'a' and 'b'. - * - * You can delete any number of characters in s to make s balanced. s is balanced if there is - * no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. - * - * Return the minimum number of deletions needed to make s balanced. - */ - -/** - * @param {string} s - * @return {number} - */ -var minimumDeletions = function(s) { - let aCountRight = 0; - for (const char of s) { - if (char === 'a') aCountRight++; - } - - let bCountLeft = 0; - let result = aCountRight; - - for (const char of s) { - if (char === 'a') aCountRight--; - else bCountLeft++; - result = Math.min(result, aCountRight + bCountLeft); - } - - return result; -}; diff --git a/solutions/1654-minimum-jumps-to-reach-home.js b/solutions/1654-minimum-jumps-to-reach-home.js deleted file mode 100644 index 22faac68..00000000 --- a/solutions/1654-minimum-jumps-to-reach-home.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1654. Minimum Jumps to Reach Home - * https://leetcode.com/problems/minimum-jumps-to-reach-home/ - * Difficulty: Medium - * - * A certain bug's home is on the x-axis at position x. Help them get there from position 0. - * - * The bug jumps according to the following rules: - * - It can jump exactly a positions forward (to the right). - * - It can jump exactly b positions backward (to the left). - * - It cannot jump backward twice in a row. - * - It cannot jump to any forbidden positions. - * - * The bug may jump forward beyond its home, but it cannot jump to positions numbered with - * negative integers. - * - * Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to - * the position forbidden[i], and integers a, b, and x, return the minimum number of jumps - * needed for the bug to reach its home. If there is no possible sequence of jumps that lands - * the bug on position x, return -1. - */ - -/** - * @param {number[]} forbidden - * @param {number} a - * @param {number} b - * @param {number} x - * @return {number} - */ -var minimumJumps = function(forbidden, a, b, x) { - const forbiddenSet = new Set(forbidden); - const maxPosition = Math.max(x, Math.max(...forbidden)) + a + b; - const queue = [[0, 0, false]]; - const visited = new Set([`0,false`]); - - while (queue.length) { - const [position, jumps, isBackward] = queue.shift(); - - if (position === x) return jumps; - - const forwardPosition = position + a; - if (forwardPosition <= maxPosition && !forbiddenSet.has(forwardPosition) - && !visited.has(`${forwardPosition},false`)) { - queue.push([forwardPosition, jumps + 1, false]); - visited.add(`${forwardPosition},false`); - } - - if (!isBackward && b > 0) { - const backwardPosition = position - b; - if (backwardPosition >= 0 && !forbiddenSet.has(backwardPosition) - && !visited.has(`${backwardPosition},true`)) { - queue.push([backwardPosition, jumps + 1, true]); - visited.add(`${backwardPosition},true`); - } - } - } - - return -1; -}; diff --git a/solutions/1655-distribute-repeating-integers.js b/solutions/1655-distribute-repeating-integers.js deleted file mode 100644 index d80e920d..00000000 --- a/solutions/1655-distribute-repeating-integers.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1655. Distribute Repeating Integers - * https://leetcode.com/problems/distribute-repeating-integers/ - * Difficulty: Hard - * - * You are given an array of n integers, nums, where there are at most 50 unique values in - * the array. You are also given an array of m customer order quantities, quantity, where - * quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible - * to distribute nums such that: - * - The ith customer gets exactly quantity[i] integers, - * - The integers the ith customer gets are all equal, and - * - Every customer is satisfied. - * - * Return true if it is possible to distribute nums according to the above conditions. - */ - -/** - * @param {number[]} nums - * @param {number[]} quantity - * @return {boolean} - */ -var canDistribute = function(nums, quantity) { - const frequencyMap = new Map(); - for (const num of nums) { - frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1); - } - - const frequencies = Array.from(frequencyMap.values()).sort((a, b) => b - a); - quantity.sort((a, b) => b - a); - - return canSatisfy(0, frequencies); - - function canSatisfy(index, counts) { - if (index === quantity.length) return true; - - for (let i = 0; i < counts.length; i++) { - if (counts[i] >= quantity[index]) { - counts[i] -= quantity[index]; - if (canSatisfy(index + 1, counts)) return true; - counts[i] += quantity[index]; - } - } - - return false; - } -}; diff --git a/solutions/1656-design-an-ordered-stream.js b/solutions/1656-design-an-ordered-stream.js deleted file mode 100644 index 4bf3310f..00000000 --- a/solutions/1656-design-an-ordered-stream.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1656. Design an Ordered Stream - * https://leetcode.com/problems/design-an-ordered-stream/ - * Difficulty: Easy - * - * There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is - * an integer between 1 and n and value is a string. No two pairs have the same id. - * - * Design a stream that returns the values in increasing order of their IDs by returning a chunk - * (list) of values after each insertion. The concatenation of all the chunks should result in a - * list of the sorted values. - * - * Implement the OrderedStream class: - * - OrderedStream(int n) Constructs the stream to take n values. - * - String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, - * then returns the largest possible chunk of currently inserted values that appear next in - * the order. - */ - -/** - * @param {number} n - */ -var OrderedStream = function(n) { - this.stream = new Array(n).fill(null); - this.nextIndex = 0; -}; - -/** - * @param {number} idKey - * @param {string} value - * @return {string[]} - */ -OrderedStream.prototype.insert = function(idKey, value) { - const index = idKey - 1; - this.stream[index] = value; - - if (index !== this.nextIndex) return []; - - const result = []; - while (this.nextIndex < this.stream.length && this.stream[this.nextIndex] !== null) { - result.push(this.stream[this.nextIndex]); - this.nextIndex++; - } - - return result; -}; diff --git a/solutions/1658-minimum-operations-to-reduce-x-to-zero.js b/solutions/1658-minimum-operations-to-reduce-x-to-zero.js deleted file mode 100644 index 83dd0ee4..00000000 --- a/solutions/1658-minimum-operations-to-reduce-x-to-zero.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1658. Minimum Operations to Reduce X to Zero - * https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/ - * Difficulty: Medium - * - * You are given an integer array nums and an integer x. In one operation, you can either remove - * the leftmost or the rightmost element from the array nums and subtract its value from x. Note - * that this modifies the array for future operations. - * - * Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, - * return -1. - */ - -/** - * @param {number[]} nums - * @param {number} x - * @return {number} - */ -var minOperations = function(nums, x) { - const targetSum = nums.reduce((sum, num) => sum + num, 0) - x; - if (targetSum < 0) return -1; - if (targetSum === 0) return nums.length; - - let currentSum = 0; - let maxLength = -1; - let left = 0; - - for (let right = 0; right < nums.length; right++) { - currentSum += nums[right]; - - while (currentSum > targetSum && left <= right) { - currentSum -= nums[left]; - left++; - } - - if (currentSum === targetSum) { - maxLength = Math.max(maxLength, right - left + 1); - } - } - - return maxLength === -1 ? -1 : nums.length - maxLength; -}; diff --git a/solutions/1659-maximize-grid-happiness.js b/solutions/1659-maximize-grid-happiness.js deleted file mode 100644 index 86c1909c..00000000 --- a/solutions/1659-maximize-grid-happiness.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * 1659. Maximize Grid Happiness - * https://leetcode.com/problems/maximize-grid-happiness/ - * Difficulty: Hard - * - * You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, - * and there are two types of people: introverts and extroverts. There are introvertsCount - * introverts and extrovertsCount extroverts. - * - * You should decide how many people you want to live in the grid and assign each of them one grid - * cell. Note that you do not have to have all the people living in the grid. - * - * The happiness of each person is calculated as follows: - * - Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or - * extrovert). - * - Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or - * extrovert). - * - * Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. - * - * The grid happiness is the sum of each person's happiness. Return the maximum possible grid - * happiness. - */ - -/** - * @param {number} m - * @param {number} n - * @param {number} introvertsCount - * @param {number} extrovertsCount - * @return {number} - */ -var getMaxGridHappiness = function(m, n, introvertsCount, extrovertsCount) { - const memo = new Map(); - const maxState = Math.pow(3, n); - - return calculateHappiness(0, 0, introvertsCount, extrovertsCount, 0); - - function calculateHappiness(row, col, introverts, extroverts, prevState) { - if (row === m || (introverts === 0 && extroverts === 0)) return 0; - if (col === n) return calculateHappiness(row + 1, 0, introverts, extroverts, prevState); - - const key = `${row},${col},${introverts},${extroverts},${prevState}`; - if (memo.has(key)) return memo.get(key); - - const nextState = (prevState * 3) % maxState; - let maxHappiness = calculateHappiness(row, col + 1, introverts, extroverts, nextState); - - if (introverts > 0) { - let happiness = 120; - const leftNeighbor = col > 0 ? prevState % 3 : 0; - const upNeighbor = row > 0 ? Math.floor(prevState / Math.pow(3, n - 1)) % 3 : 0; - - if (leftNeighbor) happiness -= 30; - if (upNeighbor) happiness -= 30; - - let neighborHappiness = 0; - if (leftNeighbor === 1) neighborHappiness -= 30; - if (leftNeighbor === 2) neighborHappiness += 20; - if (upNeighbor === 1) neighborHappiness -= 30; - if (upNeighbor === 2) neighborHappiness += 20; - - maxHappiness = Math.max( - maxHappiness, - happiness + neighborHappiness - + calculateHappiness(row, col + 1, introverts - 1, extroverts, nextState + 1) - ); - } - - if (extroverts > 0) { - let happiness = 40; - const leftNeighbor = col > 0 ? prevState % 3 : 0; - const upNeighbor = row > 0 ? Math.floor(prevState / Math.pow(3, n - 1)) % 3 : 0; - - if (leftNeighbor) happiness += 20; - if (upNeighbor) happiness += 20; - - let neighborHappiness = 0; - if (leftNeighbor === 1) neighborHappiness -= 30; - if (leftNeighbor === 2) neighborHappiness += 20; - if (upNeighbor === 1) neighborHappiness -= 30; - if (upNeighbor === 2) neighborHappiness += 20; - - maxHappiness = Math.max( - maxHappiness, - happiness + neighborHappiness - + calculateHappiness(row, col + 1, introverts, extroverts - 1, nextState + 2) - ); - } - - memo.set(key, maxHappiness); - return maxHappiness; - } -}; diff --git a/solutions/1662-check-if-two-string-arrays-are-equivalent.js b/solutions/1662-check-if-two-string-arrays-are-equivalent.js deleted file mode 100644 index ebbb213b..00000000 --- a/solutions/1662-check-if-two-string-arrays-are-equivalent.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 1662. Check If Two String Arrays are Equivalent - * https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/ - * Difficulty: Easy - * - * Given two string arrays word1 and word2, return true if the two arrays represent the same - * string, and false otherwise. - * - * A string is represented by an array if the array elements concatenated in order forms the string. - */ - -/** - * @param {string[]} word1 - * @param {string[]} word2 - * @return {boolean} - */ -var arrayStringsAreEqual = function(word1, word2) { - return word1.join('') === word2.join(''); -}; diff --git a/solutions/1663-smallest-string-with-a-given-numeric-value.js b/solutions/1663-smallest-string-with-a-given-numeric-value.js deleted file mode 100644 index 2848c484..00000000 --- a/solutions/1663-smallest-string-with-a-given-numeric-value.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1663. Smallest String With A Given Numeric Value - * https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ - * Difficulty: Medium - * - * The numeric value of a lowercase character is defined as its position (1-indexed) in the - * alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value - * of c is 3, and so on. - * - * The numeric value of a string consisting of lowercase characters is defined as the sum of - * its characters' numeric values. For example, the numeric value of the string "abe" is equal - * to 1 + 2 + 5 = 8. - * - * You are given two integers n and k. Return the lexicographically smallest string with length - * equal to n and numeric value equal to k. - * - * Note that a string x is lexicographically smaller than string y if x comes before y in - * dictionary order, that is, either x is a prefix of y, or if i is the first position - * such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. - */ - -/** - * @param {number} n - * @param {number} k - * @return {string} - */ -var getSmallestString = function(n, k) { - const result = new Array(n).fill('a'); - let remainingValue = k - n; - - for (let i = n - 1; i >= 0 && remainingValue > 0; i--) { - const addValue = Math.min(25, remainingValue); - result[i] = String.fromCharCode(97 + addValue); - remainingValue -= addValue; - } - - return result.join(''); -}; diff --git a/solutions/1664-ways-to-make-a-fair-array.js b/solutions/1664-ways-to-make-a-fair-array.js deleted file mode 100644 index 34b241c7..00000000 --- a/solutions/1664-ways-to-make-a-fair-array.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1664. Ways to Make a Fair Array - * https://leetcode.com/problems/ways-to-make-a-fair-array/ - * Difficulty: Medium - * - * You are given an integer array nums. You can choose exactly one index (0-indexed) and remove - * the element. Notice that the index of the elements may change after the removal. - * - * For example, if nums = [6,1,7,4,1]: - * - Choosing to remove index 1 results in nums = [6,7,4,1]. - * - Choosing to remove index 2 results in nums = [6,1,4,1]. - * - Choosing to remove index 4 results in nums = [6,1,7,4]. - * - * An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. - * - * Return the number of indices that you could choose such that after the removal, nums is fair. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var waysToMakeFair = function(nums) { - let evenSum = 0; - let oddSum = 0; - let result = 0; - - for (let i = 0; i < nums.length; i++) { - if (i % 2 === 0) evenSum += nums[i]; - else oddSum += nums[i]; - } - - let currentEven = 0; - let currentOdd = 0; - - for (let i = 0; i < nums.length; i++) { - if (i % 2 === 0) { - evenSum -= nums[i]; - if (currentEven + oddSum === currentOdd + evenSum) result++; - currentEven += nums[i]; - } else { - oddSum -= nums[i]; - if (currentEven + oddSum === currentOdd + evenSum) result++; - currentOdd += nums[i]; - } - } - - return result; -}; diff --git a/solutions/1665-minimum-initial-energy-to-finish-tasks.js b/solutions/1665-minimum-initial-energy-to-finish-tasks.js deleted file mode 100644 index 29da68bc..00000000 --- a/solutions/1665-minimum-initial-energy-to-finish-tasks.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1665. Minimum Initial Energy to Finish Tasks - * https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/ - * Difficulty: Hard - * - * You are given an array tasks where tasks[i] = [actuali, minimumi]: - * - actuali is the actual amount of energy you spend to finish the ith task. - * - minimumi is the minimum amount of energy you require to begin the ith task. - * - * For example, if the task is [10, 12] and your current energy is 11, you cannot start - * this task. However, if your current energy is 13, you can complete this task, and your - * energy will be 3 after finishing it. - * - * You can finish the tasks in any order you like. - * - * Return the minimum initial amount of energy you will need to finish all the tasks. - */ - -/** - * @param {number[][]} tasks - * @return {number} - */ -var minimumEffort = function(tasks) { - tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0])); - let result = 0; - let currentEnergy = 0; - - for (const [actual, minimum] of tasks) { - if (currentEnergy < minimum) { - result += minimum - currentEnergy; - currentEnergy = minimum; - } - currentEnergy -= actual; - } - - return result; -}; diff --git a/solutions/1670-design-front-middle-back-queue.js b/solutions/1670-design-front-middle-back-queue.js deleted file mode 100644 index 61189aae..00000000 --- a/solutions/1670-design-front-middle-back-queue.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * 1670. Design Front Middle Back Queue - * https://leetcode.com/problems/design-front-middle-back-queue/ - * Difficulty: Medium - * - * Design a queue that supports push and pop operations in the front, middle, and back. - * - * Implement the FrontMiddleBack class: - * - FrontMiddleBack() Initializes the queue. - * - void pushFront(int val) Adds val to the front of the queue. - * - void pushMiddle(int val) Adds val to the middle of the queue. - * - void pushBack(int val) Adds val to the back of the queue. - * - int popFront() Removes the front element of the queue and returns it. If the queue is - * empty, return -1. - * - int popMiddle() Removes the middle element of the queue and returns it. If the queue is - * empty, return -1. - * - int popBack() Removes the back element of the queue and returns it. If the queue is - * empty, return -1. - * - * Notice that when there are two middle position choices, the operation is performed on the - * frontmost middle position choice. For example: - * - Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. - * - Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6]. - */ - -var FrontMiddleBackQueue = function() { - this.elements = []; -}; - -/** - * @param {number} val - * @return {void} - */ -FrontMiddleBackQueue.prototype.pushFront = function(val) { - this.elements.unshift(val); -}; - -/** - * @param {number} val - * @return {void} - */ -FrontMiddleBackQueue.prototype.pushMiddle = function(val) { - const mid = Math.floor(this.elements.length / 2); - this.elements.splice(mid, 0, val); -}; - -/** - * @param {number} val - * @return {void} - */ -FrontMiddleBackQueue.prototype.pushBack = function(val) { - this.elements.push(val); -}; - -/** - * @return {number} - */ -FrontMiddleBackQueue.prototype.popFront = function() { - return this.elements.length ? this.elements.shift() : -1; -}; - -/** - * @return {number} - */ -FrontMiddleBackQueue.prototype.popMiddle = function() { - if (!this.elements.length) return -1; - const mid = Math.floor((this.elements.length - 1) / 2); - return this.elements.splice(mid, 1)[0]; -}; - -/** - * @return {number} - */ -FrontMiddleBackQueue.prototype.popBack = function() { - return this.elements.length ? this.elements.pop() : -1; -}; diff --git a/solutions/1671-minimum-number-of-removals-to-make-mountain-array.js b/solutions/1671-minimum-number-of-removals-to-make-mountain-array.js deleted file mode 100644 index 5e949373..00000000 --- a/solutions/1671-minimum-number-of-removals-to-make-mountain-array.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1671. Minimum Number of Removals to Make Mountain Array - * https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/ - * Difficulty: Hard - * - * You may recall that an array arr is a mountain array if and only if: - * - arr.length >= 3 - * - There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: - * - arr[0] < arr[1] < ... < arr[i - 1] < arr[i] - * - arr[i] > arr[i + 1] > ... > arr[arr.length - 1] - * - * Given an integer array nums, return the minimum number of elements to remove to make - * nums a mountain array. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minimumMountainRemovals = function(nums) { - const length = nums.length; - const leftLIS = new Array(length).fill(1); - const rightLIS = new Array(length).fill(1); - - for (let i = 1; i < length; i++) { - for (let j = 0; j < i; j++) { - if (nums[i] > nums[j]) { - leftLIS[i] = Math.max(leftLIS[i], leftLIS[j] + 1); - } - } - } - - for (let i = length - 2; i >= 0; i--) { - for (let j = length - 1; j > i; j--) { - if (nums[i] > nums[j]) { - rightLIS[i] = Math.max(rightLIS[i], rightLIS[j] + 1); - } - } - } - - let maxMountainLength = 0; - for (let i = 1; i < length - 1; i++) { - if (leftLIS[i] > 1 && rightLIS[i] > 1) { - maxMountainLength = Math.max(maxMountainLength, leftLIS[i] + rightLIS[i] - 1); - } - } - - return length - maxMountainLength; -}; diff --git a/solutions/1673-find-the-most-competitive-subsequence.js b/solutions/1673-find-the-most-competitive-subsequence.js deleted file mode 100644 index 10bfa262..00000000 --- a/solutions/1673-find-the-most-competitive-subsequence.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1673. Find the Most Competitive Subsequence - * https://leetcode.com/problems/find-the-most-competitive-subsequence/ - * Difficulty: Medium - * - * Given an integer array nums and a positive integer k, return the most competitive subsequence - * of nums of size k. - * - * An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements - * from the array. - * - * We define that a subsequence a is more competitive than a subsequence b (of the same length) if - * in the first position where a and b differ, subsequence a has a number less than the - * corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the - * first position they differ is at the final number, and 4 is less than 5. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var mostCompetitive = function(nums, k) { - const result = []; - const n = nums.length; - - for (let i = 0; i < n; i++) { - while (result.length && result[result.length - 1] > nums[i] && result.length + n - i > k) { - result.pop(); - } - if (result.length < k) { - result.push(nums[i]); - } - } - - return result; -}; diff --git a/solutions/1674-minimum-moves-to-make-array-complementary.js b/solutions/1674-minimum-moves-to-make-array-complementary.js deleted file mode 100644 index b996eff6..00000000 --- a/solutions/1674-minimum-moves-to-make-array-complementary.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1674. Minimum Moves to Make Array Complementary - * https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ - * Difficulty: Medium - * - * You are given an integer array nums of even length n and an integer limit. In one move, you - * can replace any integer from nums with another integer between 1 and limit, inclusive. - * - * The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] - * equals the same number. For example, the array [1,2,3,4] is complementary because for all - * indices i, nums[i] + nums[n - 1 - i] = 5. - * - * Return the minimum number of moves required to make nums complementary. - */ - -/** - * @param {number[]} nums - * @param {number} limit - * @return {number} - */ -var minMoves = function(nums, limit) { - const n = nums.length; - const delta = new Array(2 * limit + 2).fill(0); - let result = n; - - for (let i = 0; i < n / 2; i++) { - const left = nums[i]; - const right = nums[n - 1 - i]; - const minSum = Math.min(left, right) + 1; - const maxSum = Math.max(left, right) + limit; - delta[2] += 2; - delta[minSum] -= 1; - delta[left + right] -= 1; - delta[left + right + 1] += 1; - delta[maxSum + 1] += 1; - } - - let moves = 0; - for (let i = 2; i <= 2 * limit; i++) { - moves += delta[i]; - result = Math.min(result, moves); - } - - return result; -}; diff --git a/solutions/1675-minimize-deviation-in-array.js b/solutions/1675-minimize-deviation-in-array.js deleted file mode 100644 index add60176..00000000 --- a/solutions/1675-minimize-deviation-in-array.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1675. Minimize Deviation in Array - * https://leetcode.com/problems/minimize-deviation-in-array/ - * Difficulty: Hard - * - * You are given an array nums of n positive integers. - * - * You can perform two types of operations on any element of the array any number of times: - * - If the element is even, divide it by 2. - * - For example, if the array is [1,2,3,4], then you can do this operation on the last element, - * and the array will be [1,2,3,2]. - * - If the element is odd, multiply it by 2. - * - For example, if the array is [1,2,3,4], then you can do this operation on the first element, - * and the array will be [2,2,3,4]. - * - * The deviation of the array is the maximum difference between any two elements in the array. - * - * Return the minimum deviation the array can have after performing some number of operations. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minimumDeviation = function(nums) { - const heap = []; - let minElement = Infinity; - - for (const num of nums) { - const value = num % 2 ? num * 2 : num; - heap.push(value); - minElement = Math.min(minElement, value); - } - - for (let i = Math.floor(heap.length / 2) - 1; i >= 0; i--) { - siftDown(i); - } - - let minDeviation = heap[0] - minElement; - - while (heap[0] % 2 === 0) { - const maxElement = heap[0]; - heap[0] = maxElement / 2; - minElement = Math.min(minElement, heap[0]); - siftDown(0); - minDeviation = Math.min(minDeviation, heap[0] - minElement); - } - - return minDeviation; - - function siftDown(index) { - while (2 * index + 1 < heap.length) { - let maxChild = 2 * index + 1; - if (maxChild + 1 < heap.length && heap[maxChild + 1] > heap[maxChild]) { - maxChild++; - } - if (heap[index] < heap[maxChild]) { - [heap[index], heap[maxChild]] = [heap[maxChild], heap[index]]; - index = maxChild; - } else { - break; - } - } - } -}; diff --git a/solutions/1678-goal-parser-interpretation.js b/solutions/1678-goal-parser-interpretation.js deleted file mode 100644 index 32bb31f8..00000000 --- a/solutions/1678-goal-parser-interpretation.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1678. Goal Parser Interpretation - * https://leetcode.com/problems/goal-parser-interpretation/ - * Difficulty: Easy - * - * You own a Goal Parser that can interpret a string command. The command consists of an alphabet - * of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string - * "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then - * concatenated in the original order. - * - * Given the string command, return the Goal Parser's interpretation of command. - */ - -/** - * @param {string} command - * @return {string} - */ -var interpret = function(command) { - let result = ''; - - for (let i = 0; i < command.length; i++) { - if (command[i] === 'G') { - result += 'G'; - } else if (command[i] === '(' && command[i + 1] === ')') { - result += 'o'; - i++; - } else { - result += 'al'; - i += 3; - } - } - - return result; -}; diff --git a/solutions/1680-concatenation-of-consecutive-binary-numbers.js b/solutions/1680-concatenation-of-consecutive-binary-numbers.js deleted file mode 100644 index d41c5fa5..00000000 --- a/solutions/1680-concatenation-of-consecutive-binary-numbers.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1680. Concatenation of Consecutive Binary Numbers - * https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/ - * Difficulty: Medium - * - * Given an integer n, return the decimal value of the binary string formed by concatenating the - * binary representations of 1 to n in order, modulo 109 + 7. - */ - -/** - * @param {number} n - * @return {number} - */ -var concatenatedBinary = function(n) { - const MOD = 1e9 + 7; - let result = 0; - - for (let i = 1; i <= n; i++) { - const bitLength = Math.floor(Math.log2(i)) + 1; - result = ((result * (1 << bitLength)) % MOD + i) % MOD; - } - - return result; -}; diff --git a/solutions/1681-minimum-incompatibility.js b/solutions/1681-minimum-incompatibility.js deleted file mode 100644 index a65163f4..00000000 --- a/solutions/1681-minimum-incompatibility.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1681. Minimum Incompatibility - * https://leetcode.com/problems/minimum-incompatibility/ - * Difficulty: Hard - * - * You are given an integer array nums and an integer k. You are asked to distribute this array - * into k subsets of equal size such that there are no two equal elements in the same subset. - * - * A subset's incompatibility is the difference between the maximum and minimum elements in that - * array. - * - * Return the minimum possible sum of incompatibilities of the k subsets after distributing the - * array optimally, or return -1 if it is not possible. - * - * A subset is a group integers that appear in the array with no particular order. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var minimumIncompatibility = function(nums, k) { - const n = nums.length; - const subsetSize = n / k; - const freq = new Array(n + 1).fill(0); - for (const num of nums) { - freq[num]++; - if (freq[num] > k) return -1; - } - - nums.sort((a, b) => a - b); - const subsetValues = new Map(); - - computeSubsets(0, 0, 0, 0, 0, []); - - const dp = new Array(1 << n).fill(Infinity); - dp[0] = 0; - - for (let mask = 0; mask < (1 << n); mask++) { - if (dp[mask] === Infinity) continue; - for (const [subsetMask, value] of subsetValues) { - if ((mask & subsetMask) === 0) { - const newMask = mask | subsetMask; - dp[newMask] = Math.min(dp[newMask], dp[mask] + value); - } - } - } - - return dp[(1 << n) - 1] === Infinity ? -1 : dp[(1 << n) - 1]; - - function computeSubsets(mask, index, count, minVal, maxVal, selected) { - if (count === subsetSize) { - subsetValues.set(mask, maxVal - minVal); - return; - } - if (index >= n || n - index < subsetSize - count) return; - - computeSubsets(mask, index + 1, count, minVal, maxVal, selected); - if (!selected.includes(nums[index])) { - computeSubsets(mask | (1 << index), index + 1, count + 1, - count === 0 ? nums[index] : minVal, nums[index], [...selected, nums[index]]); - } - } -}; diff --git a/solutions/1684-count-the-number-of-consistent-strings.js b/solutions/1684-count-the-number-of-consistent-strings.js deleted file mode 100644 index 29953369..00000000 --- a/solutions/1684-count-the-number-of-consistent-strings.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1684. Count the Number of Consistent Strings - * https://leetcode.com/problems/count-the-number-of-consistent-strings/ - * Difficulty: Easy - * - * You are given a string allowed consisting of distinct characters and an array of strings words. - * A string is consistent if all characters in the string appear in the string allowed. - * - * Return the number of consistent strings in the array words. - */ - -/** - * @param {string} allowed - * @param {string[]} words - * @return {number} - */ -var countConsistentStrings = function(allowed, words) { - const allowedSet = new Set(allowed); - let result = 0; - - for (const word of words) { - let isConsistent = true; - for (const char of word) { - if (!allowedSet.has(char)) { - isConsistent = false; - break; - } - } - if (isConsistent) result++; - } - - return result; -}; diff --git a/solutions/1685-sum-of-absolute-differences-in-a-sorted-array.js b/solutions/1685-sum-of-absolute-differences-in-a-sorted-array.js deleted file mode 100644 index 1abbe093..00000000 --- a/solutions/1685-sum-of-absolute-differences-in-a-sorted-array.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1685. Sum of Absolute Differences in a Sorted Array - * https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/ - * Difficulty: Medium - * - * You are given an integer array nums sorted in non-decreasing order. - * - * Build and return an integer array result with the same length as nums such that result[i] is - * equal to the summation of absolute differences between nums[i] and all the other elements - * in the array. - * - * In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length - * and j != i (0-indexed). - */ - -/** - * @param {number[]} nums - * @return {number[]} - */ -var getSumAbsoluteDifferences = function(nums) { - const n = nums.length; - const result = new Array(n); - let prefixSum = 0; - let suffixSum = nums.reduce((sum, num) => sum + num, 0); - - for (let i = 0; i < n; i++) { - const current = nums[i]; - suffixSum -= current; - result[i] = (current * i - prefixSum) + (suffixSum - current * (n - 1 - i)); - prefixSum += current; - } - - return result; -}; diff --git a/solutions/1686-stone-game-vi.js b/solutions/1686-stone-game-vi.js deleted file mode 100644 index c0c7f9c9..00000000 --- a/solutions/1686-stone-game-vi.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1686. Stone Game VI - * https://leetcode.com/problems/stone-game-vi/ - * Difficulty: Medium - * - * Alice and Bob take turns playing a game, with Alice starting first. - * - * There are n stones in a pile. On each player's turn, they can remove a stone from the pile and - * receive points based on the stone's value. Alice and Bob may value the stones differently. - * - * You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] - * and bobValues[i] represents how Alice and Bob, respectively, value the ith stone. - * - * The winner is the person with the most points after all the stones are chosen. If both players - * have the same amount of points, the game results in a draw. Both players will play optimally. - * Both players know the other's values. - * - * Determine the result of the game, and: - * - If Alice wins, return 1. - * - If Bob wins, return -1. - * - If the game results in a draw, return 0. - */ - -/** - * @param {number[]} aliceValues - * @param {number[]} bobValues - * @return {number} - */ -var stoneGameVI = function(aliceValues, bobValues) { - const n = aliceValues.length; - const stones = aliceValues.map((alice, i) => ({ - sum: alice + bobValues[i], - alice: alice, - bob: bobValues[i] - })); - - stones.sort((a, b) => b.sum - a.sum); - - let aliceScore = 0; - let bobScore = 0; - - for (let i = 0; i < n; i++) { - if (i % 2 === 0) { - aliceScore += stones[i].alice; - } else { - bobScore += stones[i].bob; - } - } - - return aliceScore > bobScore ? 1 : aliceScore < bobScore ? -1 : 0; -}; diff --git a/solutions/1687-delivering-boxes-from-storage-to-ports.js b/solutions/1687-delivering-boxes-from-storage-to-ports.js deleted file mode 100644 index 2a6a53e2..00000000 --- a/solutions/1687-delivering-boxes-from-storage-to-ports.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1687. Delivering Boxes from Storage to Ports - * https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/ - * Difficulty: Hard - * - * You have the task of delivering some boxes from storage to their ports using only one ship. - * However, this ship has a limit on the number of boxes and the total weight that it can carry. - * - * You are given an array boxes, where boxes[i] = [portsi, weighti], and three integers - * portsCount, maxBoxes, and maxWeight. - * - portsi is the port where you need to deliver the ith box and weightsi is the weight of - * the ith box. - * - portsCount is the number of ports. - * - maxBoxes and maxWeight are the respective box and weight limits of the ship. - * - * The boxes need to be delivered in the order they are given. The ship will follow these steps: - * - The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and - * maxWeight constraints. - * - For each loaded box in order, the ship will make a trip to the port the box needs to be - * delivered to and deliver it. If the ship is already at the correct port, no trip is needed, - * and the box can immediately be delivered. - * - The ship then makes a return trip to storage to take more boxes from the queue. - * - * The ship must end at storage after all the boxes have been delivered. - * - * Return the minimum number of trips the ship needs to make to deliver all boxes to their - * respective ports. - */ - -/** - * @param {number[][]} boxes - * @param {number} portsCount - * @param {number} maxBoxes - * @param {number} maxWeight - * @return {number} - */ -var boxDelivering = function(boxes, portsCount, maxBoxes, maxWeight) { - const n = boxes.length; - const minTrips = new Array(n + 1).fill(0); - let start = 0; - let portChanges = 0; - - for (let end = 0; end < n; end++) { - maxBoxes--; - maxWeight -= boxes[end][1]; - if (end > 0 && boxes[end][0] !== boxes[end - 1][0]) portChanges++; - - while (maxBoxes < 0 || maxWeight < 0 - || (start < end && minTrips[start + 1] === minTrips[start])) { - maxBoxes++; - maxWeight += boxes[start++][1]; - if (start > 0 && boxes[start][0] !== boxes[start - 1][0]) portChanges--; - } - - minTrips[end + 1] = portChanges + 2 + minTrips[start]; - } - - return minTrips[n]; -}; diff --git a/solutions/1688-count-of-matches-in-tournament.js b/solutions/1688-count-of-matches-in-tournament.js deleted file mode 100644 index 320b7376..00000000 --- a/solutions/1688-count-of-matches-in-tournament.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 1688. Count of Matches in Tournament - * https://leetcode.com/problems/count-of-matches-in-tournament/ - * Difficulty: Easy - * - * You are given an integer n, the number of teams in a tournament that has strange rules: - * - If the current number of teams is even, each team gets paired with another team. A total - * of n / 2 matches are played, and n / 2 teams advance to the next round. - * - If the current number of teams is odd, one team randomly advances in the tournament, and - * the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams - * advance to the next round. - * - * Return the number of matches played in the tournament until a winner is decided. - */ - -/** - * @param {number} n - * @return {number} - */ -var numberOfMatches = function(n) { - return n - 1; -}; diff --git a/solutions/1689-partitioning-into-minimum-number-of-deci-binary-numbers.js b/solutions/1689-partitioning-into-minimum-number-of-deci-binary-numbers.js deleted file mode 100644 index bae86a27..00000000 --- a/solutions/1689-partitioning-into-minimum-number-of-deci-binary-numbers.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers - * https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/ - * Difficulty: Medium - * - * A decimal number is called deci-binary if each of its digits is either 0 or 1 without any - * leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. - * - * Given a string n that represents a positive decimal integer, return the minimum number of - * positive deci-binary numbers needed so that they sum up to n. - */ - -/** - * @param {string} n - * @return {number} - */ -var minPartitions = function(n) { - let maxDigit = 0; - for (const digit of n) { - maxDigit = Math.max(maxDigit, parseInt(digit)); - } - return maxDigit; -}; diff --git a/solutions/1690-stone-game-vii.js b/solutions/1690-stone-game-vii.js deleted file mode 100644 index 10591983..00000000 --- a/solutions/1690-stone-game-vii.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1690. Stone Game VII - * https://leetcode.com/problems/stone-game-vii/ - * Difficulty: Medium - * - * Alice and Bob take turns playing a game, with Alice starting first. - * - * There are n stones arranged in a row. On each player's turn, they can remove either the leftmost - * stone or the rightmost stone from the row and receive points equal to the sum of the remaining - * stones' values in the row. The winner is the one with the higher score when there are no stones - * left to remove. - * - * Bob found that he will always lose this game (poor Bob, he always loses), so he decided to - * minimize the score's difference. Alice's goal is to maximize the difference in the score. - * - * Given an array of integers stones where stones[i] represents the value of the ith stone from - * the left, return the difference in Alice and Bob's score if they both play optimally. - */ - -/** - * @param {number[]} stones - * @return {number} - */ -var stoneGameVII = function(stones) { - const n = stones.length; - const prefixSum = new Array(n + 1).fill(0); - const dp = new Array(n).fill().map(() => new Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - prefixSum[i + 1] = prefixSum[i] + stones[i]; - } - - for (let len = 2; len <= n; len++) { - for (let start = 0; start <= n - len; start++) { - const end = start + len - 1; - const leftScore = prefixSum[end + 1] - prefixSum[start + 1] - dp[start + 1][end]; - const rightScore = prefixSum[end] - prefixSum[start] - dp[start][end - 1]; - dp[start][end] = Math.max(leftScore, rightScore); - } - } - - return dp[0][n - 1]; -}; diff --git a/solutions/1691-maximum-height-by-stacking-cuboids.js b/solutions/1691-maximum-height-by-stacking-cuboids.js deleted file mode 100644 index 0a1ee49d..00000000 --- a/solutions/1691-maximum-height-by-stacking-cuboids.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1691. Maximum Height by Stacking Cuboids - * https://leetcode.com/problems/maximum-height-by-stacking-cuboids/ - * Difficulty: Hard - * - * Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] - * (0-indexed). Choose a subset of cuboids and place them on each other. - * - * You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and - * heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on - * another cuboid. - * - * Return the maximum height of the stacked cuboids. - */ - -/** - * @param {number[][]} cuboids - * @return {number} - */ -var maxHeight = function(cuboids) { - const sortedCuboids = cuboids.map(dim => dim.sort((a, b) => a - b)) - .sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]); - const n = sortedCuboids.length; - const maxHeights = new Array(n).fill(0); - let result = 0; - - for (let i = 0; i < n; i++) { - maxHeights[i] = sortedCuboids[i][2]; - for (let j = 0; j < i; j++) { - if (sortedCuboids[j][0] <= sortedCuboids[i][0] - && sortedCuboids[j][1] <= sortedCuboids[i][1] - && sortedCuboids[j][2] <= sortedCuboids[i][2]) { - maxHeights[i] = Math.max(maxHeights[i], maxHeights[j] + sortedCuboids[i][2]); - } - } - result = Math.max(result, maxHeights[i]); - } - - return result; -}; diff --git a/solutions/1694-reformat-phone-number.js b/solutions/1694-reformat-phone-number.js deleted file mode 100644 index 0c6b6a87..00000000 --- a/solutions/1694-reformat-phone-number.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1694. Reformat Phone Number - * https://leetcode.com/problems/reformat-phone-number/ - * Difficulty: Easy - * - * You are given a phone number as a string number. number consists of digits, spaces ' ', - * and/or dashes '-'. - * - * You would like to reformat the phone number in a certain manner. Firstly, remove all spaces - * and dashes. Then, group the digits from left to right into blocks of length 3 until there - * are 4 or fewer digits. The final digits are then grouped as follows: - * - 2 digits: A single block of length 2. - * - 3 digits: A single block of length 3. - * - 4 digits: Two blocks of length 2 each. - * - * The blocks are then joined by dashes. Notice that the reformatting process should never produce - * any blocks of length 1 and produce at most two blocks of length 2. - * - * Return the phone number after formatting. - */ - -/** - * @param {string} number - * @return {string} - */ -var reformatNumber = function(number) { - const digits = number.replace(/[^0-9]/g, ''); - const blocks = []; - let i = 0; - - while (i < digits.length) { - const remaining = digits.length - i; - if (remaining > 4) { - blocks.push(digits.slice(i, i + 3)); - i += 3; - } else if (remaining === 4) { - blocks.push(digits.slice(i, i + 2), digits.slice(i + 2)); - break; - } else if (remaining === 2 || remaining === 3) { - blocks.push(digits.slice(i)); - break; - } - } - - return blocks.join('-'); -}; diff --git a/solutions/1695-maximum-erasure-value.js b/solutions/1695-maximum-erasure-value.js deleted file mode 100644 index 84ae73d4..00000000 --- a/solutions/1695-maximum-erasure-value.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1695. Maximum Erasure Value - * https://leetcode.com/problems/maximum-erasure-value/ - * Difficulty: Medium - * - * You are given an array of positive integers nums and want to erase a subarray containing unique - * elements. The score you get by erasing the subarray is equal to the sum of its elements. - * - * Return the maximum score you can get by erasing exactly one subarray. - * - * An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, - * if it is equal to a[l],a[l+1],...,a[r] for some (l,r). - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maximumUniqueSubarray = function(nums) { - const seen = new Set(); - let result = 0; - let currentSum = 0; - let start = 0; - - for (let end = 0; end < nums.length; end++) { - while (seen.has(nums[end])) { - seen.delete(nums[start]); - currentSum -= nums[start]; - start++; - } - seen.add(nums[end]); - currentSum += nums[end]; - result = Math.max(result, currentSum); - } - - return result; -}; diff --git a/solutions/1696-jump-game-vi.js b/solutions/1696-jump-game-vi.js deleted file mode 100644 index ad7922f3..00000000 --- a/solutions/1696-jump-game-vi.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1696. Jump Game VI - * https://leetcode.com/problems/jump-game-vi/ - * Difficulty: Medium - * - * You are given a 0-indexed integer array nums and an integer k. - * - * You are initially standing at index 0. In one move, you can jump at most k steps forward without - * going outside the boundaries of the array. That is, you can jump from index i to any index in - * the range [i + 1, min(n - 1, i + k)] inclusive. - * - * You want to reach the last index of the array (index n - 1). Your score is the sum of all - * nums[j] for each index j you visited in the array. - * - * Return the maximum score you can get. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maxResult = function(nums, k) { - const n = nums.length; - const maxScores = new Array(n).fill(-Infinity); - const deque = []; - - maxScores[0] = nums[0]; - deque.push(0); - - for (let i = 1; i < n; i++) { - while (deque.length && deque[0] < i - k) { - deque.shift(); - } - - maxScores[i] = nums[i] + maxScores[deque[0]]; - - while (deque.length && maxScores[i] >= maxScores[deque[deque.length - 1]]) { - deque.pop(); - } - - deque.push(i); - } - - return maxScores[n - 1]; -}; diff --git a/solutions/1697-checking-existence-of-edge-length-limited-paths.js b/solutions/1697-checking-existence-of-edge-length-limited-paths.js deleted file mode 100644 index 77fb4beb..00000000 --- a/solutions/1697-checking-existence-of-edge-length-limited-paths.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 1697. Checking Existence of Edge Length Limited Paths - * https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/ - * Difficulty: Hard - * - * An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes - * an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between - * two nodes. - * - * Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each - * queries[j] whether there is a path between pj and qj such that each edge on the path has a - * distance strictly less than limitj. - * - * Return a boolean array answer, where answer.length == queries.length and the jth value of answer - * is true if there is a path for queries[j] is true, and false otherwise. - */ - -/** - * @param {number} n - * @param {number[][]} edgeList - * @param {number[][]} queries - * @return {boolean[]} - */ -var distanceLimitedPathsExist = function(n, edgeList, queries) { - const parent = new Array(n).fill().map((_, i) => i); - - edgeList.sort((a, b) => a[2] - b[2]); - const sortedQueries = queries.map((q, i) => [...q, i]).sort((a, b) => a[2] - b[2]); - const result = new Array(queries.length).fill(false); - - let edgeIndex = 0; - for (const [p, q, limit, index] of sortedQueries) { - while (edgeIndex < edgeList.length && edgeList[edgeIndex][2] < limit) { - union(edgeList[edgeIndex][0], edgeList[edgeIndex][1]); - edgeIndex++; - } - result[index] = find(p) === find(q); - } - - return result; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - parent[find(x)] = find(y); - } -}; diff --git a/solutions/1700-number-of-students-unable-to-eat-lunch.js b/solutions/1700-number-of-students-unable-to-eat-lunch.js deleted file mode 100644 index c56df9c2..00000000 --- a/solutions/1700-number-of-students-unable-to-eat-lunch.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1700. Number of Students Unable to Eat Lunch - * https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/ - * Difficulty: Easy - * - * The school cafeteria offers circular and square sandwiches at lunch break, referred to by - * numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers - * square or circular sandwiches. - * - * The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches - * are placed in a stack. At each step: - * - If the student at the front of the queue prefers the sandwich on the top of the stack, they - * will take it and leave the queue. - * - Otherwise, they will leave it and go to the queue's end. - * - * This continues until none of the queue students want to take the top sandwich and are thus - * unable to eat. - * - * You are given two integer arrays students and sandwiches where sandwiches[i] is the type of - * the ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the - * preference of the jth student in the initial queue (j = 0 is the front of the queue). - * Return the number of students that are unable to eat. - */ - -/** - * @param {number[]} students - * @param {number[]} sandwiches - * @return {number} - */ -var countStudents = function(students, sandwiches) { - const preferenceCount = [0, 0]; - for (const pref of students) { - preferenceCount[pref]++; - } - - for (const sandwich of sandwiches) { - if (preferenceCount[sandwich] === 0) { - return preferenceCount[0] + preferenceCount[1]; - } - preferenceCount[sandwich]--; - } - - return 0; -}; diff --git a/solutions/1701-average-waiting-time.js b/solutions/1701-average-waiting-time.js deleted file mode 100644 index e8347499..00000000 --- a/solutions/1701-average-waiting-time.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1701. Average Waiting Time - * https://leetcode.com/problems/average-waiting-time/ - * Difficulty: Medium - * - * There is a restaurant with a single chef. You are given an array customers, where - * customers[i] = [arrivali, timei]: - * - arrivali is the arrival time of the ith customer. The arrival times are sorted in - * non-decreasing order. - * - timei is the time needed to prepare the order of the ith customer. - * - * When a customer arrives, he gives the chef his order, and the chef starts preparing it once - * he is idle. The customer waits till the chef finishes preparing his order. The chef does not - * prepare food for more than one customer at a time. The chef prepares food for customers in - * the order they were given in the input. - * - * Return the average waiting time of all customers. Solutions within 10-5 from the actual - * answer are considered accepted. - */ - -/** - * @param {number[][]} customers - * @return {number} - */ -var averageWaitingTime = function(customers) { - let totalWait = 0; - let currentTime = 0; - - for (const [arrival, prepTime] of customers) { - const startTime = Math.max(arrival, currentTime); - const finishTime = startTime + prepTime; - totalWait += finishTime - arrival; - currentTime = finishTime; - } - - return totalWait / customers.length; -}; diff --git a/solutions/1702-maximum-binary-string-after-change.js b/solutions/1702-maximum-binary-string-after-change.js deleted file mode 100644 index f888eb99..00000000 --- a/solutions/1702-maximum-binary-string-after-change.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1702. Maximum Binary String After Change - * https://leetcode.com/problems/maximum-binary-string-after-change/ - * Difficulty: Medium - * - * You are given a binary string binary consisting of only 0's or 1's. You can apply each of - * the following operations any number of times: - * - Operation 1: If the number contains the substring "00", you can replace it with "10". - * - For example, "00010" -> "10010" - * - Operation 2: If the number contains the substring "10", you can replace it with "01". - * - For example, "00010" -> "00001" - * - * Return the maximum binary string you can obtain after any number of operations. Binary - * string x is greater than binary string y if x's decimal representation is greater than - * y's decimal representation. - */ - -/** - * @param {string} binary - * @return {string} - */ -var maximumBinaryString = function(binary) { - const n = binary.length; - let zeroCount = 0; - let firstZero = -1; - - for (let i = 0; i < n; i++) { - if (binary[i] === '0') { - if (firstZero === -1) firstZero = i; - zeroCount++; - } - } - - if (zeroCount <= 1) return binary; - - const result = new Array(n).fill('1'); - result[firstZero + zeroCount - 1] = '0'; - - return result.join(''); -}; diff --git a/solutions/1703-minimum-adjacent-swaps-for-k-consecutive-ones.js b/solutions/1703-minimum-adjacent-swaps-for-k-consecutive-ones.js deleted file mode 100644 index cb5687c9..00000000 --- a/solutions/1703-minimum-adjacent-swaps-for-k-consecutive-ones.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1703. Minimum Adjacent Swaps for K Consecutive Ones - * https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/ - * Difficulty: Hard - * - * You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In - * one move, you can choose two adjacent indices and swap their values. - * - * Return the minimum number of moves required so that nums has k consecutive 1's. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var minMoves = function(nums, k) { - const ones = []; - for (let i = 0; i < nums.length; i++) { - if (nums[i] === 1) ones.push(i); - } - - const prefixSum = [0]; - for (let i = 0; i < ones.length; i++) { - prefixSum.push(prefixSum[i] + ones[i]); - } - - let minSwaps = Infinity; - for (let i = 0; i <= ones.length - k; i++) { - const j = i + k - 1; - const mid = i + Math.floor(k / 2); - const target = ones[mid]; - const leftCount = mid - i; - const rightCount = j - mid; - const leftSum = prefixSum[mid] - prefixSum[i]; - const rightSum = prefixSum[j + 1] - prefixSum[mid + 1]; - const swaps = (target * leftCount - leftSum) + (rightSum - target * rightCount); - minSwaps = Math.min(minSwaps, swaps); - } - - const medianAdjust = Math.floor(k / 2) * Math.ceil(k / 2); - return minSwaps - medianAdjust; -}; diff --git a/solutions/1704-determine-if-string-halves-are-alike.js b/solutions/1704-determine-if-string-halves-are-alike.js deleted file mode 100644 index e2734c96..00000000 --- a/solutions/1704-determine-if-string-halves-are-alike.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1704. Determine if String Halves Are Alike - * https://leetcode.com/problems/determine-if-string-halves-are-alike/ - * Difficulty: Easy - * - * You are given a string s of even length. Split this string into two halves of equal lengths, - * and let a be the first half and b be the second half. - * - * Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', - * 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. - * - * Return true if a and b are alike. Otherwise, return false. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var halvesAreAlike = function(s) { - const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); - let firstHalfVowels = 0; - let secondHalfVowels = 0; - const mid = s.length / 2; - - for (let i = 0; i < mid; i++) { - if (vowels.has(s[i])) firstHalfVowels++; - if (vowels.has(s[i + mid])) secondHalfVowels++; - } - - return firstHalfVowels === secondHalfVowels; -}; diff --git a/solutions/1705-maximum-number-of-eaten-apples.js b/solutions/1705-maximum-number-of-eaten-apples.js deleted file mode 100644 index 8457f613..00000000 --- a/solutions/1705-maximum-number-of-eaten-apples.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1705. Maximum Number of Eaten Apples - * https://leetcode.com/problems/maximum-number-of-eaten-apples/ - * Difficulty: Medium - * - * There is a special kind of apple tree that grows apples every day for n days. On the ith day, - * the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] - * the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any - * apples, which are denoted by apples[i] == 0 and days[i] == 0. - * - * You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep - * eating after the first n days. - * - * Given two integer arrays days and apples of length n, return the maximum number of apples you - * can eat. - */ - -/** - * @param {number[]} apples - * @param {number[]} days - * @return {number} - */ -var eatenApples = function(apples, days) { - const expiryCounts = new Array(40001).fill(0); - let result = 0; - let earliestExpiry = Infinity; - let maxExpiry = apples.length; - - for (let day = 0; day <= maxExpiry; day++) { - if (earliestExpiry < day) earliestExpiry = day; - - if (day < apples.length && apples[day]) { - const expiry = day + days[day] - 1; - expiryCounts[expiry] += apples[day]; - earliestExpiry = Math.min(expiry, earliestExpiry); - maxExpiry = Math.max(expiry, maxExpiry); - } - - while (!expiryCounts[earliestExpiry] && earliestExpiry < maxExpiry) { - earliestExpiry++; - } - - if (expiryCounts[earliestExpiry]) { - result++; - expiryCounts[earliestExpiry]--; - } - } - - return result; -}; diff --git a/solutions/1706-where-will-the-ball-fall.js b/solutions/1706-where-will-the-ball-fall.js deleted file mode 100644 index 296e3d94..00000000 --- a/solutions/1706-where-will-the-ball-fall.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1706. Where Will the Ball Fall - * https://leetcode.com/problems/where-will-the-ball-fall/ - * Difficulty: Medium - * - * You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on - * the top and bottom sides. - * - * Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a - * ball to the right or to the left. - * - A board that redirects the ball to the right spans the top-left corner to the bottom-right - * corner and is represented in the grid as 1. - * - A board that redirects the ball to the left spans the top-right corner to the bottom-left - * corner and is represented in the grid as -1. - * - * We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall - * out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a - * board redirects the ball into either wall of the box. - * - * Return an array answer of size n where answer[i] is the column that the ball falls out of at the - * bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in - * the box. - */ - -/** - * @param {number[][]} grid - * @return {number[]} - */ -var findBall = function(grid) { - const m = grid.length; - const n = grid[0].length; - const result = new Array(n); - - for (let col = 0; col < n; col++) { - let currentCol = col; - let row = 0; - - while (row < m) { - const nextCol = currentCol + grid[row][currentCol]; - - if (nextCol < 0 || nextCol >= n || grid[row][currentCol] !== grid[row][nextCol]) { - currentCol = -1; - break; - } - - currentCol = nextCol; - row++; - } - - result[col] = currentCol; - } - - return result; -}; diff --git a/solutions/1707-maximum-xor-with-an-element-from-array.js b/solutions/1707-maximum-xor-with-an-element-from-array.js deleted file mode 100644 index 4fb40d17..00000000 --- a/solutions/1707-maximum-xor-with-an-element-from-array.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1707. Maximum XOR With an Element From Array - * https://leetcode.com/problems/maximum-xor-with-an-element-from-array/ - * Difficulty: Hard - * - * You are given an array nums consisting of non-negative integers. You are also given a queries - * array, where queries[i] = [xi, mi]. - * - * The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that - * does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that - * nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. - * - * Return an integer array answer where answer.length == queries.length and answer[i] is the - * answer to the ith query. - */ - -/** - * @param {number[]} nums - * @param {number[][]} queries - * @return {number[]} - */ -var maximizeXor = function(nums, queries) { - nums.sort((a, b) => a - b); - const sortedQueries = queries.map((q, i) => [q[0], q[1], i]).sort((a, b) => a[1] - b[1]); - const result = new Array(queries.length).fill(-1); - - const trie = {}; - let numIndex = 0; - - for (const [x, m, queryIndex] of sortedQueries) { - while (numIndex < nums.length && nums[numIndex] <= m) { - let node = trie; - for (let bit = 30; bit >= 0; bit--) { - const bitValue = (nums[numIndex] >> bit) & 1; - if (!node[bitValue]) node[bitValue] = {}; - node = node[bitValue]; - } - numIndex++; - } - - if (numIndex === 0) continue; - - let maxXor = 0; - let node = trie; - for (let bit = 30; bit >= 0; bit--) { - const bitValue = (x >> bit) & 1; - const oppositeBit = bitValue ^ 1; - if (node[oppositeBit]) { - maxXor |= (1 << bit); - node = node[oppositeBit]; - } else { - node = node[bitValue]; - } - } - result[queryIndex] = maxXor; - } - - return result; -}; diff --git a/solutions/1710-maximum-units-on-a-truck.js b/solutions/1710-maximum-units-on-a-truck.js deleted file mode 100644 index 5ca9d066..00000000 --- a/solutions/1710-maximum-units-on-a-truck.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1710. Maximum Units on a Truck - * https://leetcode.com/problems/maximum-units-on-a-truck/ - * Difficulty: Easy - * - * You are assigned to put some amount of boxes onto one truck. You are given a 2D array - * boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: - * - numberOfBoxesi is the number of boxes of type i. - * - numberOfUnitsPerBoxi is the number of units in each box of the type i. - * - * You are also given an integer truckSize, which is the maximum number of boxes that can be - * put on the truck. You can choose any boxes to put on the truck as long as the number of - * boxes does not exceed truckSize. - * - * Return the maximum total number of units that can be put on the truck. - */ - -/** - * @param {number[][]} boxTypes - * @param {number} truckSize - * @return {number} - */ -var maximumUnits = function(boxTypes, truckSize) { - boxTypes.sort((a, b) => b[1] - a[1]); - let result = 0; - let remainingBoxes = truckSize; - - for (const [count, units] of boxTypes) { - const boxesToTake = Math.min(count, remainingBoxes); - result += boxesToTake * units; - remainingBoxes -= boxesToTake; - if (remainingBoxes === 0) break; - } - - return result; -}; diff --git a/solutions/1711-count-good-meals.js b/solutions/1711-count-good-meals.js deleted file mode 100644 index 870cc7dd..00000000 --- a/solutions/1711-count-good-meals.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1711. Count Good Meals - * https://leetcode.com/problems/count-good-meals/ - * Difficulty: Medium - * - * A good meal is a meal that contains exactly two different food items with a sum of deliciousness - * equal to a power of two. - * - * You can pick any two different foods to make a good meal. - * - * Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the - * ith item of food, return the number of different good meals you can make from this list - * modulo 109 + 7. - * - * Note that items with different indices are considered different even if they have the same - * deliciousness value. - */ - -/** - * @param {number[]} deliciousness - * @return {number} - */ -var countPairs = function(deliciousness) { - const MOD = 1e9 + 7; - const frequency = new Map(); - let result = 0; - - for (const value of deliciousness) { - for (let power = 1; power <= 1 << 21; power <<= 1) { - const complement = power - value; - if (frequency.has(complement)) { - result = (result + frequency.get(complement)) % MOD; - } - } - frequency.set(value, (frequency.get(value) || 0) + 1); - } - - return result; -}; diff --git a/solutions/1712-ways-to-split-array-into-three-subarrays.js b/solutions/1712-ways-to-split-array-into-three-subarrays.js deleted file mode 100644 index d6eaf44c..00000000 --- a/solutions/1712-ways-to-split-array-into-three-subarrays.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * 1712. Ways to Split Array Into Three Subarrays - * https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/ - * Difficulty: Medium - * - * A split of an integer array is good if: - * - The array is split into three non-empty contiguous subarrays - named left, mid, right - * respectively from left to right. - * - The sum of the elements in left is less than or equal to the sum of the elements in mid, - * and the sum of the elements in mid is less than or equal to the sum of the elements in right. - * - * Given nums, an array of non-negative integers, return the number of good ways to split nums. - * As the number may be too large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var waysToSplit = function(nums) { - const MOD = 1e9 + 7; - const n = nums.length; - const prefixSum = new Array(n).fill(0); - - prefixSum[0] = nums[0]; - for (let i = 1; i < n; i++) { - prefixSum[i] = prefixSum[i - 1] + nums[i]; - } - - let splitCount = 0; - for (let i = 0; i < n - 2; i++) { - let left = i + 1; - let right = n - 2; - let validStart = -1; - let validEnd = -1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const leftSum = prefixSum[i]; - const midSum = prefixSum[mid] - prefixSum[i]; - const rightSum = prefixSum[n - 1] - prefixSum[mid]; - - if (leftSum <= midSum && midSum <= rightSum) { - validStart = mid; - right = mid - 1; - } else if (leftSum > midSum) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - left = validStart === -1 ? n - 1 : validStart; - right = n - 2; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const leftSum = prefixSum[i]; - const midSum = prefixSum[mid] - prefixSum[i]; - const rightSum = prefixSum[n - 1] - prefixSum[mid]; - - if (leftSum <= midSum && midSum <= rightSum) { - validEnd = mid; - left = mid + 1; - } else { - right = mid - 1; - } - } - - if (validStart !== -1 && validEnd !== -1 && validStart <= validEnd) { - splitCount = (splitCount + validEnd - validStart + 1) % MOD; - } - } - - return splitCount; -}; diff --git a/solutions/1713-minimum-operations-to-make-a-subsequence.js b/solutions/1713-minimum-operations-to-make-a-subsequence.js deleted file mode 100644 index 245e0eac..00000000 --- a/solutions/1713-minimum-operations-to-make-a-subsequence.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1713. Minimum Operations to Make a Subsequence - * https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ - * Difficulty: Hard - * - * You are given an array target that consists of distinct integers and another integer array - * arr that can have duplicates. - * - * In one operation, you can insert any integer at any position in arr. For example, if - * arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can - * insert the integer at the very beginning or end of the array. - * - * Return the minimum number of operations needed to make target a subsequence of arr. - * - * A subsequence of an array is a new array generated from the original array by deleting some - * elements (possibly none) without changing the remaining elements' relative order. For - * example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), - * while [2,4,2] is not. - */ - -/** - * @param {number[]} target - * @param {number[]} arr - * @return {number} - */ -var minOperations = function(target, arr) { - const valueToIndex = new Map(target.map((val, i) => [val, i])); - const sequence = arr.filter(val => valueToIndex.has(val)).map(val => valueToIndex.get(val)); - - const lis = []; - for (const index of sequence) { - const pos = binarySearch(lis, index); - if (pos === lis.length) { - lis.push(index); - } else { - lis[pos] = index; - } - } - - return target.length - lis.length; -}; - -function binarySearch(arr, target) { - let left = 0; - let right = arr.length; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (arr[mid] < target) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; -} diff --git a/solutions/1717-maximum-score-from-removing-substrings.js b/solutions/1717-maximum-score-from-removing-substrings.js deleted file mode 100644 index 75bae662..00000000 --- a/solutions/1717-maximum-score-from-removing-substrings.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 1717. Maximum Score From Removing Substrings - * https://leetcode.com/problems/maximum-score-from-removing-substrings/ - * Difficulty: Medium - * - * You are given a string s and two integers x and y. You can perform two types of operations - * any number of times. - * - * - Remove substring "ab" and gain x points. - * - For example, when removing "ab" from "cabxbae" it becomes "cxbae". - * - Remove substring "ba" and gain y points. - * - For example, when removing "ba" from "cabxbae" it becomes "cabxe". - * - * Return the maximum points you can gain after applying the above operations on s. - */ - -/** - * @param {string} s - * @param {number} x - * @param {number} y - * @return {number} - */ -var maximumGain = function(s, x, y) { - let result = 0; - const stack = []; - - const [primary, secondary, primaryScore, secondaryScore] = x >= y - ? ['ab', 'ba', x, y] - : ['ba', 'ab', y, x]; - - for (const char of s) { - if (stack.length && stack[stack.length - 1] === primary[0] && char === primary[1]) { - stack.pop(); - result += primaryScore; - } else { - stack.push(char); - } - } - - const remaining = []; - for (const char of stack) { - if (remaining.length && remaining[remaining.length - 1] === secondary[0] - && char === secondary[1]) { - remaining.pop(); - result += secondaryScore; - } else { - remaining.push(char); - } - } - - return result; -}; diff --git a/solutions/1719-number-of-ways-to-reconstruct-a-tree.js b/solutions/1719-number-of-ways-to-reconstruct-a-tree.js deleted file mode 100644 index 9e1347d4..00000000 --- a/solutions/1719-number-of-ways-to-reconstruct-a-tree.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * 1719. Number Of Ways To Reconstruct A Tree - * https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/ - * Difficulty: Hard - * - * You are given an array pairs, where pairs[i] = [xi, yi], and: - * - There are no duplicates. - * - xi < yi - * - * Let ways be the number of rooted trees that satisfy the following conditions: - * - The tree consists of nodes whose values appeared in pairs. - * - A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is - * an ancestor of xi. - * - Note: the tree does not have to be a binary tree. - * - * Two ways are considered to be different if there is at least one node that has different - * parents in both ways. - * - * Return: - * - 0 if ways == 0 - * - 1 if ways == 1 - * - 2 if ways > 1 - * - * A rooted tree is a tree that has a single root node, and all edges are oriented to be - * outgoing from the root. - * - * An ancestor of a node is any node on the path from the root to that node (excluding - * the node itself). The root has no ancestors. - */ - -/** - * @param {number[][]} pairs - * @return {number} - */ -var checkWays = function(pairs) { - const graph = new Map(); - for (const [x, y] of pairs) { - if (!graph.has(x)) graph.set(x, new Set()); - if (!graph.has(y)) graph.set(y, new Set()); - graph.get(x).add(y); - graph.get(y).add(x); - } - - const nodes = [...graph.keys()].sort((a, b) => graph.get(b).size - graph.get(a).size); - const n = nodes.length; - if (n === 1) return 1; - - const root = nodes[0]; - if (graph.get(root).size !== n - 1) return 0; - - let equalDegreeCount = 0; - for (let i = 1; i < n; i++) { - const node = nodes[i]; - let found = false; - - for (let j = i - 1; j >= 0; j--) { - const ancestor = nodes[j]; - if (graph.get(node).has(ancestor)) { - for (const neighbor of graph.get(node)) { - if (neighbor !== ancestor && !graph.get(ancestor).has(neighbor)) { - return 0; - } - } - if (graph.get(node).size === graph.get(ancestor).size) { - equalDegreeCount++; - } - found = true; - break; - } - } - - if (!found) return 0; - } - - return equalDegreeCount > 0 ? 2 : 1; -}; diff --git a/solutions/1720-decode-xored-array.js b/solutions/1720-decode-xored-array.js deleted file mode 100644 index 404073f1..00000000 --- a/solutions/1720-decode-xored-array.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1720. Decode XORed Array - * https://leetcode.com/problems/decode-xored-array/ - * Difficulty: Easy - * - * There is a hidden integer array arr that consists of n non-negative integers. - * - * It was encoded into another integer array encoded of length n - 1, such that - * encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. - * - * You are given the encoded array. You are also given an integer first, that is the first - * element of arr, i.e. arr[0]. - * - * Return the original array arr. It can be proved that the answer exists and is unique. - */ - -/** - * @param {number[]} encoded - * @param {number} first - * @return {number[]} - */ -var decode = function(encoded, first) { - const result = [first]; - - for (let i = 0; i < encoded.length; i++) { - result.push(result[i] ^ encoded[i]); - } - - return result; -}; diff --git a/solutions/1721-swapping-nodes-in-a-linked-list.js b/solutions/1721-swapping-nodes-in-a-linked-list.js deleted file mode 100644 index 4ec44bd7..00000000 --- a/solutions/1721-swapping-nodes-in-a-linked-list.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1721. Swapping Nodes in a Linked List - * https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ - * Difficulty: Medium - * - * You are given the head of a linked list, and an integer k. - * - * Return the head of the linked list after swapping the values of the kth node from the beginning - * and the kth node from the end (the list is 1-indexed). - */ - -/** - * 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 swapNodes = function(head, k) { - let firstNode = head; - for (let i = 1; i < k; i++) { - firstNode = firstNode.next; - } - - let slow = head; - let secondNode = firstNode.next; - while (secondNode) { - slow = slow.next; - secondNode = secondNode.next; - } - - const temp = firstNode.val; - firstNode.val = slow.val; - slow.val = temp; - - return head; -}; diff --git a/solutions/1722-minimize-hamming-distance-after-swap-operations.js b/solutions/1722-minimize-hamming-distance-after-swap-operations.js deleted file mode 100644 index 9abe3150..00000000 --- a/solutions/1722-minimize-hamming-distance-after-swap-operations.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1722. Minimize Hamming Distance After Swap Operations - * https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/ - * Difficulty: Medium - * - * You are given two integer arrays, source and target, both of length n. You are also given an - * array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to - * swap the elements at index ai and index bi (0-indexed) of array source. Note that you can - * swap elements at a specific pair of indices multiple times and in any order. - * - * The Hamming distance of two arrays of the same length, source and target, is the number of - * positions where the elements are different. Formally, it is the number of indices i for - * 0 <= i <= n-1 where source[i] != target[i] (0-indexed). - * - * Return the minimum Hamming distance of source and target after performing any amount of swap - * operations on array source. - */ - -/** - * @param {number[]} source - * @param {number[]} target - * @param {number[][]} allowedSwaps - * @return {number} - */ -var minimumHammingDistance = function(source, target, allowedSwaps) { - const n = source.length; - const parent = new Array(n).fill().map((_, i) => i); - - for (const [a, b] of allowedSwaps) { - union(a, b); - } - - const groups = new Map(); - for (let i = 0; i < n; i++) { - const root = find(i); - if (!groups.has(root)) { - groups.set(root, { source: [], target: [] }); - } - groups.get(root).source.push(source[i]); - groups.get(root).target.push(target[i]); - } - - let result = 0; - for (const { source, target } of groups.values()) { - const sourceCount = new Map(); - for (const num of source) { - sourceCount.set(num, (sourceCount.get(num) || 0) + 1); - } - for (const num of target) { - const count = sourceCount.get(num) || 0; - if (count === 0) { - result++; - } else { - sourceCount.set(num, count - 1); - } - } - } - - return result; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - parent[find(x)] = find(y); - } -}; diff --git a/solutions/1723-find-minimum-time-to-finish-all-jobs.js b/solutions/1723-find-minimum-time-to-finish-all-jobs.js deleted file mode 100644 index c5624ffb..00000000 --- a/solutions/1723-find-minimum-time-to-finish-all-jobs.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1723. Find Minimum Time to Finish All Jobs - * https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/ - * Difficulty: Hard - * - * You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete - * the ith job. - * - * There are k workers that you can assign jobs to. Each job should be assigned to exactly one - * worker. The working time of a worker is the sum of the time it takes to complete all jobs - * assigned to them. Your goal is to devise an optimal assignment such that the maximum working - * time of any worker is minimized. - * - * Return the minimum possible maximum working time of any assignment. - */ - -/** - * @param {number[]} jobs - * @param {number} k - * @return {number} - */ -var minimumTimeRequired = function(jobs, k) { - const n = jobs.length; - const workerTimes = new Array(k).fill(0); - let result = Infinity; - - jobs.sort((a, b) => b - a); - backtrack(0, 0); - - return result; - - function backtrack(jobIndex, maxTime) { - if (jobIndex === n) { - result = Math.min(result, maxTime); - return; - } - - if (maxTime >= result) return; - - for (let i = 0; i < k; i++) { - if (workerTimes[i] + jobs[jobIndex] >= result) continue; - - workerTimes[i] += jobs[jobIndex]; - backtrack(jobIndex + 1, Math.max(maxTime, workerTimes[i])); - workerTimes[i] -= jobs[jobIndex]; - - if (workerTimes[i] === 0) break; - } - } -}; diff --git a/solutions/1725-number-of-rectangles-that-can-form-the-largest-square.js b/solutions/1725-number-of-rectangles-that-can-form-the-largest-square.js deleted file mode 100644 index 63d92c44..00000000 --- a/solutions/1725-number-of-rectangles-that-can-form-the-largest-square.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1725. Number Of Rectangles That Can Form The Largest Square - * https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/ - * Difficulty: Easy - * - * You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle - * of length li and width wi. - * - * You can cut the ith rectangle to form a square with a side length of k if both k <= li and - * k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a - * side length of at most 4. - * - * Let maxLen be the side length of the largest square you can obtain from any of the given - * rectangles. - * - * Return the number of rectangles that can make a square with a side length of maxLen. - */ - -/** - * @param {number[][]} rectangles - * @return {number} - */ -var countGoodRectangles = function(rectangles) { - let maxSide = 0; - let result = 0; - - for (const [length, width] of rectangles) { - const side = Math.min(length, width); - if (side > maxSide) { - maxSide = side; - result = 1; - } else if (side === maxSide) { - result++; - } - } - - return result; -}; diff --git a/solutions/1727-largest-submatrix-with-rearrangements.js b/solutions/1727-largest-submatrix-with-rearrangements.js deleted file mode 100644 index 2c3e36db..00000000 --- a/solutions/1727-largest-submatrix-with-rearrangements.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1727. Largest Submatrix With Rearrangements - * https://leetcode.com/problems/largest-submatrix-with-rearrangements/ - * Difficulty: Medium - * - * You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the - * columns of the matrix in any order. - * - * Return the area of the largest submatrix within matrix where every element of the submatrix - * is 1 after reordering the columns optimally. - */ - -/** - * @param {number[][]} matrix - * @return {number} - */ -var largestSubmatrix = function(matrix) { - const rows = matrix.length; - const cols = matrix[0].length; - let result = 0; - - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - if (row > 0 && matrix[row][col] === 1) { - matrix[row][col] += matrix[row - 1][col]; - } - } - - const heights = matrix[row].slice().sort((a, b) => b - a); - for (let i = 0; i < cols; i++) { - if (heights[i] === 0) break; - result = Math.max(result, heights[i] * (i + 1)); - } - } - - return result; -}; diff --git a/solutions/1728-cat-and-mouse-ii.js b/solutions/1728-cat-and-mouse-ii.js deleted file mode 100644 index 32eecafa..00000000 --- a/solutions/1728-cat-and-mouse-ii.js +++ /dev/null @@ -1,107 +0,0 @@ -/** - * 1728. Cat and Mouse II - * https://leetcode.com/problems/cat-and-mouse-ii/ - * Difficulty: Hard - * - * A game is played by a cat and a mouse named Cat and Mouse. - * - * The environment is represented by a grid of size rows x cols, where each element is a wall, - * floor, player (Cat, Mouse), or food. - * - Players are represented by the characters 'C'(Cat),'M'(Mouse). - * - Floors are represented by the character '.' and can be walked on. - * - Walls are represented by the character '#' and cannot be walked on. - * - Food is represented by the character 'F' and can be walked on. - * - There is only one of each character 'C', 'M', and 'F' in grid. - * - * Mouse and Cat play according to the following rules: - * - Mouse moves first, then they take turns to move. - * - During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). - * They cannot jump over the wall nor outside of the grid. - * - catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. - * Cat and Mouse can jump less than the maximum length. - * - Staying in the same position is allowed. - * - Mouse can jump over Cat. - * - * The game can end in 4 ways: - * - If Cat occupies the same position as Mouse, Cat wins. - * - If Cat reaches the food first, Cat wins. - * - If Mouse reaches the food first, Mouse wins. - * - If Mouse cannot get to the food within 1000 turns, Cat wins. - * - * Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse - * can win the game if both Cat and Mouse play optimally, otherwise return false. - */ - -/** - * @param {string[]} grid - * @param {number} catJump - * @param {number} mouseJump - * @return {boolean} - */ -var canMouseWin = function(grid, catJump, mouseJump) { - if (typeof grid === 'string') grid = [grid]; - const rows = grid.length; - const cols = grid[0].length; - const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - let mouse; - let cat; - let food; - let available = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const cell = grid[i][j]; - if (cell !== '#') available++; - if (cell === 'M') mouse = [i, j]; - else if (cell === 'C') cat = [i, j]; - else if (cell === 'F') food = [i, j]; - } - } - - const memo = new Map(); - - return canWin(0, mouse, cat); - - function getKey(turn, [mr, mc], [cr, cc]) { - return `${turn},${mr},${mc},${cr},${cc}`; - } - - function isValid(r, c) { - return r >= 0 && r < rows && c >= 0 && c < cols && grid[r][c] !== '#'; - } - - function canWin(turn, mousePos, catPos) { - if (turn >= available * 2) return false; - - const key = getKey(turn, mousePos, catPos); - if (memo.has(key)) return memo.get(key); - - const isMouseTurn = turn % 2 === 0; - const [r, c] = isMouseTurn ? mousePos : catPos; - const maxJump = isMouseTurn ? mouseJump : catJump; - - for (const [dr, dc] of dirs) { - for (let jump = 0; jump <= maxJump; jump++) { - const nr = r + dr * jump; - const nc = c + dc * jump; - if (!isValid(nr, nc)) break; - - if (isMouseTurn) { - if (grid[nr][nc] === 'F' || canWin(turn + 1, [nr, nc], catPos)) { - memo.set(key, true); - return true; - } - } else { - if (grid[nr][nc] === 'F' || (nr === mousePos[0] && nc === mousePos[1]) - || !canWin(turn + 1, mousePos, [nr, nc])) { - memo.set(key, false); - return false; - } - } - } - } - - memo.set(key, !isMouseTurn); - return !isMouseTurn; - } -}; diff --git a/solutions/1733-minimum-number-of-people-to-teach.js b/solutions/1733-minimum-number-of-people-to-teach.js deleted file mode 100644 index 9307f936..00000000 --- a/solutions/1733-minimum-number-of-people-to-teach.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1733. Minimum Number of People to Teach - * https://leetcode.com/problems/minimum-number-of-people-to-teach/ - * Difficulty: Medium - * - * On a social network consisting of m users and some friendships between users, two users can - * communicate with each other if they know a common language. - * - * You are given an integer n, an array languages, and an array friendships where: - * - There are n languages numbered 1 through n, - * - languages[i] is the set of languages the ith user knows, and - * - friendships[i] = [ui, vi] denotes a friendship between the users ui and vi. - * - * You can choose one language and teach it to some users so that all friends can communicate - * with each other. Return the minimum number of users you need to teach. - * - * Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of - * z, this doesn't guarantee that x is a friend of z. - */ - -/** - * @param {number} n - * @param {number[][]} languages - * @param {number[][]} friendships - * @return {number} - */ -var minimumTeachings = function(n, languages, friendships) { - const languageUsers = Array.from({ length: n + 1 }, () => new Set()); - const nonCommunicating = new Set(); - - for (let i = 0; i < languages.length; i++) { - for (const lang of languages[i]) { - languageUsers[lang].add(i + 1); - } - } - - for (const [u, v] of friendships) { - let canCommunicate = false; - for (const lang of languages[u - 1]) { - if (languages[v - 1].includes(lang)) { - canCommunicate = true; - break; - } - } - if (!canCommunicate) { - nonCommunicating.add(u); - nonCommunicating.add(v); - } - } - - let result = Infinity; - for (let lang = 1; lang <= n; lang++) { - let usersToTeach = 0; - for (const user of nonCommunicating) { - if (!languages[user - 1].includes(lang)) { - usersToTeach++; - } - } - result = Math.min(result, usersToTeach); - } - - return result; -}; diff --git a/solutions/1734-decode-xored-permutation.js b/solutions/1734-decode-xored-permutation.js deleted file mode 100644 index 72388a1a..00000000 --- a/solutions/1734-decode-xored-permutation.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1734. Decode XORed Permutation - * https://leetcode.com/problems/decode-xored-permutation/ - * Difficulty: Medium - * - * There is an integer array perm that is a permutation of the first n positive integers, - * where n is always odd. - * - * It was encoded into another integer array encoded of length n - 1, such that - * encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. - * - * Given the encoded array, return the original array perm. It is guaranteed that the answer - * exists and is unique. - */ - -/** - * @param {number[]} encoded - * @return {number[]} - */ -var decode = function(encoded) { - const n = encoded.length + 1; - let totalXor = 0; - for (let i = 1; i <= n; i++) { - totalXor ^= i; - } - - let oddXor = 0; - for (let i = 1; i < encoded.length; i += 2) { - oddXor ^= encoded[i]; - } - - const result = new Array(n); - result[0] = totalXor ^ oddXor; - - for (let i = 0; i < n - 1; i++) { - result[i + 1] = result[i] ^ encoded[i]; - } - - return result; -}; diff --git a/solutions/1735-count-ways-to-make-array-with-product.js b/solutions/1735-count-ways-to-make-array-with-product.js deleted file mode 100644 index 4fa45784..00000000 --- a/solutions/1735-count-ways-to-make-array-with-product.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * 1735. Count Ways to Make Array With Product - * https://leetcode.com/problems/count-ways-to-make-array-with-product/ - * Difficulty: Hard - * - * You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], - * find the number of different ways you can place positive integers into an array of size ni - * such that the product of the integers is ki. As the number of ways may be too large, the - * answer to the ith query is the number of ways modulo 109 + 7. - * - * Return an integer array answer where answer.length == queries.length, and answer[i] is the - * answer to the ith query. - */ - -/** - * @param {number[][]} queries - * @return {number[]} - */ -var waysToFillArray = function(queries) { - const MOD = 1000000007n; - const MAX_N = 20000; - const factorial = new Array(MAX_N + 1).fill(1n); - const inverse = new Array(MAX_N + 1).fill(1n); - - for (let i = 1; i <= MAX_N; i++) { - factorial[i] = (factorial[i - 1] * BigInt(i)) % MOD; - } - inverse[MAX_N] = BigInt(modInverse(Number(factorial[MAX_N] % MOD), Number(MOD))); - for (let i = MAX_N - 1; i >= 0; i--) { - inverse[i] = (inverse[i + 1] * BigInt(i + 1)) % MOD; - } - - const result = []; - for (const [size, product] of queries) { - if (product === 1) { - result.push(1); - continue; - } - const factors = getPrimeFactors(product); - let ways = 1n; - for (const count of factors.values()) { - const n = size + count - 1; - ways = (ways * BigInt(combinations(n, count))) % MOD; - } - result.push(Number(ways)); - } - - return result; - - function modInverse(a, m) { - const m0 = m; - let t; - let q; - let x0 = 0; - let x1 = 1; - while (a > 1) { - q = Math.floor(a / m); - t = m; - m = a % m; - a = t; - t = x0; - x0 = x1 - q * x0; - x1 = t; - } - return x1 < 0 ? x1 + m0 : x1; - } - - function combinations(n, k) { - if (k < 0 || k > n || n < 0 || n > MAX_N || n - k < 0) return 0; - const result = (factorial[n] * inverse[k] * inverse[n - k]) % MOD; - return Number(result); - } - - function getPrimeFactors(num) { - const factors = new Map(); - for (let i = 2; i * i <= num; i++) { - while (num % i === 0) { - factors.set(i, (factors.get(i) || 0) + 1); - num /= i; - } - } - if (num > 1) { - factors.set(num, (factors.get(num) || 0) + 1); - } - return factors; - } -}; diff --git a/solutions/1736-latest-time-by-replacing-hidden-digits.js b/solutions/1736-latest-time-by-replacing-hidden-digits.js deleted file mode 100644 index 23e72a76..00000000 --- a/solutions/1736-latest-time-by-replacing-hidden-digits.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1736. Latest Time by Replacing Hidden Digits - * https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/ - * Difficulty: Easy - * - * You are given a string time in the form of hh:mm, where some of the digits in the string - * are hidden (represented by ?). - * - * The valid times are those inclusively between 00:00 and 23:59. - * - * Return the latest valid time you can get from time by replacing the hidden digits. - */ - -/** - * @param {string} time - * @return {string} - */ -var maximumTime = function(time) { - const result = time.split(''); - - if (result[0] === '?') { - result[0] = result[1] === '?' || result[1] <= '3' ? '2' : '1'; - } - - if (result[1] === '?') { - result[1] = result[0] === '2' ? '3' : '9'; - } - - if (result[3] === '?') { - result[3] = '5'; - } - - if (result[4] === '?') { - result[4] = '9'; - } - - return result.join(''); -}; diff --git a/solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js b/solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js deleted file mode 100644 index 3a084982..00000000 --- a/solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1737. Change Minimum Characters to Satisfy One of Three Conditions - * https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/ - * Difficulty: Medium - * - * You are given two strings a and b that consist of lowercase letters. In one operation, you can - * change any character in a or b to any lowercase letter. - * - * Your goal is to satisfy one of the following three conditions: - * - Every letter in a is strictly less than every letter in b in the alphabet. - * - Every letter in b is strictly less than every letter in a in the alphabet. - * - Both a and b consist of only one distinct letter. - * - * Return the minimum number of operations needed to achieve your goal. - */ - -/** - * @param {string} a - * @param {string} b - * @return {number} - */ -var minCharacters = function(a, b) { - const aFreq = getFrequency(a); - const bFreq = getFrequency(b); - - const condition1 = operationsForCondition1(aFreq, bFreq); - const condition2 = operationsForCondition1(bFreq, aFreq); - const condition3 = operationsForCondition3(aFreq, bFreq); - - return Math.min(condition1, condition2, condition3); - - function getFrequency(str) { - const freq = Array(26).fill(0); - for (const char of str) { - freq[char.charCodeAt(0) - 97]++; - } - return freq; - } - - function operationsForCondition1(aFreq, bFreq) { - let minOps = Infinity; - for (let i = 0; i < 25; i++) { - let ops = 0; - for (let j = 0; j <= i; j++) ops += aFreq[j]; - for (let j = i + 1; j < 26; j++) ops += bFreq[j]; - minOps = Math.min(minOps, ops); - } - return minOps; - } - - function operationsForCondition3(aFreq, bFreq) { - let minOps = Infinity; - for (let i = 0; i < 26; i++) { - const ops = a.length + b.length - aFreq[i] - bFreq[i]; - minOps = Math.min(minOps, ops); - } - return minOps; - } -}; diff --git a/solutions/1738-find-kth-largest-xor-coordinate-value.js b/solutions/1738-find-kth-largest-xor-coordinate-value.js deleted file mode 100644 index 383d4166..00000000 --- a/solutions/1738-find-kth-largest-xor-coordinate-value.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1738. Find Kth Largest XOR Coordinate Value - * https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/ - * Difficulty: Medium - * - * You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also - * given an integer k. - * - * The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where - * 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). - * - * Find the kth largest value (1-indexed) of all the coordinates of matrix. - */ - -/** - * @param {number[][]} matrix - * @param {number} k - * @return {number} - */ -var kthLargestValue = function(matrix, k) { - const rows = matrix.length; - const cols = matrix[0].length; - const xorValues = new Array(rows * cols); - const prefixXor = Array.from({ length: rows + 1 }, () => Array(cols + 1).fill(0)); - - let index = 0; - for (let i = 1; i <= rows; i++) { - for (let j = 1; j <= cols; j++) { - prefixXor[i][j] = prefixXor[i-1][j] ^ prefixXor[i][j-1] - ^ prefixXor[i-1][j-1] ^ matrix[i-1][j-1]; - xorValues[index++] = prefixXor[i][j]; - } - } - - xorValues.sort((a, b) => b - a); - return xorValues[k-1]; -}; diff --git a/solutions/1739-building-boxes.js b/solutions/1739-building-boxes.js deleted file mode 100644 index 0a80282a..00000000 --- a/solutions/1739-building-boxes.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1739. Building Boxes - * https://leetcode.com/problems/building-boxes/ - * Difficulty: Hard - * - * You have a cubic storeroom where the width, length, and height of the room are all equal to n - * units. You are asked to place n boxes in this room where each box is a cube of unit side - * length. There are however some rules to placing the boxes: - * - You can place the boxes anywhere on the floor. - * - If box x is placed on top of the box y, then each side of the four vertical sides of the box - * y must either be adjacent to another box or to a wall. - * - * Given an integer n, return the minimum possible number of boxes touching the floor. - */ - -/** - * @param {number} n - * @return {number} - */ -var minimumBoxes = function(n) { - if (n < 4) return n; - - let baseSize = 0; - let totalBoxes = 0; - const triangular = k => k * (k + 1) / 2; - - while (totalBoxes + triangular(baseSize + 1) <= n) { - baseSize++; - totalBoxes += triangular(baseSize); - } - - const remaining = n - totalBoxes; - let extraFloor = 0; - - while (triangular(extraFloor) < remaining) extraFloor++; - - return triangular(baseSize) + extraFloor; -}; diff --git a/solutions/1742-maximum-number-of-balls-in-a-box.js b/solutions/1742-maximum-number-of-balls-in-a-box.js deleted file mode 100644 index e16d7ae5..00000000 --- a/solutions/1742-maximum-number-of-balls-in-a-box.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1742. Maximum Number of Balls in a Box - * https://leetcode.com/problems/maximum-number-of-balls-in-a-box/ - * Difficulty: Easy - * - * You are working in a ball factory where you have n balls numbered from lowLimit up to - * highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of - * boxes numbered from 1 to infinity. - * - * Your job at this factory is to put each ball in the box with a number equal to the sum - * of digits of the ball's number. For example, the ball number 321 will be put in the - * box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. - * - * Given two integers lowLimit and highLimit, return the number of balls in the box with - * the most balls. - */ - -/** - * @param {number} lowLimit - * @param {number} highLimit - * @return {number} - */ -var countBalls = function(lowLimit, highLimit) { - const boxCounts = new Map(); - let result = 0; - - for (let ball = lowLimit; ball <= highLimit; ball++) { - const box = sumDigits(ball); - const count = (boxCounts.get(box) || 0) + 1; - boxCounts.set(box, count); - result = Math.max(result, count); - } - - return result; - - function sumDigits(num) { - let sum = 0; - while (num > 0) { - sum += num % 10; - num = Math.floor(num / 10); - } - return sum; - } -}; diff --git a/solutions/1743-restore-the-array-from-adjacent-pairs.js b/solutions/1743-restore-the-array-from-adjacent-pairs.js deleted file mode 100644 index f7cdbb9f..00000000 --- a/solutions/1743-restore-the-array-from-adjacent-pairs.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1743. Restore the Array From Adjacent Pairs - * https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/ - * Difficulty: Medium - * - * There is an integer array nums that consists of n unique elements, but you have - * forgotten it. However, you do remember every pair of adjacent elements in nums. - * - * You are given a 2D integer array adjacentPairs of size n - 1 where each - * adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. - * - * It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in - * adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear - * in any order. - * - * Return the original array nums. If there are multiple solutions, return any of them. - */ - -/** - * @param {number[][]} adjacentPairs - * @return {number[]} - */ -var restoreArray = function(adjacentPairs) { - const graph = new Map(); - for (const [u, v] of adjacentPairs) { - graph.set(u, (graph.get(u) || []).concat(v)); - graph.set(v, (graph.get(v) || []).concat(u)); - } - - let start; - for (const [node, neighbors] of graph) { - if (neighbors.length === 1) { - start = node; - break; - } - } - - const result = [start]; - let prev = start; - let curr = graph.get(start)[0]; - - while (graph.get(curr).length > 1) { - result.push(curr); - const next = graph.get(curr).find(n => n !== prev); - prev = curr; - curr = next; - } - result.push(curr); - - return result; -}; diff --git a/solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js b/solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js deleted file mode 100644 index ac72e529..00000000 --- a/solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1744. Can You Eat Your Favorite Candy on Your Favorite Day? - * https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/ - * Difficulty: Medium - * - * You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] - * represents the number of candies of the ith type you have. You are also given a 2D array - * queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. - * - * You play a game with the following rules: - * - You start eating candies on day 0. - * - You cannot eat any candy of type i unless you have eaten all candies of type i - 1. - * - You must eat at least one candy per day until you have eaten all the candies. - * - * Construct a boolean array answer such that answer.length == queries.length and answer[i] is - * true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more - * than dailyCapi candies on any day, and false otherwise. Note that you can eat different - * types of candy on the same day, provided that you follow rule 2. - * - * Return the constructed array answer. - */ - -/** - * @param {number[]} candiesCount - * @param {number[][]} queries - * @return {boolean[]} - */ -var canEat = function(candiesCount, queries) { - const prefixSums = [0]; - for (const count of candiesCount) { - prefixSums.push(prefixSums.at(-1) + count); - } - - const result = new Array(queries.length); - for (let i = 0; i < queries.length; i++) { - const [type, day, cap] = queries[i]; - const minCandies = day; - const maxCandies = (day + 1) * cap; - const typeStart = prefixSums[type]; - const typeEnd = prefixSums[type + 1] - 1; - result[i] = maxCandies > typeStart && minCandies <= typeEnd; - } - - return result; -}; diff --git a/solutions/1745-palindrome-partitioning-iv.js b/solutions/1745-palindrome-partitioning-iv.js deleted file mode 100644 index 7fefea0f..00000000 --- a/solutions/1745-palindrome-partitioning-iv.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1745. Palindrome Partitioning IV - * https://leetcode.com/problems/palindrome-partitioning-iv/ - * Difficulty: Hard - * - * Given a string s, return true if it is possible to split the string s into three non-empty - * palindromic substrings. Otherwise, return false. - * - * A string is said to be palindrome if it the same string when reversed. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var checkPartitioning = function(s) { - const n = s.length; - const isPalindrome = Array.from({ length: n }, () => Array(n).fill(false)); - - for (let i = n - 1; i >= 0; i--) { - for (let j = i; j < n; j++) { - if (s[i] === s[j] && (j - i <= 2 || isPalindrome[i + 1][j - 1])) { - isPalindrome[i][j] = true; - } - } - } - - for (let i = 1; i < n - 1; i++) { - for (let j = i; j < n - 1; j++) { - if (isPalindrome[0][i - 1] && isPalindrome[i][j] && isPalindrome[j + 1][n - 1]) { - return true; - } - } - } - - return false; -}; diff --git a/solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js b/solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js deleted file mode 100644 index c8cdb813..00000000 --- a/solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1750. Minimum Length of String After Deleting Similar Ends - * https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/ - * Difficulty: Medium - * - * Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the - * following algorithm on the string any number of times: - * 1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal. - * 2. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. - * 3. The prefix and the suffix should not intersect at any index. - * 4. The characters from the prefix and suffix must be the same. - * 5. Delete both the prefix and the suffix. - * - * Return the minimum length of s after performing the above operation any number of times - * (possibly zero times). - */ - -/** - * @param {string} s - * @return {number} - */ -var minimumLength = function(s) { - let left = 0; - let right = s.length - 1; - - while (left < right && s[left] === s[right]) { - const char = s[left]; - while (left <= right && s[left] === char) left++; - while (left <= right && s[right] === char) right--; - } - - return Math.max(0, right - left + 1); -}; diff --git a/solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js b/solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js deleted file mode 100644 index 74cd6ee3..00000000 --- a/solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1751. Maximum Number of Events That Can Be Attended II - * https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/ - * Difficulty: Hard - * - * You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event - * starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value - * of valuei. You are also given an integer k which represents the maximum number of events you can - * attend. - * - * You can only attend one event at a time. If you choose to attend an event, you must attend the - * entire event. Note that the end day is inclusive: that is, you cannot attend two events where - * one of them starts and the other ends on the same day. - * - * Return the maximum sum of values that you can receive by attending events. - */ - -/** - * @param {number[][]} events - * @param {number} k - * @return {number} - */ -var maxValue = function(events, k) { - events.sort((a, b) => a[0] - b[0]); - const n = events.length; - const dp = Array.from({ length: k + 1 }, () => new Array(n + 1).fill(-1)); - - return maximize(0, k); - - function findNext(index, end) { - let left = index; - let right = n; - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (events[mid][0] > end) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } - - function maximize(index, remaining) { - if (index >= n || remaining === 0) return 0; - if (dp[remaining][index] !== -1) return dp[remaining][index]; - - const nextIndex = findNext(index + 1, events[index][1]); - const take = events[index][2] + maximize(nextIndex, remaining - 1); - const skip = maximize(index + 1, remaining); - - return dp[remaining][index] = Math.max(take, skip); - } -}; diff --git a/solutions/1753-maximum-score-from-removing-stones.js b/solutions/1753-maximum-score-from-removing-stones.js deleted file mode 100644 index 24dfa2f0..00000000 --- a/solutions/1753-maximum-score-from-removing-stones.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1753. Maximum Score From Removing Stones - * https://leetcode.com/problems/maximum-score-from-removing-stones/ - * Difficulty: Medium - * - * You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. - * Each turn you choose two different non-empty piles, take one stone from each, and add 1 point - * to your score. The game stops when there are fewer than two non-empty piles (meaning there are - * no more available moves). - * - * Given three integers a, b, and c return the maximum score you can get. - */ - -/** - * @param {number} a - * @param {number} b - * @param {number} c - * @return {number} - */ -var maximumScore = function(a, b, c) { - const piles = [a, b, c].sort((x, y) => y - x); - let score = 0; - - while (piles[0] > 0 && piles[1] > 0) { - piles[0]--; - piles[1]--; - score++; - piles.sort((x, y) => y - x); - } - - return score; -}; diff --git a/solutions/1754-largest-merge-of-two-strings.js b/solutions/1754-largest-merge-of-two-strings.js deleted file mode 100644 index 0ba08bd4..00000000 --- a/solutions/1754-largest-merge-of-two-strings.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1754. Largest Merge Of Two Strings - * https://leetcode.com/problems/largest-merge-of-two-strings/ - * Difficulty: Medium - * - * You are given two strings word1 and word2. You want to construct a string merge in the - * following way: while either word1 or word2 are non-empty, choose one of the following - * options: - * - If word1 is non-empty, append the first character in word1 to merge and delete it from word1. - * - For example, if word1 = "abc" and merge = "dv", then after choosing this operation, - * word1 = "bc" and merge = "dva". - * - If word2 is non-empty, append the first character in word2 to merge and delete it from word2. - * - For example, if word2 = "abc" and merge = "", then after choosing this operation, - * word2 = "bc" and merge = "a". - * - * Return the lexicographically largest merge you can construct. - * - * A string a is lexicographically larger than a string b (of the same length) if in the first - * position where a and b differ, a has a character strictly larger than the corresponding - * character in b. For example, "abcd" is lexicographically larger than "abcc" because the - * first position they differ is at the fourth character, and d is greater than c. - */ - -/** - * @param {string} word1 - * @param {string} word2 - * @return {string} - */ -var largestMerge = function(word1, word2) { - let merge = ''; - let i = 0; - let j = 0; - - while (i < word1.length && j < word2.length) { - if (word1.slice(i) >= word2.slice(j)) { - merge += word1[i++]; - } else { - merge += word2[j++]; - } - } - - merge += word1.slice(i) + word2.slice(j); - return merge; -}; diff --git a/solutions/1755-closest-subsequence-sum.js b/solutions/1755-closest-subsequence-sum.js deleted file mode 100644 index bad15f92..00000000 --- a/solutions/1755-closest-subsequence-sum.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1755. Closest Subsequence Sum - * https://leetcode.com/problems/closest-subsequence-sum/ - * Difficulty: Hard - * - * You are given an integer array nums and an integer goal. - * - * You want to choose a subsequence of nums such that the sum of its elements is the closest - * possible to goal. That is, if the sum of the subsequence's elements is sum, then you want - * to minimize the absolute difference abs(sum - goal). - * - * Return the minimum possible value of abs(sum - goal). - * - * Note that a subsequence of an array is an array formed by removing some elements (possibly - * all or none) of the original array. - */ - -/** - * @param {number[]} nums - * @param {number} goal - * @return {number} - */ -var minAbsDifference = function(nums, goal) { - const n = nums.length; - const half = Math.floor(n / 2); - const leftSums = new Set(); - const rightSums = new Set(); - - generateSums(0, half, leftSums); - generateSums(half, n, rightSums); - - const rightArray = [...rightSums].sort((a, b) => a - b); - let minDiff = Infinity; - - for (const leftSum of leftSums) { - const target = goal - leftSum; - let left = 0; - let right = rightArray.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const sum = leftSum + rightArray[mid]; - minDiff = Math.min(minDiff, Math.abs(sum - goal)); - - if (sum < goal) { - left = mid + 1; - } else { - right = mid - 1; - } - } - } - - return minDiff; - - function generateSums(start, end, sums, current = 0) { - if (start === end) { - sums.add(current); - return; - } - generateSums(start + 1, end, sums, current); - generateSums(start + 1, end, sums, current + nums[start]); - } -}; diff --git a/solutions/1758-minimum-changes-to-make-alternating-binary-string.js b/solutions/1758-minimum-changes-to-make-alternating-binary-string.js deleted file mode 100644 index dad5e376..00000000 --- a/solutions/1758-minimum-changes-to-make-alternating-binary-string.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1758. Minimum Changes To Make Alternating Binary String - * https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/ - * Difficulty: Easy - * - * You are given a string s consisting only of the characters '0' and '1'. In one operation, you can - * change any '0' to '1' or vice versa. - * - * The string is called alternating if no two adjacent characters are equal. For example, the string - * "010" is alternating, while the string "0100" is not. - * - * Return the minimum number of operations needed to make s alternating. - */ - -/** - * @param {string} s - * @return {number} - */ -var minOperations = function(s) { - let changesToZeroStart = 0; - let changesToOneStart = 0; - - for (let i = 0; i < s.length; i++) { - const expectedZeroStart = i % 2 === 0 ? '0' : '1'; - const expectedOneStart = i % 2 === 0 ? '1' : '0'; - if (s[i] !== expectedZeroStart) changesToZeroStart++; - if (s[i] !== expectedOneStart) changesToOneStart++; - } - - return Math.min(changesToZeroStart, changesToOneStart); -}; diff --git a/solutions/1759-count-number-of-homogenous-substrings.js b/solutions/1759-count-number-of-homogenous-substrings.js deleted file mode 100644 index b6fb8fbc..00000000 --- a/solutions/1759-count-number-of-homogenous-substrings.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1759. Count Number of Homogenous Substrings - * https://leetcode.com/problems/count-number-of-homogenous-substrings/ - * Difficulty: Medium - * - * Given a string s, return the number of homogenous substrings of s. Since the answer may be - * too large, return it modulo 109 + 7. - * - * A string is homogenous if all the characters of the string are the same. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} s - * @return {number} - */ -var countHomogenous = function(s) { - const mod = 1e9 + 7; - let result = 0; - let streak = 1; - - for (let i = 1; i < s.length; i++) { - if (s[i] === s[i - 1]) { - streak++; - } else { - result = (result + (streak * (streak + 1) / 2)) % mod; - streak = 1; - } - } - - result = (result + (streak * (streak + 1) / 2)) % mod; - - return result; -}; diff --git a/solutions/1760-minimum-limit-of-balls-in-a-bag.js b/solutions/1760-minimum-limit-of-balls-in-a-bag.js deleted file mode 100644 index f8ff3efa..00000000 --- a/solutions/1760-minimum-limit-of-balls-in-a-bag.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1760. Minimum Limit of Balls in a Bag - * https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/ - * Difficulty: Medium - * - * You are given an integer array nums where the ith bag contains nums[i] balls. You are also - * given an integer maxOperations. - * - * You can perform the following operation at most maxOperations times: - * - Take any bag of balls and divide it into two new bags with a positive number of balls. - * - For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags - * of 2 and 3 balls. - * - * Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after - * the operations. - * - * Return the minimum possible penalty after performing the operations. - */ - -/** - * @param {number[]} nums - * @param {number} maxOperations - * @return {number} - */ -var minimumSize = function(nums, maxOperations) { - let left = 1; - let right = Math.max(...nums); - - while (left < right) { - const mid = Math.floor((left + right) / 2); - let operations = 0; - - for (const num of nums) { - operations += Math.ceil(num / mid) - 1; - } - - if (operations <= maxOperations) { - right = mid; - } else { - left = mid + 1; - } - } - - return left; -}; diff --git a/solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js b/solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js deleted file mode 100644 index d913b953..00000000 --- a/solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1761. Minimum Degree of a Connected Trio in a Graph - * https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/ - * Difficulty: Hard - * - * You are given an undirected graph. You are given an integer n which is the number of nodes in - * the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an - * undirected edge between ui and vi. - * - * A connected trio is a set of three nodes where there is an edge between every pair of them. - * - * The degree of a connected trio is the number of edges where one endpoint is in the trio, and - * the other is not. - * - * Return the minimum degree of a connected trio in the graph, or -1 if the graph has no - * connected trios. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number} - */ -var minTrioDegree = function(n, edges) { - const graph = Array.from({ length: n + 1 }, () => new Set()); - const degrees = Array(n + 1).fill(0); - - for (const [u, v] of edges) { - graph[u].add(v); - graph[v].add(u); - degrees[u]++; - degrees[v]++; - } - - let minDegree = Infinity; - - for (let i = 1; i <= n; i++) { - for (const j of graph[i]) { - for (const k of graph[j]) { - if (graph[k].has(i)) { - const trioDegree = degrees[i] + degrees[j] + degrees[k] - 6; - minDegree = Math.min(minDegree, trioDegree); - } - } - } - } - - return minDegree === Infinity ? -1 : minDegree; -}; diff --git a/solutions/1763-longest-nice-substring.js b/solutions/1763-longest-nice-substring.js deleted file mode 100644 index 00495b99..00000000 --- a/solutions/1763-longest-nice-substring.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1763. Longest Nice Substring - * https://leetcode.com/problems/longest-nice-substring/ - * Difficulty: Easy - * - * A string s is nice if, for every letter of the alphabet that s contains, it appears both - * in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, - * and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. - * - * Given a string s, return the longest substring of s that is nice. If there are multiple, - * return the substring of the earliest occurrence. If there are none, return an empty string. - */ - -/** - * @param {string} s - * @return {string} - */ -var longestNiceSubstring = function(s) { - let longest = ''; - - for (let i = 0; i < s.length; i++) { - for (let j = i; j < s.length; j++) { - const substr = s.slice(i, j + 1); - if (substr.length <= longest.length) continue; - const chars = new Set(substr.toLowerCase().split('')); - let isNice = true; - for (const char of chars) { - if (!substr.includes(char.toLowerCase()) || !substr.includes(char.toUpperCase())) { - isNice = false; - break; - } - } - if (isNice) longest = substr; - } - } - - return longest; -}; diff --git a/solutions/1766-tree-of-coprimes.js b/solutions/1766-tree-of-coprimes.js deleted file mode 100644 index 31ec7f8d..00000000 --- a/solutions/1766-tree-of-coprimes.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * 1766. Tree of Coprimes - * https://leetcode.com/problems/tree-of-coprimes/ - * Difficulty: Hard - * - * There is 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. Each node has a value associated with it, - * and the root of the tree is node 0. - * - * To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] - * represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes - * uj and vj in the tree. - * - * Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor - * of x and y. - * - * An ancestor of a node i is any other node on the shortest path from node i to the root. A node - * is not considered an ancestor of itself. - * - * Return an array ans of size n, where ans[i] is the closest ancestor to node i such that - * nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor. - */ - -/** - * @param {number[]} nums - * @param {number[][]} edges - * @return {number[]} - */ -var getCoprimes = function(nums, edges) { - const n = nums.length; - const graph = Array.from({ length: n }, () => []); - for (const [u, v] of edges) { - graph[u].push(v); - graph[v].push(u); - } - - const result = Array(n).fill(-1); - const valueDepth = Array(51).fill().map(() => []); - const visited = new Set(); - - dfs(0, 0, -1); - return result; - - function dfs(node, depth, parent) { - const val = nums[node]; - let maxDepth = -1; - let closestAncestor = -1; - - for (let i = 1; i <= 50; i++) { - if (gcd(val, i) === 1 && valueDepth[i].length) { - const [ancestor, d] = valueDepth[i].at(-1); - if (d > maxDepth) { - maxDepth = d; - closestAncestor = ancestor; - } - } - } - - result[node] = closestAncestor; - valueDepth[val].push([node, depth]); - visited.add(node); - - for (const neighbor of graph[node]) { - if (!visited.has(neighbor)) { - dfs(neighbor, depth + 1, node); - } - } - - valueDepth[val].pop(); - } - - function gcd(a, b) { - while (b) [a, b] = [b, a % b]; - return a; - } -}; diff --git a/solutions/1770-maximum-score-from-performing-multiplication-operations.js b/solutions/1770-maximum-score-from-performing-multiplication-operations.js deleted file mode 100644 index 73ec2746..00000000 --- a/solutions/1770-maximum-score-from-performing-multiplication-operations.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1770. Maximum Score from Performing Multiplication Operations - * https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/ - * Difficulty: Hard - * - * You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, - * where n >= m. - * - * You begin with a score of 0. You want to perform exactly m operations. On the ith operation - * (0-indexed) you will: - * - Choose one integer x from either the start or the end of the array nums. - * - Add multipliers[i] * x to your score. - * - Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second - * operation, and so on. - * - Remove x from nums. - * - * Return the maximum score after performing m operations. - */ - -/** - * @param {number[]} nums - * @param {number[]} multipliers - * @return {number} - */ -var maximumScore = function(nums, multipliers) { - const m = multipliers.length; - const dp = Array.from({ length: m + 1 }, () => Array(m + 1).fill(0)); - - for (let op = m - 1; op >= 0; op--) { - for (let left = op; left >= 0; left--) { - const right = nums.length - 1 - (op - left); - const takeLeft = multipliers[op] * nums[left] + dp[op + 1][left + 1]; - const takeRight = multipliers[op] * nums[right] + dp[op + 1][left]; - dp[op][left] = Math.max(takeLeft, takeRight); - } - } - - return dp[0][0]; -}; diff --git a/solutions/1771-maximize-palindrome-length-from-subsequences.js b/solutions/1771-maximize-palindrome-length-from-subsequences.js deleted file mode 100644 index f24d48c9..00000000 --- a/solutions/1771-maximize-palindrome-length-from-subsequences.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1771. Maximize Palindrome Length From Subsequences - * https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/ - * Difficulty: Hard - * - * You are given two strings, word1 and word2. You want to construct a string in the following - * manner: - * - Choose some non-empty subsequence subsequence1 from word1. - * - Choose some non-empty subsequence subsequence2 from word2. - * - Concatenate the subsequences: subsequence1 + subsequence2, to make the string. - * - * Return the length of the longest palindrome that can be constructed in the described manner. - * If no palindromes can be constructed, return 0. - * - * A subsequence of a string s is a string that can be made by deleting some (possibly none) - * characters from s without changing the order of the remaining characters. - * - * A palindrome is a string that reads the same forward as well as backward. - */ - -/** - * @param {string} word1 - * @param {string} word2 - * @return {number} - */ -var longestPalindrome = function(word1, word2) { - const s = word1 + word2; - const n = s.length; - const dp = Array.from({ length: n }, () => Array(n).fill(0)); - let result = 0; - - for (let i = n - 1; i >= 0; i--) { - dp[i][i] = 1; - for (let j = i + 1; j < n; j++) { - if (s[i] === s[j]) { - dp[i][j] = dp[i + 1][j - 1] + 2; - if (i < word1.length && j >= word1.length) { - result = Math.max(result, dp[i][j]); - } - } else { - dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); - } - } - } - - return result; -}; diff --git a/solutions/1773-count-items-matching-a-rule.js b/solutions/1773-count-items-matching-a-rule.js deleted file mode 100644 index 528c7169..00000000 --- a/solutions/1773-count-items-matching-a-rule.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1773. Count Items Matching a Rule - * https://leetcode.com/problems/count-items-matching-a-rule/ - * Difficulty: Easy - * - * You are given an array items, where each items[i] = [typei, colori, namei] describes the type, - * color, and name of the ith item. You are also given a rule represented by two strings, - * ruleKey and ruleValue. - * - * The ith item is said to match the rule if one of the following is true: - * - ruleKey == "type" and ruleValue == typei. - * - ruleKey == "color" and ruleValue == colori. - * - ruleKey == "name" and ruleValue == namei. - * - * Return the number of items that match the given rule. - */ - -/** - * @param {string[][]} items - * @param {string} ruleKey - * @param {string} ruleValue - * @return {number} - */ -var countMatches = function(items, ruleKey, ruleValue) { - const keyIndex = { type: 0, color: 1, name: 2 }; - let result = 0; - - for (const item of items) { - if (item[keyIndex[ruleKey]] === ruleValue) { - result++; - } - } - - return result; -}; diff --git a/solutions/1774-closest-dessert-cost.js b/solutions/1774-closest-dessert-cost.js deleted file mode 100644 index 707d1812..00000000 --- a/solutions/1774-closest-dessert-cost.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1774. Closest Dessert Cost - * https://leetcode.com/problems/closest-dessert-cost/ - * Difficulty: Medium - * - * You would like to make dessert and are preparing to buy the ingredients. You have n ice - * cream base flavors and m types of toppings to choose from. You must follow these rules - * when making your dessert: - * - There must be exactly one ice cream base. - * - You can add one or more types of topping or have no toppings at all. - * - There are at most two of each type of topping. - * - * You are given three inputs: - * - baseCosts, an integer array of length n, where each baseCosts[i] represents the price of - * the ith ice cream base flavor. - * - toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of - * one of the ith topping. - * - target, an integer representing your target price for dessert. - * - * You want to make a dessert with a total cost as close to target as possible. - * - * Return the closest possible cost of the dessert to target. If there are multiple, return - * the lower one. - */ - -/** - * @param {number[]} baseCosts - * @param {number[]} toppingCosts - * @param {number} target - * @return {number} - */ -var closestCost = function(baseCosts, toppingCosts, target) { - let result = Infinity; - - for (const base of baseCosts) { - exploreToppings(0, base); - } - - return result; - - function exploreToppings(index, currentCost) { - const diff = Math.abs(currentCost - target); - const prevDiff = Math.abs(result - target); - - if (diff < prevDiff || (diff === prevDiff && currentCost < result)) { - result = currentCost; - } - - if (index >= toppingCosts.length || currentCost > target) return; - - exploreToppings(index + 1, currentCost); - exploreToppings(index + 1, currentCost + toppingCosts[index]); - exploreToppings(index + 1, currentCost + 2 * toppingCosts[index]); - } -}; diff --git a/solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js b/solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js deleted file mode 100644 index 8c2f068f..00000000 --- a/solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 1775. Equal Sum Arrays With Minimum Number of Operations - * https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/ - * Difficulty: Medium - * - * You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values - * in the arrays are between 1 and 6, inclusive. - * - * In one operation, you can change any integer's value in any of the arrays to any value between - * 1 and 6, inclusive. - * - * Return the minimum number of operations required to make the sum of values in nums1 equal to - * the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays - * equal. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var minOperations = function(nums1, nums2) { - let sum1 = nums1.reduce((a, b) => a + b, 0); - let sum2 = nums2.reduce((a, b) => a + b, 0); - - if (sum1 < sum2) { - [nums1, nums2, sum1, sum2] = [nums2, nums1, sum2, sum1]; - } - - const maxSum1 = nums1.length * 6; - const minSum1 = nums1.length; - const maxSum2 = nums2.length * 6; - const minSum2 = nums2.length; - - if (maxSum1 < minSum2 || maxSum2 < minSum1) return -1; - - let result = 0; - const gains = []; - const losses = []; - - for (const num of nums1) { - losses.push(num - 1); - } - for (const num of nums2) { - gains.push(6 - num); - } - - losses.sort((a, b) => b - a); - gains.sort((a, b) => b - a); - - let i = 0; - let j = 0; - let diff = sum1 - sum2; - - while (diff > 0 && (i < losses.length || j < gains.length)) { - const change = i < losses.length && (j >= gains.length || losses[i] >= gains[j]) - ? losses[i++] - : gains[j++]; - const take = Math.min(diff, change); - diff -= take; - result++; - } - - return result; -}; diff --git a/solutions/1776-car-fleet-ii.js b/solutions/1776-car-fleet-ii.js deleted file mode 100644 index 176303c5..00000000 --- a/solutions/1776-car-fleet-ii.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 1776. Car Fleet II - * https://leetcode.com/problems/car-fleet-ii/ - * Difficulty: Hard - * - * There are n cars traveling at different speeds in the same direction along a one-lane road. - * You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: - * - positioni is the distance between the ith car and the beginning of the road in meters. - * It is guaranteed that positioni < positioni+1. - * - speedi is the initial speed of the ith car in meters per second. - * - * For simplicity, cars can be considered as points moving along the number line. Two cars - * collide when they occupy the same position. Once a car collides with another car, they - * unite and form a single car fleet. The cars in the formed fleet will have the same position - * and the same speed, which is the initial speed of the slowest car in the fleet. - * - * Return an array answer, where answer[i] is the time, in seconds, at which the ith car - * collides with the next car, or -1 if the car does not collide with the next car. Answers - * within 10-5 of the actual answers are accepted. - */ - -/** - * @param {number[][]} cars - * @return {number[]} - */ -var getCollisionTimes = function(cars) { - const n = cars.length; - const stack = []; - const collisionTimes = Array(n).fill(-1); - - for (let i = n - 1; i >= 0; i--) { - const [pos, speed] = cars[i]; - - while (stack.length > 0) { - const j = stack[stack.length - 1]; - const [nextPos, nextSpeed] = cars[j]; - - if (speed <= nextSpeed || (collisionTimes[j] > 0 - && (nextPos - pos) / (speed - nextSpeed) >= collisionTimes[j])) { - stack.pop(); - } else { - break; - } - } - - if (stack.length > 0) { - const j = stack[stack.length - 1]; - const [nextPos, nextSpeed] = cars[j]; - collisionTimes[i] = (nextPos - pos) / (speed - nextSpeed); - } - - stack.push(i); - } - - return collisionTimes; -}; diff --git a/solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js b/solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js deleted file mode 100644 index faf1f1b2..00000000 --- a/solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1779. Find Nearest Point That Has the Same X or Y Coordinate - * https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/ - * Difficulty: Easy - * - * You are given two integers, x and y, which represent your current location on a Cartesian - * grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents - * that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the - * same y-coordinate as your location. - * - * Return the index (0-indexed) of the valid point with the smallest Manhattan distance from - * your current location. If there are multiple, return the valid point with the smallest index. - * If there are no valid points, return -1. - * - * The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2). - */ - -/** - * @param {number} x - * @param {number} y - * @param {number[][]} points - * @return {number} - */ -var nearestValidPoint = function(x, y, points) { - let minDistance = Infinity; - let result = -1; - - for (let i = 0; i < points.length; i++) { - const [px, py] = points[i]; - if (px === x || py === y) { - const distance = Math.abs(px - x) + Math.abs(py - y); - if (distance < minDistance) { - minDistance = distance; - result = i; - } - } - } - - return result; -}; diff --git a/solutions/1781-sum-of-beauty-of-all-substrings.js b/solutions/1781-sum-of-beauty-of-all-substrings.js deleted file mode 100644 index 6c561b33..00000000 --- a/solutions/1781-sum-of-beauty-of-all-substrings.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1781. Sum of Beauty of All Substrings - * https://leetcode.com/problems/sum-of-beauty-of-all-substrings/ - * Difficulty: Medium - * - * The beauty of a string is the difference in frequencies between the most frequent and - * least frequent characters. - * - For example, the beauty of "abaacc" is 3 - 1 = 2. - * - * Given a string s, return the sum of beauty of all of its substrings. - */ - -/** - * @param {string} s - * @return {number} - */ -var beautySum = function(s) { - let result = 0; - - for (let i = 0; i < s.length; i++) { - const freq = new Map(); - for (let j = i; j < s.length; j++) { - freq.set(s[j], (freq.get(s[j]) || 0) + 1); - let maxFreq = 0; - let minFreq = Infinity; - for (const count of freq.values()) { - maxFreq = Math.max(maxFreq, count); - minFreq = Math.min(minFreq, count); - } - result += maxFreq - minFreq; - } - } - - return result; -}; diff --git a/solutions/1782-count-pairs-of-nodes.js b/solutions/1782-count-pairs-of-nodes.js deleted file mode 100644 index d0e4f00c..00000000 --- a/solutions/1782-count-pairs-of-nodes.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * 1782. Count Pairs Of Nodes - * https://leetcode.com/problems/count-pairs-of-nodes/ - * Difficulty: Hard - * - * You are given an undirected graph defined by an integer n, the number of nodes, and a 2D - * integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there - * is an undirected edge between ui and vi. You are also given an integer array queries. - * - * Let incident(a, b) be defined as the number of edges that are connected to either node a or b. - * - * The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the - * following conditions: - * - a < b - * - incident(a, b) > queries[j] - * - * Return an array answers such that answers.length == queries.length and answers[j] is the - * answer of the jth query. - * - * Note that there can be multiple edges between the same two nodes. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @param {number[]} queries - * @return {number[]} - */ -var countPairs = function(n, edges, queries) { - const degrees = Array(n + 1).fill(0); - const edgeCounts = new Map(); - - for (const [u, v] of edges) { - degrees[u]++; - degrees[v]++; - const key = u < v ? `${u},${v}` : `${v},${u}`; - edgeCounts.set(key, (edgeCounts.get(key) || 0) + 1); - } - - const sortedDegrees = [...degrees].slice(1).sort((a, b) => a - b); - const result = Array(queries.length).fill(0); - - for (let q = 0; q < queries.length; q++) { - let total = 0; - let left = 0; - let right = n - 1; - - while (left < right) { - if (sortedDegrees[left] + sortedDegrees[right] > queries[q]) { - total += right - left; - right--; - } else { - left++; - } - } - - for (const [key, count] of edgeCounts) { - const [u, v] = key.split(',').map(Number); - if (degrees[u] + degrees[v] > queries[q] && degrees[u] + degrees[v] - count <= queries[q]) { - total--; - } - } - - result[q] = total; - } - - return result; -}; diff --git a/solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js b/solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js deleted file mode 100644 index 4f3e3fb9..00000000 --- a/solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 1784. Check if Binary String Has at Most One Segment of Ones - * https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/ - * Difficulty: Easy - * - * Given a binary string s without leading zeros, return true if s contains at most one - * contiguous segment of ones. Otherwise, return false. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var checkOnesSegment = function(s) { - let seenZero = false; - - for (let i = 1; i < s.length; i++) { - if (s[i] === '0') { - seenZero = true; - } else if (seenZero) { - return false; - } - } - - return true; -}; diff --git a/solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js b/solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js deleted file mode 100644 index 7b27b2c7..00000000 --- a/solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 1785. Minimum Elements to Add to Form a Given Sum - * https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/ - * Difficulty: Medium - * - * You are given an integer array nums and two integers limit and goal. The array nums has - * an interesting property that abs(nums[i]) <= limit. - * - * Return the minimum number of elements you need to add to make the sum of the array equal - * to goal. The array must maintain its property that abs(nums[i]) <= limit. - * - * Note that abs(x) equals x if x >= 0, and -x otherwise. - */ - -/** - * @param {number[]} nums - * @param {number} limit - * @param {number} goal - * @return {number} - */ -var minElements = function(nums, limit, goal) { - const currentSum = nums.reduce((sum, num) => sum + num, 0); - const difference = Math.abs(goal - currentSum); - return Math.ceil(difference / limit); -}; diff --git a/solutions/1786-number-of-restricted-paths-from-first-to-last-node.js b/solutions/1786-number-of-restricted-paths-from-first-to-last-node.js deleted file mode 100644 index e55ddab4..00000000 --- a/solutions/1786-number-of-restricted-paths-from-first-to-last-node.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * 1786. Number of Restricted Paths From First to Last Node - * https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/ - * Difficulty: Medium - * - * There is an undirected weighted connected graph. You are given a positive integer n which - * denotes that the graph has n nodes labeled from 1 to n, and an array edges where each - * edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with - * weight equal to weighti. - * - * A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that - * z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1. - * - * The distance of a path is the sum of the weights on the edges of the path. Let - * distanceToLastNode(x) denote the shortest distance of a path between node n and node x. - * A restricted path is a path that also satisfies that - * distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1. - * - * Return the number of restricted paths from node 1 to node n. Since that number may be too - * large, return it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @return {number} - */ -var countRestrictedPaths = function(n, edges) { - const MODULO = 1e9 + 7; - const graph = {}; - for (const [u, v, weight] of edges) { - (graph[u] ??= []).push({ edge: v, weight }); - (graph[v] ??= []).push({ edge: u, weight }); - } - - const distances = new Array(n + 1).fill(Number.MAX_SAFE_INTEGER); - distances[n] = 0; - - const NOT_VISITED = 0; - const VISITED = 1; - const IN_QUEUE = 2; - const states = new Array(n + 1).fill(NOT_VISITED); - const queue = [n]; - - while (queue.length) { - const node = queue.shift(); - states[node] = IN_QUEUE; - - for (const { edge, weight } of graph[node]) { - if (distances[node] + weight >= distances[edge]) continue; - - distances[edge] = distances[node] + weight; - - if (states[edge] === NOT_VISITED) { - queue.push(edge); - states[edge] = VISITED; - } else if (states[edge] === IN_QUEUE) { - queue.unshift(edge); - } - } - } - - const memo = new Map([[n, 1]]); - - return countPaths(1); - - function countPaths(node) { - if (memo.has(node)) return memo.get(node); - - let count = 0; - for (const { edge } of graph[node]) { - if (distances[edge] < distances[node]) { - count = (count + countPaths(edge)) % MODULO; - } - } - - memo.set(node, count); - return count; - } -}; diff --git a/solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js b/solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js deleted file mode 100644 index 7817c120..00000000 --- a/solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1787. Make the XOR of All Segments Equal to Zero - * https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/ - * Difficulty: Hard - * - * You are given an array nums and an integer k. The XOR of a segment [left, right] where - * left <= right is the XOR of all the elements with indices between left and right, - * inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. - * - * Return the minimum number of elements to change in the array such that the XOR of all - * segments of size k is equal to zero. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var minChanges = function(nums, k) { - const n = nums.length; - const maxVal = 1 << 10; - const groups = new Array(k).fill().map(() => new Map()); - - for (let i = 0; i < n; i++) { - groups[i % k].set(nums[i], (groups[i % k].get(nums[i]) || 0) + 1); - } - - const dp = new Array(maxVal).fill(n); - dp[0] = 0; - - for (let pos = 0; pos < k; pos++) { - const prevDp = [...dp]; - dp.fill(n); - const groupSize = Math.floor(n / k) + (pos < n % k ? 1 : 0); - const minPrev = Math.min(...prevDp); - - for (let xor = 0; xor < maxVal; xor++) { - if (prevDp[xor] === n) continue; - for (const [val, count] of groups[pos]) { - const newXor = xor ^ val; - dp[newXor] = Math.min(dp[newXor], prevDp[xor] + groupSize - count); - } - } - - for (let xor = 0; xor < maxVal; xor++) { - dp[xor] = Math.min(dp[xor], minPrev + groupSize); - } - } - - return dp[0]; -}; diff --git a/solutions/1792-maximum-average-pass-ratio.js b/solutions/1792-maximum-average-pass-ratio.js deleted file mode 100644 index 3ff9c5b3..00000000 --- a/solutions/1792-maximum-average-pass-ratio.js +++ /dev/null @@ -1,107 +0,0 @@ -/** - * 1792. Maximum Average Pass Ratio - * https://leetcode.com/problems/maximum-average-pass-ratio/ - * Difficulty: Medium - * - * There is a school that has classes of students and each class will be having a final exam. - * You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know - * beforehand that in the ith class, there are totali total students, but only passi number - * of students will pass the exam. - * - * You are also given an integer extraStudents. There are another extraStudents brilliant - * students that are guaranteed to pass the exam of any class they are assigned to. You want - * to assign each of the extraStudents students to a class in a way that maximizes the average - * pass ratio across all the classes. - * - * The pass ratio of a class is equal to the number of students of the class that will pass - * the exam divided by the total number of students of the class. The average pass ratio is - * the sum of pass ratios of all the classes divided by the number of the classes. - * - * Return the maximum possible average pass ratio after assigning the extraStudents students. - * Answers within 10-5 of the actual answer will be accepted. - */ - -/** -* @param {number[][]} classes -* @param {number} extraStudents -* @return {number} -*/ -var maxAverageRatio = function(classes, extraStudents) { - const maxHeap = []; - - for (const [pass, total] of classes) { - const profit = getProfit(pass, total); - maxHeap.push([profit, pass, total]); - } - - heapify(); - - for (let i = 0; i < extraStudents; i++) { - const [_, pass, total] = extractMax(); - const newPass = pass + 1; - const newTotal = total + 1; - const newProfit = getProfit(newPass, newTotal); - insert([newProfit, newPass, newTotal]); - } - - let sumRatio = 0; - for (const [_, pass, total] of maxHeap) { - sumRatio += pass / total; - } - - return sumRatio / classes.length; - - function getProfit(pass, total) { - return (pass + 1) / (total + 1) - pass / total; - } - - function heapify() { - for (let i = Math.floor(maxHeap.length / 2) - 1; i >= 0; i--) { - siftDown(i); - } - } - - function siftDown(i) { - const left = 2 * i + 1; - const right = 2 * i + 2; - let largest = i; - - if (left < maxHeap.length && maxHeap[left][0] > maxHeap[largest][0]) { - largest = left; - } - - if (right < maxHeap.length && maxHeap[right][0] > maxHeap[largest][0]) { - largest = right; - } - - if (largest !== i) { - [maxHeap[i], maxHeap[largest]] = [maxHeap[largest], maxHeap[i]]; - siftDown(largest); - } - } - - function extractMax() { - const max = maxHeap[0]; - const last = maxHeap.pop(); - - if (maxHeap.length > 0) { - maxHeap[0] = last; - siftDown(0); - } - - return max; - } - - function insert(item) { - maxHeap.push(item); - - let i = maxHeap.length - 1; - let parent = Math.floor((i - 1) / 2); - - while (i > 0 && maxHeap[i][0] > maxHeap[parent][0]) { - [maxHeap[i], maxHeap[parent]] = [maxHeap[parent], maxHeap[i]]; - i = parent; - parent = Math.floor((i - 1) / 2); - } - } -}; diff --git a/solutions/1793-maximum-score-of-a-good-subarray.js b/solutions/1793-maximum-score-of-a-good-subarray.js deleted file mode 100644 index 9a662c67..00000000 --- a/solutions/1793-maximum-score-of-a-good-subarray.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1793. Maximum Score of a Good Subarray - * https://leetcode.com/problems/maximum-score-of-a-good-subarray/ - * Difficulty: Hard - * - * You are given an array of integers nums (0-indexed) and an integer k. - * - * The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * - * (j - i + 1). A good subarray is a subarray where i <= k <= j. - * - * Return the maximum possible score of a good subarray. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maximumScore = function(nums, k) { - let result = nums[k]; - let minimum = nums[k]; - let left = k; - let right = k; - const length = nums.length; - - while (left > 0 || right < length - 1) { - const leftValue = left > 0 ? nums[left - 1] : 0; - const rightValue = right < length - 1 ? nums[right + 1] : 0; - - if (leftValue >= rightValue) { - left--; - minimum = Math.min(minimum, leftValue); - } else { - right++; - minimum = Math.min(minimum, rightValue); - } - - result = Math.max(result, minimum * (right - left + 1)); - } - - return result; -}; diff --git a/solutions/1796-second-largest-digit-in-a-string.js b/solutions/1796-second-largest-digit-in-a-string.js deleted file mode 100644 index 196ba422..00000000 --- a/solutions/1796-second-largest-digit-in-a-string.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1796. Second Largest Digit in a String - * https://leetcode.com/problems/second-largest-digit-in-a-string/ - * Difficulty: Easy - * - * Given an alphanumeric string s, return the second largest numerical digit that appears in - * s, or -1 if it does not exist. - * - * An alphanumeric string is a string consisting of lowercase English letters and digits. - */ - -/** - * @param {string} s - * @return {number} - */ -var secondHighest = function(s) { - let largest = -1; - let result = -1; - - for (const char of s) { - if (/\d/.test(char)) { - const digit = parseInt(char); - if (digit > largest) { - result = largest; - largest = digit; - } else if (digit < largest && digit > result) { - result = digit; - } - } - } - - return result; -}; diff --git a/solutions/1797-design-authentication-manager.js b/solutions/1797-design-authentication-manager.js deleted file mode 100644 index e631c416..00000000 --- a/solutions/1797-design-authentication-manager.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * 1797. Design Authentication Manager - * https://leetcode.com/problems/design-authentication-manager/ - * Difficulty: Medium - * - * There is an authentication system that works with authentication tokens. For each session, - * the user will receive a new authentication token that will expire timeToLive seconds after - * the currentTime. If the token is renewed, the expiry time will be extended to expire - * timeToLive seconds after the (potentially different) currentTime. - * - * Implement the AuthenticationManager class: - * - AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the - * timeToLive. - * - generate(string tokenId, int currentTime) generates a new token with the given tokenId - * at the given currentTime in seconds. - * - renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId - * at the given currentTime in seconds. If there are no unexpired tokens with the given - * tokenId, the request is ignored, and nothing happens. - * - countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the - * given currentTime. - * - * Note that if a token expires at time t, and another action happens on time t (renew or - * countUnexpiredTokens), the expiration takes place before the other actions. - */ - -/** - * @param {number} timeToLive - */ -var AuthenticationManager = function(timeToLive) { - this.timeToLive = timeToLive; - this.tokens = new Map(); -}; - -/** - * @param {string} tokenId - * @param {number} currentTime - * @return {void} - */ -AuthenticationManager.prototype.generate = function(tokenId, currentTime) { - this.tokens.set(tokenId, currentTime + this.timeToLive); -}; - -/** - * @param {string} tokenId - * @param {number} currentTime - * @return {void} - */ -AuthenticationManager.prototype.renew = function(tokenId, currentTime) { - if (this.tokens.has(tokenId) && this.tokens.get(tokenId) > currentTime) { - this.tokens.set(tokenId, currentTime + this.timeToLive); - } -}; - -/** - * @param {number} currentTime - * @return {number} - */ -AuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) { - let count = 0; - for (const [tokenId, expiry] of this.tokens) { - if (expiry > currentTime) { - count++; - } else { - this.tokens.delete(tokenId); - } - } - return count; -}; diff --git a/solutions/1798-maximum-number-of-consecutive-values-you-can-make.js b/solutions/1798-maximum-number-of-consecutive-values-you-can-make.js deleted file mode 100644 index 0c91d2de..00000000 --- a/solutions/1798-maximum-number-of-consecutive-values-you-can-make.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1798. Maximum Number of Consecutive Values You Can Make - * https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/ - * Difficulty: Medium - * - * You are given an integer array coins of length n which represents the n coins that you - * own. The value of the ith coin is coins[i]. You can make some value x if you can choose - * some of your n coins such that their values sum up to x. - * - * Return the maximum number of consecutive integer values that you can make with your coins - * starting from and including 0. - * - * Note that you may have multiple coins of the same value. - */ - -/** - * @param {number[]} coins - * @return {number} - */ -var getMaximumConsecutive = function(coins) { - let maxReachable = 0; - - coins.sort((a, b) => a - b); - for (const coin of coins) { - if (coin > maxReachable + 1) break; - maxReachable += coin; - } - - return maxReachable + 1; -}; diff --git a/solutions/1799-maximize-score-after-n-operations.js b/solutions/1799-maximize-score-after-n-operations.js deleted file mode 100644 index eb7a2e3b..00000000 --- a/solutions/1799-maximize-score-after-n-operations.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1799. Maximize Score After N Operations - * https://leetcode.com/problems/maximize-score-after-n-operations/ - * Difficulty: Hard - * - * You are given nums, an array of positive integers of size 2 * n. You must perform n operations - * on this array. - * - * In the ith operation (1-indexed), you will: - * - Choose two elements, x and y. - * - Receive a score of i * gcd(x, y). - * - Remove x and y from nums. - * - * Return the maximum score you can receive after performing n operations. - * - * The function gcd(x, y) is the greatest common divisor of x and y. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxScore = function(nums) { - const n = nums.length; - const pairsGcd = Array(n).fill().map(() => Array(n).fill(0)); - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - pairsGcd[i][j] = gcd(nums[i], nums[j]); - } - } - - return solve(1, 0, {}, pairsGcd); - - function gcd(a, b) { - while (b) { - a %= b; - [a, b] = [b, a]; - } - return a; - } - - function solve(operations, mask, memo, pairsGcd) { - if (operations > nums.length / 2) return 0; - if (memo[mask] !== undefined) return memo[mask]; - - let maxScore = 0; - for (let i = 0; i < nums.length; i++) { - if (mask & (1 << i)) continue; - for (let j = i + 1; j < nums.length; j++) { - if (mask & (1 << j)) continue; - const newMask = mask | (1 << i) | (1 << j); - const score = operations * pairsGcd[i][j] + solve(operations + 1, newMask, memo, pairsGcd); - maxScore = Math.max(maxScore, score); - } - } - - return memo[mask] = maxScore; - } -}; diff --git a/solutions/1801-number-of-orders-in-the-backlog.js b/solutions/1801-number-of-orders-in-the-backlog.js deleted file mode 100644 index 1c9501c0..00000000 --- a/solutions/1801-number-of-orders-in-the-backlog.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 1801. Number of Orders in the Backlog - * https://leetcode.com/problems/number-of-orders-in-the-backlog/ - * Difficulty: Medium - * - * You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] - * denotes that amounti orders have been placed of type orderTypei at the price pricei. - * The orderTypei is: - * - 0 if it is a batch of buy orders, or - * - 1 if it is a batch of sell orders. - * - * Note that orders[i] represents a batch of amounti independent orders with the same price and - * order type. All orders represented by orders[i] will be placed before all orders represented - * by orders[i+1] for all valid i. - * - * There is a backlog that consists of orders that have not been executed. The backlog is initially - * empty. When an order is placed, the following happens: - * - If the order is a buy order, you look at the sell order with the smallest price in the backlog. - * If that sell order's price is smaller than or equal to the current buy order's price, they will - * match and be executed, and that sell order will be removed from the backlog. Else, the buy - * order is added to the backlog. - * - Vice versa, if the order is a sell order, you look at the buy order with the largest price in - * the backlog. If that buy order's price is larger than or equal to the current sell order's - * price, they will match and be executed, and that buy order will be removed from the backlog. - * Else, the sell order is added to the backlog. - * - * Return the total amount of orders in the backlog after placing all the orders from the input. - * Since this number can be large, return it modulo 109 + 7. - */ - -/** - * @param {number[][]} orders - * @return {number} - */ -var getNumberOfBacklogOrders = function(orders) { - const MOD = 1e9 + 7; - const buyOrders = new MinPriorityQueue(); - const sellOrders = new MinPriorityQueue(); - - for (let [price, amount, type] of orders) { - if (type === 0) { - const order = { price: -price, amount, originalPrice: price, valueOf: () => -price }; - while (amount > 0 && !sellOrders.isEmpty() && sellOrders.front().price <= price) { - const sellOrder = sellOrders.dequeue(); - const matchAmount = Math.min(amount, sellOrder.amount); - amount -= matchAmount; - sellOrder.amount -= matchAmount; - if (sellOrder.amount > 0) sellOrders.enqueue(sellOrder); - } - if (amount > 0) buyOrders.enqueue({ ...order, amount }); - } else { - const order = { price, amount, valueOf: () => price }; - while (amount > 0 && !buyOrders.isEmpty() && buyOrders.front().originalPrice >= price) { - const buyOrder = buyOrders.dequeue(); - const matchAmount = Math.min(amount, buyOrder.amount); - amount -= matchAmount; - buyOrder.amount -= matchAmount; - if (buyOrder.amount > 0) buyOrders.enqueue(buyOrder); - } - if (amount > 0) sellOrders.enqueue({ ...order, amount }); - } - } - - let total = 0; - while (!buyOrders.isEmpty()) { - total = (total + buyOrders.dequeue().amount) % MOD; - } - while (!sellOrders.isEmpty()) { - total = (total + sellOrders.dequeue().amount) % MOD; - } - - return total; -}; diff --git a/solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js b/solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js deleted file mode 100644 index bc7fba1a..00000000 --- a/solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1802. Maximum Value at a Given Index in a Bounded Array - * https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/ - * Difficulty: Medium - * - * You are given three positive integers: n, index, and maxSum. You want to construct an array - * nums (0-indexed) that satisfies the following conditions: - * - nums.length == n - * - nums[i] is a positive integer where 0 <= i < n. - * - abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. - * - The sum of all the elements of nums does not exceed maxSum. - * - nums[index] is maximized. - * - * Return nums[index] of the constructed array. - * - * Note that abs(x) equals x if x >= 0, and -x otherwise. - */ - -/** - * @param {number} n - * @param {number} index - * @param {number} maxSum - * @return {number} - */ -var maxValue = function(n, index, maxSum) { - function minSumRequired(peak) { - const leftCount = Math.min(index, peak - 1); - const rightCount = Math.min(n - index - 1, peak - 1); - let sum = peak; - sum += (peak - 1 + peak - leftCount) * leftCount / 2; - sum += (peak - 1 + peak - rightCount) * rightCount / 2; - sum += (index - leftCount) + (n - index - 1 - rightCount); - return sum; - } - - let low = 1; - let high = maxSum; - let result = 1; - - while (low <= high) { - const mid = Math.floor((low + high) / 2); - if (minSumRequired(mid) <= maxSum) { - result = mid; - low = mid + 1; - } else { - high = mid - 1; - } - } - - return result; -}; diff --git a/solutions/1803-count-pairs-with-xor-in-a-range.js b/solutions/1803-count-pairs-with-xor-in-a-range.js deleted file mode 100644 index 1912bf08..00000000 --- a/solutions/1803-count-pairs-with-xor-in-a-range.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 1803. Count Pairs With XOR in a Range - * https://leetcode.com/problems/count-pairs-with-xor-in-a-range/ - * Difficulty: Hard - * - * Given a (0-indexed) integer array nums and two integers low and high, return the number - * of nice pairs. - * - * A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR - * nums[j]) <= high. - */ - -/** - * @param {number[]} nums - * @param {number} low - * @param {number} high - * @return {number} - */ -var countPairs = function(nums, low, high) { - const root = new TrieNode(); - let total = 0; - - for (const num of nums) { - total += countPairsInRange(num, high, root) - countPairsInRange(num, low - 1, root); - insert(num, root); - } - - return total; -}; - -class TrieNode { - constructor() { - this.children = [null, null]; - this.count = 0; - } -} - -function countPairsInRange(num, limit, root, depth = 14) { - let count = 0; - let node = root; - for (let i = depth; i >= 0 && node; i--) { - const numBit = (num >> i) & 1; - const limitBit = (limit >> i) & 1; - if (limitBit === 0) { - node = node.children[numBit]; - } else { - if (node.children[numBit]) { - count += node.children[numBit].count; - } - node = node.children[numBit ^ 1]; - } - } - return count + (node ? node.count : 0); -} - -function insert(num, root) { - let node = root; - for (let i = 14; i >= 0; i--) { - const bit = (num >> i) & 1; - if (!node.children[bit]) { - node.children[bit] = new TrieNode(); - } - node = node.children[bit]; - node.count++; - } -} - diff --git a/solutions/1805-number-of-different-integers-in-a-string.js b/solutions/1805-number-of-different-integers-in-a-string.js deleted file mode 100644 index 61b6f693..00000000 --- a/solutions/1805-number-of-different-integers-in-a-string.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1805. Number of Different Integers in a String - * https://leetcode.com/problems/number-of-different-integers-in-a-string/ - * Difficulty: Easy - * - * You are given a string word that consists of digits and lowercase English letters. - * - * You will replace every non-digit character with a space. For example, "a123bc34d8ef34" - * will become " 123 34 8 34". Notice that you are left with some integers that are - * separated by at least one space: "123", "34", "8", and "34". - * - * Return the number of different integers after performing the replacement operations on word. - * - * Two integers are considered different if their decimal representations without any leading - * zeros are different. - */ - -/** - * @param {string} word - * @return {number} - */ -var numDifferentIntegers = function(word) { - const uniqueIntegers = new Set(); - let currentNum = ''; - - for (const char of word) { - if (/\d/.test(char)) { - currentNum += char; - } else if (currentNum) { - uniqueIntegers.add(String(BigInt(currentNum))); - currentNum = ''; - } - } - - if (currentNum) { - uniqueIntegers.add(String(BigInt(currentNum))); - } - - return uniqueIntegers.size; -}; diff --git a/solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js b/solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js deleted file mode 100644 index 5ba88490..00000000 --- a/solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1806. Minimum Number of Operations to Reinitialize a Permutation - * https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/ - * Difficulty: Medium - * - * You are given an even integer n. You initially have a permutation perm of size n where - * perm[i] == i (0-indexed). - * - * In one operation, you will create a new array arr, and for each i: - * - If i % 2 == 0, then arr[i] = perm[i / 2]. - * - If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. - * - * You will then assign arr to perm. - * - * Return the minimum non-zero number of operations you need to perform on perm to return the - * permutation to its initial value. - */ - -/** - * @param {number} n - * @return {number} - */ -var reinitializePermutation = function(n) { - let currentIndex = 1; - let result = 0; - - do { - if (currentIndex % 2 === 0) { - currentIndex = currentIndex / 2; - } else { - currentIndex = n / 2 + (currentIndex - 1) / 2; - } - result++; - } while (currentIndex !== 1); - - return result; -}; diff --git a/solutions/1807-evaluate-the-bracket-pairs-of-a-string.js b/solutions/1807-evaluate-the-bracket-pairs-of-a-string.js deleted file mode 100644 index 7fffdc33..00000000 --- a/solutions/1807-evaluate-the-bracket-pairs-of-a-string.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1807. Evaluate the Bracket Pairs of a String - * https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/ - * Difficulty: Medium - * - * You are given a string s that contains some bracket pairs, with each pair containing - * a non-empty key. - * - * - For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain - * the keys "name" and "age". - * - * You know the values of a wide range of keys. This is represented by a 2D string array knowledge - * where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. - * - * You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that - * contains some key keyi, you will: - * - Replace keyi and the bracket pair with the key's corresponding valuei. - * - If you do not know the value of the key, you will replace keyi and the bracket pair with a - * question mark "?" (without the quotation marks). - * - * Each key will appear at most once in your knowledge. There will not be any nested brackets in s. - * - * Return the resulting string after evaluating all of the bracket pairs. - */ - -/** - * @param {string} s - * @param {string[][]} knowledge - * @return {string} - */ -var evaluate = function(s, knowledge) { - const keyValueMap = new Map(knowledge); - let result = ''; - let i = 0; - - while (i < s.length) { - if (s[i] === '(') { - i++; - let key = ''; - while (i < s.length && s[i] !== ')') { - key += s[i++]; - } - result += keyValueMap.get(key) || '?'; - i++; - } else { - result += s[i++]; - } - } - - return result; -}; diff --git a/solutions/1808-maximize-number-of-nice-divisors.js b/solutions/1808-maximize-number-of-nice-divisors.js deleted file mode 100644 index 49f3697a..00000000 --- a/solutions/1808-maximize-number-of-nice-divisors.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1808. Maximize Number of Nice Divisors - * https://leetcode.com/problems/maximize-number-of-nice-divisors/ - * Difficulty: Hard - * - * You are given a positive integer primeFactors. You are asked to construct a positive - * integer n that satisfies the following conditions: - * - The number of prime factors of n (not necessarily distinct) is at most primeFactors. - * - The number of nice divisors of n is maximized. Note that a divisor of n is nice if it - * is divisible by every prime factor of n. For example, if n = 12, then its prime factors - * are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not. - * - * Return the number of nice divisors of n. Since that number can be too large, return it - * modulo 109 + 7. - * - * Note that a prime number is a natural number greater than 1 that is not a product of two - * smaller natural numbers. The prime factors of a number n is a list of prime numbers such - * that their product equals n. - */ - -/** - * @param {number} primeFactors - * @return {number} - */ -var maxNiceDivisors = function(primeFactors) { - const MOD = 1e9 + 7; - - if (primeFactors <= 3) return primeFactors; - - const quotient = Math.floor(primeFactors / 3); - const remainder = primeFactors % 3; - - if (remainder === 0) return power(3, quotient); - if (remainder === 1) return (power(3, quotient - 1) * 4) % MOD; - - return (power(3, quotient) * 2) % MOD; - - function power(base, exponent) { - let result = BigInt(1); - base = BigInt(base); - while (exponent > 0) { - if (exponent & 1) result = (result * base) % BigInt(MOD); - base = (base * base) % BigInt(MOD); - exponent >>= 1; - } - return Number(result); - } -}; diff --git a/solutions/1813-sentence-similarity-iii.js b/solutions/1813-sentence-similarity-iii.js deleted file mode 100644 index 872cea74..00000000 --- a/solutions/1813-sentence-similarity-iii.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1813. Sentence Similarity III - * https://leetcode.com/problems/sentence-similarity-iii/ - * Difficulty: Medium - * - * You are given two strings sentence1 and sentence2, each representing a sentence composed of - * words. A sentence is a list of words that are separated by a single space with no leading - * or trailing spaces. Each word consists of only uppercase and lowercase English characters. - * - * Two sentences s1 and s2 are considered similar if it is possible to insert an arbitrary - * sentence (possibly empty) inside one of these sentences such that the two sentences become - * equal. Note that the inserted sentence must be separated from existing words by spaces. - * - * For example: - * - s1 = "Hello Jane" and s2 = "Hello my name is Jane" can be made equal by inserting "my name is" - * between "Hello" and "Jane" in s1. - * - s1 = "Frog cool" and s2 = "Frogs are cool" are not similar, since although there is a sentence - * "s are" inserted into s1, it is not separated from "Frog" by a space. - * - * Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are - * similar. Otherwise, return false. - */ - -/** - * @param {string} sentence1 - * @param {string} sentence2 - * @return {boolean} - */ -var areSentencesSimilar = function(sentence1, sentence2) { - let words1 = sentence1.split(' '); - let words2 = sentence2.split(' '); - if (words1.length < words2.length) [words1, words2] = [words2, words1]; - - let prefixLength = 0; - while (prefixLength < words2.length && words1[prefixLength] === words2[prefixLength]) { - prefixLength++; - } - - let suffixLength = 0; - while (suffixLength < words2.length - prefixLength - && words1[words1.length - 1 - suffixLength] === words2[words2.length - 1 - suffixLength]) { - suffixLength++; - } - - return prefixLength + suffixLength >= words2.length; -}; diff --git a/solutions/1814-count-nice-pairs-in-an-array.js b/solutions/1814-count-nice-pairs-in-an-array.js deleted file mode 100644 index f8db6cc5..00000000 --- a/solutions/1814-count-nice-pairs-in-an-array.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1814. Count Nice Pairs in an Array - * https://leetcode.com/problems/count-nice-pairs-in-an-array/ - * Difficulty: Medium - * - * You are given an array nums that consists of non-negative integers. Let us define rev(x) - * as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. - * A pair of indices (i, j) is nice if it satisfies all of the following conditions: - * - 0 <= i < j < nums.length - * - nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) - * - * Return the number of nice pairs of indices. Since that number can be too large, return it - * modulo 109 + 7. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var countNicePairs = function(nums) { - const MOD = 1e9 + 7; - const map = new Map(); - let result = 0; - - for (const num of nums) { - const diff = num - reverseNumber(num); - const count = map.get(diff) || 0; - result = (result + count) % MOD; - map.set(diff, count + 1); - } - - return result; - - function reverseNumber(num) { - return Number(String(num).split('').reverse().join('')); - } -}; diff --git a/solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js b/solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js deleted file mode 100644 index fcd73dc8..00000000 --- a/solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1815. Maximum Number of Groups Getting Fresh Donuts - * https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/ - * Difficulty: Hard - * - * There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they - * must serve all of the donuts of a batch before serving any donuts of the next batch. You are - * given an integer batchSize and an integer array groups, where groups[i] denotes that there is - * a group of groups[i] customers that will visit the shop. Each customer will get exactly one - * donut. - * - * When a group visits the shop, all customers of the group must be served before serving any - * of the following groups. A group will be happy if they all get fresh donuts. That is, the - * first customer of the group does not receive a donut that was left over from the previous group. - * - * You can freely rearrange the ordering of the groups. Return the maximum possible number of - * happy groups after rearranging the groups. - */ - -/** - * @param {number} batchSize - * @param {number[]} groups - * @return {number} - */ -var maxHappyGroups = function(batchSize, groups) { - const remainders = new Array(batchSize).fill(0); - let result = 0; - - for (const size of groups) { - remainders[size % batchSize]++; - } - - result += remainders[0]; - remainders[0] = 0; - - return result + findMaxHappy(remainders, 0); - - function findMaxHappy(remainders, leftover, memo = new Map()) { - const key = remainders.join(',') + ',' + leftover; - if (memo.has(key)) return memo.get(key); - - let maxHappy = 0; - for (let i = 1; i < batchSize; i++) { - if (remainders[i] === 0) continue; - remainders[i]--; - - let current = 0; - if (leftover === 0) current = 1; - maxHappy = Math.max( - maxHappy, current + findMaxHappy(remainders, (leftover + i) % batchSize, memo) - ); - - remainders[i]++; - } - - memo.set(key, maxHappy); - return maxHappy; - } -}; diff --git a/solutions/1816-truncate-sentence.js b/solutions/1816-truncate-sentence.js deleted file mode 100644 index d0d91e32..00000000 --- a/solutions/1816-truncate-sentence.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * 1816. Truncate Sentence - * https://leetcode.com/problems/truncate-sentence/ - * Difficulty: Easy - * - * A sentence is a list of words that are separated by a single space with no leading or - * trailing spaces. Each of the words consists of only uppercase and lowercase English - * letters (no punctuation). - * - For example, "Hello World", "HELLO", and "hello world hello world" are all sentences. - * - * You are given a sentence s and an integer k. You want to truncate s such that it contains - * only the first k words. Return s after truncating it. - */ - -/** - * @param {string} s - * @param {number} k - * @return {string} - */ -var truncateSentence = function(s, k) { - return s.split(' ').slice(0, k).join(' '); -}; diff --git a/solutions/1818-minimum-absolute-sum-difference.js b/solutions/1818-minimum-absolute-sum-difference.js deleted file mode 100644 index fb1cc1dc..00000000 --- a/solutions/1818-minimum-absolute-sum-difference.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1818. Minimum Absolute Sum Difference - * https://leetcode.com/problems/minimum-absolute-sum-difference/ - * Difficulty: Medium - * - * You are given two positive integer arrays nums1 and nums2, both of length n. - * - * The absolute sum difference of arrays nums1 and nums2 is defined as the sum of - * |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). - * - * You can replace at most one element of nums1 with any other element in nums1 to minimize - * the absolute sum difference. - * - * Return the minimum absolute sum difference after replacing at most one element in the - * array nums1. Since the answer may be large, return it modulo 109 + 7. - * - * |x| is defined as: - * - x if x >= 0, or - * - -x if x < 0. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var minAbsoluteSumDiff = function(nums1, nums2) { - const MOD = 1e9 + 7; - const sortedNums1 = [...nums1].sort((a, b) => a - b); - let totalDiff = 0; - let maxReduction = 0; - - for (let i = 0; i < nums1.length; i++) { - const currentDiff = Math.abs(nums1[i] - nums2[i]); - totalDiff = (totalDiff + currentDiff) % MOD; - - let left = 0; - let right = nums1.length - 1; - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const newDiff = Math.abs(sortedNums1[mid] - nums2[i]); - const reduction = currentDiff - newDiff; - maxReduction = Math.max(maxReduction, reduction); - - if (sortedNums1[mid] < nums2[i]) left = mid + 1; - else right = mid - 1; - } - } - - return (totalDiff - maxReduction + MOD) % MOD; -}; diff --git a/solutions/1819-number-of-different-subsequences-gcds.js b/solutions/1819-number-of-different-subsequences-gcds.js deleted file mode 100644 index 04842fef..00000000 --- a/solutions/1819-number-of-different-subsequences-gcds.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 1819. Number of Different Subsequences GCDs - * https://leetcode.com/problems/number-of-different-subsequences-gcds/ - * Difficulty: Hard - * - * You are given an array nums that consists of positive integers. - * - * The GCD of a sequence of numbers is defined as the greatest integer that divides all the - * numbers in the sequence evenly. - * - For example, the GCD of the sequence [4,6,16] is 2. - * - * A subsequence of an array is a sequence that can be formed by removing some elements (possibly - * none) of the array. - * - For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. - * - * Return the number of different GCDs among all non-empty subsequences of nums. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var countDifferentSubsequenceGCDs = function(nums) { - const maxNum = Math.max(...nums); - const exists = new Array(maxNum + 1).fill(false); - let result = 0; - - function gcd(a, b) { - while (b) [a, b] = [b, a % b]; - return a; - } - - for (const num of nums) { - exists[num] = true; - } - - for (let i = 1; i <= maxNum; i++) { - let currentGcd = 0; - for (let j = i; j <= maxNum; j += i) { - if (exists[j]) { - currentGcd = currentGcd ? gcd(currentGcd, j) : j; - } - } - if (currentGcd === i) result++; - } - - return result; -}; diff --git a/solutions/1822-sign-of-the-product-of-an-array.js b/solutions/1822-sign-of-the-product-of-an-array.js deleted file mode 100644 index f235ea51..00000000 --- a/solutions/1822-sign-of-the-product-of-an-array.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1822. Sign of the Product of an Array - * https://leetcode.com/problems/sign-of-the-product-of-an-array/ - * Difficulty: Easy - * - * Implement a function signFunc(x) that returns: - * - 1 if x is positive. - * - -1 if x is negative. - * - 0 if x is equal to 0. - * - * You are given an integer array nums. Let product be the product of all values in the array nums. - * - * Return signFunc(product). - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var arraySign = function(nums) { - let negativeCount = 0; - - for (const num of nums) { - if (num === 0) return 0; - if (num < 0) negativeCount++; - } - - return negativeCount % 2 === 0 ? 1 : -1; -}; diff --git a/solutions/1823-find-the-winner-of-the-circular-game.js b/solutions/1823-find-the-winner-of-the-circular-game.js deleted file mode 100644 index 3138d5bb..00000000 --- a/solutions/1823-find-the-winner-of-the-circular-game.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1823. Find the Winner of the Circular Game - * https://leetcode.com/problems/find-the-winner-of-the-circular-game/ - * Difficulty: Medium - * - * There are n friends that are playing a game. The friends are sitting in a circle and are - * numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith - * friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the - * nth friend brings you to the 1st friend. - * - * The rules of the game are as follows: - * 1. Start at the 1st friend. - * 2. Count the next k friends in the clockwise direction including the friend you started at. - * The counting wraps around the circle and may count some friends more than once. - * 3. The last friend you counted leaves the circle and loses the game. - * 4. If there is still more than one friend in the circle, go back to step 2 starting from the - * friend immediately clockwise of the friend who just lost and repeat. - * 5. Else, the last friend in the circle wins the game. - * - * Given the number of friends, n, and an integer k, return the winner of the game. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var findTheWinner = function(n, k) { - let winner = 0; - - for (let i = 1; i <= n; i++) { - winner = (winner + k) % i; - } - - return winner + 1; -}; diff --git a/solutions/1824-minimum-sideway-jumps.js b/solutions/1824-minimum-sideway-jumps.js deleted file mode 100644 index e4eb60d3..00000000 --- a/solutions/1824-minimum-sideway-jumps.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1824. Minimum Sideway Jumps - * https://leetcode.com/problems/minimum-sideway-jumps/ - * Difficulty: Medium - * - * There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog - * starts at point 0 in the second lane and wants to jump to point n. However, there could be - * obstacles along the way. - * - * You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) - * describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no - * obstacles at point i. There will be at most one obstacle in the 3 lanes at each point. - * - For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2. - * - * The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle - * on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump - * to another lane (even if they are not adjacent) at the same point if there is no obstacle on - * the new lane. - * - For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. - * - * Return the minimum number of side jumps the frog needs to reach any lane at point n starting - * from lane 2 at point 0. - * - * Note: There will be no obstacles on points 0 and n. - */ - -/** - * @param {number[]} obstacles - * @return {number} - */ -var minSideJumps = function(obstacles) { - const n = obstacles.length; - let dp = [1, 0, 1]; - - for (let i = 1; i < n; i++) { - const currentObstacle = obstacles[i]; - const nextDp = [Infinity, Infinity, Infinity]; - - for (let lane = 1; lane <= 3; lane++) { - if (lane === currentObstacle) continue; - - nextDp[lane - 1] = dp[lane - 1]; - - for (let fromLane = 1; fromLane <= 3; fromLane++) { - if (fromLane !== lane && fromLane !== currentObstacle) { - nextDp[lane - 1] = Math.min(nextDp[lane - 1], dp[fromLane - 1] + 1); - } - } - } - - dp = nextDp; - } - - return Math.min(...dp); -}; diff --git a/solutions/1825-finding-mk-average.js b/solutions/1825-finding-mk-average.js deleted file mode 100644 index ddc2b83e..00000000 --- a/solutions/1825-finding-mk-average.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * 1825. Finding MK Average - * https://leetcode.com/problems/finding-mk-average/ - * Difficulty: Hard - * - * You are given two integers, m and k, and a stream of integers. You are tasked to implement a data - * structure that calculates the MKAverage for the stream. - * - * The MKAverage can be calculated using these steps: - * - If the number of the elements in the stream is less than m you should consider the MKAverage to - * be -1. Otherwise, copy the last m elements of the stream to a separate container. - * - Remove the smallest k elements and the largest k elements from the container. - * - Calculate the average value for the rest of the elements rounded down to the nearest integer. - * - * Implement the MKAverage class: - * - MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two - * integers m and k. - * - void addElement(int num) Inserts a new element num into the stream. - * - int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded - * down to the nearest integer. - */ - -/** - * @param {number} m - * @param {number} k - */ -var MKAverage = function(m, k) { - this.m = m; - this.k = k; - this.stream = []; - this.sortedStream = []; - this.sum = 0; -}; - -/** - * @param {number} num - * @return {void} - */ -MKAverage.prototype.addElement = function(num) { - this.stream.push(num); - - const insertIndex = this.findInsertPosition(num); - this.sortedStream.splice(insertIndex, 0, num); - this.sum += num; - - if (this.stream.length > this.m) { - const oldestElement = this.stream.shift(); - const oldestIndex = this.sortedStream.indexOf(oldestElement); - this.sortedStream.splice(oldestIndex, 1); - this.sum -= oldestElement; - } -}; - -/** - * @return {number} - */ -MKAverage.prototype.calculateMKAverage = function() { - if (this.stream.length < this.m) { - return -1; - } - - let adjustedSum = this.sum; - - for (let i = 0; i < this.k; i++) { - adjustedSum -= this.sortedStream[i]; - } - for (let i = this.sortedStream.length - this.k; i < this.sortedStream.length; i++) { - adjustedSum -= this.sortedStream[i]; - } - - return Math.floor(adjustedSum / (this.m - 2 * this.k)); -}; - -/** - * Helper method to find insert position using binary search - * @param {number} num - * @return {number} - */ -MKAverage.prototype.findInsertPosition = function(num) { - let left = 0; - let right = this.sortedStream.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (this.sortedStream[mid] < num) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return left; -}; diff --git a/solutions/1827-minimum-operations-to-make-the-array-increasing.js b/solutions/1827-minimum-operations-to-make-the-array-increasing.js deleted file mode 100644 index 5eef57d6..00000000 --- a/solutions/1827-minimum-operations-to-make-the-array-increasing.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1827. Minimum Operations to Make the Array Increasing - * https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/ - * Difficulty: Easy - * - * You are given an integer array nums (0-indexed). In one operation, you can choose an - * element of the array and increment it by 1. - * - For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. - * - * Return the minimum number of operations needed to make nums strictly increasing. - * - * An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. - * An array of length 1 is trivially strictly increasing. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minOperations = function(nums) { - let result = 0; - let previousValue = nums[0]; - - for (let i = 1; i < nums.length; i++) { - if (nums[i] <= previousValue) { - const requiredValue = previousValue + 1; - result += requiredValue - nums[i]; - previousValue = requiredValue; - } else { - previousValue = nums[i]; - } - } - - return result; -}; diff --git a/solutions/1828-queries-on-number-of-points-inside-a-circle.js b/solutions/1828-queries-on-number-of-points-inside-a-circle.js deleted file mode 100644 index bfc1e4b8..00000000 --- a/solutions/1828-queries-on-number-of-points-inside-a-circle.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1828. Queries on Number of Points Inside a Circle - * https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/ - * Difficulty: Medium - * - * You are given an array points where points[i] = [xi, yi] is the coordinates of the ith - * point on a 2D plane. Multiple points can have the same coordinates. - * - * You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle - * centered at (xj, yj) with a radius of rj. - * - * For each query queries[j], compute the number of points inside the jth circle. Points on - * the border of the circle are considered inside. - * - * Return an array answer, where answer[j] is the answer to the jth query. - */ - -/** - * @param {number[][]} points - * @param {number[][]} queries - * @return {number[]} - */ -var countPoints = function(points, queries) { - const result = []; - - for (const [centerX, centerY, radius] of queries) { - let pointsInside = 0; - for (const [pointX, pointY] of points) { - const distance = Math.sqrt((centerX - pointX) ** 2 + (centerY - pointY) ** 2); - if (distance <= radius) { - pointsInside++; - } - } - result.push(pointsInside); - } - - return result; -}; diff --git a/solutions/1829-maximum-xor-for-each-query.js b/solutions/1829-maximum-xor-for-each-query.js deleted file mode 100644 index 43a867f6..00000000 --- a/solutions/1829-maximum-xor-for-each-query.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1829. Maximum XOR for Each Query - * https://leetcode.com/problems/maximum-xor-for-each-query/ - * Difficulty: Medium - * - * You are given a sorted array nums of n non-negative integers and an integer maximumBit. - * You want to perform the following query n times: - * - Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR - * nums[nums.length-1] XOR k is maximized. k is the answer to the ith query. - * - Remove the last element from the current array nums. - * - * Return an array answer, where answer[i] is the answer to the ith query. - */ - -/** - * @param {number[]} nums - * @param {number} maximumBit - * @return {number[]} - */ -var getMaximumXor = function(nums, maximumBit) { - const result = []; - let currentXor = 0; - const maxValue = (1 << maximumBit) - 1; - - for (const num of nums) { - currentXor ^= num; - } - - for (let i = nums.length - 1; i >= 0; i--) { - const optimalK = currentXor ^ maxValue; - result.push(optimalK); - currentXor ^= nums[i]; - } - - return result; -}; diff --git a/solutions/1830-minimum-number-of-operations-to-make-string-sorted.js b/solutions/1830-minimum-number-of-operations-to-make-string-sorted.js deleted file mode 100644 index 51cbb535..00000000 --- a/solutions/1830-minimum-number-of-operations-to-make-string-sorted.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1830. Minimum Number of Operations to Make String Sorted - * https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/ - * Difficulty: Hard - * - * You are given a string s (0-indexed). You are asked to perform the following operation on - * s until you get a sorted string: - * 1. Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1]. - * 2. Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the - * possible values of k in the range [i, j] inclusive. - * 3. Swap the two characters at indices i - 1 and j. - * 4. Reverse the suffix starting at index i. - * - * Return the number of operations needed to make the string sorted. Since the answer can be too - * large, return it modulo 109 + 7. - */ - -/** - * @param {string} s - * @return {number} - */ -var makeStringSorted = function(s) { - const MOD = 1e9 + 7; - const length = s.length; - const factorials = new Array(length + 1).fill(1n); - const inverses = new Array(length + 1).fill(1n); - - for (let i = 2; i <= length; i++) { - factorials[i] = (factorials[i - 1] * BigInt(i)) % BigInt(MOD); - } - - for (let i = 1; i <= length; i++) { - inverses[i] = modInverse(factorials[i], BigInt(MOD)); - } - - let result = 0n; - const charCounts = new Array(26).fill(0); - for (let i = length - 1; i >= 0; i--) { - const charIndex = s.charCodeAt(i) - 97; - charCounts[charIndex]++; - let smallerChars = 0; - for (let j = 0; j < charIndex; j++) { - smallerChars += charCounts[j]; - } - let totalPermutations = factorials[length - i - 1]; - for (const count of charCounts) { - totalPermutations = (totalPermutations * inverses[count]) % BigInt(MOD); - } - result = (result + BigInt(smallerChars) * totalPermutations) % BigInt(MOD); - } - - return Number(result); - - function modInverse(a, m) { - const m0 = m; - let q; - let x0 = 0n; - let x1 = 1n; - while (a > 1n) { - q = a / m; - [a, m] = [m, a % m]; - [x0, x1] = [x1 - q * x0, x0]; - } - return x1 < 0n ? x1 + m0 : x1; - } - - function combinations(n, k) { - if (k < 0 || k > n) return 0n; - return (factorials[n] * inverses[k] % BigInt(MOD)) * inverses[n - k] % BigInt(MOD); - } -}; diff --git a/solutions/1834-single-threaded-cpu.js b/solutions/1834-single-threaded-cpu.js deleted file mode 100644 index e07dd7dc..00000000 --- a/solutions/1834-single-threaded-cpu.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1834. Single-Threaded CPU - * https://leetcode.com/problems/single-threaded-cpu/ - * Difficulty: Medium - * - * You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, - * where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available - * to process at enqueueTimei and will take processingTimei to finish processing. - * - * You have a single-threaded CPU that can process at most one task at a time and will act in - * the following way: - * - If the CPU is idle and there are no available tasks to process, the CPU remains idle. - * - If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest - * processing time. If multiple tasks have the same shortest processing time, it will choose the - * task with the smallest index. - * - Once a task is started, the CPU will process the entire task without stopping. - * - The CPU can finish a task then start a new one instantly. - * - * Return the order in which the CPU will process the tasks. - */ - -/** - * @param {number[][]} tasks - * @return {number[]} - */ -var getOrder = function(tasks) { - const indexedTasks = tasks.map(([enqueue, process], index) => ({ enqueue, process, index })) - .sort((a, b) => a.enqueue - b.enqueue); - - const result = []; - const availableTasks = new PriorityQueue((a, b) => a.process - b.process || a.index - b.index); - let currentTime = indexedTasks[0].enqueue; - let taskIndex = 0; - - while (result.length < tasks.length) { - while (taskIndex < tasks.length && indexedTasks[taskIndex].enqueue <= currentTime) { - availableTasks.push(indexedTasks[taskIndex]); - taskIndex++; - } - - if (availableTasks.size() > 0) { - const task = availableTasks.pop(); - result.push(task.index); - currentTime += task.process; - } else { - currentTime = indexedTasks[taskIndex].enqueue; - } - } - - return result; -}; diff --git a/solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js b/solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js deleted file mode 100644 index f57b405d..00000000 --- a/solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1835. Find XOR Sum of All Pairs Bitwise AND - * https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/ - * Difficulty: Hard - * - * The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one - * element, then its XOR sum will be equal to this element. - * - For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR - * sum of [3] is equal to 3. - * - * You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. - * - * Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) - * pair where 0 <= i < arr1.length and 0 <= j < arr2.length. - * - * Return the XOR sum of the aforementioned list. - */ - -/** - * @param {number[]} arr1 - * @param {number[]} arr2 - * @return {number} - */ -var getXORSum = function(arr1, arr2) { - let xor1 = 0; - let xor2 = 0; - - for (const num of arr1) { - xor1 ^= num; - } - - for (const num of arr2) { - xor2 ^= num; - } - - return xor1 & xor2; -}; diff --git a/solutions/1837-sum-of-digits-in-base-k.js b/solutions/1837-sum-of-digits-in-base-k.js deleted file mode 100644 index 48223a4d..00000000 --- a/solutions/1837-sum-of-digits-in-base-k.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 1837. Sum of Digits in Base K - * https://leetcode.com/problems/sum-of-digits-in-base-k/ - * Difficulty: Easy - * - * Given an integer n (in base 10) and a base k, return the sum of the digits of n after - * converting n from base 10 to base k. - * - * After converting, each digit should be interpreted as a base 10 number, and the sum should - * be returned in base 10. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var sumBase = function(n, k) { - let digitSum = 0; - - while (n > 0) { - digitSum += n % k; - n = Math.floor(n / k); - } - - return digitSum; -}; diff --git a/solutions/1838-frequency-of-the-most-frequent-element.js b/solutions/1838-frequency-of-the-most-frequent-element.js deleted file mode 100644 index d13b8eb2..00000000 --- a/solutions/1838-frequency-of-the-most-frequent-element.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1838. Frequency of the Most Frequent Element - * https://leetcode.com/problems/frequency-of-the-most-frequent-element/ - * Difficulty: Medium - * - * The frequency of an element is the number of times it occurs in an array. - * - * You are given an integer array nums and an integer k. In one operation, you can choose - * an index of nums and increment the element at that index by 1. - * - * Return the maximum possible frequency of an element after performing at most k operations. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maxFrequency = function(nums, k) { - nums.sort((a, b) => a - b); - - let result = 0; - let currentSum = 0; - let left = 0; - - for (let right = 0; right < nums.length; right++) { - currentSum += nums[right]; - while (currentSum + k < nums[right] * (right - left + 1)) { - currentSum -= nums[left]; - left++; - } - result = Math.max(result, right - left + 1); - } - - return result; -}; diff --git a/solutions/1839-longest-substring-of-all-vowels-in-order.js b/solutions/1839-longest-substring-of-all-vowels-in-order.js deleted file mode 100644 index 343f0279..00000000 --- a/solutions/1839-longest-substring-of-all-vowels-in-order.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 1839. Longest Substring Of All Vowels in Order - * https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/ - * Difficulty: Medium - * - * A string is considered beautiful if it satisfies the following conditions: - * - Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. - * - The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's - * before 'i's, etc.). - * - * For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", - * and "aaaeeeooo" are not beautiful. - * - * Given a string word consisting of English vowels, return the length of the longest beautiful - * substring of word. If no such substring exists, return 0. - * - * A substring is a contiguous sequence of characters in a string. - */ - -/** - * @param {string} word - * @return {number} - */ -var longestBeautifulSubstring = function(word) { - let result = 0; - let start = 0; - let vowelCount = 1; - - for (let i = 1; i < word.length; i++) { - if (word[i] < word[i - 1]) { - start = i; - vowelCount = 1; - } else if (word[i] > word[i - 1]) { - vowelCount++; - } - - if (vowelCount === 5) { - result = Math.max(result, i - start + 1); - } - } - - return result; -}; diff --git a/solutions/1840-maximum-building-height.js b/solutions/1840-maximum-building-height.js deleted file mode 100644 index d77cdd46..00000000 --- a/solutions/1840-maximum-building-height.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1840. Maximum Building Height - * https://leetcode.com/problems/maximum-building-height/ - * Difficulty: Hard - * - * You want to build n new buildings in a city. The new buildings will be built in a line - * and are labeled from 1 to n. - * - * However, there are city restrictions on the heights of the new buildings: - * - The height of each building must be a non-negative integer. - * - The height of the first building must be 0. - * - The height difference between any two adjacent buildings cannot exceed 1. - * - * Additionally, there are city restrictions on the maximum height of specific buildings. - * These restrictions are given as a 2D integer array restrictions where - * restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height - * less than or equal to maxHeighti. - * - * It is guaranteed that each building will appear at most once in restrictions, and building - * 1 will not be in restrictions. - * - * Return the maximum possible height of the tallest building. - */ - -/** - * @param {number} n - * @param {number[][]} restrictions - * @return {number} - */ -var maxBuilding = function(n, restrictions) { - restrictions.push([1, 0], [n, n - 1]); - restrictions.sort((a, b) => a[0] - b[0]); - - const length = restrictions.length; - - for (let i = 1; i < length; i++) { - const [currId, currHeight] = restrictions[i]; - const [prevId, prevHeight] = restrictions[i - 1]; - restrictions[i][1] = Math.min(currHeight, prevHeight + (currId - prevId)); - } - - for (let i = length - 2; i >= 0; i--) { - const [currId, currHeight] = restrictions[i]; - const [nextId, nextHeight] = restrictions[i + 1]; - restrictions[i][1] = Math.min(currHeight, nextHeight + (nextId - currId)); - } - - let maxHeight = 0; - - for (let i = 1; i < length; i++) { - const [leftId, leftHeight] = restrictions[i - 1]; - const [rightId, rightHeight] = restrictions[i]; - const distance = rightId - leftId; - const heightDiff = Math.abs(rightHeight - leftHeight); - const peakHeight = Math.max(leftHeight, rightHeight) + Math.floor((distance - heightDiff) / 2); - maxHeight = Math.max(maxHeight, peakHeight); - } - - return maxHeight; -}; diff --git a/solutions/1844-replace-all-digits-with-characters.js b/solutions/1844-replace-all-digits-with-characters.js deleted file mode 100644 index c5efb48c..00000000 --- a/solutions/1844-replace-all-digits-with-characters.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1844. Replace All Digits with Characters - * https://leetcode.com/problems/replace-all-digits-with-characters/ - * Difficulty: Easy - * - * You are given a 0-indexed string s that has lowercase English letters in its even indices and - * digits in its odd indices. - * - * You must perform an operation shift(c, x), where c is a character and x is a digit, that returns - * the xth character after c. - * - For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'. - * - * For every odd index i, you want to replace the digit s[i] with the result of the - * shift(s[i-1], s[i]) operation. - * - * Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never - * exceed 'z'. - * - * Note that shift(c, x) is not a preloaded function, but an operation to be implemented as part - * of the solution. - */ - -/** - * @param {string} s - * @return {string} - */ -var replaceDigits = function(s) { - const result = s.split(''); - - for (let i = 1; i < s.length; i += 2) { - result[i] = shiftChar(s[i - 1], s[i]); - } - - return result.join(''); - - function shiftChar(char, shift) { - return String.fromCharCode(char.charCodeAt(0) + parseInt(shift)); - } -}; diff --git a/solutions/1845-seat-reservation-manager.js b/solutions/1845-seat-reservation-manager.js deleted file mode 100644 index 53bc7edd..00000000 --- a/solutions/1845-seat-reservation-manager.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1845. Seat Reservation Manager - * https://leetcode.com/problems/seat-reservation-manager/ - * Difficulty: Medium - * - * Design a system that manages the reservation state of n seats that are numbered from 1 to n. - * - * Implement the SeatManager class: - * - SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from - * 1 to n. All seats are initially available. - * - int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its - * number. - * - void unreserve(int seatNumber) Unreserves the seat with the given seatNumber. - */ - -/** - * @param {number} n - */ -var SeatManager = function(n) { - this.nextAvailable = 1; - this.unreservedSeats = new Set(); -}; - -/** - * @return {number} - */ -SeatManager.prototype.reserve = function() { - if (this.unreservedSeats.size > 0) { - const minSeat = Math.min(...this.unreservedSeats); - if (minSeat < this.nextAvailable) { - this.unreservedSeats.delete(minSeat); - return minSeat; - } - } - return this.nextAvailable++; -}; - -/** - * @param {number} seatNumber - * @return {void} - */ -SeatManager.prototype.unreserve = function(seatNumber) { - this.unreservedSeats.add(seatNumber); -}; diff --git a/solutions/1846-maximum-element-after-decreasing-and-rearranging.js b/solutions/1846-maximum-element-after-decreasing-and-rearranging.js deleted file mode 100644 index 266a8dc1..00000000 --- a/solutions/1846-maximum-element-after-decreasing-and-rearranging.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1846. Maximum Element After Decreasing and Rearranging - * https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/ - * Difficulty: Medium - * - * You are given an array of positive integers arr. Perform some operations (possibly none) on - * arr so that it satisfies these conditions: - * - The value of the first element in arr must be 1. - * - The absolute difference between any 2 adjacent elements must be less than or equal to 1. - * In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length - * (0-indexed). abs(x) is the absolute value of x. - * - * There are 2 types of operations that you can perform any number of times: - * - Decrease the value of any element of arr to a smaller positive integer. - * - Rearrange the elements of arr to be in any order. - * - * Return the maximum possible value of an element in arr after performing the operations to - * satisfy the conditions. - */ - -/** - * @param {number[]} arr - * @return {number} - */ -var maximumElementAfterDecrementingAndRearranging = function(arr) { - arr.sort((a, b) => a - b); - let maxPossible = 1; - - for (let i = 1; i < arr.length; i++) { - if (arr[i] > maxPossible) { - maxPossible++; - } - } - - return maxPossible; -}; diff --git a/solutions/1847-closest-room.js b/solutions/1847-closest-room.js deleted file mode 100644 index 49963145..00000000 --- a/solutions/1847-closest-room.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * 1847. Closest Room - * https://leetcode.com/problems/closest-room/ - * Difficulty: Hard - * - * There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where - * rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size - * equal to sizei. Each roomIdi is guaranteed to be unique. - * - * You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. - * The answer to the jth query is the room number id of a room such that: - * - The room has a size of at least minSizej, and - * - abs(id - preferredj) is minimized, where abs(x) is the absolute value of x. - * - * If there is a tie in the absolute difference, then use the room with the smallest such id. - * If there is no such room, the answer is -1. - * - * Return an array answer of length k where answer[j] contains the answer to the jth query. - */ - -/** - * @param {number[][]} rooms - * @param {number[][]} queries - * @return {number[]} - */ -var closestRoom = function(rooms, queries) { - rooms.sort((a, b) => b[1] - a[1]); - const sortedQueries = queries - .map((q, i) => [q[0], q[1], i]) - .sort((a, b) => b[1] - a[1]); - - const result = new Array(queries.length).fill(-1); - const roomIds = []; - let roomIndex = 0; - - for (const [preferred, minSize, queryIndex] of sortedQueries) { - while (roomIndex < rooms.length && rooms[roomIndex][1] >= minSize) { - insertSorted(rooms[roomIndex][0]); - roomIndex++; - } - - result[queryIndex] = findClosestId(preferred); - } - - return result; - - function insertSorted(id) { - let left = 0; - let right = roomIds.length; - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (roomIds[mid] < id) left = mid + 1; - else right = mid; - } - roomIds.splice(left, 0, id); - } - - function findClosestId(target) { - if (!roomIds.length) return -1; - - let left = 0; - let right = roomIds.length - 1; - let closest = roomIds[0]; - let minDiff = Math.abs(closest - target); - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - const id = roomIds[mid]; - const diff = Math.abs(id - target); - - if (diff < minDiff || (diff === minDiff && id < closest)) { - minDiff = diff; - closest = id; - } - - if (id < target) left = mid + 1; - else if (id > target) right = mid - 1; - else break; - } - - return closest; - } -}; diff --git a/solutions/1848-minimum-distance-to-the-target-element.js b/solutions/1848-minimum-distance-to-the-target-element.js deleted file mode 100644 index 567427d2..00000000 --- a/solutions/1848-minimum-distance-to-the-target-element.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1848. Minimum Distance to the Target Element - * https://leetcode.com/problems/minimum-distance-to-the-target-element/ - * Difficulty: Easy - * - * Given an integer array nums (0-indexed) and two integers target and start, find an index i - * such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute - * value of x. - * - * Return abs(i - start). - * - * It is guaranteed that target exists in nums. - */ - -/** - * @param {number[]} nums - * @param {number} target - * @param {number} start - * @return {number} - */ -var getMinDistance = function(nums, target, start) { - let result = Infinity; - - for (let i = 0; i < nums.length; i++) { - if (nums[i] === target) { - const distance = Math.abs(i - start); - result = Math.min(result, distance); - } - } - - return result; -}; diff --git a/solutions/1849-splitting-a-string-into-descending-consecutive-values.js b/solutions/1849-splitting-a-string-into-descending-consecutive-values.js deleted file mode 100644 index d993db28..00000000 --- a/solutions/1849-splitting-a-string-into-descending-consecutive-values.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1849. Splitting a String Into Descending Consecutive Values - * https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/ - * Difficulty: Medium - * - * You are given a string s that consists of only digits. - * - * Check if we can split s into two or more non-empty substrings such that the numerical values of - * the substrings are in descending order and the difference between numerical values of every two - * adjacent substrings is equal to 1. - * - For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values - * [90,89]. The values are in descending order and adjacent values differ by 1, so this way is - * valid. - * - Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or - * ["0", "0", "1"]. However all the ways are invalid because they have numerical values - * [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order. - * - * Return true if it is possible to split s as described above, or false otherwise. - * - * A substring is a contiguous sequence of characters in a string. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var splitString = function(s) { - let firstValue = 0; - for (let i = 0; i < s.length - 1; i++) { - firstValue = firstValue * 10 + parseInt(s[i]); - if (trySplit(i + 1, firstValue)) return true; - } - - return false; - - function trySplit(index, prevValue) { - if (index === s.length) return true; - - let currentValue = 0; - for (let i = index; i < s.length; i++) { - currentValue = currentValue * 10 + parseInt(s[i]); - if (currentValue >= prevValue) break; - if (prevValue - currentValue === 1 && trySplit(i + 1, currentValue)) { - return true; - } - } - - return false; - } -}; diff --git a/solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js b/solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js deleted file mode 100644 index d4853138..00000000 --- a/solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number - * https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/ - * Difficulty: Medium - * - * You are given a string num, representing a large integer, and an integer k. - * - * We call some integer wonderful if it is a permutation of the digits in num and is greater in - * value than num. There can be many wonderful integers. However, we only care about the - * smallest-valued ones. - * - For example, when num = "5489355142": - * - The 1st smallest wonderful integer is "5489355214". - * - The 2nd smallest wonderful integer is "5489355241". - * - The 3rd smallest wonderful integer is "5489355412". - * - The 4th smallest wonderful integer is "5489355421". - * - * Return the minimum number of adjacent digit swaps that needs to be applied to num to reach - * the kth smallest wonderful integer. - * - * The tests are generated in such a way that kth smallest wonderful integer exists. - */ - -/** - * @param {string} num - * @param {number} k - * @return {number} - */ -var getMinSwaps = function(num, k) { - const original = num.split(''); - const target = num.split(''); - - for (let i = 0; i < k; i++) { - nextPermutation(target); - } - - let result = 0; - for (let i = 0; i < original.length; i++) { - if (original[i] !== target[i]) { - let j = i + 1; - while (j < original.length && original[j] !== target[i]) j++; - while (j > i) { - [original[j], original[j - 1]] = [original[j - 1], original[j]]; - result++; - j--; - } - } - } - - return result; - - function nextPermutation(arr) { - let i = arr.length - 2; - while (i >= 0 && arr[i] >= arr[i + 1]) i--; - if (i < 0) return false; - - let j = arr.length - 1; - while (arr[j] <= arr[i]) j--; - - [arr[i], arr[j]] = [arr[j], arr[i]]; - - let left = i + 1; - let right = arr.length - 1; - while (left < right) { - [arr[left], arr[right]] = [arr[right], arr[left]]; - left++; - right--; - } - return true; - } -}; diff --git a/solutions/1851-minimum-interval-to-include-each-query.js b/solutions/1851-minimum-interval-to-include-each-query.js deleted file mode 100644 index a81d82ea..00000000 --- a/solutions/1851-minimum-interval-to-include-each-query.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1851. Minimum Interval to Include Each Query - * https://leetcode.com/problems/minimum-interval-to-include-each-query/ - * Difficulty: Hard - * - * You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes - * the ith interval starting at lefti and ending at righti (inclusive). The size of an interval - * is defined as the number of integers it contains, or more formally righti - lefti + 1. - * - * You are also given an integer array queries. The answer to the jth query is the size of the - * smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, - * the answer is -1. - * - * Return an array containing the answers to the queries. - */ - -/** - * @param {number[][]} intervals - * @param {number[]} queries - * @return {number[]} - */ -var minInterval = function(intervals, queries) { - intervals.sort((a, b) => a[0] - b[0]); - const sortedQueries = queries - .map((q, i) => [q, i]) - .sort((a, b) => a[0] - b[0]); - - const activeIntervals = new PriorityQueue((a, b) => a[0] - b[0]); - const result = new Array(queries.length).fill(-1); - let intervalIndex = 0; - - for (const [queryValue, queryIndex] of sortedQueries) { - while (intervalIndex < intervals.length && intervals[intervalIndex][0] <= queryValue) { - const [start, end] = intervals[intervalIndex]; - activeIntervals.enqueue([end - start + 1, end]); - intervalIndex++; - } - - while (!activeIntervals.isEmpty() && activeIntervals.front()?.[1] < queryValue) { - activeIntervals.dequeue(); - } - - if (!activeIntervals.isEmpty()) { - result[queryIndex] = activeIntervals.front()[0]; - } - } - - return result; -}; diff --git a/solutions/1854-maximum-population-year.js b/solutions/1854-maximum-population-year.js deleted file mode 100644 index 9ea9aec0..00000000 --- a/solutions/1854-maximum-population-year.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1854. Maximum Population Year - * https://leetcode.com/problems/maximum-population-year/ - * Difficulty: Easy - * - * You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the - * birth and death years of the ith person. - * - * The population of some year x is the number of people alive during that year. The ith person - * is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note - * that the person is not counted in the year that they die. - * - * Return the earliest year with the maximum population. - */ - -/** - * @param {number[][]} logs - * @return {number} - */ -var maximumPopulation = function(logs) { - const populationChanges = new Array(101).fill(0); - const baseYear = 1950; - - for (const [birth, death] of logs) { - populationChanges[birth - baseYear]++; - populationChanges[death - baseYear]--; - } - - let maxPopulation = 0; - let currentPopulation = 0; - let result = baseYear; - - for (let i = 0; i < populationChanges.length; i++) { - currentPopulation += populationChanges[i]; - if (currentPopulation > maxPopulation) { - maxPopulation = currentPopulation; - result = baseYear + i; - } - } - - return result; -}; diff --git a/solutions/1855-maximum-distance-between-a-pair-of-values.js b/solutions/1855-maximum-distance-between-a-pair-of-values.js deleted file mode 100644 index d94af4d5..00000000 --- a/solutions/1855-maximum-distance-between-a-pair-of-values.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1855. Maximum Distance Between a Pair of Values - * https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ - * Difficulty: Medium - * - * You are given two non-increasing 0-indexed integer arrays nums2 and nums2. - * - * A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, - * is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i. - * - * Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. - * - * An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var maxDistance = function(nums1, nums2) { - let result = 0; - let left = 0; - - for (let right = 0; right < nums2.length; right++) { - while (left < nums1.length && nums1[left] > nums2[right]) { - left++; - } - if (left <= right && left < nums1.length) { - result = Math.max(result, right - left); - } - } - - return result; -}; diff --git a/solutions/1856-maximum-subarray-min-product.js b/solutions/1856-maximum-subarray-min-product.js deleted file mode 100644 index 02a5f6bc..00000000 --- a/solutions/1856-maximum-subarray-min-product.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1856. Maximum Subarray Min-Product - * https://leetcode.com/problems/maximum-subarray-min-product/ - * Difficulty: Medium - * - * The min-product of an array is equal to the minimum value in the array multiplied by - * the array's sum. - * - For example, the array [3,2,5] (minimum value is 2) has a min-product of - * 2 * (3+2+5) = 2 * 10 = 20. - * - * Given an array of integers nums, return the maximum min-product of any non-empty - * subarray of nums. Since the answer may be large, return it modulo 109 + 7. - * - * Note that the min-product should be maximized before performing the modulo operation. - * Testcases are generated such that the maximum min-product without modulo will fit in - * a 64-bit signed integer. - * - * A subarray is a contiguous part of an array. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxSumMinProduct = function(nums) { - const modulo = 1000000007n; - const stack = []; - const prefixSums = [0n]; - let maxMinProduct = 0n; - - for (let i = 0; i < nums.length; i++) { - prefixSums.push(prefixSums[i] + BigInt(nums[i])); - } - - for (let right = 0; right <= nums.length; right++) { - const current = right < nums.length ? BigInt(nums[right]) : 0n; - while (stack.length && stack[stack.length - 1].value > current) { - const { index, value } = stack.pop(); - const left = stack.length ? stack[stack.length - 1].index + 1 : 0; - const subarraySum = prefixSums[right] - prefixSums[left]; - maxMinProduct = maxMinProduct > value * subarraySum ? maxMinProduct : value * subarraySum; - } - stack.push({ index: right, value: current }); - } - - return Number(maxMinProduct % modulo); -}; diff --git a/solutions/1857-largest-color-value-in-a-directed-graph.js b/solutions/1857-largest-color-value-in-a-directed-graph.js deleted file mode 100644 index c592996b..00000000 --- a/solutions/1857-largest-color-value-in-a-directed-graph.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1857. Largest Color Value in a Directed Graph - * https://leetcode.com/problems/largest-color-value-in-a-directed-graph/ - * Difficulty: Hard - * - * There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. - * - * You are given a string colors where colors[i] is a lowercase English letter representing the - * color of the ith node in this graph (0-indexed). You are also given a 2D array edges where - * edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. - * - * A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there - * is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the - * number of nodes that are colored the most frequently occurring color along that path. - * - * Return the largest color value of any valid path in the given graph, or -1 if the graph - * contains a cycle. - */ - -/** - * @param {string} colors - * @param {number[][]} edges - * @return {number} - */ -var largestPathValue = function(colors, edges) { - const nodeCount = colors.length; - const adjacencyList = Array.from({ length: nodeCount }, () => []); - const inDegree = new Array(nodeCount).fill(0); - const colorCounts = Array.from({ length: nodeCount }, () => new Array(26).fill(0)); - const queue = []; - let maxColorValue = 0; - let processedNodes = 0; - - for (const [from, to] of edges) { - adjacencyList[from].push(to); - inDegree[to]++; - } - - for (let i = 0; i < nodeCount; i++) { - if (inDegree[i] === 0) queue.push(i); - } - - while (queue.length) { - const current = queue.shift(); - processedNodes++; - const colorIndex = colors.charCodeAt(current) - 97; - colorCounts[current][colorIndex]++; - - for (const next of adjacencyList[current]) { - for (let i = 0; i < 26; i++) { - colorCounts[next][i] = Math.max(colorCounts[next][i], colorCounts[current][i]); - } - if (--inDegree[next] === 0) queue.push(next); - } - - maxColorValue = Math.max(maxColorValue, ...colorCounts[current]); - } - - return processedNodes === nodeCount ? maxColorValue : -1; -}; diff --git a/solutions/1859-sorting-the-sentence.js b/solutions/1859-sorting-the-sentence.js deleted file mode 100644 index d2d9c81f..00000000 --- a/solutions/1859-sorting-the-sentence.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1859. Sorting the Sentence - * https://leetcode.com/problems/sorting-the-sentence/ - * Difficulty: Easy - * - * A sentence is a list of words that are separated by a single space with no leading or trailing - * spaces. Each word consists of lowercase and uppercase English letters. - * - * A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging - * the words in the sentence. - * - For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or - * "is2 sentence4 This1 a3". - * - * Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original - * sentence. - */ - -/** - * @param {string} s - * @return {string} - */ -var sortSentence = function(s) { - const words = s.split(' '); - const sortedWords = new Array(words.length); - - for (const word of words) { - const position = parseInt(word.slice(-1)) - 1; - sortedWords[position] = word.slice(0, -1); - } - - return sortedWords.join(' '); -}; diff --git a/solutions/1860-incremental-memory-leak.js b/solutions/1860-incremental-memory-leak.js deleted file mode 100644 index fd72b849..00000000 --- a/solutions/1860-incremental-memory-leak.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1860. Incremental Memory Leak - * https://leetcode.com/problems/incremental-memory-leak/ - * Difficulty: Medium - * - * You are given two integers memory1 and memory2 representing the available memory in bits on - * two memory sticks. There is currently a faulty program running that consumes an increasing - * amount of memory every second. - * - * At the ith second (starting from 1), i bits of memory are allocated to the stick with more - * available memory (or from the first memory stick if both have the same available memory). - * If neither stick has at least i bits of available memory, the program crashes. - * - * Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the - * time (in seconds) when the program crashed and memory1crash and memory2crash are the - * available bits of memory in the first and second sticks respectively. - */ - -/** - * @param {number} memory1 - * @param {number} memory2 - * @return {number[]} - */ -var memLeak = function(memory1, memory2) { - let time = 1; - let stick1 = memory1; - let stick2 = memory2; - - while (time <= stick1 || time <= stick2) { - if (stick1 >= stick2) { - if (stick1 < time) break; - stick1 -= time; - } else { - if (stick2 < time) break; - stick2 -= time; - } - time++; - } - - return [time, stick1, stick2]; -}; diff --git a/solutions/1861-rotating-the-box.js b/solutions/1861-rotating-the-box.js deleted file mode 100644 index 0b874c74..00000000 --- a/solutions/1861-rotating-the-box.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1861. Rotating the Box - * https://leetcode.com/problems/rotating-the-box/ - * Difficulty: Medium - * - * You are given an m x n matrix of characters boxGrid representing a side-view of a box. - * Each cell of the box is one of the following: - * - A stone '#' - * - A stationary obstacle '*' - * - Empty '.' - * - * The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. - * Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. - * Gravity does not affect the obstacles' positions, and the inertia from the box's rotation - * does not affect the stones' horizontal positions. - * - * It is guaranteed that each stone in boxGrid rests on an obstacle, another stone, or the - * bottom of the box. - * - * Return an n x m matrix representing the box after the rotation described above. - */ - -/** - * @param {character[][]} boxGrid - * @return {character[][]} - */ -var rotateTheBox = function(boxGrid) { - const rows = boxGrid.length; - const cols = boxGrid[0].length; - const result = Array.from({ length: cols }, () => new Array(rows).fill('.')); - - for (let row = 0; row < rows; row++) { - let freePosition = cols - 1; - for (let col = cols - 1; col >= 0; col--) { - if (boxGrid[row][col] === '*') { - result[col][rows - 1 - row] = '*'; - freePosition = col - 1; - } else if (boxGrid[row][col] === '#') { - result[freePosition][rows - 1 - row] = '#'; - freePosition--; - } - } - } - - return result; -}; diff --git a/solutions/1862-sum-of-floored-pairs.js b/solutions/1862-sum-of-floored-pairs.js deleted file mode 100644 index 4d470c3c..00000000 --- a/solutions/1862-sum-of-floored-pairs.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1862. Sum of Floored Pairs - * https://leetcode.com/problems/sum-of-floored-pairs/ - * Difficulty: Hard - * - * Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of - * indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return - * it modulo 109 + 7. - * - * The floor() function returns the integer part of the division. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var sumOfFlooredPairs = function(nums) { - const modulo = 1e9 + 7; - const maxValue = Math.max(...nums); - const frequency = new Array(maxValue + 1).fill(0); - const prefixSum = new Array(maxValue + 1).fill(0); - let result = 0; - - for (const num of nums) { - frequency[num]++; - } - - for (let i = 1; i <= maxValue; i++) { - prefixSum[i] = prefixSum[i - 1] + frequency[i]; - } - - for (let i = 1; i <= maxValue; i++) { - if (frequency[i] === 0) continue; - for (let divisor = i; divisor <= maxValue; divisor += i) { - const quotient = Math.floor(divisor / i); - const count = ( - prefixSum[Math.min(maxValue, divisor + i - 1)] - prefixSum[divisor - 1] - ) % modulo; - result = (result + quotient * frequency[i] * count) % modulo; - } - } - - return result; -}; diff --git a/solutions/1863-sum-of-all-subset-xor-totals.js b/solutions/1863-sum-of-all-subset-xor-totals.js deleted file mode 100644 index 9ac07e3b..00000000 --- a/solutions/1863-sum-of-all-subset-xor-totals.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1863. Sum of All Subset XOR Totals - * https://leetcode.com/problems/sum-of-all-subset-xor-totals/ - * Difficulty: Easy - * - * The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if - * the array is empty. - * - * For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1. - * Given an array nums, return the sum of all XOR totals for every subset of nums. - * Note: Subsets with the same elements should be counted multiple times. - * - * An array a is a subset of an array b if a can be obtained from b by deleting some (possibly - * zero) elements of b. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var subsetXORSum = function(nums) { - const totalSubsets = 1 << nums.length; - let result = 0; - - for (let mask = 0; mask < totalSubsets; mask++) { - let currentXOR = 0; - for (let i = 0; i < nums.length; i++) { - if (mask & (1 << i)) { - currentXOR ^= nums[i]; - } - } - result += currentXOR; - } - - return result; -}; diff --git a/solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js b/solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js deleted file mode 100644 index 28378e0b..00000000 --- a/solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 1864. Minimum Number of Swaps to Make the Binary String Alternating - * https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/ - * Difficulty: Medium - * - * Given a binary string s, return the minimum number of character swaps to make it alternating, - * or -1 if it is impossible. - * - * The string is called alternating if no two adjacent characters are equal. For example, the - * strings "010" and "1010" are alternating, while the string "0100" is not. - * - * Any two characters may be swapped, even if they are not adjacent. - */ - -/** - * @param {string} s - * @return {number} - */ -var minSwaps = function(s) { - const length = s.length; - let ones = 0; - let zeros = 0; - - for (const char of s) { - if (char === '1') ones++; - else zeros++; - } - - if (Math.abs(ones - zeros) > 1) return -1; - - let mismatchesStartWithZero = 0; - let mismatchesStartWithOne = 0; - - for (let i = 0; i < length; i++) { - if (i % 2 === 0) { - if (s[i] !== '0') mismatchesStartWithZero++; - if (s[i] !== '1') mismatchesStartWithOne++; - } else { - if (s[i] !== '1') mismatchesStartWithZero++; - if (s[i] !== '0') mismatchesStartWithOne++; - } - } - - if (ones === zeros) { - return Math.min(mismatchesStartWithZero, mismatchesStartWithOne) >> 1; - } - - return (ones > zeros ? mismatchesStartWithOne : mismatchesStartWithZero) >> 1; -}; diff --git a/solutions/1865-finding-pairs-with-a-certain-sum.js b/solutions/1865-finding-pairs-with-a-certain-sum.js deleted file mode 100644 index 9a100a1b..00000000 --- a/solutions/1865-finding-pairs-with-a-certain-sum.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1865. Finding Pairs With a Certain Sum - * https://leetcode.com/problems/finding-pairs-with-a-certain-sum/ - * Difficulty: Medium - * - * You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure - * that supports queries of two types: - * 1. Add a positive integer to an element of a given index in the array nums2. - * 2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given - * value (0 <= i < nums1.length and 0 <= j < nums2.length). - * - * Implement the FindSumPairs class: - * - FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer - * arrays nums1 and nums2. - * - void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val. - * - int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - */ -var FindSumPairs = function(nums1, nums2) { - this.firstArray = nums1; - this.secondArray = nums2; - this.frequency = new Map(); - - for (const num of nums2) { - this.frequency.set(num, (this.frequency.get(num) || 0) + 1); - } -}; - -/** - * @param {number} index - * @param {number} val - * @return {void} - */ -FindSumPairs.prototype.add = function(index, val) { - const oldValue = this.secondArray[index]; - this.secondArray[index] += val; - const newValue = this.secondArray[index]; - - this.frequency.set(oldValue, this.frequency.get(oldValue) - 1); - this.frequency.set(newValue, (this.frequency.get(newValue) || 0) + 1); -}; - -/** - * @param {number} tot - * @return {number} - */ -FindSumPairs.prototype.count = function(tot) { - let result = 0; - - for (const num of this.firstArray) { - const complement = tot - num; - result += this.frequency.get(complement) || 0; - } - - return result; -}; diff --git a/solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js b/solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js deleted file mode 100644 index 3a2ffed6..00000000 --- a/solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1866. Number of Ways to Rearrange Sticks With K Sticks Visible - * https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/ - * Difficulty: Hard - * - * There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange - * the sticks such that exactly k sticks are visible from the left. A stick is visible from the - * left if there are no longer sticks to the left of it. - * - For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, - * and 5 are visible from the left. - * - * Given n and k, return the number of such arrangements. Since the answer may be large, return - * it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var rearrangeSticks = function(n, k) { - const modulo = 1e9 + 7; - const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(0)); - dp[0][0] = 1; - - for (let sticks = 1; sticks <= n; sticks++) { - for (let visible = 0; visible <= k; visible++) { - if (visible > sticks) continue; - if (visible > 0) { - dp[sticks][visible] = (dp[sticks][visible] + dp[sticks - 1][visible - 1]) % modulo; - } - dp[sticks][visible] = (dp[sticks][visible] + dp[sticks - 1][visible] * (sticks - 1)) % modulo; - } - } - - return dp[n][k]; -}; diff --git a/solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js b/solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js deleted file mode 100644 index bc6acf26..00000000 --- a/solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1869. Longer Contiguous Segments of Ones than Zeros - * https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/ - * Difficulty: Easy - * - * Given a binary string s, return true if the longest contiguous segment of 1's is strictly - * longer than the longest contiguous segment of 0's in s, or return false otherwise. - * - For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the - * longest continuous segment of 0s has length 3. - * - * Note that if there are no 0's, then the longest continuous segment of 0's is considered to - * have a length 0. The same applies if there is no 1's. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var checkZeroOnes = function(s) { - let maxOnes = 0; - let maxZeros = 0; - let currentOnes = 0; - let currentZeros = 0; - - for (const char of s) { - if (char === '1') { - currentOnes++; - currentZeros = 0; - maxOnes = Math.max(maxOnes, currentOnes); - } else { - currentZeros++; - currentOnes = 0; - maxZeros = Math.max(maxZeros, currentZeros); - } - } - - return maxOnes > maxZeros; -}; diff --git a/solutions/1870-minimum-speed-to-arrive-on-time.js b/solutions/1870-minimum-speed-to-arrive-on-time.js deleted file mode 100644 index fd7633a5..00000000 --- a/solutions/1870-minimum-speed-to-arrive-on-time.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1870. Minimum Speed to Arrive on Time - * https://leetcode.com/problems/minimum-speed-to-arrive-on-time/ - * Difficulty: Medium - * - * You are given a floating-point number hour, representing the amount of time you have to reach - * the office. To commute to the office, you must take n trains in sequential order. You are also - * given an integer array dist of length n, where dist[i] describes the distance (in kilometers) - * of the ith train ride. - * - * Each train can only depart at an integer hour, so you may need to wait in between each train - * ride. - * - For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours - * before you can depart on the 2nd train ride at the 2 hour mark. - * - * Return the minimum positive integer speed (in kilometers per hour) that all the trains must - * travel at for you to reach the office on time, or -1 if it is impossible to be on time. - * - * Tests are generated such that the answer will not exceed 107 and hour will have at most two - * digits after the decimal point. - */ - -/** - * @param {number[]} dist - * @param {number} hour - * @return {number} - */ -var minSpeedOnTime = function(dist, hour) { - const trainCount = dist.length; - if (Math.ceil(trainCount - 1) > hour) return -1; - - let minSpeed = 1; - let maxSpeed = 10000000; - let result = -1; - - while (minSpeed <= maxSpeed) { - const midSpeed = (minSpeed + maxSpeed) >> 1; - let totalTime = 0; - - for (let i = 0; i < trainCount - 1; i++) { - totalTime += Math.ceil(dist[i] / midSpeed); - } - totalTime += dist[trainCount - 1] / midSpeed; - - if (totalTime <= hour) { - result = midSpeed; - maxSpeed = midSpeed - 1; - } else { - minSpeed = midSpeed + 1; - } - } - - return result; -}; diff --git a/solutions/1871-jump-game-vii.js b/solutions/1871-jump-game-vii.js deleted file mode 100644 index 92a47cc2..00000000 --- a/solutions/1871-jump-game-vii.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1871. Jump Game VII - * https://leetcode.com/problems/jump-game-vii/ - * Difficulty: Medium - * - * You are given a 0-indexed binary string s and two integers minJump and maxJump. In the - * beginning, you are standing at index 0, which is equal to '0'. You can move from index - * i to index j if the following conditions are fulfilled: - * - i + minJump <= j <= min(i + maxJump, s.length - 1), and - * - s[j] == '0'. - * - * Return true if you can reach index s.length - 1 in s, or false otherwise. - */ - -/** - * @param {string} s - * @param {number} minJump - * @param {number} maxJump - * @return {boolean} - */ -var canReach = function(s, minJump, maxJump) { - const length = s.length; - const reachable = new Array(length).fill(false); - reachable[0] = true; - const queue = [0]; - let farthest = 0; - - while (queue.length) { - const current = queue.shift(); - const start = current + minJump; - const end = Math.min(current + maxJump, length - 1); - - for (let next = Math.max(start, farthest + 1); next <= end; next++) { - if (s[next] === '0' && !reachable[next]) { - reachable[next] = true; - queue.push(next); - if (next === length - 1) return true; - } - } - farthest = Math.max(farthest, end); - } - - return false; -}; diff --git a/solutions/1872-stone-game-viii.js b/solutions/1872-stone-game-viii.js deleted file mode 100644 index c8e74328..00000000 --- a/solutions/1872-stone-game-viii.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1872. Stone Game VIII - * https://leetcode.com/problems/stone-game-viii/ - * Difficulty: Hard - * - * Alice and Bob take turns playing a game, with Alice starting first. - * - * There are n stones arranged in a row. On each player's turn, while the number of stones is more - * than one, they will do the following: - * 1. Choose an integer x > 1, and remove the leftmost x stones from the row. - * 2. Add the sum of the removed stones' values to the player's score. - * 3. Place a new stone, whose value is equal to that sum, on the left side of the row. - * - * The game stops when only one stone is left in the row. - * - * The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to - * maximize the score difference, and Bob's goal is the minimize the score difference. - * - * Given an integer array stones of length n where stones[i] represents the value of the ith stone - * from the left, return the score difference between Alice and Bob if they both play optimally. - */ - -/** - * @param {number[]} stones - * @return {number} - */ -var stoneGameVIII = function(stones) { - const length = stones.length; - const prefixSums = new Array(length).fill(0); - prefixSums[0] = stones[0]; - - for (let i = 1; i < length; i++) { - prefixSums[i] = prefixSums[i - 1] + stones[i]; - } - - let result = prefixSums[length - 1]; - for (let i = length - 2; i >= 1; i--) { - result = Math.max(result, prefixSums[i] - result); - } - - return result; -}; diff --git a/solutions/1876-substrings-of-size-three-with-distinct-characters.js b/solutions/1876-substrings-of-size-three-with-distinct-characters.js deleted file mode 100644 index cbe56e47..00000000 --- a/solutions/1876-substrings-of-size-three-with-distinct-characters.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1876. Substrings of Size Three with Distinct Characters - * https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/ - * Difficulty: Easy - * - * A string is good if there are no repeated characters. - * - * Given a string s, return the number of good substrings of length three in s. - * - * Note that if there are multiple occurrences of the same substring, every occurrence should - * be counted. - * - * A substring is a contiguous sequence of characters in a string. - */ - -/** - * @param {string} s - * @return {number} - */ -var countGoodSubstrings = function(s) { - if (s.length < 3) return 0; - - let result = 0; - const charCount = new Map(); - - for (let i = 0; i < 3; i++) { - charCount.set(s[i], (charCount.get(s[i]) || 0) + 1); - } - if (charCount.size === 3) result++; - - for (let i = 3; i < s.length; i++) { - const oldChar = s[i - 3]; - charCount.set(oldChar, charCount.get(oldChar) - 1); - if (charCount.get(oldChar) === 0) charCount.delete(oldChar); - - charCount.set(s[i], (charCount.get(s[i]) || 0) + 1); - if (charCount.size === 3) result++; - } - - return result; -}; diff --git a/solutions/1877-minimize-maximum-pair-sum-in-array.js b/solutions/1877-minimize-maximum-pair-sum-in-array.js deleted file mode 100644 index 264d9569..00000000 --- a/solutions/1877-minimize-maximum-pair-sum-in-array.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1877. Minimize Maximum Pair Sum in Array - * https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/ - * Difficulty: Medium - * - * The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum - * in a list of pairs. - * - For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be - * max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. - * - * Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: - * - Each element of nums is in exactly one pair, and - * - The maximum pair sum is minimized. - * - * Return the minimized maximum pair sum after optimally pairing up the elements. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minPairSum = function(nums) { - nums.sort((a, b) => a - b); - let result = 0; - let left = 0; - let right = nums.length - 1; - - while (left < right) { - result = Math.max(result, nums[left] + nums[right]); - left++; - right--; - } - - return result; -}; diff --git a/solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js b/solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js deleted file mode 100644 index f10c1b56..00000000 --- a/solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1878. Get Biggest Three Rhombus Sums in a Grid - * https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/ - * Difficulty: Medium - * - * You are given an m x n integer matrix grid. - * - * A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in - * grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners - * centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding - * colored cells that should be included in each rhombus sum. - * - * Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the - * bottom right corner. - * - * Return the biggest three distinct rhombus sums in the grid in descending order. If there are - * less than three distinct values, return all of them. - */ - -/** - * @param {number[][]} grid - * @return {number[]} - */ -var getBiggestThree = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const sums = new Set(); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - sums.add(grid[i][j]); - for (let size = 1; size <= Math.min(i, rows - 1 - i, j, cols - 1 - j); size++) { - let rhombusSum = 0; - rhombusSum += grid[i - size][j] + grid[i + size][j] + grid[i][j - size] + grid[i][j + size]; - for (let offset = 1; offset < size; offset++) { - rhombusSum += grid[i - size + offset][j + offset] + grid[i + size - offset][j + offset]; - rhombusSum += grid[i - size + offset][j - offset] + grid[i + size - offset][j - offset]; - } - sums.add(rhombusSum); - } - } - } - - const sortedSums = [...sums].sort((a, b) => b - a); - return sortedSums.slice(0, Math.min(3, sortedSums.length)); -}; diff --git a/solutions/1879-minimum-xor-sum-of-two-arrays.js b/solutions/1879-minimum-xor-sum-of-two-arrays.js deleted file mode 100644 index 2f7c4f61..00000000 --- a/solutions/1879-minimum-xor-sum-of-two-arrays.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1879. Minimum XOR Sum of Two Arrays - * https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/ - * Difficulty: Hard - * - * You are given two integer arrays nums1 and nums2 of length n. - * - * The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) - * + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). - * - For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + - * (3 XOR 1) = 2 + 0 + 2 = 4. - * - * Rearrange the elements of nums2 such that the resulting XOR sum is minimized. - * - * Return the XOR sum after the rearrangement. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var minimumXORSum = function(nums1, nums2) { - const n = nums1.length; - const dp = new Array(1 << n).fill(Infinity); - dp[0] = 0; - - for (let mask = 0; mask < (1 << n); mask++) { - const usedCount = mask.toString(2).split('1').length - 1; - for (let j = 0; j < n; j++) { - if (!(mask & (1 << j))) { - const newMask = mask | (1 << j); - dp[newMask] = Math.min(dp[newMask], dp[mask] + (nums1[usedCount] ^ nums2[j])); - } - } - } - - return dp[(1 << n) - 1]; -}; diff --git a/solutions/1881-maximum-value-after-insertion.js b/solutions/1881-maximum-value-after-insertion.js deleted file mode 100644 index 4ba804d7..00000000 --- a/solutions/1881-maximum-value-after-insertion.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 1881. Maximum Value after Insertion - * https://leetcode.com/problems/maximum-value-after-insertion/ - * Difficulty: Medium - * - * You are given a very large integer n, represented as a string, and an integer digit x. - * The digits in n and the digit x are in the inclusive range [1, 9], and n may represent - * a negative number. - * - * You want to maximize n's numerical value by inserting x anywhere in the decimal representation - * of n. You cannot insert x to the left of the negative sign. - * - For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making - * n = 763. - * - If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255. - * - * Return a string representing the maximum value of n after the insertion. - */ - -/** - * @param {string} n - * @param {number} x - * @return {string} - */ -var maxValue = function(n, x) { - const isNegative = n[0] === '-'; - const digits = n.slice(isNegative ? 1 : 0); - let result = ''; - - if (isNegative) { - for (let i = 0; i <= digits.length; i++) { - if (i === digits.length || x < parseInt(digits[i])) { - result = '-' + digits.slice(0, i) + x + digits.slice(i); - break; - } - } - } else { - for (let i = 0; i <= digits.length; i++) { - if (i === digits.length || x > parseInt(digits[i])) { - result = digits.slice(0, i) + x + digits.slice(i); - break; - } - } - } - - return result; -}; diff --git a/solutions/1882-process-tasks-using-servers.js b/solutions/1882-process-tasks-using-servers.js deleted file mode 100644 index e82ad99f..00000000 --- a/solutions/1882-process-tasks-using-servers.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1882. Process Tasks Using Servers - * https://leetcode.com/problems/process-tasks-using-servers/ - * Difficulty: Medium - * - * You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. - * servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the - * jth task in seconds. - * - * Tasks are assigned to the servers using a task queue. Initially, all servers are free, and - * the queue is empty. - * - * At second j, the jth task is inserted into the queue (starting with the 0th task being inserted - * at second 0). As long as there are free servers and the queue is not empty, the task in the front - * of the queue will be assigned to a free server with the smallest weight, and in case of a tie, - * it is assigned to a free server with the smallest index. - * - * If there are no free servers and the queue is not empty, we wait until a server becomes free - * and immediately assign the next task. If multiple servers become free at the same time, then - * multiple tasks from the queue will be assigned in order of insertion following the weight and - * index priorities above. - * - * A server that is assigned task j at second t will be free again at second t + tasks[j]. - * - * Build an array ans of length m, where ans[j] is the index of the server the jth task will - * be assigned to. - * - * Return the array ans. - */ - -/** - * @param {number[]} servers - * @param {number[]} tasks - * @return {number[]} - */ -var assignTasks = function(servers, tasks) { - const serverHeap = new PriorityQueue((a, b) => a[0] * 1000000 + a[1] - (b[0] * 1000000 + b[1])); - const busyHeap = new PriorityQueue((a, b) => a[0] - b[0]); - const result = new Array(tasks.length); - - for (let i = 0; i < servers.length; i++) { - serverHeap.enqueue([servers[i], i]); - } - - let time = 0; - let taskIndex = 0; - - while (taskIndex < tasks.length) { - time = Math.max(time, taskIndex); - - while (!busyHeap.isEmpty() && busyHeap.front()[0] <= time) { - const [, weight, index] = busyHeap.dequeue(); - serverHeap.enqueue([weight, index]); - } - - while (serverHeap.size() && taskIndex < tasks.length && taskIndex <= time) { - const [weight, index] = serverHeap.dequeue(); - result[taskIndex] = index; - busyHeap.enqueue([time + tasks[taskIndex], weight, index]); - taskIndex++; - } - - if (serverHeap.isEmpty() && taskIndex < tasks.length) { - const [freeTime, weight, index] = busyHeap.dequeue(); - time = freeTime; - serverHeap.enqueue([weight, index]); - } - } - - return result; -}; diff --git a/solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js b/solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js deleted file mode 100644 index 23d83b18..00000000 --- a/solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1883. Minimum Skips to Arrive at Meeting On Time - * https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/ - * Difficulty: Hard - * - * You are given an integer hoursBefore, the number of hours you have to travel to your meeting. - * To arrive at your meeting, you have to travel through n roads. The road lengths are given as - * an integer array dist of length n, where dist[i] describes the length of the ith road in - * kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you - * will travel at. - * - * After you travel road i, you must rest and wait for the next integer hour before you can begin - * traveling on the next road. Note that you do not have to rest after traveling the last road - * because you are already at the meeting. - * - For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before - * traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait. - * - * However, you are allowed to skip some rests to be able to arrive on time, meaning you do not - * need to wait for the next integer hour. Note that this means you may finish traveling future - * roads at different hour marks. - * - For example, suppose traveling the first road takes 1.4 hours and traveling the second road - * takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the - * second road right at the 2 hour mark, letting you start traveling the third road immediately. - * - * Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is - * impossible. - */ - -/** - * @param {number[]} dist - * @param {number} speed - * @param {number} hoursBefore - * @return {number} - */ -var minSkips = function(dist, speed, hoursBefore) { - const n = dist.length; - const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(Infinity)); - dp[0][0] = 0; - - for (let i = 1; i <= n; i++) { - for (let skips = 0; skips <= i; skips++) { - if (skips < i) { - const prevTime = dp[i - 1][skips]; - if (prevTime !== Infinity) { - const time = prevTime + dist[i - 1]; - dp[i][skips] = Math.min(dp[i][skips], Math.ceil(time / speed) * speed); - } - } - if (skips > 0) { - const prevTime = dp[i - 1][skips - 1]; - if (prevTime !== Infinity) { - dp[i][skips] = Math.min(dp[i][skips], prevTime + dist[i - 1]); - } - } - } - } - - const targetTime = hoursBefore * speed; - for (let skips = 0; skips <= n; skips++) { - if (dp[n][skips] <= targetTime) { - return skips; - } - } - - return -1; -}; diff --git a/solutions/1884-egg-drop-with-2-eggs-and-n-floors.js b/solutions/1884-egg-drop-with-2-eggs-and-n-floors.js deleted file mode 100644 index 4b5ccb3f..00000000 --- a/solutions/1884-egg-drop-with-2-eggs-and-n-floors.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1884. Egg Drop With 2 Eggs and N Floors - * https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/ - * Difficulty: Medium - * - * You are given two identical eggs and you have access to a building with n floors labeled - * from 1 to n. - * - * You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor - * higher than f will break, and any egg dropped at or below floor f will not break. - * - * In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). - * If the egg breaks, you can no longer use it. However, if the egg does not break, you may - * reuse it in future moves. - * - * Return the minimum number of moves that you need to determine with certainty what the value - * of f is. - */ - -/** - * @param {number} n - * @return {number} - */ -var twoEggDrop = function(n) { - const dp = Array.from({ length: 3 }, () => new Array(n + 1).fill(Infinity)); - dp[0][0] = 0; - dp[1][0] = 0; - dp[2][0] = 0; - - for (let floors = 1; floors <= n; floors++) { - dp[1][floors] = floors; - for (let eggs = 2; eggs <= 2; eggs++) { - for (let k = 1; k <= floors; k++) { - const breaks = dp[eggs - 1][k - 1]; - const survives = dp[eggs][floors - k]; - dp[eggs][floors] = Math.min(dp[eggs][floors], 1 + Math.max(breaks, survives)); - } - } - } - - return dp[2][n]; -}; diff --git a/solutions/1887-reduction-operations-to-make-the-array-elements-equal.js b/solutions/1887-reduction-operations-to-make-the-array-elements-equal.js deleted file mode 100644 index d6672d7b..00000000 --- a/solutions/1887-reduction-operations-to-make-the-array-elements-equal.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1887. Reduction Operations to Make the Array Elements Equal - * https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/ - * Difficulty: Medium - * - * Given an integer array nums, your goal is to make all elements in nums equal. To complete one - * operation, follow these steps: - * 1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. - * If there are multiple elements with the largest value, pick the smallest i. - * 2. Find the next largest value in nums strictly smaller than largest. Let its value be - * nextLargest. - * 3. Reduce nums[i] to nextLargest. - * - * Return the number of operations to make all elements in nums equal. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var reductionOperations = function(nums) { - nums.sort((a, b) => a - b); - let result = 0; - let count = 0; - - for (let i = 1; i < nums.length; i++) { - if (nums[i] !== nums[i - 1]) { - count++; - } - result += count; - } - - return result; -}; diff --git a/solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js b/solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js deleted file mode 100644 index 24795a9f..00000000 --- a/solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1888. Minimum Number of Flips to Make the Binary String Alternating - * https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/ - * Difficulty: Medium - * - * You are given a binary string s. You are allowed to perform two types of operations on the - * string in any sequence: - * - Type-1: Remove the character at the start of the string s and append it to the end of - * the string. - * - Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes - * '1' and vice-versa. - * - * Return the minimum number of type-2 operations you need to perform such that s becomes - * alternating. - * - * The string is called alternating if no two adjacent characters are equal. - * - * For example, the strings "010" and "1010" are alternating, while the string "0100" is not. - */ - -/** - * @param {string} s - * @return {number} - */ -var minFlips = function(s) { - const n = s.length; - let result = n; - let flipsZeroStart = 0; - let flipsOneStart = 0; - - for (let i = 0; i < n; i++) { - if (s[i] !== (i % 2 === 0 ? '0' : '1')) flipsZeroStart++; - if (s[i] !== (i % 2 === 0 ? '1' : '0')) flipsOneStart++; - } - - result = Math.min(flipsZeroStart, flipsOneStart); - - for (let i = 0; i < n - 1; i++) { - if (s[i] !== (i % 2 === 0 ? '0' : '1')) flipsZeroStart--; - if (s[i] !== (i % 2 === 0 ? '1' : '0')) flipsOneStart--; - if (s[i] !== ((n + i) % 2 === 0 ? '0' : '1')) flipsZeroStart++; - if (s[i] !== ((n + i) % 2 === 0 ? '1' : '0')) flipsOneStart++; - result = Math.min(result, flipsZeroStart, flipsOneStart); - } - - return result; -}; diff --git a/solutions/1889-minimum-space-wasted-from-packaging.js b/solutions/1889-minimum-space-wasted-from-packaging.js deleted file mode 100644 index de010d0f..00000000 --- a/solutions/1889-minimum-space-wasted-from-packaging.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * 1889. Minimum Space Wasted From Packaging - * https://leetcode.com/problems/minimum-space-wasted-from-packaging/ - * Difficulty: Hard - * - * You have n packages that you are trying to place in boxes, one package in each box. There are - * m suppliers that each produce boxes of different sizes (with infinite supply). A package can - * be placed in a box if the size of the package is less than or equal to the size of the box. - * - * The package sizes are given as an integer array packages, where packages[i] is the size of the - * ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array - * of box sizes that the jth supplier produces. - * - * You want to choose a single supplier and use boxes from them such that the total wasted space - * is minimized. For each package in a box, we define the space wasted to be size of the box - size - * of the package. The total wasted space is the sum of the space wasted in all the boxes. - * - For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of - * sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the - * package with size-5 into a box of size-8. This would result in a waste - * of (4-2) + (4-3) + (8-5) = 6. - * - * Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is - * impossible to fit all the packages inside boxes. Since the answer may be large, return it - * modulo 109 + 7. - */ - -/** - * @param {number[]} packages - * @param {number[][]} boxes - * @return {number} - */ -var minWastedSpace = function(packages, boxes) { - const modulo = 1e9 + 7; - packages.sort((a, b) => a - b); - let minWaste = BigInt(2) ** BigInt(60); - const n = packages.length; - - const prefixSums = new Array(n + 1).fill(BigInt(0)); - for (let i = 0; i < n; i++) { - prefixSums[i + 1] = prefixSums[i] + BigInt(packages[i]); - } - - for (const supplier of boxes) { - supplier.sort((a, b) => a - b); - if (supplier[supplier.length - 1] < packages[n - 1]) continue; - - let waste = BigInt(0); - let packageIndex = 0; - - for (const box of supplier) { - if (packageIndex >= n) break; - const upperBound = binarySearch(packages, box, packageIndex); - if (upperBound > packageIndex) { - const count = BigInt(upperBound - packageIndex); - waste += count * BigInt(box) - (prefixSums[upperBound] - prefixSums[packageIndex]); - packageIndex = upperBound; - } - } - - if (packageIndex === n) { - minWaste = minWaste < waste ? minWaste : waste; - } - } - - return minWaste === BigInt(2) ** BigInt(60) ? -1 : Number(minWaste % BigInt(modulo)); -}; - -function binarySearch(arr, target, start) { - let left = start; - let right = arr.length; - - while (left < right) { - const mid = (left + right) >> 1; - if (arr[mid] <= target) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; -} diff --git a/solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js b/solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js deleted file mode 100644 index def56b8c..00000000 --- a/solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1893. Check if All the Integers in a Range Are Covered - * https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/ - * Difficulty: Easy - * - * You are given a 2D integer array ranges and two integers left and right. Each - * ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. - * - * Return true if each integer in the inclusive range [left, right] is covered by at least - * one interval in ranges. Return false otherwise. - * - * An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. - */ - -/** - * @param {number[][]} ranges - * @param {number} left - * @param {number} right - * @return {boolean} - */ -var isCovered = function(ranges, left, right) { - const covered = new Array(51).fill(false); - - for (const [start, end] of ranges) { - for (let i = start; i <= end; i++) { - covered[i] = true; - } - } - - for (let i = left; i <= right; i++) { - if (!covered[i]) return false; - } - - return true; -}; diff --git a/solutions/1894-find-the-student-that-will-replace-the-chalk.js b/solutions/1894-find-the-student-that-will-replace-the-chalk.js deleted file mode 100644 index 387fd854..00000000 --- a/solutions/1894-find-the-student-that-will-replace-the-chalk.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 1894. Find the Student that Will Replace the Chalk - * https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/ - * Difficulty: Medium - * - * There are n students in a class numbered from 0 to n - 1. The teacher will give each student - * a problem starting with the student number 0, then the student number 1, and so on until the - * teacher reaches the student number n - 1. After that, the teacher will restart the process, - * starting with the student number 0 again. - * - * You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces - * of chalk. When the student number i is given a problem to solve, they will use chalk[i] - * pieces of chalk to solve that problem. However, if the current number of chalk pieces is - * strictly less than chalk[i], then the student number i will be asked to replace the chalk. - * - * Return the index of the student that will replace the chalk pieces. - */ - -/** - * @param {number[]} chalk - * @param {number} k - * @return {number} - */ -var chalkReplacer = function(chalk, k) { - let totalChalk = 0; - for (const amount of chalk) { - totalChalk += amount; - } - - k = k % totalChalk; - - for (let i = 0; i < chalk.length; i++) { - if (k < chalk[i]) return i; - k -= chalk[i]; - } - - return 0; -}; diff --git a/solutions/1895-largest-magic-square.js b/solutions/1895-largest-magic-square.js deleted file mode 100644 index e23a71cc..00000000 --- a/solutions/1895-largest-magic-square.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1895. Largest Magic Square - * https://leetcode.com/problems/largest-magic-square/ - * Difficulty: Medium - * - * A k x k magic square is a k x k grid filled with integers such that every row sum, every - * column sum, and both diagonal sums are all equal. The integers in the magic square do not - * have to be distinct. Every 1 x 1 grid is trivially a magic square. - * - * Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic - * square that can be found within this grid. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var largestMagicSquare = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - const rowSums = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0)); - const colSums = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0)); - - for (let i = 1; i <= rows; i++) { - for (let j = 1; j <= cols; j++) { - rowSums[i][j] = rowSums[i][j - 1] + grid[i - 1][j - 1]; - colSums[i][j] = colSums[i - 1][j] + grid[i - 1][j - 1]; - } - } - - const maxSize = 1; - for (let size = Math.min(rows, cols); size >= 2; size--) { - for (let i = size; i <= rows; i++) { - for (let j = size; j <= cols; j++) { - const rowSum = rowSums[i][j] - rowSums[i][j - size]; - let isMagic = true; - - for (let k = 1; k < size; k++) { - if (rowSums[i - k][j] - rowSums[i - k][j - size] !== rowSum) { - isMagic = false; - break; - } - } - - if (!isMagic) continue; - - for (let k = 0; k < size; k++) { - if (colSums[i][j - k] - colSums[i - size][j - k] !== rowSum) { - isMagic = false; - break; - } - } - - if (!isMagic) continue; - - let diagSum1 = 0; - let diagSum2 = 0; - for (let k = 0; k < size; k++) { - diagSum1 += grid[i - size + k][j - size + k]; - diagSum2 += grid[i - size + k][j - 1 - k]; - } - - if (diagSum1 === rowSum && diagSum2 === rowSum) { - return size; - } - } - } - } - - return maxSize; -}; diff --git a/solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js b/solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js deleted file mode 100644 index 1e430149..00000000 --- a/solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * 1896. Minimum Cost to Change the Final Value of Expression - * https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression/ - * Difficulty: Hard - * - * You are given a valid boolean expression as a string expression consisting of the - * characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. - * - For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" - * are valid expressions. - * - * Return the minimum cost to change the final value of the expression. - * - For example, if expression = "1|1|(0&0)&1", its value is - * 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new - * expression evaluates to 0. - * - * The cost of changing the final value of an expression is the number of operations performed - * on the expression. The types of operations are described as follows: - * - Turn a '1' into a '0'. - * - Turn a '0' into a '1'. - * - Turn a '&' into a '|'. - * - Turn a '|' into a '&'. - * - * Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses - * first, then in left-to-right order. - */ - -/** - * @param {string} expression - * @return {number} - */ -var minOperationsToFlip = function(expression) { - const stack = []; - for (const char of expression) { - if (char === ')') { - const values = []; - while (stack.length && stack[stack.length - 1][0] !== '(') { - values.push(stack.pop()); - } - stack.pop(); - let [val1, cost1] = values.pop(); - while (values.length) { - const [op] = values.pop(); - const [val2, cost2] = values.pop(); - if (op === '&') { - if (val1 === 1 && val2 === 1) { - val1 = 1; - cost1 = Math.min(cost1, cost2); - } else if (val1 === 0 && val2 === 0) { - val1 = 0; - cost1 = Math.min(cost1 + 1, cost2 + 1); - } else { - val1 = 0; - cost1 = Math.min(cost1 + cost2, 1); - } - } else { - if (val1 === 1 && val2 === 1) { - val1 = 1; - cost1 = Math.min(cost1 + 1, cost2 + 1); - } else if (val1 === 0 && val2 === 0) { - val1 = 0; - cost1 = Math.min(cost1, cost2); - } else { - val1 = 1; - cost1 = Math.min(cost1 + cost2, 1); - } - } - } - stack.push([val1, cost1]); - } else if (char === '1') { - stack.push([1, 1]); - } else if (char === '0') { - stack.push([0, 1]); - } else { - stack.push([char]); - } - } - - const values = []; - while (stack.length) { - values.push(stack.pop()); - } - - let [val1, cost1] = values.pop(); - while (values.length) { - const [op] = values.pop(); - const [val2, cost2] = values.pop(); - if (op === '&') { - if (val1 === 1 && val2 === 1) { - val1 = 1; - cost1 = Math.min(cost1, cost2); - } else if (val1 === 0 && val2 === 0) { - val1 = 0; - cost1 = Math.min(cost1 + 1, cost2 + 1); - } else { - val1 = 0; - cost1 = Math.min(cost1 + cost2, 1); - } - } else { - if (val1 === 1 && val2 === 1) { - val1 = 1; - cost1 = Math.min(cost1 + 1, cost2 + 1); - } else if (val1 === 0 && val2 === 0) { - val1 = 0; - cost1 = Math.min(cost1, cost2); - } else { - val1 = 1; - cost1 = Math.min(cost1 + cost2, 1); - } - } - } - - return cost1; -}; diff --git a/solutions/1897-redistribute-characters-to-make-all-strings-equal.js b/solutions/1897-redistribute-characters-to-make-all-strings-equal.js deleted file mode 100644 index b58b05ba..00000000 --- a/solutions/1897-redistribute-characters-to-make-all-strings-equal.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1897. Redistribute Characters to Make All Strings Equal - * https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/ - * Difficulty: Easy - * - * You are given an array of strings words (0-indexed). - * - * In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, - * and move any character from words[i] to any position in words[j]. - * - * Return true if you can make every string in words equal using any number of operations, and - * false otherwise. - */ - -/** - * @param {string[]} words - * @return {boolean} - */ -var makeEqual = function(words) { - const charCount = new Array(26).fill(0); - const wordCount = words.length; - - for (const word of words) { - for (const char of word) { - charCount[char.charCodeAt(0) - 97]++; - } - } - - for (const count of charCount) { - if (count % wordCount !== 0) return false; - } - - return true; -}; diff --git a/solutions/1898-maximum-number-of-removable-characters.js b/solutions/1898-maximum-number-of-removable-characters.js deleted file mode 100644 index 1a4c15fa..00000000 --- a/solutions/1898-maximum-number-of-removable-characters.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1898. Maximum Number of Removable Characters - * https://leetcode.com/problems/maximum-number-of-removable-characters/ - * Difficulty: Medium - * - * You are given two strings s and p where p is a subsequence of s. You are also given a distinct - * 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). - * - * You want to choose an integer k (0 <= k <= removable.length) such that, after removing k - * characters from s using the first k indices in removable, p is still a subsequence of s. - * More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then - * remove all marked characters and check if p is still a subsequence. - * - * Return the maximum k you can choose such that p is still a subsequence of s after the removals. - * - * A subsequence of a string is a new string generated from the original string with some - * characters (can be none) deleted without changing the relative order of the remaining characters. - */ - -/** - * @param {string} s - * @param {string} p - * @param {number[]} removable - * @return {number} - */ -var maximumRemovals = function(s, p, removable) { - let left = 0; - let right = removable.length; - - while (left <= right) { - const mid = (left + right) >> 1; - const removed = new Set(removable.slice(0, mid)); - let i = 0; - let j = 0; - - while (i < s.length && j < p.length) { - if (!removed.has(i) && s[i] === p[j]) { - j++; - } - i++; - } - - if (j === p.length) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return right; -}; diff --git a/solutions/1899-merge-triplets-to-form-target-triplet.js b/solutions/1899-merge-triplets-to-form-target-triplet.js deleted file mode 100644 index 606dacf4..00000000 --- a/solutions/1899-merge-triplets-to-form-target-triplet.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 1899. Merge Triplets to Form Target Triplet - * https://leetcode.com/problems/merge-triplets-to-form-target-triplet/ - * Difficulty: Medium - * - * A triplet is an array of three integers. You are given a 2D integer array triplets, where - * triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array - * target = [x, y, z] that describes the triplet you want to obtain. - * - * To obtain target, you may apply the following operation on triplets any number of times - * (possibly zero): - * - Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become - * [max(ai, aj), max(bi, bj), max(ci, cj)]. - * - For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will - * be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. - * - * Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, - * or false otherwise. - */ - -/** - * @param {number[][]} triplets - * @param {number[]} target - * @return {boolean} - */ -var mergeTriplets = function(triplets, target) { - let canFormX = false; - let canFormY = false; - let canFormZ = false; - - for (const [a, b, c] of triplets) { - if (a <= target[0] && b <= target[1] && c <= target[2]) { - if (a === target[0]) canFormX = true; - if (b === target[1]) canFormY = true; - if (c === target[2]) canFormZ = true; - } - } - - return canFormX && canFormY && canFormZ; -}; diff --git a/solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js b/solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js deleted file mode 100644 index 47d9293b..00000000 --- a/solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * 1900. The Earliest and Latest Rounds Where Players Compete - * https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete/ - * Difficulty: Hard - * - * There is a tournament where n players are participating. The players are standing in a single row - * and are numbered from 1 to n based on their initial standing position (player 1 is the first - * player in the row, player 2 is the second player in the row, etc.). - * - * The tournament consists of multiple rounds (starting from round number 1). In each round, the ith - * player from the front of the row competes against the ith player from the end of the row, and the - * winner advances to the next round. When the number of players is odd for the current round, the - * player in the middle automatically advances to the next round. - * - For example, if the row consists of players 1, 2, 4, 6, 7 - * - Player 1 competes against player 7. - * - Player 2 competes against player 6. - * - Player 4 automatically advances to the next round. - * - * After each round is over, the winners are lined back up in the row based on the original ordering - * assigned to them initially (ascending order). - * - * The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win - * against any other player before they compete against each other. If any two other players compete - * against each other, either of them might win, and thus you may choose the outcome of this round. - * - * Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two - * values, the earliest possible round number and the latest possible round number in which these - * two players will compete against each other, respectively. - */ - -/** - * @param {number} n - * @param {number} firstPlayer - * @param {number} secondPlayer - * @return {number[]} - */ -var earliestAndLatest = function(numPlayers, firstPlayer, secondPlayer) { - let minRounds = Infinity; - let maxRounds = 0; - - dfs(0, 1); - - return [minRounds, maxRounds]; - - function dfs(playersEliminated, numRounds) { - let roundResults = [playersEliminated]; - let i = 1; - let j = numPlayers; - - while (true) { - while (playersEliminated & (1 << i)) i++; - while (playersEliminated & (1 << j)) j--; - - if (i >= j) break; - - if (i === firstPlayer && j === secondPlayer) { - minRounds = Math.min(minRounds, numRounds); - maxRounds = Math.max(maxRounds, numRounds); - return; - } - - const newRoundResults = []; - - if (j !== firstPlayer && j !== secondPlayer) { - for (const roundResult of roundResults) { - newRoundResults.push(roundResult | (1 << j)); - } - } - - if (i !== firstPlayer && i !== secondPlayer) { - for (const roundResult of roundResults) { - newRoundResults.push(roundResult | (1 << i)); - } - } - - i++; - j--; - roundResults = newRoundResults; - } - - if (!roundResults.length) return; - - numRounds++; - roundResults.forEach(roundResult => dfs(roundResult, numRounds)); - } -}; diff --git a/solutions/1901-find-a-peak-element-ii.js b/solutions/1901-find-a-peak-element-ii.js deleted file mode 100644 index fc0a48ca..00000000 --- a/solutions/1901-find-a-peak-element-ii.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 1901. Find a Peak Element II - * https://leetcode.com/problems/find-a-peak-element-ii/ - * Difficulty: Medium - * - * A peak element in a 2D grid is an element that is strictly greater than all of its adjacent - * neighbors to the left, right, top, and bottom. - * - * Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element - * mat[i][j] and return the length 2 array [i,j]. - * - * You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in - * each cell. - * - * You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time. - */ - -/** - * @param {number[][]} mat - * @return {number[]} - */ -var findPeakGrid = function(mat) { - const rows = mat.length; - const cols = mat[0].length; - - return binarySearch(0, rows - 1); - - function getMaxIndexInRow(row, left, right) { - let maxIndex = left; - for (let i = left; i <= right; i++) { - if (mat[row][i] > mat[row][maxIndex]) { - maxIndex = i; - } - } - return maxIndex; - } - - function binarySearch(startRow, endRow) { - if (startRow > endRow) return null; - - const midRow = Math.floor((startRow + endRow) / 2); - const maxCol = getMaxIndexInRow(midRow, 0, cols - 1); - const maxValue = mat[midRow][maxCol]; - - const topValue = midRow > 0 ? mat[midRow - 1][maxCol] : -1; - const bottomValue = midRow < rows - 1 ? mat[midRow + 1][maxCol] : -1; - const leftValue = maxCol > 0 ? mat[midRow][maxCol - 1] : -1; - const rightValue = maxCol < cols - 1 ? mat[midRow][maxCol + 1] : -1; - - if (maxValue > topValue && maxValue > bottomValue - && maxValue > leftValue && maxValue > rightValue) { - return [midRow, maxCol]; - } - - if (midRow > 0 && topValue > maxValue) { - return binarySearch(startRow, midRow - 1); - } - - return binarySearch(midRow + 1, endRow); - } -}; diff --git a/solutions/1903-largest-odd-number-in-string.js b/solutions/1903-largest-odd-number-in-string.js deleted file mode 100644 index 9914883e..00000000 --- a/solutions/1903-largest-odd-number-in-string.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1903. Largest Odd Number in String - * https://leetcode.com/problems/largest-odd-number-in-string/ - * Difficulty: Easy - * - * You are given a string num, representing a large integer. Return the largest-valued odd - * integer (as a string) that is a non-empty substring of num, or an empty string "" if no - * odd integer exists. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string} num - * @return {string} - */ -var largestOddNumber = function(num) { - for (let i = num.length - 1; i >= 0; i--) { - if (parseInt(num[i]) % 2 === 1) { - return num.slice(0, i + 1); - } - } - return ''; -}; diff --git a/solutions/1904-the-number-of-full-rounds-you-have-played.js b/solutions/1904-the-number-of-full-rounds-you-have-played.js deleted file mode 100644 index 4c7ad2d6..00000000 --- a/solutions/1904-the-number-of-full-rounds-you-have-played.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1904. The Number of Full Rounds You Have Played - * https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/ - * Difficulty: Medium - * - * You are participating in an online chess tournament. There is a chess round that starts - * every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, - * a new round starts. - * - For example, the second round starts at 00:15, the fourth round starts at 00:45, and the - * seventh round starts at 01:30. - * - * You are given two strings loginTime and logoutTime where: - * - loginTime is the time you will login to the game, and - * - logoutTime is the time you will logout from the game. - * - * If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight - * and from midnight to logoutTime. - * - * Return the number of full chess rounds you have played in the tournament. - * - * Note: All the given times follow the 24-hour clock. That means the first round of the day starts - * at 00:00 and the last round of the day starts at 23:45. - */ - -/** - * @param {string} loginTime - * @param {string} logoutTime - * @return {number} - */ -var numberOfRounds = function(loginTime, logoutTime) { - let start = toMinutes(loginTime); - let end = toMinutes(logoutTime); - - if (end < start) { - end += 24 * 60; - } - - start = Math.ceil(start / 15); - end = Math.floor(end / 15); - - return Math.max(0, end - start); - - function toMinutes(time) { - const [hours, minutes] = time.split(':').map(Number); - return hours * 60 + minutes; - } -}; diff --git a/solutions/1905-count-sub-islands.js b/solutions/1905-count-sub-islands.js deleted file mode 100644 index d6cf98c8..00000000 --- a/solutions/1905-count-sub-islands.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 1905. Count Sub Islands - * https://leetcode.com/problems/count-sub-islands/ - * Difficulty: Medium - * - * You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) - * and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal - * or vertical). Any cells outside of the grid are considered water cells. - * - * An island in grid2 is considered a sub-island if there is an island in grid1 that contains all - * the cells that make up this island in grid2. - * - * Return the number of islands in grid2 that are considered sub-islands. - */ - -/** - * @param {number[][]} grid1 - * @param {number[][]} grid2 - * @return {number} - */ -var countSubIslands = function(grid1, grid2) { - const rows = grid1.length; - const cols = grid1[0].length; - let result = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid2[i][j] === 1 && isValidSubIsland(i, j)) { - result++; - } - } - } - - return result; - - function isValidSubIsland(row, col) { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid2[row][col] === 0) { - return true; - } - - grid2[row][col] = 0; - let isSubIsland = grid1[row][col] === 1; - - isSubIsland &= isValidSubIsland(row - 1, col); - isSubIsland &= isValidSubIsland(row + 1, col); - isSubIsland &= isValidSubIsland(row, col - 1); - isSubIsland &= isValidSubIsland(row, col + 1); - - return isSubIsland; - } -}; diff --git a/solutions/1906-minimum-absolute-difference-queries.js b/solutions/1906-minimum-absolute-difference-queries.js deleted file mode 100644 index 62cfc15f..00000000 --- a/solutions/1906-minimum-absolute-difference-queries.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 1906. Minimum Absolute Difference Queries - * https://leetcode.com/problems/minimum-absolute-difference-queries/ - * Difficulty: Medium - * - * The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, - * where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum - * absolute difference is -1. - * - For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note - * that it is not 0 because a[i] and a[j] must be different. - * - * You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each - * query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the - * elements of nums between the 0-based indices li and ri (inclusive). - * - * Return an array ans where ans[i] is the answer to the ith query. - * - * A subarray is a contiguous sequence of elements in an array. - * - * The value of |x| is defined as: - * - x if x >= 0. - * - -x if x < 0. - */ - -/** - * @param {number[]} nums - * @param {number[][]} queries - * @return {number[]} - */ -var minDifference = function(nums, queries) { - const maxValue = 100; - const prefixCounts = new Array(nums.length + 1).fill().map(() => new Array(maxValue + 1).fill(0)); - - for (let i = 0; i < nums.length; i++) { - for (let j = 1; j <= maxValue; j++) { - prefixCounts[i + 1][j] = prefixCounts[i][j] + (nums[i] === j ? 1 : 0); - } - } - - return queries.map(([start, end]) => getMinDiff(start, end)); - - function getMinDiff(start, end) { - let minDiff = Infinity; - let prevValue = -1; - - for (let j = 1; j <= maxValue; j++) { - if (prefixCounts[end + 1][j] - prefixCounts[start][j] > 0) { - if (prevValue !== -1) { - minDiff = Math.min(minDiff, j - prevValue); - } - prevValue = j; - } - } - - return minDiff === Infinity ? -1 : minDiff; - } -}; diff --git a/solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js b/solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js deleted file mode 100644 index 3e47a059..00000000 --- a/solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1909. Remove One Element to Make the Array Strictly Increasing - * https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/ - * Difficulty: Easy - * - * Given a 0-indexed integer array nums, return true if it can be made strictly increasing after - * removing exactly one element, or false otherwise. If the array is already strictly increasing, - * return true. - * - * The array nums is strictly increasing if nums[i - 1] < nums[i] for each index - * (1 <= i < nums.length). - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var canBeIncreasing = function(nums) { - for (let i = 0; i < nums.length; i++) { - if (isStrictlyIncreasing(nums, i)) return true; - } - - return false; - - function isStrictlyIncreasing(arr, skipIndex) { - for (let i = 1; i < arr.length; i++) { - if (i === skipIndex) continue; - const prev = i - 1 === skipIndex ? i - 2 : i - 1; - if (prev >= 0 && arr[i] <= arr[prev]) return false; - } - return true; - } -}; diff --git a/solutions/1911-maximum-alternating-subsequence-sum.js b/solutions/1911-maximum-alternating-subsequence-sum.js deleted file mode 100644 index cd33635e..00000000 --- a/solutions/1911-maximum-alternating-subsequence-sum.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1911. Maximum Alternating Subsequence Sum - * https://leetcode.com/problems/maximum-alternating-subsequence-sum/ - * Difficulty: Medium - * - * The alternating sum of a 0-indexed array is defined as the sum of the elements at even - * indices minus the sum of the elements at odd indices. - * - For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4. - * - * Given an array nums, return the maximum alternating sum of any subsequence of nums (after - * reindexing the elements of the subsequence). - * - * A subsequence of an array is a new array generated from the original array by deleting some - * elements (possibly none) without changing the remaining elements' relative order. For - * example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), - * while [2,4,2] is not. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxAlternatingSum = function(nums) { - let result = 0; - let oddSum = 0; - - for (const num of nums) { - const prevEven = result; - result = Math.max(result, oddSum + num); - oddSum = Math.max(oddSum, prevEven - num); - } - - return result; -}; diff --git a/solutions/1912-design-movie-rental-system.js b/solutions/1912-design-movie-rental-system.js deleted file mode 100644 index 8f07b991..00000000 --- a/solutions/1912-design-movie-rental-system.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * 1912. Design Movie Rental System - * https://leetcode.com/problems/design-movie-rental-system/ - * Difficulty: Hard - * - * You have a movie renting company consisting of n shops. You want to implement a renting system - * that supports searching for, booking, and returning movies. The system should also support - * generating a report of the currently rented movies. - * - * Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] - * indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. - * Each shop carries at most one copy of a movie moviei. - * - * The system should support the following functions: - * - Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops - * should be sorted by price in ascending order, and in case of a tie, the one with the smaller - * shopi should appear first. If there are less than 5 matching shops, then all of them should be - * returned. If no shop has an unrented copy, then an empty list should be returned. - * - Rent: Rents an unrented copy of a given movie from a given shop. - * - Drop: Drops off a previously rented copy of a given movie at a given shop. - * - Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res - * where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented - * from the shop shopj. The movies in res should be sorted by price in ascending order, and in - * case of a tie, the one with the smaller shopj should appear first, and if there is still tie, - * the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, - * then all of them should be returned. If no movies are currently being rented, then an empty - * list should be returned. - * - * Implement the MovieRentingSystem class: - * - MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n - * shops and the movies in entries. - * - List search(int movie) Returns a list of shops that have an unrented copy of the - * given movie as described above. - * - void rent(int shop, int movie) Rents the given movie from the given shop. - * - void drop(int shop, int movie) Drops off a previously rented movie at the given shop. - * - List> report() Returns a list of cheapest rented movies as described above. - * - * Note: The test cases will be generated such that rent will only be called if the shop has an - * unrented copy of the movie, and drop will only be called if the shop had previously rented out - * the movie. - */ - -/** - * @param {number} n - * @param {number[][]} entries - */ -var MovieRentingSystem = function(n, entries) { - this.shopMovies = new Map(); - this.movieShops = new Map(); - this.rented = new PriorityQueue((a, b) => { - if (a[2] !== b[2]) return a[2] - b[2]; - if (a[0] !== b[0]) return a[0] - b[0]; - return a[1] - b[1]; - }); - this.rentedLookup = new Map(); - - for (const [shop, movie, price] of entries) { - if (!this.shopMovies.has(shop)) { - this.shopMovies.set(shop, new Map()); - } - this.shopMovies.get(shop).set(movie, price); - - if (!this.movieShops.has(movie)) { - this.movieShops.set(movie, new PriorityQueue((a, b) => { - if (a[1] !== b[1]) return a[1] - b[1]; - return a[0] - b[0]; - })); - } - this.movieShops.get(movie).enqueue([shop, price]); - } -}; - -/** - * @param {number} movie - * @return {number[]} - */ -MovieRentingSystem.prototype.search = function(movie) { - if (!this.movieShops.has(movie)) return []; - - const queue = this.movieShops.get(movie); - const result = []; - const seen = new Set(); - - while (!queue.isEmpty() && result.length < 5) { - const [shop, price] = queue.dequeue(); - if (this.shopMovies.get(shop)?.has(movie) && !seen.has(shop)) { - result.push(shop); - seen.add(shop); - } - } - - for (const shop of result) { - queue.enqueue([shop, this.shopMovies.get(shop).get(movie)]); - } - - return result; -}; - -/** - * @param {number} shop - * @param {number} movie - * @return {void} - */ -MovieRentingSystem.prototype.rent = function(shop, movie) { - const price = this.shopMovies.get(shop).get(movie); - this.shopMovies.get(shop).delete(movie); - this.rented.enqueue([shop, movie, price]); - this.rentedLookup.set(`${shop}:${movie}`, price); -}; - -/** - * @param {number} shop - * @param {number} movie - * @return {void} - */ -MovieRentingSystem.prototype.drop = function(shop, movie) { - const price = this.rentedLookup.get(`${shop}:${movie}`); - this.rentedLookup.delete(`${shop}:${movie}`); - if (!this.shopMovies.get(shop).has(movie)) { - this.shopMovies.get(shop).set(movie, price); - this.movieShops.get(movie).enqueue([shop, price]); - } -}; - -/** - * @return {number[][]} - */ -MovieRentingSystem.prototype.report = function() { - const result = []; - const seen = new Set(); - - while (!this.rented.isEmpty() && result.length < 5) { - const [shop, movie, price] = this.rented.dequeue(); - const key = `${shop}:${movie}`; - if (this.rentedLookup.has(key) && !seen.has(key)) { - result.push([shop, movie]); - seen.add(key); - } - } - - for (const [shop, movie] of result) { - const price = this.rentedLookup.get(`${shop}:${movie}`); - this.rented.enqueue([shop, movie, price]); - } - - return result; -}; diff --git a/solutions/1913-maximum-product-difference-between-two-pairs.js b/solutions/1913-maximum-product-difference-between-two-pairs.js deleted file mode 100644 index 91e73220..00000000 --- a/solutions/1913-maximum-product-difference-between-two-pairs.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 1913. Maximum Product Difference Between Two Pairs - * https://leetcode.com/problems/maximum-product-difference-between-two-pairs/ - * Difficulty: Easy - * - * The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). - * - For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16. - * - * Given an integer array nums, choose four distinct indices w, x, y, and z such that the product - * difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. - * - * Return the maximum such product difference. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var maxProductDifference = function(nums) { - let max1 = 0; - let max2 = 0; - let min1 = Infinity; - let min2 = Infinity; - - for (const num of nums) { - if (num > max1) { - max2 = max1; - max1 = num; - } else if (num > max2) { - max2 = num; - } - - if (num < min1) { - min2 = min1; - min1 = num; - } else if (num < min2) { - min2 = num; - } - } - - return max1 * max2 - min1 * min2; -}; diff --git a/solutions/1914-cyclically-rotating-a-grid.js b/solutions/1914-cyclically-rotating-a-grid.js deleted file mode 100644 index 84724945..00000000 --- a/solutions/1914-cyclically-rotating-a-grid.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1914. Cyclically Rotating a Grid - * https://leetcode.com/problems/cyclically-rotating-a-grid/ - * Difficulty: Medium - * - * You are given an m x n integer matrix grid, where m and n are both even integers, and - * an integer k. - * - * The matrix is composed of several layers, which is shown in the below image, where each - * color is its own layer. - * - * A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. - * To cyclically rotate a layer once, each element in the layer will take the place of the - * adjacent element in the counter-clockwise direction. An example rotation is shown below. - */ - -/** - * @param {number[][]} grid - * @param {number} k - * @return {number[][]} - */ -var rotateGrid = function(grid, k) { - const rows = grid.length; - const cols = grid[0].length; - const result = grid.map(row => [...row]); - - for (let layer = 0; layer < Math.min(rows, cols) / 2; layer++) { - rotateLayer(layer, layer, rows - 1 - layer, cols - 1 - layer, k); - } - - return result; - - function rotateLayer(top, left, bottom, right, rotations) { - if (top >= bottom || left >= right) return; - - const perimeter = 2 * (bottom - top + right - left); - const effectiveRotations = rotations % perimeter; - if (effectiveRotations === 0) return; - - const elements = []; - for (let i = top; i <= bottom; i++) elements.push(grid[i][left]); - for (let j = left + 1; j <= right; j++) elements.push(grid[bottom][j]); - for (let i = bottom - 1; i >= top; i--) elements.push(grid[i][right]); - for (let j = right - 1; j > left; j--) elements.push(grid[top][j]); - - const offset = (perimeter - effectiveRotations) % perimeter; - let index = offset; - - for (let i = top; i <= bottom; i++) { - result[i][left] = elements[index % perimeter]; - index++; - } - for (let j = left + 1; j <= right; j++) { - result[bottom][j] = elements[index % perimeter]; - index++; - } - for (let i = bottom - 1; i >= top; i--) { - result[i][right] = elements[index % perimeter]; - index++; - } - for (let j = right - 1; j > left; j--) { - result[top][j] = elements[index % perimeter]; - index++; - } - } -}; diff --git a/solutions/1915-number-of-wonderful-substrings.js b/solutions/1915-number-of-wonderful-substrings.js deleted file mode 100644 index b9aaf680..00000000 --- a/solutions/1915-number-of-wonderful-substrings.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1915. Number of Wonderful Substrings - * https://leetcode.com/problems/number-of-wonderful-substrings/ - * Difficulty: Medium - * - * A wonderful string is a string where at most one letter appears an odd number of times. - * - For example, "ccjjc" and "abab" are wonderful, but "ab" is not. - * - * Given a string word that consists of the first ten lowercase English letters ('a' through - * 'j'), return the number of wonderful non-empty substrings in word. If the same substring - * appears multiple times in word, then count each occurrence separately. - * - * A substring is a contiguous sequence of characters in a string. - */ - -/** - * @param {string} word - * @return {number} - */ -var wonderfulSubstrings = function(word) { - let count = 0; - const freq = new Map([[0, 1]]); - let state = 0; - - for (const char of word) { - const bit = 1 << (char.charCodeAt(0) - 97); - state ^= bit; - - count += freq.get(state) || 0; - freq.set(state, (freq.get(state) || 0) + 1); - - for (let i = 0; i < 10; i++) { - const oddBit = state ^ (1 << i); - count += freq.get(oddBit) || 0; - } - } - - return count; -}; diff --git a/solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js b/solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js deleted file mode 100644 index 93f715af..00000000 --- a/solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 1916. Count Ways to Build Rooms in an Ant Colony - * https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/ - * Difficulty: Hard - * - * You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given - * the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] - * indicates that you must build room prevRoom[i] before building room i, and these two rooms - * must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan - * is given such that once all the rooms are built, every room will be reachable from room 0. - * - * You can only build one room at a time, and you can travel freely between rooms you have - * already built only if they are connected. You can choose to build any room as long as its - * previous room is already built. - * - * Return the number of different orders you can build all the rooms in. Since the answer may - * be large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} prevRoom - * @return {number} - */ -var waysToBuildRooms = function(prevRoom) { - const n = prevRoom.length; - const mod = 1e9 + 7; - const graph = Array(n).fill().map(() => []); - const factorial = Array(n + 1).fill(1n); - const invFactorial = Array(n + 1).fill(1n); - - for (let i = 1; i <= n; i++) { - factorial[i] = (factorial[i - 1] * BigInt(i)) % BigInt(mod); - } - - for (let i = 1; i <= n; i++) { - invFactorial[i] = modInverse(factorial[i], BigInt(mod)); - } - - for (let i = 1; i < n; i++) { - graph[prevRoom[i]].push(i); - } - - return Number(countSubtreeSizes(0)[1]); - - function countSubtreeSizes(node) { - let size = 1; - let result = 1n; - - for (const child of graph[node]) { - const [childSize, childResult] = countSubtreeSizes(child); - size += childSize; - result = (result * childResult * invFactorial[childSize]) % BigInt(mod); - } - - return [size, (result * factorial[size - 1]) % BigInt(mod)]; - } - - function modInverse(a, m) { - const m0 = m; - let q; - let x0 = 0n; - let x1 = 1n; - - while (a > 1n) { - q = a / m; - [a, m] = [m, a % m]; - [x0, x1] = [x1 - q * x0, x0]; - } - return x1 < 0n ? x1 + m0 : x1; - } -}; diff --git a/solutions/1921-eliminate-maximum-number-of-monsters.js b/solutions/1921-eliminate-maximum-number-of-monsters.js deleted file mode 100644 index e9f43cd1..00000000 --- a/solutions/1921-eliminate-maximum-number-of-monsters.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 1921. Eliminate Maximum Number of Monsters - * https://leetcode.com/problems/eliminate-maximum-number-of-monsters/ - * Difficulty: Medium - * - * You are playing a video game where you are defending your city from a group of n monsters. You - * are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in - * kilometers of the ith monster from the city. - * - * The monsters walk toward the city at a constant speed. The speed of each monster is given to - * you in an integer array speed of size n, where speed[i] is the speed of the ith monster in - * kilometers per minute. - * - * You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon - * takes one minute to charge. The weapon is fully charged at the very start. - * - * You lose when any monster reaches your city. If a monster reaches the city at the exact moment - * the weapon is fully charged, it counts as a loss, and the game ends before you can use your - * weapon. - * - * Return the maximum number of monsters that you can eliminate before you lose, or n if you can - * eliminate all the monsters before they reach the city. - */ - -/** - * @param {number[]} dist - * @param {number[]} speed - * @return {number} - */ -var eliminateMaximum = function(dist, speed) { - const n = dist.length; - const arrivalTimes = new Array(n); - - for (let i = 0; i < n; i++) { - arrivalTimes[i] = dist[i] / speed[i]; - } - - arrivalTimes.sort((a, b) => a - b); - - for (let i = 0; i < n; i++) { - if (arrivalTimes[i] <= i) { - return i; - } - } - - return n; -}; diff --git a/solutions/1922-count-good-numbers.js b/solutions/1922-count-good-numbers.js deleted file mode 100644 index b9c8d29d..00000000 --- a/solutions/1922-count-good-numbers.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1922. Count Good Numbers - * https://leetcode.com/problems/count-good-numbers/ - * Difficulty: Medium - * - * A digit string is good if the digits (0-indexed) at even indices are even and the digits - * at odd indices are prime (2, 3, 5, or 7). - * - * For example, "2582" is good because the digits (2 and 8) at even positions are even and - * the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 - * is at an even index but is not even. - * - * Given an integer n, return the total number of good digit strings of length n. Since the - * answer may be large, return it modulo 109 + 7. - * - * A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. - */ - -/** - * @param {number} n - * @return {number} - */ -var countGoodNumbers = function(n) { - const MOD = 1e9 + 7; - const evenCount = 5; - const primeCount = 4; - const evenPositions = Math.ceil(n / 2); - const oddPositions = Math.floor(n / 2); - const evenResult = power(evenCount, evenPositions); - const oddResult = power(primeCount, oddPositions); - - return Number(BigInt(evenResult) * BigInt(oddResult) % BigInt(MOD)); - - function power(base, exponent) { - if (exponent === 0) return 1; - let half = power(base, Math.floor(exponent / 2)); - half = BigInt(half) * BigInt(half) % BigInt(MOD); - if (exponent % 2) half = half * BigInt(base) % BigInt(MOD); - return Number(half); - } -}; diff --git a/solutions/1923-longest-common-subpath.js b/solutions/1923-longest-common-subpath.js deleted file mode 100644 index 1c2e1b0d..00000000 --- a/solutions/1923-longest-common-subpath.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * 1923. Longest Common Subpath - * https://leetcode.com/problems/longest-common-subpath/ - * Difficulty: Hard - * - * There is a country of n cities numbered from 0 to n - 1. In this country, there is a road - * connecting every pair of cities. - * - * There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one - * of them will take a path consisting of some cities. Each path is represented by an integer - * array that contains the visited cities in order. The path may contain a city more than once, - * but the same city will not be listed consecutively. - * - * Given an integer n and a 2D integer array paths where paths[i] is an integer array representing - * the path of the ith friend, return the length of the longest common subpath that is shared - * by every friend's path, or 0 if there is no common subpath at all. - * - * A subpath of a path is a contiguous sequence of cities within that path. - */ - -/** - * @param {number} n - * @param {number[][]} paths - * @return {number} - */ -var longestCommonSubpath = function(n, paths) { - if (paths.length === 0) return 0; - - paths.sort((a, b) => a.length - b.length); - - let left = 0; - let right = paths[0].length; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - - if (checkCommonSubpathExists(paths, mid)) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return right; -}; - -function checkCommonSubpathExists(paths, length) { - if (length === 0) return true; - - const firstPath = paths[0]; - - if (firstPath.length < length) return false; - - const prime = 1000000007; - const base = 100003; - - let highestPower = 1; - for (let i = 0; i < length - 1; i++) { - highestPower = (highestPower * base) % prime; - } - - let hashToPositions = new Map(); - - let hash = 0; - for (let i = 0; i < length; i++) { - hash = (hash * base + firstPath[i]) % prime; - } - - if (!hashToPositions.has(hash)) { - hashToPositions.set(hash, []); - } - hashToPositions.get(hash).push(0); - - for (let i = 1; i <= firstPath.length - length; i++) { - hash = ((hash - firstPath[i - 1] * highestPower % prime + prime) - % prime * base + firstPath[i + length - 1]) % prime; - - if (!hashToPositions.has(hash)) { - hashToPositions.set(hash, []); - } - hashToPositions.get(hash).push(i); - } - - for (let pathIdx = 1; pathIdx < paths.length; pathIdx++) { - const path = paths[pathIdx]; - - if (path.length < length) return false; - - const newHashToPositions = new Map(); - hash = 0; - for (let i = 0; i < length; i++) { - hash = (hash * base + path[i]) % prime; - } - - if (hashToPositions.has(hash)) { - const positions = hashToPositions.get(hash); - for (const pos of positions) { - let isMatch = true; - for (let j = 0; j < length; j++) { - if (firstPath[pos + j] !== path[j]) { - isMatch = false; - break; - } - } - - if (isMatch) { - if (!newHashToPositions.has(hash)) { - newHashToPositions.set(hash, []); - } - newHashToPositions.get(hash).push(pos); - break; - } - } - } - - for (let i = 1; i <= path.length - length; i++) { - hash = ((hash - path[i - 1] * highestPower % prime + prime) - % prime * base + path[i + length - 1]) % prime; - - if (hashToPositions.has(hash)) { - const positions = hashToPositions.get(hash); - for (const pos of positions) { - let isMatch = true; - for (let j = 0; j < length; j++) { - if (firstPath[pos + j] !== path[i + j]) { - isMatch = false; - break; - } - } - - if (isMatch) { - if (!newHashToPositions.has(hash)) { - newHashToPositions.set(hash, []); - } - newHashToPositions.get(hash).push(pos); - break; - } - } - } - } - - if (newHashToPositions.size === 0) return false; - - hashToPositions = newHashToPositions; - } - - return hashToPositions.size > 0; -} diff --git a/solutions/1925-count-square-sum-triples.js b/solutions/1925-count-square-sum-triples.js deleted file mode 100644 index b917c4e1..00000000 --- a/solutions/1925-count-square-sum-triples.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1925. Count Square Sum Triples - * https://leetcode.com/problems/count-square-sum-triples/ - * Difficulty: Easy - * - * A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. - * - * Given an integer n, return the number of square triples such that 1 <= a, b, c <= n. - */ - -/** - * @param {number} n - * @return {number} - */ -var countTriples = function(n) { - let result = 0; - - for (let a = 1; a <= n; a++) { - for (let b = 1; b <= n; b++) { - const sum = a * a + b * b; - const c = Math.sqrt(sum); - if (c <= n && Number.isInteger(c)) { - result++; - } - } - } - - return result; -}; diff --git a/solutions/1927-sum-game.js b/solutions/1927-sum-game.js deleted file mode 100644 index 178435f2..00000000 --- a/solutions/1927-sum-game.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 1927. Sum Game - * https://leetcode.com/problems/sum-game/ - * Difficulty: Medium - * - * Alice and Bob take turns playing a game, with Alice starting first. - * - * You are given a string num of even length consisting of digits and '?' characters. On each - * turn, a player will do the following if there is still at least one '?' in num: - * 1. Choose an index i where num[i] == '?'. - * 2. Replace num[i] with any digit between '0' and '9'. - * - * The game ends when there are no more '?' characters in num. - * - * For Bob to win, the sum of the digits in the first half of num must be equal to the sum of - * the digits in the second half. For Alice to win, the sums must not be equal. - * - For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. - * If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3. - * - * Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win. - */ - -/** - * @param {string} num - * @return {boolean} - */ -var sumGame = function(num) { - const n = num.length; - const half = n / 2; - - let leftSum = 0; - let rightSum = 0; - let leftQuestionMarks = 0; - let rightQuestionMarks = 0; - - for (let i = 0; i < n; i++) { - if (i < half) { - if (num[i] === '?') { - leftQuestionMarks++; - } else { - leftSum += parseInt(num[i]); - } - } else { - if (num[i] === '?') { - rightQuestionMarks++; - } else { - rightSum += parseInt(num[i]); - } - } - } - - const sumDiff = leftSum - rightSum; - const diff = leftQuestionMarks - rightQuestionMarks; - - return (diff % 2 !== 0) || (sumDiff + diff * 4.5 !== 0); -}; diff --git a/solutions/1928-minimum-cost-to-reach-destination-in-time.js b/solutions/1928-minimum-cost-to-reach-destination-in-time.js deleted file mode 100644 index a601d545..00000000 --- a/solutions/1928-minimum-cost-to-reach-destination-in-time.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 1928. Minimum Cost to Reach Destination in Time - * https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/ - * Difficulty: Hard - * - * There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by - * bi-directional roads. The roads are represented as a 2D integer array edges where - * edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes - * to travel. There may be multiple roads of differing travel times connecting the same two - * cities, but no road connects a city to itself. - * - * Each time you pass through a city, you must pay a passing fee. This is represented as a - * 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars - * you must pay when you pass through city j. - * - * In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. - * The cost of your journey is the summation of passing fees for each city that you passed - * through at some moment of your journey (including the source and destination cities). - * - * Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, - * or -1 if you cannot complete it within maxTime minutes. - */ - -/** - * @param {number} maxTime - * @param {number[][]} edges - * @param {number[]} passingFees - * @return {number} - */ -var minCost = function(maxTime, edges, passingFees) { - const n = passingFees.length; - const dp = new Array(n).fill().map(() => new Array(maxTime + 1).fill(Infinity)); - dp[0][0] = passingFees[0]; - - const graph = new Array(n).fill().map(() => []); - for (const [u, v, time] of edges) { - graph[u].push([v, time]); - graph[v].push([u, time]); - } - - const pq = new PriorityQueue((a, b) => a.cost - b.cost); - pq.enqueue({ cost: passingFees[0], city: 0, time: 0 }); - - while (!pq.isEmpty()) { - const { cost, city, time } = pq.dequeue(); - if (cost > dp[city][time]) continue; - - for (const [nextCity, travelTime] of graph[city]) { - const newTime = time + travelTime; - if (newTime > maxTime) continue; - - const newCost = cost + passingFees[nextCity]; - if (newCost < dp[nextCity][newTime]) { - dp[nextCity][newTime] = newCost; - pq.enqueue({ cost: newCost, city: nextCity, time: newTime }); - } - } - } - - let minCost = Infinity; - for (let t = 0; t <= maxTime; t++) { - minCost = Math.min(minCost, dp[n - 1][t]); - } - - return minCost === Infinity ? -1 : minCost; -}; diff --git a/solutions/1931-painting-a-grid-with-three-different-colors.js b/solutions/1931-painting-a-grid-with-three-different-colors.js deleted file mode 100644 index ef8bf15b..00000000 --- a/solutions/1931-painting-a-grid-with-three-different-colors.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 1931. Painting a Grid With Three Different Colors - * https://leetcode.com/problems/painting-a-grid-with-three-different-colors/ - * Difficulty: Hard - * - * You are given two integers m and n. Consider an m x n grid where each cell is initially white. - * You can paint each cell red, green, or blue. All cells must be painted. - * - * Return the number of ways to color the grid with no two adjacent cells having the same color. - * Since the answer can be very large, return it modulo 109 + 7. - */ - -/** - * @param {number} m - * @param {number} n - * @return {number} - */ -var colorTheGrid = function(m, n) { - const MOD = 1e9 + 7; - const colors = 3; - const validStates = generateValidStates(m, colors); - const stateCount = validStates.length; - let dp = new Array(stateCount).fill(1); - - for (let col = 1; col < n; col++) { - const nextDp = new Array(stateCount).fill(0); - for (let i = 0; i < stateCount; i++) { - for (let j = 0; j < stateCount; j++) { - if (isCompatible(validStates[i], validStates[j])) { - nextDp[j] = (nextDp[j] + dp[i]) % MOD; - } - } - } - dp = nextDp; - } - - let totalWays = 0; - for (const count of dp) { - totalWays = (totalWays + count) % MOD; - } - - return totalWays; - - function generateValidStates(rows, colors) { - const states = []; - generateStates([], rows, colors, states); - return states; - } - - function generateStates(current, rows, colors, states) { - if (current.length === rows) { - states.push([...current]); - return; - } - for (let c = 0; c < colors; c++) { - if (current.length === 0 || current[current.length - 1] !== c) { - current.push(c); - generateStates(current, rows, colors, states); - current.pop(); - } - } - } - - function isCompatible(prevState, currState) { - for (let i = 0; i < prevState.length; i++) { - if (prevState[i] === currState[i]) { - return false; - } - } - return true; - } -}; diff --git a/solutions/1932-merge-bsts-to-create-single-bst.js b/solutions/1932-merge-bsts-to-create-single-bst.js deleted file mode 100644 index a118a41a..00000000 --- a/solutions/1932-merge-bsts-to-create-single-bst.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * 1932. Merge BSTs to Create Single BST - * https://leetcode.com/problems/merge-bsts-to-create-single-bst/ - * Difficulty: Hard - * - * You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array - * trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same - * value. In one operation, you can: - * - Select two distinct indices i and j such that the value stored at one of the leaves of - * trees[i] is equal to the root value of trees[j]. - * - Replace the leaf node in trees[i] with trees[j]. - * - Remove trees[j] from trees. - * - * Return the root of the resulting BST if it is possible to form a valid BST after - * performing n - 1 operations, or null if it is impossible to create a valid BST. - * - * A BST (binary search tree) is a binary tree where each node satisfies the following property: - * - Every node in the node's left subtree has a value strictly less than the node's value. - * - Every node in the node's right subtree has a value strictly greater than the node's value. - * - * A leaf is a node that has 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[]} trees - * @return {TreeNode} - */ -var canMerge = function(trees) { - const valueToTree = new Map(); - const leafValues = new Set(); - const inDegree = new Map(); - - for (const tree of trees) { - valueToTree.set(tree.val, tree); - if (tree.left) leafValues.add(tree.left.val); - if (tree.right) leafValues.add(tree.right.val); - } - - let root = null; - for (const tree of trees) { - if (!leafValues.has(tree.val)) { - if (root) return null; - root = tree; - } - if (tree.left) inDegree.set(tree.left.val, (inDegree.get(tree.left.val) || 0) + 1); - if (tree.right) inDegree.set(tree.right.val, (inDegree.get(tree.right.val) || 0) + 1); - } - - if (!root) return null; - - const merged = mergeTrees(root, valueToTree, inDegree); - if (!merged || valueToTree.size > 1 || !isValidBST(merged, -Infinity, Infinity)) { - return null; - } - - return merged; - - function mergeTrees(node, valueToTree, inDegree) { - if (!node) return node; - - if (!node.left && !node.right && valueToTree.has(node.val) && inDegree.get(node.val) === 1) { - const tree = valueToTree.get(node.val); - if (tree === node) return node; - valueToTree.delete(node.val); - return mergeTrees(tree, valueToTree, inDegree); - } - - node.left = mergeTrees(node.left, valueToTree, inDegree); - node.right = mergeTrees(node.right, valueToTree, inDegree); - return node; - } - - function isValidBST(node, min, max) { - if (!node) return true; - if (node.val <= min || node.val >= max) return false; - return isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max); - } -}; diff --git a/solutions/1936-add-minimum-number-of-rungs.js b/solutions/1936-add-minimum-number-of-rungs.js deleted file mode 100644 index 2dba6511..00000000 --- a/solutions/1936-add-minimum-number-of-rungs.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1936. Add Minimum Number of Rungs - * https://leetcode.com/problems/add-minimum-number-of-rungs/ - * Difficulty: Medium - * - * You are given a strictly increasing integer array rungs that represents the height of rungs - * on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. - * - * You are also given an integer dist. You can only climb to the next highest rung if the - * distance between where you are currently at (the floor or on a rung) and the next rung is - * at most dist. You are able to insert rungs at any positive integer height if a rung is not - * already there. - * - * Return the minimum number of rungs that must be added to the ladder in order for you to climb - * to the last rung. - */ - -/** - * @param {number[]} rungs - * @param {number} dist - * @return {number} - */ -var addRungs = function(rungs, dist) { - let currentHeight = 0; - let result = 0; - - for (const rung of rungs) { - const gap = rung - currentHeight; - if (gap > dist) { - result += Math.ceil(gap / dist) - 1; - } - currentHeight = rung; - } - - return result; -}; diff --git a/solutions/1937-maximum-number-of-points-with-cost.js b/solutions/1937-maximum-number-of-points-with-cost.js deleted file mode 100644 index 288c1888..00000000 --- a/solutions/1937-maximum-number-of-points-with-cost.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1937. Maximum Number of Points with Cost - * https://leetcode.com/problems/maximum-number-of-points-with-cost/ - * Difficulty: Medium - * - * You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want - * to maximize the number of points you can get from the matrix. - * - * To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) - * will add points[r][c] to your score. - * - * However, you will lose points if you pick a cell too far from the cell that you picked in - * the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking - * cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. - * - * Return the maximum number of points you can achieve. - * - * abs(x) is defined as: - * - x for x >= 0. - * - -x for x < 0. - */ - -/** - * @param {number[][]} points - * @return {number} - */ -var maxPoints = function(points) { - const rows = points.length; - const cols = points[0].length; - let prevRow = points[0].slice(); - - for (let r = 1; r < rows; r++) { - const currRow = new Array(cols).fill(0); - const leftMax = new Array(cols).fill(0); - const rightMax = new Array(cols).fill(0); - - leftMax[0] = prevRow[0]; - for (let c = 1; c < cols; c++) { - leftMax[c] = Math.max(leftMax[c - 1] - 1, prevRow[c]); - } - - rightMax[cols - 1] = prevRow[cols - 1]; - for (let c = cols - 2; c >= 0; c--) { - rightMax[c] = Math.max(rightMax[c + 1] - 1, prevRow[c]); - } - - for (let c = 0; c < cols; c++) { - currRow[c] = points[r][c] + Math.max(leftMax[c], rightMax[c]); - } - - prevRow = currRow; - } - - return Math.max(...prevRow); -}; diff --git a/solutions/1938-maximum-genetic-difference-query.js b/solutions/1938-maximum-genetic-difference-query.js deleted file mode 100644 index e7b88f18..00000000 --- a/solutions/1938-maximum-genetic-difference-query.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * 1938. Maximum Genetic Difference Query - * https://leetcode.com/problems/maximum-genetic-difference-query/ - * Difficulty: Hard - * - * There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes - * its unique genetic value (i.e. the genetic value of node x is x). The genetic difference - * between two genetic values is defined as the bitwise-XOR of their values. You are given - * the integer array parents, where parents[i] is the parent for node i. If node x is the root - * of the tree, then parents[x] == -1. - * - * You are also given the array queries where queries[i] = [nodei, vali]. For each query i, - * find the maximum genetic difference between vali and pi, where pi is the genetic value of - * any node that is on the path between nodei and the root (including nodei and the root). - * More formally, you want to maximize vali XOR pi. - * - * Return an array ans where ans[i] is the answer to the ith query. - */ - -/** - * @param {number[]} parents - * @param {number[][]} queries - * @return {number[]} - */ -var maxGeneticDifference = function(parents, queries) { - const n = parents.length; - const graph = Array(n).fill().map(() => []); - let root = -1; - - for (let i = 0; i < n; i++) { - if (parents[i] === -1) { - root = i; - } else { - graph[parents[i]].push(i); - } - } - - const trie = { count: 0, children: {} }; - const queryMap = Array(n).fill().map(() => []); - const result = new Array(queries.length).fill(0); - - for (let i = 0; i < queries.length; i++) { - queryMap[queries[i][0]].push([queries[i][1], i]); - } - - dfs(root); - return result; - - function insertTrie(val) { - let node = trie; - for (let bit = 17; bit >= 0; bit--) { - const b = (val >> bit) & 1; - if (!node.children[b]) { - node.children[b] = { count: 0, children: {} }; - } - node = node.children[b]; - node.count++; - } - } - - function removeTrie(val) { - let node = trie; - for (let bit = 17; bit >= 0; bit--) { - const b = (val >> bit) & 1; - node = node.children[b]; - node.count--; - } - } - - function queryTrie(val) { - let node = trie; - let maxXor = 0; - for (let bit = 17; bit >= 0; bit--) { - const b = (val >> bit) & 1; - if (node.children[1 - b]?.count > 0) { - maxXor |= (1 << bit); - node = node.children[1 - b]; - } else if (node.children[b]?.count > 0) { - node = node.children[b]; - } else { - return maxXor; - } - } - return maxXor; - } - - function dfs(node) { - insertTrie(node); - for (const [val, idx] of queryMap[node]) { - result[idx] = queryTrie(val); - } - for (const child of graph[node]) { - dfs(child); - } - removeTrie(node); - } -}; diff --git a/solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js b/solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js deleted file mode 100644 index aa742eb2..00000000 --- a/solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 1941. Check if All Characters Have Equal Number of Occurrences - * https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/ - * Difficulty: Easy - * - * Given a string s, return true if s is a good string, or false otherwise. - * - * A string s is good if all the characters that appear in s have the same number of occurrences - * (i.e., the same frequency). - */ - -/** - * @param {string} s - * @return {boolean} - */ -var areOccurrencesEqual = function(s) { - const map = new Map(); - for (const char of s) { - map.set(char, (map.get(char) || 0) + 1); - } - - const frequencies = new Set(map.values()); - return frequencies.size === 1; -}; diff --git a/solutions/1943-describe-the-painting.js b/solutions/1943-describe-the-painting.js deleted file mode 100644 index 3e5c287a..00000000 --- a/solutions/1943-describe-the-painting.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1943. Describe the Painting - * https://leetcode.com/problems/describe-the-painting/ - * Difficulty: Medium - * - * There is a long and thin painting that can be represented by a number line. The painting was - * painted with multiple overlapping segments where each segment was painted with a unique color. - * You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] - * represents the half-closed segment [starti, endi) with colori as the color. - * - * The colors in the overlapping segments of the painting were mixed when it was painted. When - * two or more colors mix, they form a new color that can be represented as a set of mixed colors. - * - For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}. - * - * For the sake of simplicity, you should only output the sum of the elements in the set rather - * than the full set. - * - * You want to describe the painting with the minimum number of non-overlapping half-closed - * segments of these mixed colors. These segments can be represented by the 2D array painting - * where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) - * with the mixed color sum of mixj. - * - For example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by - * painting = [[1,4,12],[4,7,7]] because: - * - [1,4) is colored {5,7} (with a sum of 12) from both the first and second segments. - * - [4,7) is colored {7} from only the second segment. - * - * Return the 2D array painting describing the finished painting (excluding any parts that are - * not painted). You may return the segments in any order. - * - * A half-closed segment [a, b) is the section of the number line between points a and b including - * point a and not including point b. - */ - -/** - * @param {number[][]} segments - * @return {number[][]} - */ -var splitPainting = function(segments) { - const events = []; - for (const [start, end, color] of segments) { - events.push([start, color]); - events.push([end, -color]); - } - - events.sort((a, b) => a[0] - b[0] || a[1] - b[1]); - - const result = []; - let currentSum = 0; - let prevPoint = events[0][0]; - - for (const [point, color] of events) { - if (currentSum > 0 && point > prevPoint) { - result.push([prevPoint, point, currentSum]); - } - currentSum += color; - prevPoint = point; - } - - return result; -}; diff --git a/solutions/1944-number-of-visible-people-in-a-queue.js b/solutions/1944-number-of-visible-people-in-a-queue.js deleted file mode 100644 index 8297710b..00000000 --- a/solutions/1944-number-of-visible-people-in-a-queue.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 1944. Number of Visible People in a Queue - * https://leetcode.com/problems/number-of-visible-people-in-a-queue/ - * Difficulty: Hard - * - * There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right - * order. You are given an array heights of distinct integers where heights[i] represents the - * height of the ith person. - * - * A person can see another person to their right in the queue if everybody in between is - * shorter than both of them. More formally, the ith person can see the jth person - * if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). - * - * Return an array answer of length n where answer[i] is the number of people the ith person - * can see to their right in the queue. - */ - -/** - * @param {number[]} heights - * @return {number[]} - */ -var canSeePersonsCount = function(heights) { - const n = heights.length; - const result = new Array(n).fill(0); - const stack = []; - - for (let i = n - 1; i >= 0; i--) { - while (stack.length && heights[i] > stack[stack.length - 1]) { - stack.pop(); - result[i]++; - } - if (stack.length) { - result[i]++; - } - stack.push(heights[i]); - } - - return result; -}; diff --git a/solutions/1945-sum-of-digits-of-string-after-convert.js b/solutions/1945-sum-of-digits-of-string-after-convert.js deleted file mode 100644 index 7e6e47d1..00000000 --- a/solutions/1945-sum-of-digits-of-string-after-convert.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1945. Sum of Digits of String After Convert - * https://leetcode.com/problems/sum-of-digits-of-string-after-convert/ - * Difficulty: Easy - * - * You are given a string s consisting of lowercase English letters, and an integer k. Your task - * is to convert the string into an integer by a special process, and then transform it by - * summing its digits repeatedly k times. More specifically, perform the following steps: - * 1. Convert s into an integer by replacing each letter with its position in the alphabet (i.e. - * replace 'a' with 1, 'b' with 2, ..., 'z' with 26). - * 2. Transform the integer by replacing it with the sum of its digits. - * 3. Repeat the transform operation (step 2) k times in total. - * - * For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following - * operations: - * 1. Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 - * 2. Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 - * 3. Transform #2: 17 ➝ 1 + 7 ➝ 8 - * - * Return the resulting integer after performing the operations described above. - */ - -/** - * @param {string} s - * @param {number} k - * @return {number} - */ -var getLucky = function(s, k) { - let number = ''; - for (const char of s) { - number += (char.charCodeAt(0) - 96).toString(); - } - - let result = 0; - for (let i = 0; i < k; i++) { - result = 0; - for (const digit of number) { - result += parseInt(digit); - } - number = result.toString(); - } - - return result; -}; diff --git a/solutions/1946-largest-number-after-mutating-substring.js b/solutions/1946-largest-number-after-mutating-substring.js deleted file mode 100644 index f64e4db0..00000000 --- a/solutions/1946-largest-number-after-mutating-substring.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1946. Largest Number After Mutating Substring - * https://leetcode.com/problems/largest-number-after-mutating-substring/ - * Difficulty: Medium - * - * You are given a string num, which represents a large integer. You are also given a 0-indexed - * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, - * digit d maps to digit change[d]. - * - * You may choose to mutate a single substring of num. To mutate a substring, replace each digit - * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). - * - * Return a string representing the largest possible integer after mutating (or choosing not to) - * a single substring of num. - * - * A substring is a contiguous sequence of characters within the string. - */ - -/** - * @param {string} num - * @param {number[]} change - * @return {string} - */ -var maximumNumber = function(num, change) { - const digits = num.split(''); - let mutated = false; - - for (let i = 0; i < digits.length; i++) { - const currentDigit = parseInt(digits[i]); - const mappedDigit = change[currentDigit]; - - if (mappedDigit > currentDigit) { - digits[i] = mappedDigit.toString(); - mutated = true; - } else if (mappedDigit < currentDigit && mutated) { - break; - } - } - - return digits.join(''); -}; diff --git a/solutions/1947-maximum-compatibility-score-sum.js b/solutions/1947-maximum-compatibility-score-sum.js deleted file mode 100644 index 985d1deb..00000000 --- a/solutions/1947-maximum-compatibility-score-sum.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1947. Maximum Compatibility Score Sum - * https://leetcode.com/problems/maximum-compatibility-score-sum/ - * Difficulty: Medium - * - * There is a survey that consists of n questions where each question's answer is either 0 - * (no) or 1 (yes). - * - * The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from - * 0 to m - 1. The answers of the students are represented by a 2D integer array students - * where students[i] is an integer array that contains the answers of the ith student - * (0-indexed). The answers of the mentors are represented by a 2D integer array mentors - * where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). - * - * Each student will be assigned to one mentor, and each mentor will have one student assigned - * to them. The compatibility score of a student-mentor pair is the number of answers that - * are the same for both the student and the mentor. - * - For example, if the student's answers were [1, 0, 1] and the mentor's answers were - * [0, 0, 1], then their compatibility score is 2 because only the second and the third - * answers are the same. - * - * You are tasked with finding the optimal student-mentor pairings to maximize the sum of the - * compatibility scores. - * - * Given students and mentors, return the maximum compatibility score sum that can be achieved. - */ - -/** - * @param {number[][]} students - * @param {number[][]} mentors - * @return {number} - */ -var maxCompatibilitySum = function(students, mentors) { - const m = students.length; - let maxScore = 0; - - backtrack(0, new Array(m).fill(false), 0); - return maxScore; - - function calculateScore(student, mentor) { - let score = 0; - for (let i = 0; i < student.length; i++) { - if (student[i] === mentor[i]) score++; - } - return score; - } - - function backtrack(studentIndex, usedMentors, currentScore) { - if (studentIndex === m) { - maxScore = Math.max(maxScore, currentScore); - return; - } - - for (let mentorIndex = 0; mentorIndex < m; mentorIndex++) { - if (!usedMentors[mentorIndex]) { - usedMentors[mentorIndex] = true; - backtrack(studentIndex + 1, usedMentors, - currentScore + calculateScore(students[studentIndex], mentors[mentorIndex])); - usedMentors[mentorIndex] = false; - } - } - } -}; diff --git a/solutions/1948-delete-duplicate-folders-in-system.js b/solutions/1948-delete-duplicate-folders-in-system.js deleted file mode 100644 index 085f6d72..00000000 --- a/solutions/1948-delete-duplicate-folders-in-system.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * 1948. Delete Duplicate Folders in System - * https://leetcode.com/problems/delete-duplicate-folders-in-system/ - * Difficulty: Hard - * - * Due to a bug, there are many duplicate folders in a file system. You are given a 2D array - * paths, where paths[i] is an array representing an absolute path to the ith folder in the - * file system. - * - For example, ["one", "two", "three"] represents the path "/one/two/three". - * - * Two folders (not necessarily on the same level) are identical if they contain the same - * non-empty set of identical subfolders and underlying subfolder structure. The folders do - * not need to be at the root level to be identical. If two or more folders are identical, - * then mark the folders as well as all their subfolders. - * - For example, folders "/a" and "/b" in the file structure below are identical. They (as - * well as their subfolders) should all be marked: - * - /a - * - /a/x - * - /a/x/y - * - /a/z - * - /b - * - /b/x - * - /b/x/y - * - /b/z - * - However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" - * would not be identical. Note that "/a/x" and "/b/x" would still be considered identical - * even with the added folder. - * - * Once all the identical folders and their subfolders have been marked, the file system will delete - * all of them. The file system only runs the deletion once, so any folders that become identical - * after the initial deletion are not deleted. - * - * Return the 2D array ans containing the paths of the remaining folders after deleting all the - * marked folders. The paths may be returned in any order. - */ - -/** - * @param {string[][]} paths - * @return {string[][]} - */ -var deleteDuplicateFolder = function(paths) { - const root = {}; - - for (const path of paths) { - let node = root; - for (const folder of path) { - if (!node[folder]) node[folder] = {}; - node = node[folder]; - } - } - - const structures = new Map(); - - const serialize = (node, path) => { - if (Object.keys(node).length === 0) return ''; - - const folders = []; - const keys = Object.keys(node); - for (const folder of keys) { - const serialized = serialize(node[folder], [...path, folder]); - if (serialized !== null) { - folders.push(`${folder}(${serialized})`); - } else { - delete node[folder]; - } - } - - folders.sort(); - const key = folders.join(''); - - if (key.length > 0) { - if (!structures.has(key)) { - structures.set(key, []); - } - structures.get(key).push(path); - } - - return key; - }; - - serialize(root, []); - - const toDelete = new Set(); - - for (const [structure, paths] of structures.entries()) { - if (paths.length > 1) { - for (const path of paths) { - toDelete.add(path.join('/')); - } - } - } - - const result = []; - - const collectPaths = (node, path) => { - const currentPath = path.join('/'); - if (toDelete.has(currentPath)) return; - - if (path.length > 0) { - result.push([...path]); - } - - const keys = Object.keys(node); - for (const folder of keys) { - collectPaths(node[folder], [...path, folder]); - } - }; - - const rootFolders = Object.keys(root); - for (const folder of rootFolders) { - collectPaths(root[folder], [folder]); - } - - return result; -}; diff --git a/solutions/1952-three-divisors.js b/solutions/1952-three-divisors.js deleted file mode 100644 index c09cf96e..00000000 --- a/solutions/1952-three-divisors.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 1952. Three Divisors - * https://leetcode.com/problems/three-divisors/ - * Difficulty: Easy - * - * Given an integer n, return true if n has exactly three positive divisors. Otherwise, - * return false. - * - * An integer m is a divisor of n if there exists an integer k such that n = k * m. - */ - -/** - * @param {number} n - * @return {boolean} - */ -var isThree = function(n) { - let divisorCount = 0; - - for (let i = 1; i <= n; i++) { - if (n % i === 0) { - divisorCount++; - if (divisorCount > 3) return false; - } - } - - return divisorCount === 3; -}; diff --git a/solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js b/solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js deleted file mode 100644 index 730198a0..00000000 --- a/solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1953. Maximum Number of Weeks for Which You Can Work - * https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/ - * Difficulty: Medium - * - * There are n projects numbered from 0 to n - 1. You are given an integer array milestones where - * each milestones[i] denotes the number of milestones the ith project has. - * - * You can work on the projects following these two rules: - * - Every week, you will finish exactly one milestone of one project. You must work every week. - * - You cannot work on two milestones from the same project for two consecutive weeks. - * - Once all the milestones of all the projects are finished, or if the only milestones that you - * can work on will cause you to violate the above rules, you will stop working. Note that you - * may not be able to finish every project's milestones due to these constraints. - * - * Return the maximum number of weeks you would be able to work on the projects without violating - * the rules mentioned above. - */ - -/** - * @param {number[]} milestones - * @return {number} - */ -var numberOfWeeks = function(milestones) { - let total = 0; - let maxMilestones = 0; - - for (const count of milestones) { - total += count; - maxMilestones = Math.max(maxMilestones, count); - } - - return Math.min(total, 2 * (total - maxMilestones) + 1); -}; diff --git a/solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js b/solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js deleted file mode 100644 index e064083c..00000000 --- a/solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1954. Minimum Garden Perimeter to Collect Enough Apples - * https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/ - * Difficulty: Medium - * - * In a garden represented as an infinite 2D grid, there is an apple tree planted at every - * integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| - * apples growing on it. - * - * You will buy an axis-aligned square plot of land that is centered at (0, 0). - * - * Given an integer neededApples, return the minimum perimeter of a plot such that at least - * neededApples apples are inside or on the perimeter of that plot. - * - * The value of |x| is defined as: - * - x if x >= 0 - * - -x if x < 0 - */ - -/** - * @param {number} neededApples - * @return {number} - */ -var minimumPerimeter = function(neededApples) { - let n = 0; - let totalApples = 0; - - while (totalApples < neededApples) { - n++; - totalApples = 2 * n * (n + 1) * (2 * n + 1); - } - - return 8 * n; -}; diff --git a/solutions/1955-count-number-of-special-subsequences.js b/solutions/1955-count-number-of-special-subsequences.js deleted file mode 100644 index 5daa07ec..00000000 --- a/solutions/1955-count-number-of-special-subsequences.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 1955. Count Number of Special Subsequences - * https://leetcode.com/problems/count-number-of-special-subsequences/ - * Difficulty: Hard - * - * A sequence is special if it consists of a positive number of 0s, followed by a positive number - * of 1s, then a positive number of 2s. - * - For example, [0,1,2] and [0,0,1,1,1,2] are special. - * - In contrast, [2,1,0], [1], and [0,1,2,0] are not special. - * - * Given an array nums (consisting of only integers 0, 1, and 2), return the number of different - * subsequences that are special. Since the answer may be very large, return it modulo 109 + 7. - * - * A subsequence of an array is a sequence that can be derived from the array by deleting some - * or no elements without changing the order of the remaining elements. Two subsequences are - * different if the set of indices chosen are different. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var countSpecialSubsequences = function(nums) { - const MOD = 1e9 + 7; - const dp = [1, 0, 0, 0]; - - for (const num of nums) { - dp[num + 1] = (dp[num + 1] * 2 % MOD + dp[num]) % MOD; - } - - return dp[3]; -}; diff --git a/solutions/1957-delete-characters-to-make-fancy-string.js b/solutions/1957-delete-characters-to-make-fancy-string.js deleted file mode 100644 index 39c92ece..00000000 --- a/solutions/1957-delete-characters-to-make-fancy-string.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1957. Delete Characters to Make Fancy String - * https://leetcode.com/problems/delete-characters-to-make-fancy-string/ - * Difficulty: Easy - * - * A fancy string is a string where no three consecutive characters are equal. - * - * Given a string s, delete the minimum possible number of characters from s to make - * it fancy. - * - * Return the final string after the deletion. It can be shown that the answer will - * always be unique. - */ - -/** - * @param {string} s - * @return {string} - */ -var makeFancyString = function(s) { - let result = s[0]; - let count = 1; - - for (let i = 1; i < s.length; i++) { - if (s[i] === s[i - 1]) { - if (count < 2) { - result += s[i]; - count++; - } - } else { - result += s[i]; - count = 1; - } - } - - return result; -}; diff --git a/solutions/1958-check-if-move-is-legal.js b/solutions/1958-check-if-move-is-legal.js deleted file mode 100644 index 7fef6e2a..00000000 --- a/solutions/1958-check-if-move-is-legal.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1958. Check if Move is Legal - * https://leetcode.com/problems/check-if-move-is-legal/ - * Difficulty: Medium - * - * You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a - * game board. On the board, free cells are represented by '.', white cells are represented by - * 'W', and black cells are represented by 'B'. - * - * Each move in this game consists of choosing a free cell and changing it to the color you are - * playing as (either white or black). However, a move is only legal if, after changing it, the - * cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). - * - * A good line is a line of three or more cells (including the endpoints) where the endpoints of - * the line are one color, and the remaining cells in the middle are the opposite color (no cells - * in the line are free). You can find examples for good lines in the figure below. - * - * Given two integers rMove and cMove and a character color representing the color you are playing - * as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, - * or false if it is not legal. - */ - -/** - * @param {character[][]} board - * @param {number} rMove - * @param {number} cMove - * @param {character} color - * @return {boolean} - */ -var checkMove = function(board, rMove, cMove, color) { - const opposite = color === 'B' ? 'W' : 'B'; - const directions = [ - [0, 1], [0, -1], [1, 0], [-1, 0], - [1, 1], [1, -1], [-1, 1], [-1, -1] - ]; - - for (const [dr, dc] of directions) { - let row = rMove + dr; - let col = cMove + dc; - let count = 1; - - while (row >= 0 && row < 8 && col >= 0 && col < 8 && board[row][col] === opposite) { - row += dr; - col += dc; - count++; - } - - if (count >= 2 && row >= 0 && row < 8 && col >= 0 && col < 8 && board[row][col] === color) { - return true; - } - } - - return false; -}; diff --git a/solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js b/solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js deleted file mode 100644 index 9576849d..00000000 --- a/solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1959. Minimum Total Space Wasted With K Resizing Operations - * https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/ - * Difficulty: Medium - * - * You are currently designing a dynamic array. You are given a 0-indexed integer array nums, - * where nums[i] is the number of elements that will be in the array at time i. In addition, - * you are given an integer k, the maximum number of times you can resize the array (to any size). - * - * The size of the array at time t, sizet, must be at least nums[t] because there needs to be - * enough space in the array to hold all the elements. The space wasted at time t is defined - * as sizet - nums[t], and the total space wasted is the sum of the space wasted across every - * time t where 0 <= t < nums.length. - * - * Return the minimum total space wasted if you can resize the array at most k times. - * - * Note: The array can have any size at the start and does not count towards the number of - * resizing operations. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var minSpaceWastedKResizing = function(nums, k) { - const n = nums.length; - const dp = new Array(n + 1).fill().map(() => new Array(k + 2).fill(Infinity)); - dp[0][0] = 0; - - for (let i = 1; i <= n; i++) { - let maxVal = 0; - let sum = 0; - - for (let j = i; j > 0; j--) { - maxVal = Math.max(maxVal, nums[j - 1]); - sum += nums[j - 1]; - const waste = maxVal * (i - j + 1) - sum; - - for (let resizes = 0; resizes <= k; resizes++) { - if (dp[j - 1][resizes] !== Infinity) { - dp[i][resizes + 1] = Math.min(dp[i][resizes + 1], dp[j - 1][resizes] + waste); - } - } - } - } - - let result = Infinity; - for (let resizes = 1; resizes <= k + 1; resizes++) { - result = Math.min(result, dp[n][resizes]); - } - - return result; -}; diff --git a/solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js b/solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js deleted file mode 100644 index 10d34b76..00000000 --- a/solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 1960. Maximum Product of the Length of Two Palindromic Substrings - * https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/ - * Difficulty: Hard - * - * You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic - * substrings of odd length such that the product of their lengths is maximized. - * - * More formally, you want to choose four integers i, j, k, l such that - * 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes - * and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive. - * - * Return the maximum possible product of the lengths of the two non-intersecting palindromic - * substrings. - * - * A palindrome is a string that is the same forward and backward. A substring is a contiguous - * sequence of characters in a string. - */ - -/** -* @param {string} s -* @return {number} -*/ -var maxProduct = function(s) { - const n = s.length; - const before = new Array(n).fill(0); - const after = new Array(n).fill(0); - - let center = -1; - let right = -1; - const dp = new Array(n).fill(0); - - for (let i = 0; i < n; i++) { - const radius = i <= right ? Math.min(dp[2 * center - i], right - i) : 0; - let left = i - radius; - let rt = i + radius; - - while (left >= 0 && rt < n && s[left] === s[rt]) { - before[rt] = Math.max(before[rt], rt - left + 1); - after[left] = Math.max(after[left], rt - left + 1); - left--; - rt++; - } - - dp[i] = rt - i - 1; - - if (rt - 1 > right) { - center = i; - right = rt - 1; - } - } - - for (let i = 1; i < n; i++) { - before[i] = Math.max(before[i - 1], before[i]); - } - - for (let i = n - 2; i >= 0; i--) { - after[i] = Math.max(after[i + 1], after[i]); - } - - let result = 0; - for (let i = 1; i < n; i++) { - result = Math.max(result, before[i - 1] * after[i]); - } - - return result; -}; diff --git a/solutions/1961-check-if-string-is-a-prefix-of-array.js b/solutions/1961-check-if-string-is-a-prefix-of-array.js deleted file mode 100644 index 68aaf4c0..00000000 --- a/solutions/1961-check-if-string-is-a-prefix-of-array.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 1961. Check If String Is a Prefix of Array - * https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/ - * Difficulty: Easy - * - * Given a string s and an array of strings words, determine whether s is a prefix string of words. - * - * A string s is a prefix string of words if s can be made by concatenating the first k strings in - * words for some positive k no larger than words.length. - * - * Return true if s is a prefix string of words, or false otherwise. - */ - -/** - * @param {string} s - * @param {string[]} words - * @return {boolean} - */ -var isPrefixString = function(s, words) { - let currentIndex = 0; - - for (const word of words) { - if (currentIndex + word.length > s.length) return false; - if (s.slice(currentIndex, currentIndex + word.length) !== word) return false; - currentIndex += word.length; - if (currentIndex === s.length) return true; - } - - return false; -}; diff --git a/solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js b/solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js deleted file mode 100644 index 2f687a52..00000000 --- a/solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 1963. Minimum Number of Swaps to Make the String Balanced - * https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/ - * Difficulty: Medium - * - * You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening - * brackets '[' and n / 2 closing brackets ']'. - * - * A string is called balanced if and only if: - * - It is the empty string, or - * - It can be written as AB, where both A and B are balanced strings, or - * - It can be written as [C], where C is a balanced string. - * - * You may swap the brackets at any two indices any number of times. - * - * Return the minimum number of swaps to make s balanced. - */ - -/** - * @param {string} s - * @return {number} - */ -var minSwaps = function(s) { - let imbalance = 0; - let maxImbalance = 0; - - for (const bracket of s) { - if (bracket === '[') { - imbalance--; - } else { - imbalance++; - maxImbalance = Math.max(maxImbalance, imbalance); - } - } - - return Math.ceil(maxImbalance / 2); -}; diff --git a/solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js b/solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js deleted file mode 100644 index cafb25a7..00000000 --- a/solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 1964. Find the Longest Valid Obstacle Course at Each Position - * https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/ - * Difficulty: Hard - * - * You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of - * length n, where obstacles[i] describes the height of the ith obstacle. - * - * For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle - * course in obstacles such that: - * - You choose any number of obstacles between 0 and i inclusive. - * - You must include the ith obstacle in the course. - * - You must put the chosen obstacles in the same order as they appear in obstacles. - * - Every obstacle (except the first) is taller than or the same height as the obstacle immediately - * before it. - * - * Return an array ans of length n, where ans[i] is the length of the longest obstacle course for - * index i as described above. - */ - -/** - * @param {number[]} obstacles - * @return {number[]} - */ -var longestObstacleCourseAtEachPosition = function(obstacles) { - const n = obstacles.length; - const result = new Array(n).fill(1); - const stack = []; - - for (let i = 0; i < n; i++) { - const height = obstacles[i]; - let left = 0; - let right = stack.length; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (stack[mid] <= height) { - left = mid + 1; - } else { - right = mid; - } - } - - if (left < stack.length) { - stack[left] = height; - } else { - stack.push(height); - } - - result[i] = left + 1; - } - - return result; -}; diff --git a/solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js b/solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js deleted file mode 100644 index b0cb45d5..00000000 --- a/solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 1967. Number of Strings That Appear as Substrings in Word - * https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/ - * Difficulty: Easy - * - * Given an array of strings patterns and a string word, return the number of strings in patterns - * that exist as a substring in word. - * - * A substring is a contiguous sequence of characters within a string. - */ - -/** - * @param {string[]} patterns - * @param {string} word - * @return {number} - */ -var numOfStrings = function(patterns, word) { - return patterns.reduce((count, pattern) => word.includes(pattern) ? count + 1 : count, 0); -}; diff --git a/solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js b/solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js deleted file mode 100644 index 67994987..00000000 --- a/solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1968. Array With Elements Not Equal to Average of Neighbors - * https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ - * Difficulty: Medium - * - * You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements - * in the array such that every element in the rearranged array is not equal to the average of - * its neighbors. - * - * More formally, the rearranged array should have the property such that for every i in the - * range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i]. - * - * Return any rearrangement of nums that meets the requirements. - */ - -/** - * @param {number[]} nums - * @return {number[]} - */ -var rearrangeArray = function(nums) { - const result = new Array(nums.length); - nums.sort((a, b) => a - b); - - for (let i = 0, left = 0, right = nums.length - 1; i < nums.length; i++) { - result[i] = i % 2 === 0 ? nums[left++] : nums[right--]; - } - - return result; -}; diff --git a/solutions/1969-minimum-non-zero-product-of-the-array-elements.js b/solutions/1969-minimum-non-zero-product-of-the-array-elements.js deleted file mode 100644 index 9165df8e..00000000 --- a/solutions/1969-minimum-non-zero-product-of-the-array-elements.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 1969. Minimum Non-Zero Product of the Array Elements - * https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/ - * Difficulty: Medium - * - * You are given a positive integer p. Consider an array nums (1-indexed) that consists of the - * integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed - * to do the following operation any number of times: - * - Choose two elements x and y from nums. - * - Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to - * the bit that is in the same position in the other integer. - * - * For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have - * x = 1111 and y = 0001. - * - * Find the minimum non-zero product of nums after performing the above operation any number - * of times. Return this product modulo 109 + 7. - * - * Note: The answer should be the minimum product before the modulo operation is done. - */ - -/** - * @param {number} p - * @return {number} - */ -var minNonZeroProduct = function(p) { - const MOD = 1000000007n; - const maxVal = (1n << BigInt(p)) - 1n; - const halfCount = (maxVal - 1n) / 2n; - const base = maxVal - 1n; - - function pow(base, exp, mod) { - let result = 1n; - base = base % mod; - while (exp > 0n) { - if (exp & 1n) result = (result * base) % mod; - base = (base * base) % mod; - exp >>= 1n; - } - return result; - } - - return Number((maxVal * pow(base, halfCount, MOD)) % MOD); -}; diff --git a/solutions/1970-last-day-where-you-can-still-cross.js b/solutions/1970-last-day-where-you-can-still-cross.js deleted file mode 100644 index 7b36cd06..00000000 --- a/solutions/1970-last-day-where-you-can-still-cross.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * 1970. Last Day Where You Can Still Cross - * https://leetcode.com/problems/last-day-where-you-can-still-cross/ - * Difficulty: Hard - * - * There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given - * integers row and col representing the number of rows and columns in the matrix, respectively. - * - * Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded - * with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that - * on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered - * with water (i.e., changed to 1). - * - * You want to find the last day that it is possible to walk from the top to the bottom by only - * walking on land cells. You can start from any cell in the top row and end at any cell in the - * bottom row. You can only travel in the four cardinal directions (left, right, up, and down). - * - * Return the last day where it is possible to walk from the top to the bottom by only walking - * on land cells. - */ - -/** - * @param {number} row - * @param {number} col - * @param {number[][]} cells - * @return {number} - */ -var latestDayToCross = function(row, col, cells) { - const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - let left = 1; - let right = cells.length; - let result = 0; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (canCross(mid)) { - result = mid; - left = mid + 1; - } else { - right = mid - 1; - } - } - - return result; - - function canCross(day) { - const grid = new Array(row).fill().map(() => new Array(col).fill(0)); - for (let i = 0; i < day; i++) { - const [r, c] = cells[i]; - grid[r - 1][c - 1] = 1; - } - - const queue = []; - const visited = new Array(row).fill().map(() => new Array(col).fill(false)); - - for (let c = 0; c < col; c++) { - if (grid[0][c] === 0) { - queue.push([0, c]); - visited[0][c] = true; - } - } - - while (queue.length) { - const [r, c] = queue.shift(); - if (r === row - 1) return true; - - for (const [dr, dc] of directions) { - const nr = r + dr; - const nc = c + dc; - if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] === 0) { - queue.push([nr, nc]); - visited[nr][nc] = true; - } - } - } - return false; - } -}; diff --git a/solutions/1971-find-if-path-exists-in-graph.js b/solutions/1971-find-if-path-exists-in-graph.js deleted file mode 100644 index 4b032666..00000000 --- a/solutions/1971-find-if-path-exists-in-graph.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 1971. Find if Path Exists in Graph - * https://leetcode.com/problems/find-if-path-exists-in-graph/ - * Difficulty: Easy - * - * There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to - * n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, - * where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and - * vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an - * edge to itself. - * - * You want to determine if there is a valid path that exists from vertex source to vertex - * destination. - * - * Given edges and the integers n, source, and destination, return true if there is a valid - * path from source to destination, or false otherwise. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @param {number} source - * @param {number} destination - * @return {boolean} - */ -var validPath = function(n, edges, source, destination) { - const graph = Array.from({ length: n }, () => []); - for (const [u, v] of edges) { - graph[u].push(v); - graph[v].push(u); - } - - const visited = new Set(); - const queue = [source]; - - while (queue.length) { - const vertex = queue.shift(); - if (vertex === destination) return true; - if (visited.has(vertex)) continue; - visited.add(vertex); - - for (const neighbor of graph[vertex]) { - if (!visited.has(neighbor)) { - queue.push(neighbor); - } - } - } - - return false; -}; diff --git a/solutions/1974-minimum-time-to-type-word-using-special-typewriter.js b/solutions/1974-minimum-time-to-type-word-using-special-typewriter.js deleted file mode 100644 index 9c1641e7..00000000 --- a/solutions/1974-minimum-time-to-type-word-using-special-typewriter.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 1974. Minimum Time to Type Word Using Special Typewriter - * https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/ - * Difficulty: Easy - * - * There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle - * with a pointer. A character can only be typed if the pointer is pointing to that character. - * The pointer is initially pointing to the character 'a'. - * - * Each second, you may perform one of the following operations: - * - Move the pointer one character counterclockwise or clockwise. - * - Type the character the pointer is currently on. - * - * Given a string word, return the minimum number of seconds to type out the characters in word. - */ - -/** - * @param {string} word - * @return {number} - */ -var minTimeToType = function(word) { - let position = 'a'; - let result = 0; - - for (const char of word) { - const clockwise = Math.abs(char.charCodeAt(0) - position.charCodeAt(0)); - const counterclockwise = 26 - clockwise; - const moves = Math.min(clockwise, counterclockwise); - result += moves + 1; - position = char; - } - - return result; -}; diff --git a/solutions/1975-maximum-matrix-sum.js b/solutions/1975-maximum-matrix-sum.js deleted file mode 100644 index 92b65dd2..00000000 --- a/solutions/1975-maximum-matrix-sum.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 1975. Maximum Matrix Sum - * https://leetcode.com/problems/maximum-matrix-sum/ - * Difficulty: Medium - * - * You are given an n x n integer matrix. You can do the following operation any number of times: - * - Choose any two adjacent elements of matrix and multiply each of them by -1. - * - * Two elements are considered adjacent if and only if they share a border. - * - * Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the - * matrix's elements using the operation mentioned above. - */ - -/** - * @param {number[][]} matrix - * @return {number} - */ -var maxMatrixSum = function(matrix) { - let totalSum = 0; - let negativeCount = 0; - let minAbs = Infinity; - - for (const row of matrix) { - for (const num of row) { - totalSum += Math.abs(num); - if (num < 0) negativeCount++; - minAbs = Math.min(minAbs, Math.abs(num)); - } - } - - return negativeCount % 2 === 0 ? totalSum : totalSum - 2 * minAbs; -}; diff --git a/solutions/1976-number-of-ways-to-arrive-at-destination.js b/solutions/1976-number-of-ways-to-arrive-at-destination.js deleted file mode 100644 index 85b4ad9f..00000000 --- a/solutions/1976-number-of-ways-to-arrive-at-destination.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 1976. Number of Ways to Arrive at Destination - * https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/ - * Difficulty: Medium - * - * You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional - * roads between some intersections. The inputs are generated such that you can reach any - * intersection from any other intersection and that there is at most one road between any two - * intersections. - * - * You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means - * that there is a road between intersections ui and vi that takes timei minutes to travel. You - * want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the - * shortest amount of time. - * - * Return the number of ways you can arrive at your destination in the shortest amount of time. - * Since the answer may be large, return it modulo 109 + 7. - */ - -/** - * @param {number} n - * @param {number[][]} roads - * @return {number} - */ -var countPaths = function(n, roads) { - const MOD = 1e9 + 7; - const graph = Array.from({ length: n }, () => []); - const distances = new Array(n).fill(Infinity); - const ways = new Array(n).fill(0); - - for (const [u, v, time] of roads) { - graph[u].push([v, time]); - graph[v].push([u, time]); - } - - const queue = [[0, 0]]; - distances[0] = 0; - ways[0] = 1; - - while (queue.length) { - const [dist, node] = queue.shift(); - - if (dist > distances[node]) continue; - - for (const [next, time] of graph[node]) { - const newDist = dist + time; - - if (newDist < distances[next]) { - distances[next] = newDist; - ways[next] = ways[node]; - queue.push([newDist, next]); - queue.sort((a, b) => a[0] - b[0]); - } else if (newDist === distances[next]) { - ways[next] = (ways[next] + ways[node]) % MOD; - } - } - } - - return ways[n - 1]; -}; diff --git a/solutions/1977-number-of-ways-to-separate-numbers.js b/solutions/1977-number-of-ways-to-separate-numbers.js deleted file mode 100644 index 6fad6b5d..00000000 --- a/solutions/1977-number-of-ways-to-separate-numbers.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 1977. Number of Ways to Separate Numbers - * https://leetcode.com/problems/number-of-ways-to-separate-numbers/ - * Difficulty: Hard - * - * You wrote down many positive integers in a string called num. However, you realized that you - * forgot to add commas to seperate the different numbers. You remember that the list of integers - * was non-decreasing and that no integer had leading zeros. - * - * Return the number of possible lists of integers that you could have written down to get the - * string num. Since the answer may be large, return it modulo 109 + 7. - */ - -/** - * @param {string} num - * @return {number} - */ -var numberOfCombinations = function(num) { - const n = num.length; - if (num[0] === '0') return 0; - - const MOD = 1e9 + 7; - const lcp = new Array(n + 1).fill().map(() => new Array(n + 1).fill(0)); - - for (let i = n - 1; i >= 0; i--) { - for (let j = n - 1; j >= 0; j--) { - if (num[i] === num[j]) { - lcp[i][j] = lcp[i + 1][j + 1] + 1; - } - } - } - - const dp = new Array(n).fill().map(() => new Array(n + 1).fill(0)); - const prefixSum = new Array(n).fill().map(() => new Array(n + 1).fill(0)); - - dp[0][1] = 1; - prefixSum[0][1] = 1; - - for (let i = 1; i < n; i++) { - for (let j = 1; j <= i; j++) { - prefixSum[i - 1][j] = (prefixSum[i - 1][j - 1] + dp[i - 1][j]) % MOD; - } - - for (let len = 1; len <= i + 1; len++) { - if (num[i - len + 1] === '0') continue; - - if (i - len < 0) { - dp[i][len] = 1; - continue; - } - - dp[i][len] = prefixSum[i - len][Math.min(i - len + 1, len)]; - - if (len <= i - len + 1) { - const start1 = i - 2 * len + 1; - const start2 = i - len + 1; - - if (!compare(start1, start2, len)) { - dp[i][len] = (dp[i][len] - dp[i - len][len] + MOD) % MOD; - } - } - } - - prefixSum[i][0] = 0; - for (let j = 1; j <= i + 1; j++) { - prefixSum[i][j] = (prefixSum[i][j - 1] + dp[i][j]) % MOD; - } - } - - return prefixSum[n - 1][n]; - - function compare(i1, i2, len) { - const commonLen = lcp[i1][i2]; - if (commonLen >= len) return true; - return i1 + commonLen < n && i2 + commonLen < n && num[i1 + commonLen] <= num[i2 + commonLen]; - } -}; diff --git a/solutions/1979-find-greatest-common-divisor-of-array.js b/solutions/1979-find-greatest-common-divisor-of-array.js deleted file mode 100644 index acf2c5df..00000000 --- a/solutions/1979-find-greatest-common-divisor-of-array.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 1979. Find Greatest Common Divisor of Array - * https://leetcode.com/problems/find-greatest-common-divisor-of-array/ - * Difficulty: Easy - * - * Given an integer array nums, return the greatest common divisor of the smallest number and - * largest number in nums. - * - * The greatest common divisor of two numbers is the largest positive integer that evenly - * divides both numbers. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findGCD = function(nums) { - return gcd(Math.min(...nums), Math.max(...nums)); - - function gcd(a, b) { - return b === 0 ? a : gcd(b, a % b); - } -}; diff --git a/solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js b/solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js deleted file mode 100644 index 6e66a493..00000000 --- a/solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 1981. Minimize the Difference Between Target and Chosen Elements - * https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/ - * Difficulty: Medium - * - * You are given an m x n integer matrix mat and an integer target. - * - * Choose one integer from each row in the matrix such that the absolute difference between - * target and the sum of the chosen elements is minimized. - * - * Return the minimum absolute difference. - * - * The absolute difference between two numbers a and b is the absolute value of a - b. - */ - -/** - * @param {number[][]} mat - * @param {number} target - * @return {number} - */ -var minimizeTheDifference = function(mat, target) { - const m = mat.length; - const maxSum = 70 * m; - let possibleSums = new Set([0]); - - for (const row of mat) { - const nextSums = new Set(); - for (const num of row) { - for (const sum of possibleSums) { - const newSum = sum + num; - if (newSum <= target + maxSum) { - nextSums.add(newSum); - } - } - } - possibleSums = nextSums; - } - - let result = Infinity; - for (const sum of possibleSums) { - result = Math.min(result, Math.abs(sum - target)); - } - - return result; -}; diff --git a/solutions/1982-find-array-given-subset-sums.js b/solutions/1982-find-array-given-subset-sums.js deleted file mode 100644 index da9ab09f..00000000 --- a/solutions/1982-find-array-given-subset-sums.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 1982. Find Array Given Subset Sums - * https://leetcode.com/problems/find-array-given-subset-sums/ - * Difficulty: Hard - * - * You are given an integer n representing the length of an unknown array that you are trying - * to recover. You are also given an array sums containing the values of all 2n subset sums of - * the unknown array (in no particular order). - * - * Return the array ans of length n representing the unknown array. If multiple answers exist, - * return any of them. - * - * An array sub is a subset of an array arr if sub can be obtained from arr by deleting some - * (possibly zero or all) elements of arr. The sum of the elements in sub is one possible - * subset sum of arr. The sum of an empty array is considered to be 0. - * - * Note: Test cases are generated such that there will always be at least one correct answer. - */ - -/** -* @param {number} n -* @param {number[]} sums -* @return {number[]} -*/ -var recoverArray = function(n, sums) { - sums.sort((a, b) => a - b); - - const result = []; - while (result.length < n) { - const diff = sums[1] - sums[0]; - - const withNum = []; - const withoutNum = []; - const freq = new Map(); - for (const sum of sums) { - freq.set(sum, (freq.get(sum) || 0) + 1); - } - - for (const sum of sums) { - if (freq.get(sum) > 0) { - freq.set(sum, freq.get(sum) - 1); - - if (freq.get(sum + diff) > 0) { - freq.set(sum + diff, freq.get(sum + diff) - 1); - withoutNum.push(sum); - withNum.push(sum + diff); - } else { - return []; - } - } - } - - if (withoutNum.includes(0)) { - result.push(diff); - sums = withoutNum; - } else { - result.push(-diff); - sums = withNum; - } - } - - return result; -}; diff --git a/solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js b/solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js deleted file mode 100644 index 889aae95..00000000 --- a/solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 1984. Minimum Difference Between Highest and Lowest of K Scores - * https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/ - * Difficulty: Easy - * - * You are given a 0-indexed integer array nums, where nums[i] represents the score of the - * ith student. You are also given an integer k. - * - * Pick the scores of any k students from the array so that the difference between the highest - * and the lowest of the k scores is minimized. - * - * Return the minimum possible difference. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var minimumDifference = function(nums, k) { - nums.sort((a, b) => a - b); - let result = Infinity; - - for (let i = 0; i <= nums.length - k; i++) { - result = Math.min(result, nums[i + k - 1] - nums[i]); - } - - return result; -}; diff --git a/solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js b/solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js deleted file mode 100644 index f6174274..00000000 --- a/solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 1986. Minimum Number of Work Sessions to Finish the Tasks - * https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/ - * Difficulty: Medium - * - * There are n tasks assigned to you. The task times are represented as an integer array tasks of - * length n, where the ith task takes tasks[i] hours to finish. A work session is when you work - * for at most sessionTime consecutive hours and then take a break. - * - * You should finish the given tasks in a way that satisfies the following conditions: - * - If you start a task in a work session, you must complete it in the same work session. - * - You can start a new task immediately after finishing the previous one. - * - You may complete the tasks in any order. - * - * Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the - * tasks following the conditions above. - * - * The tests are generated such that sessionTime is greater than or equal to the maximum element - * in tasks[i]. - */ - -/** - * @param {number[]} tasks - * @param {number} sessionTime - * @return {number} - */ -var minSessions = function(tasks, sessionTime) { - const n = tasks.length; - const dp = new Array(1 << n).fill(n + 1); - dp[0] = 0; - - for (let mask = 1; mask < 1 << n; mask++) { - let time = 0; - for (let i = 0; i < n; i++) { - if (mask & (1 << i)) { - time += tasks[i]; - } - } - - for (let subset = mask; subset; subset = (subset - 1) & mask) { - if (subset === mask) continue; - let subsetTime = 0; - for (let i = 0; i < n; i++) { - if (subset & (1 << i)) { - subsetTime += tasks[i]; - } - } - if (subsetTime <= sessionTime) { - dp[mask] = Math.min(dp[mask], dp[mask ^ subset] + 1); - } - } - - if (time <= sessionTime) { - dp[mask] = 1; - } - } - - return dp[(1 << n) - 1]; -}; diff --git a/solutions/1987-number-of-unique-good-subsequences.js b/solutions/1987-number-of-unique-good-subsequences.js deleted file mode 100644 index e0d6651c..00000000 --- a/solutions/1987-number-of-unique-good-subsequences.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 1987. Number of Unique Good Subsequences - * https://leetcode.com/problems/number-of-unique-good-subsequences/ - * Difficulty: Hard - * - * You are given a binary string binary. A subsequence of binary is considered good if it is not - * empty and has no leading zeros (with the exception of "0"). - * - * Find the number of unique good subsequences of binary. - * - For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the - * unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are - * not good because they have leading zeros. - * - * Return the number of unique good subsequences of binary. Since the answer may be very large, - * return it modulo 109 + 7. - * - * A subsequence is a sequence that can be derived from another sequence by deleting some or no - * elements without changing the order of the remaining elements. - */ - -/** - * @param {string} binary - * @return {number} - */ -var numberOfUniqueGoodSubsequences = function(binary) { - const MOD = 1e9 + 7; - let endsWithZero = 0; - let endsWithOne = 0; - let hasZero = false; - - for (const digit of binary) { - if (digit === '0') { - hasZero = true; - endsWithZero = (endsWithZero + endsWithOne) % MOD; - } else { - endsWithOne = (endsWithOne + endsWithZero + 1) % MOD; - } - } - - return (endsWithZero + endsWithOne + (hasZero ? 1 : 0)) % MOD; -}; diff --git a/solutions/1991-find-the-middle-index-in-array.js b/solutions/1991-find-the-middle-index-in-array.js deleted file mode 100644 index fa993684..00000000 --- a/solutions/1991-find-the-middle-index-in-array.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 1991. Find the Middle Index in Array - * https://leetcode.com/problems/find-the-middle-index-in-array/ - * Difficulty: Easy - * - * Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst - * all the possible ones). - * - * A middleIndex is an index where nums[0] + nums[1] + ... + - * nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. - * - * If middleIndex == 0, the left side sum is considered to be 0. Similarly, if - * middleIndex == nums.length - 1, the right side sum is considered to be 0. - * - * Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var findMiddleIndex = 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/solutions/1992-find-all-groups-of-farmland.js b/solutions/1992-find-all-groups-of-farmland.js deleted file mode 100644 index 0e39fd7f..00000000 --- a/solutions/1992-find-all-groups-of-farmland.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 1992. Find All Groups of Farmland - * https://leetcode.com/problems/find-all-groups-of-farmland/ - * Difficulty: Medium - * - * You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested - * land and a 1 represents a hectare of farmland. - * - * To keep the land organized, there are designated rectangular areas of hectares that consist - * entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, - * meaning farmland in one group is not four-directionally adjacent to another farmland in a - * different group. - * - * land can be represented by a coordinate system where the top left corner of land is (0, 0) - * and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and - * bottom right corner of each group of farmland. A group of farmland with a top left corner - * at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length - * array [r1, c1, r2, c2]. - * - * Return a 2D array containing the 4-length arrays described above for each group of farmland - * in land. If there are no groups of farmland, return an empty array. You may return the answer - * in any order. - */ - -/** - * @param {number[][]} land - * @return {number[][]} - */ -var findFarmland = function(land) { - const m = land.length; - const n = land[0].length; - const result = []; - - for (let r = 0; r < m; r++) { - for (let c = 0; c < n; c++) { - if (land[r][c] === 1) { - let r2 = r; - let c2 = c; - - while (r2 + 1 < m && land[r2 + 1][c] === 1) r2++; - while (c2 + 1 < n && land[r][c2 + 1] === 1) c2++; - - result.push([r, c, r2, c2]); - - for (let i = r; i <= r2; i++) { - for (let j = c; j <= c2; j++) { - land[i][j] = 0; - } - } - } - } - } - - return result; -}; diff --git a/solutions/1993-operations-on-tree.js b/solutions/1993-operations-on-tree.js deleted file mode 100644 index e1f5952c..00000000 --- a/solutions/1993-operations-on-tree.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * 1993. Operations on Tree - * https://leetcode.com/problems/operations-on-tree/ - * Difficulty: Medium - * - * You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array - * parent where parent[i] is the parent of the ith node. The root of the tree is node 0, - * so parent[0] = -1 since it has no parent. You want to design a data structure that - * allows users to lock, unlock, and upgrade nodes in the tree. - * - * The data structure should support the following functions: - * - Lock: Locks the given node for the given user and prevents other users from locking - * the same node. You may only lock a node using this function if the node is unlocked. - * - Unlock: Unlocks the given node for the given user. You may only unlock a node using - * this function if it is currently locked by the same user. - * - Upgrade: Locks the given node for the given user and unlocks all of its descendants - * regardless of who locked it. You may only upgrade a node if all 3 conditions are true: - * - The node is unlocked, - * - It has at least one locked descendant (by any user), and - * - It does not have any locked ancestors. - * - * Implement the LockingTree class: - * - LockingTree(int[] parent) initializes the data structure with the parent array. - * - lock(int num, int user) returns true if it is possible for the user with id user to lock - * the node num, or false otherwise. If it is possible, the node num will become locked by - * the user with id user. - * - unlock(int num, int user) returns true if it is possible for the user with id user to - * unlock the node num, or false otherwise. If it is possible, the node num will become unlocked. - * - upgrade(int num, int user) returns true if it is possible for the user with id user to - * upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded. - */ - -/** - * @param {number[]} parent - */ -var LockingTree = function(parent) { - this.parent = parent; - this.locked = new Map(); - this.children = new Array(parent.length).fill().map(() => []); - for (let i = 1; i < parent.length; i++) { - this.children[parent[i]].push(i); - } -}; - -/** - * @param {number} num - * @param {number} user - * @return {boolean} - */ -LockingTree.prototype.lock = function(num, user) { - if (this.locked.has(num)) return false; - this.locked.set(num, user); - return true; -}; - -/** - * @param {number} num - * @param {number} user - * @return {boolean} - */ -LockingTree.prototype.unlock = function(num, user) { - if (!this.locked.has(num) || this.locked.get(num) !== user) return false; - this.locked.delete(num); - return true; -}; - -/** - * @param {number} num - * @param {number} user - * @return {boolean} - */ -LockingTree.prototype.upgrade = function(num, user) { - if (this.locked.has(num)) return false; - - let node = num; - while (node !== -1) { - if (this.locked.has(node)) return false; - node = this.parent[node]; - } - - const descendants = []; - const queue = [num]; - let hasLockedDescendant = false; - - while (queue.length) { - const curr = queue.shift(); - if (this.locked.has(curr)) { - hasLockedDescendant = true; - descendants.push(curr); - } - queue.push(...this.children[curr]); - } - - if (!hasLockedDescendant) return false; - - for (const descendant of descendants) { - this.locked.delete(descendant); - } - this.locked.set(num, user); - return true; -}; diff --git a/solutions/1994-the-number-of-good-subsets.js b/solutions/1994-the-number-of-good-subsets.js deleted file mode 100644 index 7fb63535..00000000 --- a/solutions/1994-the-number-of-good-subsets.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 1994. The Number of Good Subsets - * https://leetcode.com/problems/the-number-of-good-subsets/ - * Difficulty: Hard - * - * You are given an integer array nums. We call a subset of nums good if its product can be - * represented as a product of one or more distinct prime numbers. - * - * - For example, if nums = [1, 2, 3, 4]: - * - [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 - * respectively. - * - [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively. - * - * Return the number of different good subsets in nums modulo 109 + 7. - * - * A subset of nums is any array that can be obtained by deleting some (possibly none or all) - * elements from nums. Two subsets are different if and only if the chosen indices to delete - * are different. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var numberOfGoodSubsets = function(nums) { - const MOD = 1e9 + 7; - const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; - const freq = new Array(31).fill(0); - for (const num of nums) { - freq[num]++; - } - - const dp = new Array(1 << primes.length).fill(0); - dp[0] = 1; - for (let i = 0; i < freq[1]; i++) { - dp[0] = (dp[0] * 2) % MOD; - } - - for (let num = 2; num <= 30; num++) { - if (freq[num] === 0) continue; - let mask = 0; - let valid = true; - for (let i = 0; i < primes.length; i++) { - let count = 0; - let temp = num; - while (temp % primes[i] === 0) { - count++; - temp /= primes[i]; - } - if (count > 1) { - valid = false; - break; - } - if (count === 1) { - mask |= 1 << i; - } - } - - if (!valid) continue; - - const prev = dp.slice(); - for (let j = 0; j < 1 << primes.length; j++) { - if ((j & mask) === 0) { - dp[j | mask] = (dp[j | mask] + prev[j] * freq[num]) % MOD; - } - } - } - - let result = 0; - for (let i = 1; i < 1 << primes.length; i++) { - result = (result + dp[i]) % MOD; - } - - return result; -}; diff --git a/solutions/1995-count-special-quadruplets.js b/solutions/1995-count-special-quadruplets.js deleted file mode 100644 index e37902ac..00000000 --- a/solutions/1995-count-special-quadruplets.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 1995. Count Special Quadruplets - * https://leetcode.com/problems/count-special-quadruplets/ - * Difficulty: Easy - * - * Given a 0-indexed integer array nums, return the number of distinct quadruplets - * (a, b, c, d) such that: - * - nums[a] + nums[b] + nums[c] == nums[d], and - * - a < b < c < d - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var countQuadruplets = function(nums) { - const map = new Map(); - let result = 0; - - for (let c = nums.length - 2; c >= 2; c--) { - map.set(nums[c + 1], (map.get(nums[c + 1]) || 0) + 1); - for (let a = 0; a < c - 1; a++) { - for (let b = a + 1; b < c; b++) { - const sum = nums[a] + nums[b] + nums[c]; - result += map.get(sum) || 0; - } - } - } - - return result; -}; diff --git a/solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js b/solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js deleted file mode 100644 index 6dde2362..00000000 --- a/solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 1997. First Day Where You Have Been in All the Rooms - * https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/ - * Difficulty: Medium - * - * There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting - * from 0. You will go in and visit one room a day. - * - * Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is - * determined by the following rules and a given 0-indexed array nextVisit of length n: - * - Assuming that on a day, you visit room i, - * - if you have been in room i an odd number of times (including the current visit), on the next - * day you will visit a room with a lower or equal room number specified by nextVisit[i] - * where 0 <= nextVisit[i] <= i; - * - if you have been in room i an even number of times (including the current visit), on the - * next day you will visit room (i + 1) mod n. - * - * Return the label of the first day where you have been in all the rooms. It can be shown - * that such a day exists. Since the answer may be very large, return it modulo 109 + 7. - */ - -/** - * @param {number[]} nextVisit - * @return {number} - */ -var firstDayBeenInAllRooms = function(nextVisit) { - const MOD = 1e9 + 7; - const n = nextVisit.length; - const dp = new Array(n).fill(0); - - for (let i = 1; i < n; i++) { - dp[i] = (2 * dp[i - 1] + 2 - dp[nextVisit[i - 1]] + MOD) % MOD; - } - - return dp[n - 1]; -}; diff --git a/solutions/1998-gcd-sort-of-an-array.js b/solutions/1998-gcd-sort-of-an-array.js deleted file mode 100644 index 97bb5a39..00000000 --- a/solutions/1998-gcd-sort-of-an-array.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * 1998. GCD Sort of an Array - * https://leetcode.com/problems/gcd-sort-of-an-array/ - * Difficulty: Hard - * - * You are given an integer array nums, and you can perform the following operation any - * number of times on nums: - * - Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 - * where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j]. - * - * Return true if it is possible to sort nums in non-decreasing order using the above swap - * method, or false otherwise. - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ -var gcdSort = function(nums) { - const maxNum = Math.max(...nums); - const parent = new Array(maxNum + 1).fill().map((_, i) => i); - const minPrime = new Array(maxNum + 1).fill(0); - for (let i = 2; i <= maxNum; i++) { - if (minPrime[i] === 0) { - for (let j = i; j <= maxNum; j += i) { - minPrime[j] = i; - } - } - } - - const groups = new Map(); - for (const num of nums) { - let curr = num; - const primes = new Set(); - while (curr > 1) { - const prime = minPrime[curr]; - primes.add(prime); - curr /= prime; - } - for (const prime of primes) { - if (!groups.has(prime)) groups.set(prime, []); - groups.get(prime).push(num); - } - } - - for (const numbers of groups.values()) { - for (let i = 1; i < numbers.length; i++) { - union(numbers[i - 1], numbers[i], parent); - } - } - - const sorted = [...nums].sort((a, b) => a - b); - for (let i = 0; i < nums.length; i++) { - if (find(nums[i], parent) !== find(sorted[i], parent)) { - return false; - } - } - - return true; - - function find(x, parent) { - if (parent[x] !== x) parent[x] = find(parent[x], parent); - return parent[x]; - } - - function union(x, y, parent) { - parent[find(x, parent)] = find(y, parent); - } -}; diff --git a/solutions/2001-number-of-pairs-of-interchangeable-rectangles.js b/solutions/2001-number-of-pairs-of-interchangeable-rectangles.js deleted file mode 100644 index 89f2611e..00000000 --- a/solutions/2001-number-of-pairs-of-interchangeable-rectangles.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 2001. Number of Pairs of Interchangeable Rectangles - * https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/ - * Difficulty: Medium - * - * You are given n rectangles represented by a 0-indexed 2D integer array rectangles, - * where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. - * - * Two rectangles i and j (i < j) are considered interchangeable if they have the same - * width-to-height ratio. More formally, two rectangles are interchangeable if - * widthi/heighti == widthj/heightj (using decimal division, not integer division). - * - * Return the number of pairs of interchangeable rectangles in rectangles. - */ - -/** - * @param {number[][]} rectangles - * @return {number} - */ -var interchangeableRectangles = function(rectangles) { - const map = new Map(); - let result = 0; - - for (const [width, height] of rectangles) { - const gcd = (a, b) => b === 0 ? a : gcd(b, a % b); - const divisor = gcd(width, height); - const ratio = `${width / divisor}/${height / divisor}`; - - if (map.has(ratio)) { - result += map.get(ratio); - map.set(ratio, map.get(ratio) + 1); - } else { - map.set(ratio, 1); - } - } - - return result; -}; diff --git a/solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js b/solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js deleted file mode 100644 index ae489e83..00000000 --- a/solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 2002. Maximum Product of the Length of Two Palindromic Subsequences - * https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/ - * Difficulty: Medium - * - * Given a string s, find two disjoint palindromic subsequences of s such that the product of their - * lengths is maximized. The two subsequences are disjoint if they do not both pick a character at - * the same index. - * - * Return the maximum possible product of the lengths of the two palindromic subsequences. - * - * A subsequence is a string that can be derived from another string by deleting some or no - * characters without changing the order of the remaining characters. A string is palindromic - * if it reads the same forward and backward. - */ - -/** - * @param {string} s - * @return {number} - */ -var maxProduct = function(s) { - const n = s.length; - let result = 0; - - for (let mask1 = 1; mask1 < (1 << n); mask1++) { - for (let mask2 = 1; mask2 < (1 << n); mask2++) { - if (mask1 & mask2) continue; - const len1 = isPalindrome(s, mask1); - if (len1 === 0) continue; - const len2 = isPalindrome(s, mask2); - if (len2 === 0) continue; - result = Math.max(result, len1 * len2); - } - } - - return result; - - function isPalindrome(str, mask) { - const chars = []; - for (let i = 0; i < n; i++) { - if (mask & (1 << i)) chars.push(str[i]); - } - let left = 0; - let right = chars.length - 1; - while (left < right) { - if (chars[left++] !== chars[right--]) return 0; - } - return chars.length; - } -}; diff --git a/solutions/2003-smallest-missing-genetic-value-in-each-subtree.js b/solutions/2003-smallest-missing-genetic-value-in-each-subtree.js deleted file mode 100644 index f57b89d8..00000000 --- a/solutions/2003-smallest-missing-genetic-value-in-each-subtree.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 2003. Smallest Missing Genetic Value in Each Subtree - * https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/ - * Difficulty: Hard - * - * There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a - * 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is - * the root, parents[0] == -1. - * - * There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. - * You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for - * node i. - * - * Return an array ans of length n where ans[i] is the smallest genetic value that is missing - * from the subtree rooted at node i. - * - * The subtree rooted at a node x contains node x and all of its descendant nodes. - */ - -/** - * @param {number[]} parents - * @param {number[]} nums - * @return {number[]} - */ -var smallestMissingValueSubtree = function(parents, nums) { - const n = parents.length; - const result = new Array(n).fill(1); - const children = Array.from({ length: n }, () => []); - const seen = new Set(); - let maxMissing = 1; - - for (let i = 1; i < n; i++) { - children[parents[i]].push(i); - } - - const nodeWithOne = nums.indexOf(1); - if (nodeWithOne === -1) return result; - - let current = nodeWithOne; - while (current !== -1) { - const stack = [current]; - while (stack.length) { - const node = stack.pop(); - seen.add(nums[node]); - for (const child of children[node]) { - if (!seen.has(nums[child])) stack.push(child); - } - } - while (seen.has(maxMissing)) maxMissing++; - result[current] = maxMissing; - current = parents[current]; - } - - return result; -}; diff --git a/solutions/2006-count-number-of-pairs-with-absolute-difference-k.js b/solutions/2006-count-number-of-pairs-with-absolute-difference-k.js deleted file mode 100644 index 022c9b4d..00000000 --- a/solutions/2006-count-number-of-pairs-with-absolute-difference-k.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 2006. Count Number of Pairs With Absolute Difference K - * https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ - * Difficulty: Easy - * - * Given an integer array nums and an integer k, return the number of pairs (i, j) where - * i < j such that |nums[i] - nums[j]| == k. - * - * The value of |x| is defined as: - * - x if x >= 0. - * - -x if x < 0. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var countKDifference = function(nums, k) { - const map = new Map(); - let result = 0; - - for (const num of nums) { - result += (map.get(num - k) || 0) + (map.get(num + k) || 0); - map.set(num, (map.get(num) || 0) + 1); - } - - return result; -}; diff --git a/solutions/2007-find-original-array-from-doubled-array.js b/solutions/2007-find-original-array-from-doubled-array.js deleted file mode 100644 index ca1d1357..00000000 --- a/solutions/2007-find-original-array-from-doubled-array.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 2007. Find Original Array From Doubled Array - * https://leetcode.com/problems/find-original-array-from-doubled-array/ - * Difficulty: Medium - * - * An integer array original is transformed into a doubled array changed by appending twice the - * value of every element in original, and then randomly shuffling the resulting array. - * - * Given an array changed, return original if changed is a doubled array. If changed is not a - * doubled array, return an empty array. The elements in original may be returned in any order. - */ - -/** - * @param {number[]} changed - * @return {number[]} - */ -var findOriginalArray = function(changed) { - if (changed.length % 2 !== 0) return []; - - const frequency = new Map(); - const result = []; - - changed.sort((a, b) => a - b); - - for (const num of changed) { - frequency.set(num, (frequency.get(num) || 0) + 1); - } - - for (const num of changed) { - if (frequency.get(num) === 0) continue; - - frequency.set(num, frequency.get(num) - 1); - - const doubled = num * 2; - if (!frequency.has(doubled) || frequency.get(doubled) === 0) return []; - - frequency.set(doubled, frequency.get(doubled) - 1); - result.push(num); - } - - return result; -}; diff --git a/solutions/2008-maximum-earnings-from-taxi.js b/solutions/2008-maximum-earnings-from-taxi.js deleted file mode 100644 index fd7cbaac..00000000 --- a/solutions/2008-maximum-earnings-from-taxi.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 2008. Maximum Earnings From Taxi - * https://leetcode.com/problems/maximum-earnings-from-taxi/ - * Difficulty: Medium - * - * There are n points on a road you are driving your taxi on. The n points on the road are - * labeled from 1 to n in the direction you are going, and you want to drive from point 1 - * to point n to make money by picking up passengers. You cannot change the direction of the taxi. - * - * The passengers are represented by a 0-indexed 2D integer array rides, where - * rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point - * starti to point endi who is willing to give a tipi dollar tip. - * - * For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive - * at most one passenger at a time. - * - * Given n and rides, return the maximum number of dollars you can earn by picking up the - * passengers optimally. - * - * Note: You may drop off a passenger and pick up a different passenger at the same point. - */ - -/** - * @param {number} n - * @param {number[][]} rides - * @return {number} - */ -var maxTaxiEarnings = function(n, rides) { - rides.sort((a, b) => a[1] - b[1]); - const dp = new Array(n + 1).fill(0); - let rideIndex = 0; - - for (let point = 1; point <= n; point++) { - dp[point] = dp[point - 1]; - while (rideIndex < rides.length && rides[rideIndex][1] === point) { - const [start, end, tip] = rides[rideIndex]; - dp[point] = Math.max(dp[point], dp[start] + (end - start + tip)); - rideIndex++; - } - } - - return dp[n]; -}; diff --git a/solutions/2009-minimum-number-of-operations-to-make-array-continuous.js b/solutions/2009-minimum-number-of-operations-to-make-array-continuous.js deleted file mode 100644 index d4cd063e..00000000 --- a/solutions/2009-minimum-number-of-operations-to-make-array-continuous.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 2009. Minimum Number of Operations to Make Array Continuous - * https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/ - * Difficulty: Hard - * - * You are given an integer array nums. In one operation, you can replace any element in nums - * with any integer. - * - * nums is considered continuous if both of the following conditions are fulfilled: - * - All elements in nums are unique. - * - The difference between the maximum element and the minimum element in nums equals - * nums.length - 1. - * - * For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. - * - * Return the minimum number of operations to make nums continuous. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minOperations = function(nums) { - const n = nums.length; - const uniqueNums = [...new Set(nums)].sort((a, b) => a - b); - let result = n; - - for (let i = 0, j = 0; i < uniqueNums.length; i++) { - while (j < uniqueNums.length && uniqueNums[j] - uniqueNums[i] <= n - 1) { - j++; - } - result = Math.min(result, n - (j - i)); - } - - return result; -}; diff --git a/solutions/2012-sum-of-beauty-in-the-array.js b/solutions/2012-sum-of-beauty-in-the-array.js deleted file mode 100644 index 957da790..00000000 --- a/solutions/2012-sum-of-beauty-in-the-array.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 2012. Sum of Beauty in the Array - * https://leetcode.com/problems/sum-of-beauty-in-the-array/ - * Difficulty: Medium - * - * You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) - * the beauty of nums[i] equals: - * - 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1. - * - 1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied. - * - 0, if none of the previous conditions holds. - * - * Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var sumOfBeauties = function(nums) { - const n = nums.length; - let result = 0; - const leftMax = new Array(n).fill(nums[0]); - const rightMin = new Array(n).fill(nums[n - 1]); - - for (let i = 1; i < n; i++) { - leftMax[i] = Math.max(leftMax[i - 1], nums[i - 1]); - } - - for (let i = n - 2; i >= 0; i--) { - rightMin[i] = Math.min(rightMin[i + 1], nums[i + 1]); - } - - for (let i = 1; i < n - 1; i++) { - if (leftMax[i] < nums[i] && nums[i] < rightMin[i]) { - result += 2; - } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { - result += 1; - } - } - - return result; -}; diff --git a/solutions/2013-detect-squares.js b/solutions/2013-detect-squares.js deleted file mode 100644 index 606076c3..00000000 --- a/solutions/2013-detect-squares.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 2013. Detect Squares - * https://leetcode.com/problems/detect-squares/ - * Difficulty: Medium - * - * You are given a stream of points on the X-Y plane. Design an algorithm that: - * - Adds new points from the stream into a data structure. Duplicate points are allowed and should - * be treated as different points. - * - Given a query point, counts the number of ways to choose three points from the data structure - * such that the three points and the query point form an axis-aligned square with positive area. - * - * An axis-aligned square is a square whose edges are all the same length and are either parallel - * or perpendicular to the x-axis and y-axis. - * - * Implement the DetectSquares class: - * - DetectSquares() Initializes the object with an empty data structure. - * - void add(int[] point) Adds a new point point = [x, y] to the data structure. - * - int count(int[] point) Counts the number of ways to form axis-aligned squares with point - * point = [x, y] as described above. - */ - -var DetectSquares = function() { - this.points = new Map(); -}; - -/** - * @param {number[]} point - * @return {void} - */ -DetectSquares.prototype.add = function(point) { - const [x, y] = point; - const key = `${x},${y}`; - this.points.set(key, (this.points.get(key) || 0) + 1); -}; - -/** - * @param {number[]} point - * @return {number} - */ -DetectSquares.prototype.count = function(point) { - const [x, y] = point; - let result = 0; - - for (const [key, count] of this.points) { - const [px, py] = key.split(',').map(Number); - if (px === x || py === y || Math.abs(px - x) !== Math.abs(py - y)) continue; - - const point1 = `${x},${py}`; - const point2 = `${px},${y}`; - result += count * (this.points.get(point1) || 0) * (this.points.get(point2) || 0); - } - - return result; -}; diff --git a/solutions/2014-longest-subsequence-repeated-k-times.js b/solutions/2014-longest-subsequence-repeated-k-times.js deleted file mode 100644 index ec575695..00000000 --- a/solutions/2014-longest-subsequence-repeated-k-times.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 2014. Longest Subsequence Repeated k Times - * https://leetcode.com/problems/longest-subsequence-repeated-k-times/ - * Difficulty: Hard - * - * You are given a string s of length n, and an integer k. You are tasked to find the longest - * subsequence repeated k times in string s. - * - * A subsequence is a string that can be derived from another string by deleting some or no - * characters without changing the order of the remaining characters. - * - * A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, - * where seq * k represents a string constructed by concatenating seq k times. - * - For example, "bba" is repeated 2 times in the string "bababcba", because the string - * "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the - * string "bababcba". - * - * Return the longest subsequence repeated k times in string s. If multiple such subsequences - * are found, return the lexicographically largest one. If there is no such subsequence, - * return an empty string. - */ - -/** - * @param {string} s - * @param {number} k - * @return {string} - */ -var longestSubsequenceRepeatedK = function(s, k) { - const n = s.length; - const freq = new Array(26).fill(0); - for (const char of s) { - freq[char.charCodeAt(0) - 97]++; - } - - let candidates = ''; - for (let i = 0; i < 26; i++) { - const count = Math.floor(freq[i] / k); - candidates += String.fromCharCode(97 + i).repeat(count); - } - - function canFormSubsequence(seq) { - let j = 0; - for (let i = 0; i < n && j < seq.length * k; i++) { - if (s[i] === seq[j % seq.length]) j++; - } - return j >= seq.length * k; - } - - let result = ''; - backtrack('', candidates); - return result; - - function backtrack(curr, remaining) { - if (curr.length > result.length || (curr.length === result.length && curr > result)) { - if (canFormSubsequence(curr)) result = curr; - } - if (!remaining) return; - - for (let i = remaining.length - 1; i >= 0; i--) { - const nextChar = remaining[i]; - backtrack(curr + nextChar, remaining.slice(0, i) + remaining.slice(i + 1)); - } - } -}; diff --git a/solutions/2018-check-if-word-can-be-placed-in-crossword.js b/solutions/2018-check-if-word-can-be-placed-in-crossword.js deleted file mode 100644 index 0a22bd5c..00000000 --- a/solutions/2018-check-if-word-can-be-placed-in-crossword.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 2018. Check if Word Can Be Placed In Crossword - * https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/ - * Difficulty: Medium - * - * You are given an m x n matrix board, representing the current state of a crossword puzzle. - * The crossword contains lowercase English letters (from solved words), ' ' to represent any - * empty cells, and '#' to represent any blocked cells. - * - * A word can be placed horizontally (left to right or right to left) or vertically (top to - * bottom or bottom to top) in the board if: - * - It does not occupy a cell containing the character '#'. - * - The cell each letter is placed in must either be ' ' (empty) or match the letter already - * on the board. - * - There must not be any empty cells ' ' or other lowercase letters directly left or right - * of the word if the word was placed horizontally. - * - There must not be any empty cells ' ' or other lowercase letters directly above or below - * the word if the word was placed vertically. - * - * Given a string word, return true if word can be placed in board, or false otherwise. - */ - -/** - * @param {character[][]} board - * @param {string} word - * @return {boolean} - */ -var placeWordInCrossword = function(board, word) { - const rows = board.length; - const cols = board[0].length; - const wordLen = word.length; - - function canPlace(row, col, dr, dc) { - for (let i = 0; i < wordLen; i++) { - const r = row + i * dr; - const c = col + i * dc; - if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] === '#') return false; - if (board[r][c] !== ' ' && board[r][c] !== word[i]) return false; - } - - const beforeR = row - dr; - const beforeC = col - dc; - const afterR = row + wordLen * dr; - const afterC = col + wordLen * dc; - - if ((beforeR >= 0 && beforeR < rows && beforeC >= 0 - && beforeC < cols && board[beforeR][beforeC] !== '#') - || (afterR >= 0 && afterR < rows && afterC >= 0 - && afterC < cols && board[afterR][afterC] !== '#')) { - return false; - } - - return true; - } - - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (canPlace(r, c, 0, 1) || canPlace(r, c, 0, -1) - || canPlace(r, c, 1, 0) || canPlace(r, c, -1, 0)) { - return true; - } - } - } - - return false; -}; diff --git a/solutions/2019-the-score-of-students-solving-math-expression.js b/solutions/2019-the-score-of-students-solving-math-expression.js deleted file mode 100644 index b4391da2..00000000 --- a/solutions/2019-the-score-of-students-solving-math-expression.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 2019. The Score of Students Solving Math Expression - * https://leetcode.com/problems/the-score-of-students-solving-math-expression/ - * Difficulty: Hard - * - * You are given a string s that contains digits 0-9, addition symbols '+', and multiplication - * symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). - * This expression was given to n elementary school students. The students were instructed to - * get the answer of the expression by following this order of operations: - * 1. Compute multiplication, reading from left to right; Then, - * 2. Compute addition, reading from left to right. - * - * You are given an integer array answers of length n, which are the submitted answers of the - * students in no particular order. You are asked to grade the answers, by following these rules: - * - If an answer equals the correct answer of the expression, this student will be rewarded - * 5 points; - * - Otherwise, if the answer could be interpreted as if the student applied the operators in - * the wrong order but had correct arithmetic, this student will be rewarded 2 points; - * - Otherwise, this student will be rewarded 0 points. - * - * Return the sum of the points of the students. - */ - -/** - * @param {string} s - * @param {number[]} answers - * @return {number} - */ -var scoreOfStudents = function(s, answers) { - const correct = eval(s.replace(/(\d)([*+])/g, '$1 $2 ')); - - const n = s.length; - const dp = new Map(); - - function compute(start, end) { - const key = `${start},${end}`; - if (dp.has(key)) return dp.get(key); - - const results = new Set(); - if (start === end) { - results.add(Number(s[start])); - dp.set(key, results); - return results; - } - - for (let i = start + 1; i < end; i += 2) { - const leftResults = compute(start, i - 1); - const rightResults = compute(i + 1, end); - const op = s[i]; - - for (const left of leftResults) { - for (const right of rightResults) { - const val = op === '+' ? left + right : left * right; - if (val <= 1000) results.add(val); - } - } - } - - dp.set(key, results); - return results; - } - - const wrongAnswers = compute(0, n - 1); - let result = 0; - - for (const answer of answers) { - if (answer === correct) result += 5; - else if (wrongAnswers.has(answer)) result += 2; - } - - return result; -}; diff --git a/solutions/2022-convert-1d-array-into-2d-array.js b/solutions/2022-convert-1d-array-into-2d-array.js deleted file mode 100644 index a550b710..00000000 --- a/solutions/2022-convert-1d-array-into-2d-array.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 2022. Convert 1D Array Into 2D Array - * https://leetcode.com/problems/convert-1d-array-into-2d-array/ - * Difficulty: Easy - * - * You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, - * m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n - * columns using all the elements from original. - * - * The elements from indices 0 to n - 1 (inclusive) of original should form the first row - * of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should - * form the second row of the constructed 2D array, and so on. - * - * Return an m x n 2D array constructed according to the above procedure, or an empty 2D array - * if it is impossible. - */ - -/** - * @param {number[]} original - * @param {number} m - * @param {number} n - * @return {number[][]} - */ -var construct2DArray = function(original, m, n) { - if (original.length !== m * n) return []; - - const result = []; - for (let i = 0; i < m; i++) { - result.push(original.slice(i * n, (i + 1) * n)); - } - - return result; -}; diff --git a/solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js b/solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js deleted file mode 100644 index f2e98de0..00000000 --- a/solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 2023. Number of Pairs of Strings With Concatenation Equal to Target - * https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/ - * Difficulty: Medium - * - * Given an array of digit strings nums and a digit string target, return the number of pairs of - * indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target. - */ - -/** - * @param {string[]} nums - * @param {string} target - * @return {number} - */ -var numOfPairs = function(nums, target) { - const map = new Map(); - let result = 0; - - for (const num of nums) { - if (target.startsWith(num)) { - const suffix = target.slice(num.length); - result += map.get(suffix) || 0; - } - if (target.endsWith(num)) { - const prefix = target.slice(0, target.length - num.length); - result += map.get(prefix) || 0; - } - map.set(num, (map.get(num) || 0) + 1); - } - - return result; -}; diff --git a/solutions/2024-maximize-the-confusion-of-an-exam.js b/solutions/2024-maximize-the-confusion-of-an-exam.js deleted file mode 100644 index f79d25b1..00000000 --- a/solutions/2024-maximize-the-confusion-of-an-exam.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 2024. Maximize the Confusion of an Exam - * https://leetcode.com/problems/maximize-the-confusion-of-an-exam/ - * Difficulty: Medium - * - * A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting - * false. He wants to confuse the students by maximizing the number of consecutive questions with - * the same answer (multiple trues or multiple falses in a row). - * - * You are given a string answerKey, where answerKey[i] is the original answer to the ith question. - * In addition, you are given an integer k, the maximum number of times you may perform the - * following operation: - * - Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). - * - * Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the - * operation at most k times. - */ - -/** - * @param {string} answerKey - * @param {number} k - * @return {number} - */ -var maxConsecutiveAnswers = function(answerKey, k) { - const flipsLeft = k; - const count = { T: 0, F: 0 }; - let result = 0; - let left = 0; - - for (let right = 0; right < answerKey.length; right++) { - count[answerKey[right]]++; - const maxCount = Math.max(count.T, count.F); - - while (right - left + 1 - maxCount > flipsLeft) { - count[answerKey[left]]--; - left++; - } - - result = Math.max(result, right - left + 1); - } - - return result; -}; diff --git a/solutions/2025-maximum-number-of-ways-to-partition-an-array.js b/solutions/2025-maximum-number-of-ways-to-partition-an-array.js deleted file mode 100644 index 2e28cd39..00000000 --- a/solutions/2025-maximum-number-of-ways-to-partition-an-array.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 2025. Maximum Number of Ways to Partition an Array - * https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/ - * Difficulty: Hard - * - * You are given a 0-indexed integer array nums of length n. The number of ways to partition - * nums is the number of pivot indices that satisfy both conditions: - * - 1 <= pivot < n - * - nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1] - * - * You are also given an integer k. You can choose to change the value of one element of nums to - * k, or to leave the array unchanged. - * - * Return the maximum possible number of ways to partition nums to satisfy both conditions after - * changing at most one element. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var waysToPartition = function(nums, k) { - const n = nums.length; - const prefixSums = [nums[0]]; - const leftDiffs = new Map(); - const rightDiffs = new Map(); - - for (let i = 1; i < n; i++) { - prefixSums[i] = prefixSums[i - 1] + nums[i]; - const diff = prefixSums[i - 1]; - rightDiffs.set(diff, (rightDiffs.get(diff) || 0) + 1); - } - - const totalSum = prefixSums[n - 1]; - let result = totalSum % 2 === 0 ? (rightDiffs.get(totalSum / 2) || 0) : 0; - - for (let i = 0; i < n; i++) { - const delta = k - nums[i]; - const newTotalSum = totalSum + delta; - - if (newTotalSum % 2 === 0) { - const targetSum = newTotalSum / 2; - const waysFromLeft = leftDiffs.get(targetSum) || 0; - const waysFromRight = rightDiffs.get(targetSum - delta) || 0; - result = Math.max(result, waysFromLeft + waysFromRight); - } - - if (i < n - 1) { - const currentDiff = prefixSums[i]; - leftDiffs.set(currentDiff, (leftDiffs.get(currentDiff) || 0) + 1); - rightDiffs.set(currentDiff, rightDiffs.get(currentDiff) - 1); - } - } - - return result; -}; diff --git a/solutions/2028-find-missing-observations.js b/solutions/2028-find-missing-observations.js deleted file mode 100644 index 29296fbc..00000000 --- a/solutions/2028-find-missing-observations.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 2028. Find Missing Observations - * https://leetcode.com/problems/find-missing-observations/ - * Difficulty: Medium - * - * You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n - * of the observations went missing, and you only have the observations of m rolls. - * Fortunately, you have also calculated the average value of the n + m rolls. - * - * You are given an integer array rolls of length m where rolls[i] is the value of the ith - * observation. You are also given the two integers mean and n. - * - * Return an array of length n containing the missing observations such that the average - * value of the n + m rolls is exactly mean. If there are multiple valid answers, return - * any of them. If no such array exists, return an empty array. - * - * The average value of a set of k numbers is the sum of the numbers divided by k. - * - * Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m. - */ - -/** - * @param {number[]} rolls - * @param {number} mean - * @param {number} n - * @return {number[]} - */ -var missingRolls = function(rolls, mean, n) { - const totalRolls = rolls.length + n; - const targetSum = mean * totalRolls; - const currentSum = rolls.reduce((sum, roll) => sum + roll, 0); - const missingSum = targetSum - currentSum; - - if (missingSum < n || missingSum > 6 * n) return []; - - const baseValue = Math.floor(missingSum / n); - const remainder = missingSum % n; - const result = []; - - for (let i = 0; i < n; i++) { - if (i < remainder) { - result.push(baseValue + 1); - } else { - result.push(baseValue); - } - } - - return result; -}; diff --git a/solutions/2029-stone-game-ix.js b/solutions/2029-stone-game-ix.js deleted file mode 100644 index 31ea3bb8..00000000 --- a/solutions/2029-stone-game-ix.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 2029. Stone Game IX - * https://leetcode.com/problems/stone-game-ix/ - * Difficulty: Medium - * - * Alice and Bob continue their games with stones. There is a row of n stones, and each stone has - * an associated value. You are given an integer array stones, where stones[i] is the value of the - * ith stone. - * - * Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any - * stone from stones. The player who removes a stone loses if the sum of the values of all - * removed stones is divisible by 3. Bob will win automatically if there are no remaining stones - * (even if it is Alice's turn). - * - * Assuming both players play optimally, return true if Alice wins and false if Bob wins. - */ - -/** - * @param {number[]} stones - * @return {boolean} - */ -var stoneGameIX = function(stones) { - const remainderCount = [0, 0, 0]; - for (const stone of stones) { - remainderCount[stone % 3]++; - } - - if (remainderCount[0] % 2 === 0) { - return remainderCount[1] >= 1 && remainderCount[2] >= 1; - } - - return Math.abs(remainderCount[1] - remainderCount[2]) > 2; -}; diff --git a/solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js b/solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js deleted file mode 100644 index 9e3f916b..00000000 --- a/solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * 2030. Smallest K-Length Subsequence With Occurrences of a Letter - * https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/ - * Difficulty: Hard - * - * You are given a string s, an integer k, a letter letter, and an integer repetition. - * - * Return the lexicographically smallest subsequence of s of length k that has the letter - * letter appear at least repetition times. The test cases are generated so that the letter - * appears in s at least repetition times. - * - * A subsequence is a string that can be derived from another string by deleting some or no - * characters without changing the order of the remaining characters. - * - * A string a is lexicographically smaller than a string b if in the first position where a - * and b differ, string a has a letter that appears earlier in the alphabet than the - * corresponding letter in b. - */ - -/** - * @param {string} s - * @param {number} k - * @param {character} letter - * @param {number} repetition - * @return {string} - */ -var smallestSubsequence = function(s, k, letter, repetition) { - const n = s.length; - let letterTotal = 0; - for (let i = 0; i < n; i++) { - if (s[i] === letter) letterTotal++; - } - - const stack = []; - let stackLetterCount = 0; - let remainingCount = letterTotal; - - for (let i = 0; i < n; i++) { - const char = s[i]; - - if (char === letter) { - remainingCount--; - } - - while ( - stack.length > 0 && stack[stack.length - 1] > char && stack.length - 1 + (n - i) >= k - && (stack[stack.length - 1] !== letter || stackLetterCount + remainingCount > repetition) - ) { - if (stack[stack.length - 1] === letter) { - stackLetterCount--; - } - stack.pop(); - } - - if (stack.length < k) { - if (char === letter) { - stackLetterCount++; - } - - const neededLetters = repetition - stackLetterCount; - const remainingPositions = k - stack.length - 1; - if (char === letter || remainingPositions >= neededLetters) { - stack.push(char); - } - } - } - - if (stackLetterCount < repetition) { - let missingLetters = repetition - stackLetterCount; - const result = [...stack]; - - for (let i = k - 1; i >= 0 && missingLetters > 0; i--) { - if (result[i] !== letter) { - result[i] = letter; - missingLetters--; - } - } - - return result.join(''); - } - - return stack.join(''); -}; diff --git a/solutions/2032-two-out-of-three.js b/solutions/2032-two-out-of-three.js deleted file mode 100644 index 566e6033..00000000 --- a/solutions/2032-two-out-of-three.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 2032. Two Out of Three - * https://leetcode.com/problems/two-out-of-three/ - * Difficulty: Easy - * - * Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all - * the values that are present in at least two out of the three arrays. You may return the - * values in any order. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @param {number[]} nums3 - * @return {number[]} - */ -var twoOutOfThree = function(nums1, nums2, nums3) { - const set1 = new Set(nums1); - const set2 = new Set(nums2); - const set3 = new Set(nums3); - const count = new Map(); - - for (const num of set1) { - count.set(num, (count.get(num) || 0) + 1); - } - - for (const num of set2) { - count.set(num, (count.get(num) || 0) + 1); - } - - for (const num of set3) { - count.set(num, (count.get(num) || 0) + 1); - } - - const result = []; - for (const [num, freq] of count) { - if (freq >= 2) result.push(num); - } - - return result; -}; diff --git a/solutions/2033-minimum-operations-to-make-a-uni-value-grid.js b/solutions/2033-minimum-operations-to-make-a-uni-value-grid.js deleted file mode 100644 index 64aec2bc..00000000 --- a/solutions/2033-minimum-operations-to-make-a-uni-value-grid.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 2033. Minimum Operations to Make a Uni-Value Grid - * https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/ - * Difficulty: Medium - * - * You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x - * to or subtract x from any element in the grid. - * - * A uni-value grid is a grid where all the elements of it are equal. - * - * Return the minimum number of operations to make the grid uni-value. If it is not possible, - * return -1. - */ - -/** - * @param {number[][]} grid - * @param {number} x - * @return {number} - */ -var minOperations = function(grid, x) { - if (values.length === 1) return 0; - const values = grid.flat(); - values.sort((a, b) => a - b); - const median = values[Math.floor(values.length / 2)]; - let operations = 0; - - for (const value of values) { - const diff = Math.abs(value - median); - if (diff % x !== 0) return -1; - operations += diff / x; - } - - return operations; -}; diff --git a/solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js b/solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js deleted file mode 100644 index 1f3266b1..00000000 --- a/solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * 2035. Partition Array Into Two Arrays to Minimize Sum Difference - * https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/ - * Difficulty: Hard - * - * You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays - * of length n to minimize the absolute difference of the sums of the arrays. To partition nums, - * put each element of nums into one of the two arrays. - * - * Return the minimum possible absolute difference. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minimumDifference = function(nums) { - const n = nums.length / 2; - let result = Infinity; - const totalSum = nums.reduce((sum, num) => sum + num, 0); - const firstHalfSubsets = new Map(); - - for (let mask = 0; mask < (1 << n); mask++) { - let size = 0; - let subsetSum = 0; - - for (let i = 0; i < n; i++) { - if ((mask & (1 << i)) !== 0) { - size++; - subsetSum += nums[i]; - } - } - - if (!firstHalfSubsets.has(size)) { - firstHalfSubsets.set(size, []); - } - firstHalfSubsets.get(size).push(subsetSum); - } - - for (const [size, sums] of firstHalfSubsets) { - sums.sort((a, b) => a - b); - } - - for (let mask = 0; mask < (1 << n); mask++) { - let size = 0; - let secondHalfSum = 0; - - for (let i = 0; i < n; i++) { - if ((mask & (1 << i)) !== 0) { - size++; - secondHalfSum += nums[n + i]; - } - } - - const complementSize = n - size; - const firstHalfSums = firstHalfSubsets.get(complementSize); - const target = (totalSum - 2 * secondHalfSum) / 2; - const closestIndex = binarySearch(firstHalfSums, target); - - if (closestIndex < firstHalfSums.length) { - result = Math.min( - result, Math.abs(totalSum - 2 * (secondHalfSum + firstHalfSums[closestIndex])) - ); - } - - if (closestIndex > 0) { - result = Math.min( - result, Math.abs(totalSum - 2 * (secondHalfSum + firstHalfSums[closestIndex - 1])) - ); - } - } - - return result; -}; - -function binarySearch(arr, target) { - let left = 0; - let right = arr.length - 1; - - if (right < 0) return 0; - - while (left < right) { - const mid = Math.floor((left + right) / 2); - - if (arr[mid] < target) { - left = mid + 1; - } else { - right = mid; - } - } - - return left; -} diff --git a/solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js b/solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js deleted file mode 100644 index 7a42cfcb..00000000 --- a/solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 2038. Remove Colored Pieces if Both Neighbors are the Same Color - * https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/ - * Difficulty: Medium - * - * There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. - * You are given a string colors of length n where colors[i] is the color of the ith piece. - * - * Alice and Bob are playing a game where they take alternating turns removing pieces from the - * line. In this game, Alice moves first. - * - Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored - * 'A'. She is not allowed to remove pieces that are colored 'B'. - * - Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored - * 'B'. He is not allowed to remove pieces that are colored 'A'. - * - Alice and Bob cannot remove pieces from the edge of the line. - * - If a player cannot make a move on their turn, that player loses and the other player wins. - * - * Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. - */ - -/** - * @param {string} colors - * @return {boolean} - */ -var winnerOfGame = function(colors) { - let aliceMoves = 0; - let bobMoves = 0; - - for (let i = 1; i < colors.length - 1; i++) { - if (colors[i] === 'A' && colors[i - 1] === 'A' && colors[i + 1] === 'A') { - aliceMoves++; - } else if (colors[i] === 'B' && colors[i - 1] === 'B' && colors[i + 1] === 'B') { - bobMoves++; - } - } - - return aliceMoves > bobMoves; -}; diff --git a/solutions/2039-the-time-when-the-network-becomes-idle.js b/solutions/2039-the-time-when-the-network-becomes-idle.js deleted file mode 100644 index 38287340..00000000 --- a/solutions/2039-the-time-when-the-network-becomes-idle.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 2039. The Time When the Network Becomes Idle - * https://leetcode.com/problems/the-time-when-the-network-becomes-idle/ - * Difficulty: Medium - * - * There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array - * edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui - * and vi, and they can pass any number of messages to each other directly in one second. - * You are also given a 0-indexed integer array patience of length n. - * - * All servers are connected, i.e., a message can be passed from one server to any other - * server(s) directly or indirectly through the message channels. - * - * The server labeled 0 is the master server. The rest are data servers. Each data server - * needs to send its message to the master server for processing and wait for a reply. - * Messages move between servers optimally, so every message takes the least amount of - * time to arrive at the master server. The master server will process all newly arrived - * messages instantly and send a reply to the originating server via the reversed path - * the message had gone through. - * - * At the beginning of second 0, each data server sends its message to be processed. Starting - * from second 1, at the beginning of every second, each data server will check if it has - * received a reply to the message it sent (including any newly arrived replies) from the - * master server: - * - If it has not, it will resend the message periodically. The data server i will resend - * the message every patience[i] second(s), i.e., the data server i will resend the message - * if patience[i] second(s) have elapsed since the last time the message was sent from this - * server. - * - Otherwise, no more resending will occur from this server. - * - * The network becomes idle when there are no messages passing between servers or arriving - * at servers. - * - * Return the earliest second starting from which the network becomes idle. - */ - -/** - * @param {number[][]} edges - * @param {number[]} patience - * @return {number} - */ -var networkBecomesIdle = function(edges, patience) { - const n = patience.length; - const adjList = Array.from({ length: n }, () => []); - for (const [u, v] of edges) { - adjList[u].push(v); - adjList[v].push(u); - } - - const distances = new Array(n).fill(Infinity); - distances[0] = 0; - const queue = [0]; - let maxTime = 0; - - while (queue.length) { - const curr = queue.shift(); - for (const next of adjList[curr]) { - if (distances[next] === Infinity) { - distances[next] = distances[curr] + 1; - queue.push(next); - if (next !== 0) { - const roundTrip = 2 * distances[next]; - const lastSent = Math.floor((roundTrip - 1) / patience[next]) * patience[next]; - maxTime = Math.max(maxTime, lastSent + roundTrip); - } - } - } - } - - return maxTime + 1; -}; diff --git a/solutions/2040-kth-smallest-product-of-two-sorted-arrays.js b/solutions/2040-kth-smallest-product-of-two-sorted-arrays.js deleted file mode 100644 index 80a4da8c..00000000 --- a/solutions/2040-kth-smallest-product-of-two-sorted-arrays.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 2040. Kth Smallest Product of Two Sorted Arrays - * https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/ - * Difficulty: Hard - * - * Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return - * the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length - * and 0 <= j < nums2.length. - */ - -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @param {number} k - * @return {number} - */ -var kthSmallestProduct = function(nums1, nums2, k) { - function countProducts(maxProduct) { - let count = 0; - for (const num1 of nums1) { - let left = 0; - let right = nums2.length; - - if (num1 >= 0) { - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (num1 * nums2[mid] <= maxProduct) left = mid + 1; - else right = mid; - } - count += left; - } else { - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (num1 * nums2[mid] <= maxProduct) right = mid; - else left = mid + 1; - } - count += nums2.length - left; - } - } - return count; - } - - let low = -(10 ** 10); - let high = 10 ** 10; - - while (low < high) { - const mid = Math.floor((low + high) / 2); - if (countProducts(mid) >= k) high = mid; - else low = mid + 1; - } - - return low; -}; diff --git a/solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js b/solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js deleted file mode 100644 index 5b91979b..00000000 --- a/solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 2042. Check if Numbers Are Ascending in a Sentence - * https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/ - * Difficulty: Easy - * - * A sentence is a list of tokens separated by a single space with no leading or trailing spaces. - * Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a - * word consisting of lowercase English letters. - * - For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are - * numbers and the other tokens such as "puppy" are words. - * - * Given a string s representing a sentence, you need to check if all the numbers in s are strictly - * increasing from left to right (i.e., other than the last number, each number is strictly smaller - * than the number on its right in s). - * - * Return true if so, or false otherwise. - */ - -/** - * @param {string} s - * @return {boolean} - */ -var areNumbersAscending = function(s) { - const numbers = s.split(' ').filter(token => !isNaN(token)).map(Number); - for (let i = 1; i < numbers.length; i++) { - if (numbers[i] <= numbers[i - 1]) return false; - } - return true; -}; diff --git a/solutions/2043-simple-bank-system.js b/solutions/2043-simple-bank-system.js deleted file mode 100644 index 3cb80cb1..00000000 --- a/solutions/2043-simple-bank-system.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 2043. Simple Bank System - * https://leetcode.com/problems/simple-bank-system/ - * Difficulty: Medium - * - * You have been tasked with writing a program for a popular bank that will automate all its - * incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered - * from 1 to n. The initial balance of each account is stored in a 0-indexed integer array - * balance, with the (i + 1)th account having an initial balance of balance[i]. - * - * Execute all the valid transactions. A transaction is valid if: - * - The given account number(s) are between 1 and n, and - * - The amount of money withdrawn or transferred from is less than or equal to the balance - * of the account. - * - * Implement the Bank class: - * - Bank(long[] balance) Initializes the object with the 0-indexed integer array balance. - * - boolean transfer(int account1, int account2, long money) Transfers money dollars from the - * account numbered account1 to the account numbered account2. Return true if the transaction - * was successful, false otherwise. - * - boolean deposit(int account, long money) Deposit money dollars into the account numbered - * account. Return true if the transaction was successful, false otherwise. - * - boolean withdraw(int account, long money) Withdraw money dollars from the account numbered - * account. Return true if the transaction was successful, false otherwise. - */ - -/** - * @param {number[]} balance - */ -var Bank = function(balance) { - this.accounts = balance; -}; - -/** - * @param {number} account1 - * @param {number} account2 - * @param {number} money - * @return {boolean} - */ -Bank.prototype.transfer = function(account1, account2, money) { - if (account1 > this.accounts.length || account2 > this.accounts.length) return false; - if (this.accounts[account1 - 1] < money) return false; - - this.accounts[account1 - 1] -= money; - this.accounts[account2 - 1] += money; - return true; -}; - -/** - * @param {number} account - * @param {number} money - * @return {boolean} - */ -Bank.prototype.deposit = function(account, money) { - if (account > this.accounts.length) return false; - - this.accounts[account - 1] += money; - return true; -}; - -/** - * @param {number} account - * @param {number} money - * @return {boolean} - */ -Bank.prototype.withdraw = function(account, money) { - if (account > this.accounts.length || this.accounts[account - 1] < money) return false; - - this.accounts[account - 1] -= money; - return true; -}; diff --git a/solutions/2044-count-number-of-maximum-bitwise-or-subsets.js b/solutions/2044-count-number-of-maximum-bitwise-or-subsets.js deleted file mode 100644 index c318115a..00000000 --- a/solutions/2044-count-number-of-maximum-bitwise-or-subsets.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 2044. Count Number of Maximum Bitwise-OR Subsets - * https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/ - * Difficulty: Medium - * - * Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return - * the number of different non-empty subsets with the maximum bitwise OR. - * - * An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) - * elements of b. Two subsets are considered different if the indices of the elements chosen are - * different. - * - * The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed). - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var countMaxOrSubsets = function(nums) { - const maxOr = nums.reduce((or, num) => or | num, 0); - let count = 0; - - backtrack(0, 0); - - return count; - - function backtrack(index, currentOr) { - if (currentOr === maxOr) count++; - for (let i = index; i < nums.length; i++) { - backtrack(i + 1, currentOr | nums[i]); - } - } -}; diff --git a/solutions/2045-second-minimum-time-to-reach-destination.js b/solutions/2045-second-minimum-time-to-reach-destination.js deleted file mode 100644 index 522eabab..00000000 --- a/solutions/2045-second-minimum-time-to-reach-destination.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 2045. Second Minimum Time to Reach Destination - * https://leetcode.com/problems/second-minimum-time-to-reach-destination/ - * Difficulty: Hard - * - * A city is represented as a bi-directional connected graph with n vertices where each vertex - * is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer - * array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex - * ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has - * an edge to itself. The time taken to traverse any edge is time minutes. - * - * Each vertex has a traffic signal which changes its color from green to red and vice versa - * every change minutes. All signals change at the same time. You can enter a vertex at any - * time, but can leave a vertex only when the signal is green. You cannot wait at a vertex - * if the signal is green. - * - * The second minimum value is defined as the smallest value strictly larger than the minimum value. - * - For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of - * [2, 2, 4] is 4. - * - * Given n, edges, time, and change, return the second minimum time it will take to go from - * vertex 1 to vertex n. - */ - -/** - * @param {number} n - * @param {number[][]} edges - * @param {number} time - * @param {number} change - * @return {number} - */ -var secondMinimum = function(n, edges, time, change) { - const adjList = Array.from({ length: n + 1 }, () => []); - for (const [u, v] of edges) { - adjList[u].push(v); - adjList[v].push(u); - } - - const distances = Array.from({ length: n + 1 }, () => [Infinity, Infinity]); - const queue = [[1, 0]]; - distances[1][0] = 0; - - while (queue.length) { - const [node, currTime] = queue.shift(); - - for (const next of adjList[node]) { - const signalCycle = Math.floor(currTime / change); - const isGreen = signalCycle % 2 === 0; - let nextTime = currTime + time; - - if (!isGreen) { - nextTime = (signalCycle + 1) * change + time; - } - - if (nextTime < distances[next][0]) { - distances[next][1] = distances[next][0]; - distances[next][0] = nextTime; - queue.push([next, nextTime]); - } else if (nextTime > distances[next][0] && nextTime < distances[next][1]) { - distances[next][1] = nextTime; - queue.push([next, nextTime]); - } - } - } - - return distances[n][1]; -}; diff --git a/solutions/2048-next-greater-numerically-balanced-number.js b/solutions/2048-next-greater-numerically-balanced-number.js deleted file mode 100644 index 523a302a..00000000 --- a/solutions/2048-next-greater-numerically-balanced-number.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 2048. Next Greater Numerically Balanced Number - * https://leetcode.com/problems/next-greater-numerically-balanced-number/ - * Difficulty: Medium - * - * An integer x is numerically balanced if for every digit d in the number x, there are exactly - * d occurrences of that digit in x. - * - * Given an integer n, return the smallest numerically balanced number strictly greater than n. - */ - -/** - * @param {number} n - * @return {number} - */ -var nextBeautifulNumber = function(n) { - let candidate = n + 1; - while (candidate <= 10000000) { - if (isBalanced(candidate)) return candidate; - candidate++; - } - - return -1; - - function isBalanced(num) { - const freq = new Array(10).fill(0); - const str = num.toString(); - - for (const digit of str) { - freq[digit]++; - } - - for (const digit of str) { - if (freq[digit] !== parseInt(digit)) return false; - } - - return true; - } -}; diff --git a/solutions/2049-count-nodes-with-the-highest-score.js b/solutions/2049-count-nodes-with-the-highest-score.js deleted file mode 100644 index 1f13961e..00000000 --- a/solutions/2049-count-nodes-with-the-highest-score.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 2049. Count Nodes With the Highest Score - * https://leetcode.com/problems/count-nodes-with-the-highest-score/ - * Difficulty: Medium - * - * There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. - * You are given a 0-indexed integer array parents representing the tree, where parents[i] is the - * parent of node i. Since node 0 is the root, parents[0] == -1. - * - * Each node has a score. To find the score of a node, consider if the node and the edges connected - * to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree - * is the number of the nodes in it. The score of the node is the product of the sizes of all - * those subtrees. - * - * Return the number of nodes that have the highest score. - */ - -/** - * @param {number[]} parents - * @return {number} - */ -var countHighestScoreNodes = function(parents) { - const n = parents.length; - const children = Array.from({ length: n }, () => []); - for (let i = 1; i < n; i++) { - children[parents[i]].push(i); - } - - const sizes = new Array(n).fill(0); - let maxScore = 0n; - let maxScoreCount = 0; - - calculateSize(0); - - return maxScoreCount; - - function calculateSize(node) { - let leftSize = 0; - let rightSize = 0; - - if (children[node].length > 0) leftSize = calculateSize(children[node][0]); - if (children[node].length > 1) rightSize = calculateSize(children[node][1]); - - sizes[node] = leftSize + rightSize + 1; - - let score = 1n; - if (leftSize > 0) score *= BigInt(leftSize); - if (rightSize > 0) score *= BigInt(rightSize); - const parentSize = n - sizes[node]; - if (parentSize > 0) score *= BigInt(parentSize); - - if (score > maxScore) { - maxScore = score; - maxScoreCount = 1; - } else if (score === maxScore) { - maxScoreCount++; - } - - return sizes[node]; - } -}; diff --git a/solutions/2050-parallel-courses-iii.js b/solutions/2050-parallel-courses-iii.js deleted file mode 100644 index 62cdec65..00000000 --- a/solutions/2050-parallel-courses-iii.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 2050. Parallel Courses III - * https://leetcode.com/problems/parallel-courses-iii/ - * Difficulty: Hard - * - * You are given an integer n, which indicates that there are n courses labeled from 1 to n. - * You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] - * denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite - * relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes - * how many months it takes to complete the (i+1)th course. - * - * You must find the minimum number of months needed to complete all the courses following these - * rules: - * - You may start taking a course at any time if the prerequisites are met. - * - Any number of courses can be taken at the same time. - * - * Return the minimum number of months needed to complete all the courses. - * - * Note: The test cases are generated such that it is possible to complete every course (i.e., the - * graph is a directed acyclic graph). - */ - -/** - * @param {number} n - * @param {number[][]} relations - * @param {number[]} time - * @return {number} - */ -var minimumTime = function(n, relations, time) { - const adjacencyList = Array.from({ length: n + 1 }, () => []); - const inDegree = new Array(n + 1).fill(0); - const completionTime = new Array(n + 1).fill(0); - - for (const [prev, next] of relations) { - adjacencyList[prev].push(next); - inDegree[next]++; - } - - const queue = []; - for (let i = 1; i <= n; i++) { - if (inDegree[i] === 0) { - queue.push(i); - completionTime[i] = time[i - 1]; - } - } - - while (queue.length) { - const current = queue.shift(); - for (const next of adjacencyList[current]) { - completionTime[next] = Math.max( - completionTime[next], - completionTime[current] + time[next - 1] - ); - if (--inDegree[next] === 0) { - queue.push(next); - } - } - } - - return Math.max(...completionTime); -}; diff --git a/solutions/2055-plates-between-candles.js b/solutions/2055-plates-between-candles.js deleted file mode 100644 index 347ed4ae..00000000 --- a/solutions/2055-plates-between-candles.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 2055. Plates Between Candles - * https://leetcode.com/problems/plates-between-candles/ - * Difficulty: Medium - * - * There is a long table with a line of plates and candles arranged on top of it. You are given - * a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate - * and a '|' represents a candle. - * - * You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] - * denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the - * number of plates between candles that are in the substring. A plate is considered between - * candles if there is at least one candle to its left and at least one candle to its right - * in the substring. - * - For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number - * of plates between candles in this substring is 2, as each of the two plates has at least one - * candle in the substring to its left and right. - * - * Return an integer array answer where answer[i] is the answer to the ith query. - */ - -/** - * @param {string} s - * @param {number[][]} queries - * @return {number[]} - */ -var platesBetweenCandles = function(s, queries) { - const n = s.length; - const prefixPlates = new Array(n + 1).fill(0); - const leftCandle = new Array(n).fill(-1); - const rightCandle = new Array(n).fill(-1); - - for (let i = 0, candle = -1; i < n; i++) { - prefixPlates[i + 1] = prefixPlates[i] + (s[i] === '*' ? 1 : 0); - if (s[i] === '|') candle = i; - leftCandle[i] = candle; - } - - for (let i = n - 1, candle = -1; i >= 0; i--) { - if (s[i] === '|') candle = i; - rightCandle[i] = candle; - } - - const result = new Array(queries.length).fill(0); - for (let i = 0; i < queries.length; i++) { - const [start, end] = queries[i]; - const left = rightCandle[start]; - const right = leftCandle[end]; - if (left !== -1 && right !== -1 && left < right) { - result[i] = prefixPlates[right] - prefixPlates[left]; - } - } - - return result; -}; diff --git a/solutions/2056-number-of-valid-move-combinations-on-chessboard.js b/solutions/2056-number-of-valid-move-combinations-on-chessboard.js deleted file mode 100644 index 94716f2b..00000000 --- a/solutions/2056-number-of-valid-move-combinations-on-chessboard.js +++ /dev/null @@ -1,108 +0,0 @@ -/** - * 2056. Number of Valid Move Combinations On Chessboard - * https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/ - * Difficulty: Hard - * - * There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a - * string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) - * of the ith piece. In addition, you are given a 2D integer array positions also of length n, - * where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based - * coordinate (ri, ci) on the chessboard. - * - * When making a move for a piece, you choose a destination square that the piece will travel - * toward and stop on. - * - A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), - * (r-1, c), (r, c+1), or (r, c-1). - * - A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction - * of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). - * - A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), - * (r-1, c+1), (r-1, c-1). - * - * You must make a move for every piece on the board simultaneously. A move combination consists of - * all the moves performed on all the given pieces. Every second, each piece will instantaneously - * travel one square towards their destination if they are not already at it. All pieces start - * traveling at the 0th second. A move combination is invalid if, at a given time, two or more - * pieces occupy the same square. - * - * Return the number of valid move combinations. - * - * Notes: - * - No two pieces will start in the same square. - * - You may choose the square a piece is already on as its destination. - * - If two pieces are directly adjacent to each other, it is valid for them to move past each other - * and swap positions in one second. - */ - -/** - * @param {string[]} pieces - * @param {number[][]} positions - * @return {number} - */ -var countCombinations = function(pieces, positions) { - const n = pieces.length; - const directions = { - rook: [[0, 1], [0, -1], [1, 0], [-1, 0]], - bishop: [[1, 1], [1, -1], [-1, 1], [-1, -1]], - queen: [[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]] - }; - - return generateCombinations(0, [], []); - - function isValidPosition(row, col) { - return row >= 1 && row <= 8 && col >= 1 && col <= 8; - } - - function simulateMoves(moves, steps) { - const current = positions.map(([r, c]) => [r, c]); - const maxSteps = Math.max(...steps); - - for (let t = 0; t <= maxSteps; t++) { - const positionsAtTime = new Set(); - for (let i = 0; i < n; i++) { - const [dr, dc] = moves[i]; - const step = Math.min(t, steps[i]); - const newRow = current[i][0] + dr * step; - const newCol = current[i][1] + dc * step; - - if (t > steps[i] && steps[i] > 0 && !isValidPosition(newRow, newCol)) continue; - - const posKey = `${newRow},${newCol}`; - if (positionsAtTime.has(posKey)) return false; - positionsAtTime.add(posKey); - } - } - - return true; - } - - function generateCombinations(index, selectedMoves, selectedSteps) { - if (index === n) { - return simulateMoves(selectedMoves, selectedSteps) ? 1 : 0; - } - - let total = 0; - const [startRow, startCol] = positions[index]; - const pieceDirections = directions[pieces[index]]; - - total += generateCombinations(index + 1, [...selectedMoves, [0, 0]], [...selectedSteps, 0]); - - for (const [dr, dc] of pieceDirections) { - let row = startRow; - let col = startCol; - let step = 0; - - while (isValidPosition(row + dr, col + dc)) { - row += dr; - col += dc; - step++; - total += generateCombinations( - index + 1, - [...selectedMoves, [dr, dc]], - [...selectedSteps, step] - ); - } - } - - return total; - } -}; diff --git a/solutions/2057-smallest-index-with-equal-value.js b/solutions/2057-smallest-index-with-equal-value.js deleted file mode 100644 index 3fe1c453..00000000 --- a/solutions/2057-smallest-index-with-equal-value.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 2057. Smallest Index With Equal Value - * https://leetcode.com/problems/smallest-index-with-equal-value/ - * Difficulty: Easy - * - * Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod - * 10 == nums[i], or -1 if such index does not exist. - * - * x mod y denotes the remainder when x is divided by y. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var smallestEqual = function(nums) { - for (let i = 0; i < nums.length; i++) { - if (i % 10 === nums[i]) { - return i; - } - } - return -1; -}; diff --git a/solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js b/solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js deleted file mode 100644 index da92ff90..00000000 --- a/solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points - * https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/ - * Difficulty: Medium - * - * A critical point in a linked list is defined as either a local maxima or a local minima. - * - * A node is a local maxima if the current node has a value strictly greater than the previous node - * and the next node. - * - * A node is a local minima if the current node has a value strictly smaller than the previous node - * and the next node. - * - * Note that a node can only be a local maxima/minima if there exists both a previous node and a - * next node. - * - * Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] - * where minDistance is the minimum distance between any two distinct critical points and - * maxDistance is the maximum distance between any two distinct critical points. If there are - * fewer than two critical points, return [-1, -1]. - */ - -/** - * 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 nodesBetweenCriticalPoints = function(head) { - const criticalPositions = []; - let position = 1; - let prev = head; - let current = head.next; - - while (current.next) { - const next = current.next; - if ((current.val > prev.val && current.val > next.val) || - (current.val < prev.val && current.val < next.val)) { - criticalPositions.push(position); - } - prev = current; - current = next; - position++; - } - - if (criticalPositions.length < 2) { - return [-1, -1]; - } - - let minDistance = Infinity; - for (let i = 1; i < criticalPositions.length; i++) { - minDistance = Math.min(minDistance, criticalPositions[i] - criticalPositions[i - 1]); - } - - const maxDistance = criticalPositions[criticalPositions.length - 1] - criticalPositions[0]; - - return [minDistance, maxDistance]; -}; diff --git a/solutions/2059-minimum-operations-to-convert-number.js b/solutions/2059-minimum-operations-to-convert-number.js deleted file mode 100644 index 677e5de9..00000000 --- a/solutions/2059-minimum-operations-to-convert-number.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 2059. Minimum Operations to Convert Number - * https://leetcode.com/problems/minimum-operations-to-convert-number/ - * Difficulty: Medium - * - * You are given a 0-indexed integer array nums containing distinct numbers, an integer start, - * and an integer goal. There is an integer x that is initially set to start, and you want to - * perform operations on x such that it is converted to goal. You can perform the following - * operation repeatedly on the number x: - * - * If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x - * to any of the following: - * - x + nums[i] - * - x - nums[i] - * - x ^ nums[i] (bitwise-XOR) - * - * Note that you can use each nums[i] any number of times in any order. Operations that set x - * to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. - * - * Return the minimum number of operations needed to convert x = start into goal, and -1 if it - * is not possible. - */ - -/** - * @param {number[]} nums - * @param {number} start - * @param {number} goal - * @return {number} - */ -var minimumOperations = function(nums, start, goal) { - const queue = [[start, 0]]; - const visited = new Set([start]); - - while (queue.length) { - const [current, steps] = queue.shift(); - - for (const num of nums) { - const candidates = [ - current + num, - current - num, - current ^ num - ]; - - for (const next of candidates) { - if (next === goal) { - return steps + 1; - } - if (next >= 0 && next <= 1000 && !visited.has(next)) { - visited.add(next); - queue.push([next, steps + 1]); - } - } - } - } - - return -1; -}; diff --git a/solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js b/solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js deleted file mode 100644 index 520e531e..00000000 --- a/solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 2060. Check if an Original String Exists Given Two Encoded Strings - * https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/ - * Difficulty: Hard - * - * An original string, consisting of lowercase English letters, can be encoded by the following - * steps: - * - Arbitrarily split it into a sequence of some number of non-empty substrings. - * - Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its - * length (as a numeric string). - * - Concatenate the sequence as the encoded string. - * - * For example, one way to encode an original string "abcdefghijklmnop" might be: - * - Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"]. - * - Choose the second and third elements to be replaced by their lengths, respectively. The - * sequence becomes ["ab", "12", "1", "p"]. - * - Concatenate the elements of the sequence to get the encoded string: "ab121p". - * - * Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 - * (inclusive), return true if there exists an original string that could be encoded as both s1 - * and s2. Otherwise, return false. - * - * Note: The test cases are generated such that the number of consecutive digits in s1 and s2 - * does not exceed 3. - */ - -/** - * @param {string} s1 - * @param {string} s2 - * @return {boolean} - */ -var possiblyEquals = function(s1, s2) { - const memo = new Array(s1.length + 1).fill().map(() => new Array(s2.length + 1).fill() - .map(() => ({}))); - - function match(pos1, pos2, diff) { - if (pos1 === s1.length && pos2 === s2.length) return diff === 0; - if (memo[pos1][pos2][diff] !== undefined) return memo[pos1][pos2][diff]; - - const char1 = s1[pos1]; - const char2 = s2[pos2]; - - if (pos1 < s1.length && pos2 < s2.length && char1 === char2 && diff === 0) { - if (match(pos1 + 1, pos2 + 1, 0)) return true; - } - - if (pos1 < s1.length && isNaN(char1) && diff < 0) { - if (match(pos1 + 1, pos2, diff + 1)) return true; - } - - if (pos2 < s2.length && isNaN(char2) && diff > 0) { - if (match(pos1, pos2 + 1, diff - 1)) return true; - } - - let num = 0; - for (let i = 0; i < 3 && pos1 + i < s1.length; i++) { - if (isNaN(s1[pos1 + i])) break; - num = num * 10 + parseInt(s1[pos1 + i]); - if (match(pos1 + i + 1, pos2, diff + num)) return true; - } - - num = 0; - for (let i = 0; i < 3 && pos2 + i < s2.length; i++) { - if (isNaN(s2[pos2 + i])) break; - num = num * 10 + parseInt(s2[pos2 + i]); - if (match(pos1, pos2 + i + 1, diff - num)) return true; - } - - return memo[pos1][pos2][diff] = false; - } - - return match(0, 0, 0); -}; diff --git a/solutions/2062-count-vowel-substrings-of-a-string.js b/solutions/2062-count-vowel-substrings-of-a-string.js deleted file mode 100644 index 8d427ac8..00000000 --- a/solutions/2062-count-vowel-substrings-of-a-string.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 2062. Count Vowel Substrings of a String - * https://leetcode.com/problems/count-vowel-substrings-of-a-string/ - * Difficulty: Easy - * - * A substring is a contiguous (non-empty) sequence of characters within a string. - * - * A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') - * and has all five vowels present in it. - * - * Given a string word, return the number of vowel substrings in word. - */ - -/** - * @param {string} word - * @return {number} - */ -var countVowelSubstrings = function(word) { - const vowels = new Set(['a', 'e', 'i', 'o', 'u']); - let total = 0; - - for (let start = 0; start < word.length; start++) { - const vowelCount = new Map(); - for (let end = start; end < word.length && vowels.has(word[end]); end++) { - vowelCount.set(word[end], (vowelCount.get(word[end]) || 0) + 1); - if (vowelCount.size === 5) { - total++; - } - } - } - - return total; -}; diff --git a/solutions/2063-vowels-of-all-substrings.js b/solutions/2063-vowels-of-all-substrings.js deleted file mode 100644 index bde705e8..00000000 --- a/solutions/2063-vowels-of-all-substrings.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 2063. Vowels of All Substrings - * https://leetcode.com/problems/vowels-of-all-substrings/ - * Difficulty: Medium - * - * Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in - * every substring of word. - * - * A substring is a contiguous (non-empty) sequence of characters within a string. - * - * Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please - * be careful during the calculations. - */ - -/** - * @param {string} word - * @return {number} - */ -var countVowels = function(word) { - const vowels = new Set(['a', 'e', 'i', 'o', 'u']); - let total = 0; - - for (let i = 0; i < word.length; i++) { - if (vowels.has(word[i])) { - total += (i + 1) * (word.length - i); - } - } - - return total; -}; diff --git a/solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js b/solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js deleted file mode 100644 index b1781081..00000000 --- a/solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 2064. Minimized Maximum of Products Distributed to Any Store - * https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/ - * Difficulty: Medium - * - * You are given an integer n indicating there are n specialty retail stores. There are m product - * types of varying amounts, which are given as a 0-indexed integer array quantities, where - * quantities[i] represents the number of products of the ith product type. - * - * You need to distribute all products to the retail stores following these rules: - * - A store can only be given at most one product type but can be given any amount of it. - * - After distribution, each store will have been given some number of products (possibly 0). - * Let x represent the maximum number of products given to any store. You want x to be as small - * as possible, i.e., you want to minimize the maximum number of products that are given to any - * store. - * - * Return the minimum possible x. - */ - -/** - * @param {number} n - * @param {number[]} quantities - * @return {number} - */ -var minimizedMaximum = function(n, quantities) { - let left = 1; - let right = Math.max(...quantities); - - while (left < right) { - const mid = Math.floor((left + right) / 2); - let storesNeeded = 0; - - for (const quantity of quantities) { - storesNeeded += Math.ceil(quantity / mid); - } - - if (storesNeeded <= n) { - right = mid; - } else { - left = mid + 1; - } - } - - return left; -}; diff --git a/solutions/2065-maximum-path-quality-of-a-graph.js b/solutions/2065-maximum-path-quality-of-a-graph.js deleted file mode 100644 index 9d07048c..00000000 --- a/solutions/2065-maximum-path-quality-of-a-graph.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 2065. Maximum Path Quality of a Graph - * https://leetcode.com/problems/maximum-path-quality-of-a-graph/ - * Difficulty: Hard - * - * There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a - * 0-indexed integer array values where values[i] is the value of the ith node. You are also given - * a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there - * is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between - * the two nodes. Finally, you are given an integer maxTime. - * - * A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most - * maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid - * path is the sum of the values of the unique nodes visited in the path (each node's value is - * added at most once to the sum). - * - * Return the maximum quality of a valid path. - * - * Note: There are at most four edges connected to each node. - */ - -/** - * @param {number[]} values - * @param {number[][]} edges - * @param {number} maxTime - * @return {number} - */ -var maximalPathQuality = function(values, edges, maxTime) { - const n = values.length; - const adjList = Array.from({ length: n }, () => []); - - for (const [u, v, time] of edges) { - adjList[u].push([v, time]); - adjList[v].push([u, time]); - } - - let result = 0; - const initialVisited = new Set([0]); - - dfs(0, maxTime, values[0], initialVisited); - - return result; - - function dfs(node, timeLeft, quality, visited) { - if (timeLeft < 0) return 0; - if (node === 0) { - result = Math.max(result, quality); - } - - for (const [nextNode, travelTime] of adjList[node]) { - const newVisited = new Set(visited); - const newQuality = newVisited.has(nextNode) ? quality : quality + values[nextNode]; - newVisited.add(nextNode); - dfs(nextNode, timeLeft - travelTime, newQuality, newVisited); - } - - return result; - } -}; diff --git a/solutions/2068-check-whether-two-strings-are-almost-equivalent.js b/solutions/2068-check-whether-two-strings-are-almost-equivalent.js deleted file mode 100644 index 210aeb88..00000000 --- a/solutions/2068-check-whether-two-strings-are-almost-equivalent.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 2068. Check Whether Two Strings are Almost Equivalent - * https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/ - * Difficulty: Easy - * - * Two strings word1 and word2 are considered almost equivalent if the differences between the - * frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. - * - * Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost - * equivalent, or false otherwise. - * - * The frequency of a letter x is the number of times it occurs in the string. - */ - -/** - * @param {string} word1 - * @param {string} word2 - * @return {boolean} - */ -var checkAlmostEquivalent = function(word1, word2) { - const map = new Array(26).fill(0); - - for (let i = 0; i < word1.length; i++) { - map[word1.charCodeAt(i) - 97]++; - map[word2.charCodeAt(i) - 97]--; - } - - return map.every(diff => Math.abs(diff) <= 3); -}; diff --git a/solutions/2069-walking-robot-simulation-ii.js b/solutions/2069-walking-robot-simulation-ii.js deleted file mode 100644 index e4896040..00000000 --- a/solutions/2069-walking-robot-simulation-ii.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 2069. Walking Robot Simulation II - * https://leetcode.com/problems/walking-robot-simulation-ii/ - * Difficulty: Medium - * - * A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the - * top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal - * directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) - * facing direction "East". - * - * The robot can be instructed to move for a specific number of steps. For each step, it does - * the following. - * 1. Attempts to move forward one cell in the direction it is facing. - * 2. If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees - * counterclockwise and retries the step. - * - * After the robot finishes moving the number of steps required, it stops and awaits the next - * instruction. - * - * Implement the Robot class: - * - Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) - * facing "East". - * - void step(int num) Instructs the robot to move forward num steps. - * - int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y]. - * - String getDir() Returns the current direction of the robot, "North", "East", "South", or - * "West". - */ - -/** - * @param {number} width - * @param {number} height - */ -var Robot = function(width, height) { - this.width = width; - this.height = height; - this.position = [0, 0]; - this.directionIndex = 0; - this.directions = ['East', 'North', 'West', 'South']; - this.moves = [[1, 0], [0, 1], [-1, 0], [0, -1]]; - this.perimeter = 2 * (width + height - 2); -}; - -/** - * @param {number} num - * @return {void} - */ -Robot.prototype.step = function(num) { - num %= this.perimeter; - if (num === 0) num = this.perimeter; - - while (num > 0) { - const [dx, dy] = this.moves[this.directionIndex]; - const [x, y] = this.position; - let steps; - - if (this.directionIndex === 0) steps = this.width - 1 - x; - else if (this.directionIndex === 1) steps = this.height - 1 - y; - else if (this.directionIndex === 2) steps = x; - else steps = y; - - if (steps >= num) { - this.position = [x + dx * num, y + dy * num]; - num = 0; - } else { - this.position = [x + dx * steps, y + dy * steps]; - this.directionIndex = (this.directionIndex + 1) % 4; - num -= steps; - } - } -}; - -/** - * @return {number[]} - */ -Robot.prototype.getPos = function() { - return this.position; -}; - -/** - * @return {string} - */ -Robot.prototype.getDir = function() { - return this.directions[this.directionIndex]; -}; diff --git a/solutions/2070-most-beautiful-item-for-each-query.js b/solutions/2070-most-beautiful-item-for-each-query.js deleted file mode 100644 index 1931e875..00000000 --- a/solutions/2070-most-beautiful-item-for-each-query.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 2070. Most Beautiful Item for Each Query - * https://leetcode.com/problems/most-beautiful-item-for-each-query/ - * Difficulty: Medium - * - * You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and - * beauty of an item respectively. - * - * You are also given a 0-indexed integer array queries. For each queries[j], you want to determine - * the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item - * exists, then the answer to this query is 0. - * - * Return an array answer of the same length as queries where answer[j] is the answer to the jth - * query. - */ - -/** - * @param {number[][]} items - * @param {number[]} queries - * @return {number[]} - */ -var maximumBeauty = function(items, queries) { - items.sort((a, b) => a[0] - b[0]); - const maxBeauty = []; - let currentMax = 0; - - for (const [, beauty] of items) { - currentMax = Math.max(currentMax, beauty); - maxBeauty.push(currentMax); - } - - const result = new Array(queries.length).fill(0); - - for (let i = 0; i < queries.length; i++) { - const price = queries[i]; - let left = 0; - let right = items.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - if (items[mid][0] <= price) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - if (right >= 0) { - result[i] = maxBeauty[right]; - } - } - - return result; -}; diff --git a/solutions/2071-maximum-number-of-tasks-you-can-assign.js b/solutions/2071-maximum-number-of-tasks-you-can-assign.js deleted file mode 100644 index 5382d5d5..00000000 --- a/solutions/2071-maximum-number-of-tasks-you-can-assign.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 2071. Maximum Number of Tasks You Can Assign - * https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/ - * Difficulty: Hard - * - * You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed - * integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength - * of each worker is stored in a 0-indexed integer array workers, with the jth worker having - * workers[j] strength. Each worker can only be assigned to a single task and must have a - * strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). - * - * Additionally, you have pills magical pills that will increase a worker's strength by strength. - * You can decide which workers receive the magical pills, however, you may only give each worker - * at most one magical pill. - * - * Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, - * return the maximum number of tasks that can be completed. - */ - -/** - * @param {number[]} tasks - * @param {number[]} workers - * @param {number} pills - * @param {number} strength - * @return {number} - */ -var maxTaskAssign = function(tasks, workers, pills, strength) { - tasks.sort((a, b) => a - b); - workers.sort((a, b) => a - b); - - const n = tasks.length; - const m = workers.length; - - let left = 0; - let right = Math.min(n, m); - - while (left < right) { - const mid = Math.floor((left + right + 1) / 2); - - if (canAssign(mid)) { - left = mid; - } else { - right = mid - 1; - } - } - - return left; - - function canAssign(k) { - const availableTasks = tasks.slice(0, k); - const availableWorkers = workers.slice(m - k); - let remainingPills = pills; - - for (let i = k - 1; i >= 0; i--) { - const task = availableTasks[i]; - - if (availableWorkers[availableWorkers.length - 1] >= task) { - availableWorkers.pop(); - continue; - } - - if (remainingPills === 0) return false; - - let found = false; - for (let j = 0; j < availableWorkers.length; j++) { - if (availableWorkers[j] + strength >= task) { - availableWorkers.splice(j, 1); - remainingPills--; - found = true; - break; - } - } - - if (!found) return false; - } - - return true; - } -}; diff --git a/solutions/2074-reverse-nodes-in-even-length-groups.js b/solutions/2074-reverse-nodes-in-even-length-groups.js deleted file mode 100644 index 2608277e..00000000 --- a/solutions/2074-reverse-nodes-in-even-length-groups.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 2074. Reverse Nodes in Even Length Groups - * https://leetcode.com/problems/reverse-nodes-in-even-length-groups/ - * Difficulty: Medium - * - * You are given the head of a linked list. - * - * The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form - * the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number - * of nodes assigned to it. In other words: - * - The 1st node is assigned to the first group. - * - The 2nd and the 3rd nodes are assigned to the second group. - * - The 4th, 5th, and 6th nodes are assigned to the third group, and so on. - * - * Note that the length of the last group may be less than or equal to 1 + the length of the second - * to last group. - * - * Reverse the nodes in each group with an even length, and return the head of the modified 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 {ListNode} - */ -var reverseEvenLengthGroups = function(head) { - let prevGroup = head; - let groupLength = 2; - - while (prevGroup.next) { - let count = 0; - let current = prevGroup.next; - const groupStart = current; - - while (current && count < groupLength) { - current = current.next; - count++; - } - - if (count % 2 === 0) { - prevGroup.next = reverseGroup(groupStart, count); - } - - for (let i = 0; i < count; i++) { - prevGroup = prevGroup.next; - } - - groupLength++; - } - - return head; - - function reverseGroup(start, length) { - let prev = null; - let current = start; - for (let i = 0; i < length; i++) { - const next = current.next; - current.next = prev; - prev = current; - current = next; - } - start.next = current; - return prev; - } -}; diff --git a/solutions/2075-decode-the-slanted-ciphertext.js b/solutions/2075-decode-the-slanted-ciphertext.js deleted file mode 100644 index 63f5a41d..00000000 --- a/solutions/2075-decode-the-slanted-ciphertext.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 2075. Decode the Slanted Ciphertext - * https://leetcode.com/problems/decode-the-slanted-ciphertext/ - * Difficulty: Medium - * - * A string originalText is encoded using a slanted transposition cipher to a string encodedText - * with the help of a matrix having a fixed number of rows rows. - * - * originalText is placed first in a top-left to bottom-right manner. - * - * The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, - * until we reach the end of originalText. The arrow indicates the order in which the cells are - * filled. All empty cells are filled with ' '. The number of columns is chosen such that the - * rightmost column will not be empty after filling in originalText. - * - * encodedText is then formed by appending all characters of the matrix in a row-wise fashion. - * - * The characters in the blue cells are appended first to encodedText, then the red cells, and so - * on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. - * - * For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner. - * - * The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the - * order in which encodedText is formed. In the above example, encodedText = "ch ie pr". - * - * Given the encoded string encodedText and number of rows rows, return the original string - * originalText. - * - * Note: originalText does not have any trailing spaces ' '. The test cases are generated such that - * there is only one possible originalText. - */ - -/** - * @param {string} encodedText - * @param {number} rows - * @return {string} - */ -var decodeCiphertext = function(encodedText, rows) { - if (rows === 1) return encodedText; - - const count = encodedText.length / rows; - let result = ''; - - for (let i = 0; i < count; i++) { - for (let row = 0; row < rows && row + i < count; row++) { - result += encodedText[row * count + i + row]; - } - } - - return result.trimEnd(); -}; diff --git a/solutions/2076-process-restricted-friend-requests.js b/solutions/2076-process-restricted-friend-requests.js deleted file mode 100644 index dff94d09..00000000 --- a/solutions/2076-process-restricted-friend-requests.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * 2076. Process Restricted Friend Requests - * https://leetcode.com/problems/process-restricted-friend-requests/ - * Difficulty: Hard - * - * You are given an integer n indicating the number of people in a network. Each person is - * labeled from 0 to n - 1. - * - * You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] - * means that person xi and person yi cannot become friends, either directly or indirectly through - * other people. - * - * Initially, no one is friends with each other. You are given a list of friend requests as a - * 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between - * person uj and person vj. - * - * A friend request is successful if uj and vj can be friends. Each friend request is processed - * in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful - * request, uj and vj become direct friends for all future friend requests. - * - * Return a boolean array result, where each result[j] is true if the jth friend request is - * successful or false if it is not. - * - * Note: If uj and vj are already direct friends, the request is still successful. - */ - -/** - * @param {number} n - * @param {number[][]} restrictions - * @param {number[][]} requests - * @return {boolean[]} - */ -var friendRequests = function(n, restrictions, requests) { - const parent = Array.from({ length: n }, (_, i) => i); - const result = new Array(requests.length).fill(true); - - for (let j = 0; j < requests.length; j++) { - const [u, v] = requests[j]; - const pu = find(u); - const pv = find(v); - - let canBeFriends = true; - for (const [x, y] of restrictions) { - const px = find(x); - const py = find(y); - if ((pu === px && pv === py) || (pu === py && pv === px)) { - canBeFriends = false; - break; - } - } - - result[j] = canBeFriends; - if (canBeFriends) { - union(u, v); - } - } - - return result; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - parent[find(x)] = find(y); - } -}; diff --git a/solutions/2078-two-furthest-houses-with-different-colors.js b/solutions/2078-two-furthest-houses-with-different-colors.js deleted file mode 100644 index 9a42b696..00000000 --- a/solutions/2078-two-furthest-houses-with-different-colors.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 2078. Two Furthest Houses With Different Colors - * https://leetcode.com/problems/two-furthest-houses-with-different-colors/ - * Difficulty: Easy - * - * There are n houses evenly lined up on the street, and each house is beautifully painted. - * You are given a 0-indexed integer array colors of length n, where colors[i] represents - * the color of the ith house. - * - * Return the maximum distance between two houses with different colors. - * - * The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute - * value of x. - */ - -/** - * @param {number[]} colors - * @return {number} - */ -var maxDistance = function(colors) { - let result = 0; - - for (let i = 0; i < colors.length; i++) { - for (let j = i + 1; j < colors.length; j++) { - if (colors[i] !== colors[j]) { - result = Math.max(result, j - i); - } - } - } - - return result; -}; diff --git a/solutions/2079-watering-plants.js b/solutions/2079-watering-plants.js deleted file mode 100644 index ba77b302..00000000 --- a/solutions/2079-watering-plants.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 2079. Watering Plants - * https://leetcode.com/problems/watering-plants/ - * Difficulty: Medium - * - * You want to water n plants in your garden with a watering can. The plants are arranged in - * a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at - * x = i. There is a river at x = -1 that you can refill your watering can at. - * - * Each plant needs a specific amount of water. You will water the plants in the following way: - * - Water the plants in order from left to right. - * - After watering the current plant, if you do not have enough water to completely water the - * next plant, return to the river to fully refill the watering can. - * - You cannot refill the watering can early. - * - * You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. - * - * Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water - * the ith plant needs, and an integer capacity representing the watering can capacity, return - * the number of steps needed to water all the plants. - */ - -/** - * @param {number[]} plants - * @param {number} capacity - * @return {number} - */ -var wateringPlants = function(plants, capacity) { - let water = capacity; - let result = 0; - - for (let i = 0; i < plants.length; i++) { - if (water < plants[i]) { - result += 2 * i; - water = capacity; - } - water -= plants[i]; - result++; - } - - return result; -}; diff --git a/solutions/2080-range-frequency-queries.js b/solutions/2080-range-frequency-queries.js deleted file mode 100644 index 32b1bb27..00000000 --- a/solutions/2080-range-frequency-queries.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 2080. Range Frequency Queries - * https://leetcode.com/problems/range-frequency-queries/ - * Difficulty: Medium - * - * Design a data structure to find the frequency of a given value in a given subarray. - * - * The frequency of a value in a subarray is the number of occurrences of that value in - * the subarray. - * - * Implement the RangeFreqQuery class: - * - RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed - * integer array arr. - * - int query(int left, int right, int value) Returns the frequency of value in the subarray - * arr[left...right]. - * - A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes - * the subarray that contains the elements of nums between indices left and right (inclusive). - */ - -/** - * @param {number[]} arr - */ -var RangeFreqQuery = function(arr) { - this.frequencyMap = new Map(); - - for (let i = 0; i < arr.length; i++) { - if (!this.frequencyMap.has(arr[i])) { - this.frequencyMap.set(arr[i], []); - } - this.frequencyMap.get(arr[i]).push(i); - } -}; - -/** - * @param {number} left - * @param {number} right - * @param {number} value - * @return {number} - */ -RangeFreqQuery.prototype.query = function(left, right, value) { - if (!this.frequencyMap.has(value)) return 0; - - const indices = this.frequencyMap.get(value); - let start = 0; - let end = indices.length - 1; - let leftBound = -1; - let rightBound = -1; - - while (start <= end) { - const mid = Math.floor((start + end) / 2); - if (indices[mid] >= left) { - leftBound = mid; - end = mid - 1; - } else { - start = mid + 1; - } - } - - start = 0; - end = indices.length - 1; - while (start <= end) { - const mid = Math.floor((start + end) / 2); - if (indices[mid] <= right) { - rightBound = mid; - start = mid + 1; - } else { - end = mid - 1; - } - } - - return leftBound === -1 || rightBound === -1 ? 0 : rightBound - leftBound + 1; -}; diff --git a/solutions/2081-sum-of-k-mirror-numbers.js b/solutions/2081-sum-of-k-mirror-numbers.js deleted file mode 100644 index 600d62d8..00000000 --- a/solutions/2081-sum-of-k-mirror-numbers.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * 2081. Sum of k-Mirror Numbers - * https://leetcode.com/problems/sum-of-k-mirror-numbers/ - * Difficulty: Hard - * - * A k-mirror number is a positive integer without leading zeros that reads the same both forward - * and backward in base-10 as well as in base-k. - * - For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and - * 1001 respectively, which read the same both forward and backward. - * - On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which - * does not read the same both forward and backward. - * - * Given the base k and the number n, return the sum of the n smallest k-mirror numbers. - */ - -/** - * @param {number} k - * @param {number} n - * @return {number} - */ -var kMirror = function(k, n) { - const kMirrorNumbers = []; - let sum = 0; - let length = 1; - - while (kMirrorNumbers.length < n) { - generatePalindromes(length).forEach(num => { - if (kMirrorNumbers.length < n && isKMirror(num, k)) { - kMirrorNumbers.push(num); - sum += num; - } - }); - length++; - } - - return sum; -}; - -function toBaseK(num, k) { - if (num === 0) return '0'; - - let result = ''; - while (num > 0) { - result = (num % k) + result; - num = Math.floor(num / k); - } - - return result; -} - -function isKMirror(num, k) { - const baseKRepresentation = toBaseK(num, k); - return isPalindrome(baseKRepresentation); -} - -function isPalindrome(str) { - let left = 0; - let right = str.length - 1; - - while (left < right) { - if (str[left] !== str[right]) return false; - left++; - right--; - } - - return true; -} - -function generatePalindromes(length) { - const palindromes = []; - - if (length === 1) { - for (let i = 1; i <= 9; i++) { - palindromes.push(i); - } - return palindromes; - } - - if (length % 2 === 0) { - const half = length / 2; - const start = Math.pow(10, half - 1); - const end = Math.pow(10, half) - 1; - - for (let i = start; i <= end; i++) { - const firstHalf = i.toString(); - const secondHalf = firstHalf.split('').reverse().join(''); - palindromes.push(parseInt(firstHalf + secondHalf)); - } - } else { - const half = Math.floor(length / 2); - const start = Math.pow(10, half); - const end = Math.pow(10, half + 1) - 1; - - for (let i = start; i <= end; i++) { - const withoutMiddle = Math.floor(i / 10); - const middle = i % 10; - const firstHalf = withoutMiddle.toString(); - const secondHalf = firstHalf.split('').reverse().join(''); - palindromes.push(parseInt(firstHalf + middle + secondHalf)); - } - } - - return palindromes; -} - diff --git a/solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js b/solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js deleted file mode 100644 index 5cda9132..00000000 --- a/solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 2086. Minimum Number of Food Buckets to Feed the Hamsters - * https://leetcode.com/problems/minimum-number-of-food-buckets-to-feed-the-hamsters/ - * Difficulty: Medium - * - * You are given a 0-indexed string hamsters where hamsters[i] is either: - * - 'H' indicating that there is a hamster at index i, or - * - '.' indicating that index i is empty. - * - * You will add some number of food buckets at the empty indices in order to feed the hamsters. - * A hamster can be fed if there is at least one food bucket to its left or to its right. More - * formally, a hamster at index i can be fed if you place a food bucket at index i - 1 and/or - * at index i + 1. - * - * Return the minimum number of food buckets you should place at empty indices to feed all the - * hamsters or -1 if it is impossible to feed all of them. - */ - -/** - * @param {string} hamsters - * @return {number} - */ -var minimumBuckets = function(hamsters) { - const n = hamsters.length; - let result = 0; - - for (let i = 0; i < n; i++) { - if (hamsters[i] === 'H') { - if (i > 0 && hamsters[i - 1] === 'B') continue; - if (i < n - 1 && hamsters[i + 1] === '.') { - result++; - hamsters = hamsters.slice(0, i + 1) + 'B' + hamsters.slice(i + 2); - } else if (i > 0 && hamsters[i - 1] === '.') { - result++; - hamsters = hamsters.slice(0, i - 1) + 'B' + hamsters.slice(i); - } else { - return -1; - } - } - } - - return result; -}; diff --git a/solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js b/solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js deleted file mode 100644 index 8fde0697..00000000 --- a/solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 2087. Minimum Cost Homecoming of a Robot in a Grid - * https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/ - * Difficulty: Medium - * - * There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right - * cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates - * that initially, a robot is at the cell (startrow, startcol). You are also given an integer array - * homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, - * homecol). - * - * The robot needs to go to its home. It can move one cell in four directions: left, right, up, - * or down, and it can not move outside the boundary. Every move incurs some cost. You are further - * given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. - * - If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. - * - If the robot moves left or right into a cell whose column is c, then this move costs - * colCosts[c]. - * - * Return the minimum total cost for this robot to return home. - */ - -/** - * @param {number[]} startPos - * @param {number[]} homePos - * @param {number[]} rowCosts - * @param {number[]} colCosts - * @return {number} - */ -var minCost = function(startPos, homePos, rowCosts, colCosts) { - let result = 0; - const [startRow, startCol] = startPos; - const [homeRow, homeCol] = homePos; - - const rowStep = startRow < homeRow ? 1 : -1; - for (let row = startRow + rowStep; row !== homeRow + rowStep; row += rowStep) { - result += rowCosts[row]; - } - - const colStep = startCol < homeCol ? 1 : -1; - for (let col = startCol + colStep; col !== homeCol + colStep; col += colStep) { - result += colCosts[col]; - } - - return result; -}; diff --git a/solutions/2088-count-fertile-pyramids-in-a-land.js b/solutions/2088-count-fertile-pyramids-in-a-land.js deleted file mode 100644 index 0780710b..00000000 --- a/solutions/2088-count-fertile-pyramids-in-a-land.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 2088. Count Fertile Pyramids in a Land - * https://leetcode.com/problems/count-fertile-pyramids-in-a-land/ - * Difficulty: Hard - * - * A farmer has a rectangular grid of land with m rows and n columns that can be divided into - * unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). - * All cells outside the grid are considered barren. - * - * A pyramidal plot of land can be defined as a set of cells with the following criteria: - * 1. The number of cells in the set has to be greater than 1 and all cells must be fertile. - * 2. The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the - * number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. - * Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and - * c - (i - r) <= j <= c + (i - r). - * - * An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: - * 1. The number of cells in the set has to be greater than 1 and all cells must be fertile. - * 2. The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height - * of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the - * pyramid, and its height be h. Then, the plot comprises of cells (i, j) where - * r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i). - * - * Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. - * Black cells indicate fertile cells. - * - * Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number - * of pyramidal and inverse pyramidal plots that can be found in grid. - */ - -/** - * @param {number[][]} grid - * @return {number} - */ -var countPyramids = function(grid) { - const rows = grid.length; - const cols = grid[0].length; - let result = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j] === 1) { - result += countPyramidAt(i, j, false); - result += countPyramidAt(i, j, true); - } - } - } - - return result; - - function countPyramidAt(row, col, isInverse) { - let height = 0; - for (let h = 1; ; h++) { - const r = isInverse ? row - h : row + h; - if (r < 0 || r >= rows) break; - const left = col - h; - const right = col + h; - if (left < 0 || right >= cols) break; - let valid = true; - for (let j = left; j <= right; j++) { - if (grid[r][j] === 0) { - valid = false; - break; - } - } - if (!valid) break; - height++; - } - return height; - } -}; diff --git a/solutions/2089-find-target-indices-after-sorting-array.js b/solutions/2089-find-target-indices-after-sorting-array.js deleted file mode 100644 index c7235faa..00000000 --- a/solutions/2089-find-target-indices-after-sorting-array.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 2089. Find Target Indices After Sorting Array - * https://leetcode.com/problems/find-target-indices-after-sorting-array/ - * Difficulty: Easy - * - * You are given a 0-indexed integer array nums and a target element target. - * - * A target index is an index i such that nums[i] == target. - * - * Return a list of the target indices of nums after sorting nums in non-decreasing order. - * If there are no target indices, return an empty list. The returned list must be sorted - * in increasing order. - */ - -/** - * @param {number[]} nums - * @param {number} target - * @return {number[]} - */ -var targetIndices = function(nums, target) { - const result = []; - - nums.sort((a, b) => a - b); - - for (let i = 0; i < nums.length; i++) { - if (nums[i] === target) { - result.push(i); - } - } - - return result; -}; diff --git a/solutions/2090-k-radius-subarray-averages.js b/solutions/2090-k-radius-subarray-averages.js deleted file mode 100644 index 3808077d..00000000 --- a/solutions/2090-k-radius-subarray-averages.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 2090. K Radius Subarray Averages - * https://leetcode.com/problems/k-radius-subarray-averages/ - * Difficulty: Medium - * - * You are given a 0-indexed array nums of n integers, and an integer k. - * - * The k-radius average for a subarray of nums centered at some index i with the radius k is - * the average of all elements in nums between the indices i - k and i + k (inclusive). If - * there are less than k elements before or after the index i, then the k-radius average is -1. - * - * Build and return an array avgs of length n where avgs[i] is the k-radius average for the - * subarray centered at index i. - * - * The average of x elements is the sum of the x elements divided by x, using integer division. - * The integer division truncates toward zero, which means losing its fractional part. - * - For example, the average of four elements 2, 3, 1, and - * 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2. - */ - -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var getAverages = function(nums, k) { - const n = nums.length; - const windowSize = 2 * k + 1; - const result = new Array(n).fill(-1); - - if (windowSize > n) return result; - - let sum = 0; - for (let i = 0; i < windowSize; i++) { - sum += nums[i]; - } - - result[k] = Math.floor(sum / windowSize); - - for (let i = k + 1; i < n - k; i++) { - sum = sum - nums[i - k - 1] + nums[i + k]; - result[i] = Math.floor(sum / windowSize); - } - - return result; -}; diff --git a/solutions/2091-removing-minimum-and-maximum-from-array.js b/solutions/2091-removing-minimum-and-maximum-from-array.js deleted file mode 100644 index b62e781e..00000000 --- a/solutions/2091-removing-minimum-and-maximum-from-array.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 2091. Removing Minimum and Maximum From Array - * https://leetcode.com/problems/removing-minimum-and-maximum-from-array/ - * Difficulty: Medium - * - * You are given a 0-indexed array of distinct integers nums. - * - * There is an element in nums that has the lowest value and an element that has the highest - * value. We call them the minimum and maximum respectively. Your goal is to remove both these - * elements from the array. - * - * A deletion is defined as either removing an element from the front of the array or removing - * an element from the back of the array. - * - * Return the minimum number of deletions it would take to remove both the minimum and maximum - * element from the array. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var minimumDeletions = function(nums) { - const n = nums.length; - let minIndex = 0; - let maxIndex = 0; - - for (let i = 1; i < n; i++) { - if (nums[i] < nums[minIndex]) minIndex = i; - if (nums[i] > nums[maxIndex]) maxIndex = i; - } - - const left = Math.min(minIndex, maxIndex); - const right = Math.max(minIndex, maxIndex); - - return Math.min( - right + 1, - n - left, - left + 1 + n - right - ); -}; diff --git a/solutions/2092-find-all-people-with-secret.js b/solutions/2092-find-all-people-with-secret.js deleted file mode 100644 index f5fecbdc..00000000 --- a/solutions/2092-find-all-people-with-secret.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 2092. Find All People With Secret - * https://leetcode.com/problems/find-all-people-with-secret/ - * Difficulty: Hard - * - * You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also - * given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that - * person xi and person yi have a meeting at timei. A person may attend multiple meetings at the - * same time. Finally, you are given an integer firstPerson. - * - * Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This - * secret is then shared every time a meeting takes place with a person that has the secret. More - * formally, for every meeting, if a person xi has the secret at timei, then they will share the - * secret with person yi, and vice versa. - * - * The secrets are shared instantaneously. That is, a person may receive the secret and share it - * with people in other meetings within the same time frame. - * - * Return a list of all the people that have the secret after all the meetings have taken place. - * You may return the answer in any order. - */ - -/** - * @param {number} n - * @param {number[][]} meetings - * @param {number} firstPerson - * @return {number[]} - */ -var findAllPeople = function(n, meetings, firstPerson) { - const parent = Array.from({ length: n }, (_, i) => i); - - union(0, firstPerson); - meetings.sort((a, b) => a[2] - b[2]); - - let i = 0; - while (i < meetings.length) { - const currentTime = meetings[i][2]; - const group = []; - - while (i < meetings.length && meetings[i][2] === currentTime) { - const [x, y] = meetings[i]; - group.push(x, y); - union(x, y); - i++; - } - - for (const person of group) { - if (find(person) !== find(0)) { - parent[person] = person; - } - } - } - - const result = []; - for (let j = 0; j < n; j++) { - if (find(j) === find(0)) { - result.push(j); - } - } - - return result; - - function find(x) { - if (parent[x] !== x) { - parent[x] = find(parent[x]); - } - return parent[x]; - } - - function union(x, y) { - parent[find(x)] = find(y); - } -}; diff --git a/solutions/2094-finding-3-digit-even-numbers.js b/solutions/2094-finding-3-digit-even-numbers.js deleted file mode 100644 index f021bdff..00000000 --- a/solutions/2094-finding-3-digit-even-numbers.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 2094. Finding 3-Digit Even Numbers - * https://leetcode.com/problems/finding-3-digit-even-numbers/ - * Difficulty: Easy - * - * You are given an integer array digits, where each element is a digit. The array may contain - * duplicates. - * - * You need to find all the unique integers that follow the given requirements: - * - The integer consists of the concatenation of three elements from digits in any arbitrary order. - * - The integer does not have leading zeros. - * - The integer is even. - * - * For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. - * - * Return a sorted array of the unique integers. - */ - -/** - * @param {number[]} digits - * @return {number[]} - */ -var findEvenNumbers = function(digits) { - const frequency = new Array(10).fill(0); - const uniqueNumbers = new Set(); - - for (const digit of digits) { - frequency[digit]++; - } - - for (let hundreds = 1; hundreds <= 9; hundreds++) { - if (frequency[hundreds] === 0) continue; - frequency[hundreds]--; - - for (let tens = 0; tens <= 9; tens++) { - if (frequency[tens] === 0) continue; - frequency[tens]--; - - for (let ones = 0; ones <= 8; ones += 2) { - if (frequency[ones] === 0) continue; - uniqueNumbers.add(hundreds * 100 + tens * 10 + ones); - } - - frequency[tens]++; - } - - frequency[hundreds]++; - } - - return Array.from(uniqueNumbers).sort((a, b) => a - b); -}; diff --git a/solutions/2095-delete-the-middle-node-of-a-linked-list.js b/solutions/2095-delete-the-middle-node-of-a-linked-list.js deleted file mode 100644 index 92ff7870..00000000 --- a/solutions/2095-delete-the-middle-node-of-a-linked-list.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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/solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js b/solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js deleted file mode 100644 index 4eb7d4e9..00000000 --- a/solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 2096. Step-By-Step Directions From a Binary Tree Node to Another - * https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/ - * Difficulty: Medium - * - * You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value - * from 1 to n. You are also given an integer startValue representing the value of the start node - * s, and a different integer destValue representing the value of the destination node t. - * - * Find the shortest path starting from node s and ending at node t. Generate step-by-step - * directions of such path as a string consisting of only the uppercase letters 'L', 'R', and - * 'U'. Each letter indicates a specific direction: - * - 'L' means to go from a node to its left child node. - * - 'R' means to go from a node to its right child node. - * - 'U' means to go from a node to its parent node. - * - * Return the step-by-step directions of the shortest path from node s to node t. - */ - -/** - * 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} startValue - * @param {number} destValue - * @return {string} - */ -var getDirections = function(root, startValue, destValue) { - const startPath = []; - const destPath = []; - - findPath(root, startValue, startPath); - findPath(root, destValue, destPath); - - let i = 0; - while (i < startPath.length && i < destPath.length && startPath[i] === destPath[i]) { - i++; - } - - const upMoves = 'U'.repeat(startPath.length - i); - const downMoves = destPath.slice(i).join(''); - - return upMoves + downMoves; - - function findPath(node, value, path) { - if (!node) return false; - if (node.val === value) return true; - - path.push('L'); - if (findPath(node.left, value, path)) return true; - path.pop(); - - path.push('R'); - if (findPath(node.right, value, path)) return true; - path.pop(); - - return false; - } -}; diff --git a/solutions/2097-valid-arrangement-of-pairs.js b/solutions/2097-valid-arrangement-of-pairs.js deleted file mode 100644 index d3c5ee1c..00000000 --- a/solutions/2097-valid-arrangement-of-pairs.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 2097. Valid Arrangement of Pairs - * https://leetcode.com/problems/valid-arrangement-of-pairs/ - * Difficulty: Hard - * - * You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement - * of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. - * - * Return any valid arrangement of pairs. - * - * Note: The inputs will be generated such that there exists a valid arrangement of pairs. - */ - -/** - * @param {number[][]} pairs - * @return {number[][]} - */ -var validArrangement = function(pairs) { - const graph = new Map(); - const degree = new Map(); - - for (const [start, end] of pairs) { - if (!graph.has(start)) graph.set(start, []); - graph.get(start).push(end); - - degree.set(start, (degree.get(start) || 0) + 1); - degree.set(end, (degree.get(end) || 0) - 1); - } - - let startNode = pairs[0][0]; - for (const [node, deg] of degree) { - if (deg > 0) { - startNode = node; - break; - } - } - - const result = []; - helper(startNode); - - return result.reverse(); - - function helper(node) { - while (graph.get(node)?.length) { - const next = graph.get(node).pop(); - helper(next); - result.push([node, next]); - } - } -}; diff --git a/solutions/2100-find-good-days-to-rob-the-bank.js b/solutions/2100-find-good-days-to-rob-the-bank.js deleted file mode 100644 index 1dc59611..00000000 --- a/solutions/2100-find-good-days-to-rob-the-bank.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 2100. Find Good Days to Rob the Bank - * https://leetcode.com/problems/find-good-days-to-rob-the-bank/ - * Difficulty: Medium - * - * You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer - * array security, where security[i] is the number of guards on duty on the ith day. The days - * are numbered starting from 0. You are also given an integer time. - * - * The ith day is a good day to rob the bank if: - * - There are at least time days before and after the ith day, - * - The number of guards at the bank for the time days before i are non-increasing, and - * - The number of guards at the bank for the time days after i are non-decreasing. - * - * More formally, this means day i is a good day to rob the bank if and only if - * security[i - time] >= security[i - time + 1] >= ... >= security[i] - * <= ... <= security[i + time - 1] <= security[i + time]. - * - * Return a list of all days (0-indexed) that are good days to rob the bank. The order that the - * days are returned in does not matter. - */ - -/** - * @param {number[]} security - * @param {number} time - * @return {number[]} - */ -var goodDaysToRobBank = function(security, time) { - const n = security.length; - const nonIncreasing = new Array(n).fill(0); - const nonDecreasing = new Array(n).fill(0); - const result = []; - - for (let i = 1; i < n; i++) { - if (security[i] <= security[i - 1]) { - nonIncreasing[i] = nonIncreasing[i - 1] + 1; - } - if (security[n - i - 1] <= security[n - i]) { - nonDecreasing[n - i - 1] = nonDecreasing[n - i] + 1; - } - } - - for (let i = time; i < n - time; i++) { - if (nonIncreasing[i] >= time && nonDecreasing[i] >= time) { - result.push(i); - } - } - - return result; -}; diff --git a/solutions/2101-detonate-the-maximum-bombs.js b/solutions/2101-detonate-the-maximum-bombs.js deleted file mode 100644 index 11069857..00000000 --- a/solutions/2101-detonate-the-maximum-bombs.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 2101. Detonate the Maximum Bombs - * https://leetcode.com/problems/detonate-the-maximum-bombs/ - * Difficulty: Medium - * - * You are given a list of bombs. The range of a bomb is defined as the area where its effect - * can be felt. This area is in the shape of a circle with the center as the location of the bomb. - * - * The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. - * xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri - * denotes the radius of its range. - * - * You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs - * that lie in its range. These bombs will further detonate the bombs that lie in their ranges. - * - * Given the list of bombs, return the maximum number of bombs that can be detonated if you are - * allowed to detonate only one bomb. - */ - -/** - * @param {number[][]} bombs - * @return {number} - */ -var maximumDetonation = function(bombs) { - const n = bombs.length; - const graph = Array.from({ length: n }, () => []); - - for (let i = 0; i < n; i++) { - const [x1, y1, r1] = bombs[i]; - for (let j = 0; j < n; j++) { - if (i === j) continue; - const [x2, y2] = bombs[j]; - const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); - if (distance <= r1) { - graph[i].push(j); - } - } - } - - let result = 0; - for (let i = 0; i < n; i++) { - result = Math.max(result, dfs(i, new Set())); - } - - return result; - - function dfs(node, visited) { - visited.add(node); - let count = 1; - for (const neighbor of graph[node]) { - if (!visited.has(neighbor)) { - count += dfs(neighbor, visited); - } - } - return count; - } -}; diff --git a/solutions/2103-rings-and-rods.js b/solutions/2103-rings-and-rods.js deleted file mode 100644 index b7cc219e..00000000 --- a/solutions/2103-rings-and-rods.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 2103. Rings and Rods - * https://leetcode.com/problems/rings-and-rods/ - * Difficulty: Easy - * - * There are n rings and each ring is either red, green, or blue. The rings are distributed across - * ten rods labeled from 0 to 9. - * - * You are given a string rings of length 2n that describes the n rings that are placed onto the - * rods. Every two characters in rings forms a color-position pair that is used to describe each - * ring where: - * - The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B'). - * - The second character of the ith pair denotes the rod that the ith ring is placed on - * ('0' to '9'). - * - * For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green - * ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. - * - * Return the number of rods that have all three colors of rings on them. - */ - -/** - * @param {string} rings - * @return {number} - */ -var countPoints = function(rings) { - const map = new Map(); - - for (let i = 0; i < rings.length; i += 2) { - const color = rings[i]; - const rod = rings[i + 1]; - if (!map.has(rod)) map.set(rod, new Set()); - map.get(rod).add(color); - } - - let result = 0; - for (const colors of map.values()) { - if (colors.size === 3) result++; - } - - return result; -}; diff --git a/solutions/2104-sum-of-subarray-ranges.js b/solutions/2104-sum-of-subarray-ranges.js deleted file mode 100644 index 0efaf1d7..00000000 --- a/solutions/2104-sum-of-subarray-ranges.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 2104. Sum of Subarray Ranges - * https://leetcode.com/problems/sum-of-subarray-ranges/ - * Difficulty: Medium - * - * You are given an integer array nums. The range of a subarray of nums is the difference between - * the largest and smallest element in the subarray. - * - * Return the sum of all subarray ranges of nums. - * - * A subarray is a contiguous non-empty sequence of elements within an array. - */ - -/** - * @param {number[]} nums - * @return {number} - */ -var subArrayRanges = function(nums) { - let result = 0; - - for (let i = 0; i < nums.length; i++) { - let min = nums[i]; - let max = nums[i]; - - for (let j = i; j < nums.length; j++) { - min = Math.min(min, nums[j]); - max = Math.max(max, nums[j]); - result += max - min; - } - } - - return result; -}; diff --git a/solutions/2105-watering-plants-ii.js b/solutions/2105-watering-plants-ii.js deleted file mode 100644 index dcdaf994..00000000 --- a/solutions/2105-watering-plants-ii.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 2105. Watering Plants II - * https://leetcode.com/problems/watering-plants-ii/ - * Difficulty: Medium - * - * Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are - * labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. - * - * Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially - * full. They water the plants in the following way: - * - Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters - * the plants in order from right to left, starting from the (n - 1)th plant. They begin watering - * the plants simultaneously. - * - It takes the same amount of time to water each plant regardless of how much water it needs. - * - Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, - * they first refill their can (instantaneously) then water the plant. - * - In case both Alice and Bob reach the same plant, the one with more water currently in his/her - * watering can should water this plant. If they have the same amount of water, then Alice should - * water this plant. - * - * Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the - * ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's - * and Bob's watering cans respectively, return the number of times they have to refill to water all - * the plants. - */ - -/** - * @param {number[]} plants - * @param {number} capacityA - * @param {number} capacityB - * @return {number} - */ -var minimumRefill = function(plants, capacityA, capacityB) { - let result = 0; - let left = 0; - let right = plants.length - 1; - let waterA = capacityA; - let waterB = capacityB; - - while (left <= right) { - if (left === right) { - if (waterA >= waterB && waterA < plants[left]) result++; - if (waterB > waterA && waterB < plants[right]) result++; - break; - } - - if (waterA < plants[left]) { - waterA = capacityA; - result++; - } - waterA -= plants[left++]; - - if (waterB < plants[right]) { - waterB = capacityB; - result++; - } - waterB -= plants[right--]; - } - - return result; -}; diff --git a/solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js b/solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js deleted file mode 100644 index bd81e17e..00000000 --- a/solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * 2106. Maximum Fruits Harvested After at Most K Steps - * https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/ - * Difficulty: Hard - * - * Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array - * fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. - * fruits is already sorted by positioni in ascending order, and each positioni is unique. - * - * You are also given an integer startPos and an integer k. Initially, you are at the position - * startPos. From any position, you can either walk to the left or right. It takes one step to - * move one unit on the x-axis, and you can walk at most k steps in total. For every position - * you reach, you harvest all the fruits at that position, and the fruits will disappear from - * that position. - * - * Return the maximum total number of fruits you can harvest. - */ - -/** - * @param {number[][]} fruits - * @param {number} startPos - * @param {number} k - * @return {number} - */ -var maxTotalFruits = function(fruits, startPos, k) { - let result = 0; - let left = 0; - let currentSum = 0; - - for (let right = 0; right < fruits.length; right++) { - currentSum += fruits[right][1]; - - while (left <= right) { - const minPos = fruits[left][0]; - const maxPos = fruits[right][0]; - const steps = Math.min( - Math.abs(startPos - minPos) + (maxPos - minPos), - Math.abs(startPos - maxPos) + (maxPos - minPos) - ); - - if (steps <= k) break; - currentSum -= fruits[left][1]; - left++; - } - - if (left <= right) { - result = Math.max(result, currentSum); - } - } - - return result; -}; diff --git a/solutions/2108-find-first-palindromic-string-in-the-array.js b/solutions/2108-find-first-palindromic-string-in-the-array.js deleted file mode 100644 index a72a02b0..00000000 --- a/solutions/2108-find-first-palindromic-string-in-the-array.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 2108. Find First Palindromic String in the Array - * https://leetcode.com/problems/find-first-palindromic-string-in-the-array/ - * Difficulty: Easy - * - * Given an array of strings words, return the first palindromic string in the array. If there is - * no such string, return an empty string "". - * - * A string is palindromic if it reads the same forward and backward. - */ - -/** - * @param {string[]} words - * @return {string} - */ -var firstPalindrome = function(words) { - for (const word of words) { - if (word === word.split('').reverse().join('')) { - return word; - } - } - return ''; -}; diff --git a/solutions/2109-adding-spaces-to-a-string.js b/solutions/2109-adding-spaces-to-a-string.js deleted file mode 100644 index 7f4a85ba..00000000 --- a/solutions/2109-adding-spaces-to-a-string.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 2109. Adding Spaces to a String - * https://leetcode.com/problems/adding-spaces-to-a-string/ - * Difficulty: Medium - * - * You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the - * indices in the original string where spaces will be added. Each space should be inserted - * before the character at the given index. - * - For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' - * and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee". - * - * Return the modified string after the spaces have been added. - */ - -/** - * @param {string} s - * @param {number[]} spaces - * @return {string} - */ -var addSpaces = function(s, spaces) { - let result = ''; - let spaceIndex = 0; - - for (let i = 0; i < s.length; i++) { - if (spaceIndex < spaces.length && i === spaces[spaceIndex]) { - result += ' '; - spaceIndex++; - } - result += s[i]; - } - - return result; -}; diff --git a/solutions/2110-number-of-smooth-descent-periods-of-a-stock.js b/solutions/2110-number-of-smooth-descent-periods-of-a-stock.js deleted file mode 100644 index 09a08e95..00000000 --- a/solutions/2110-number-of-smooth-descent-periods-of-a-stock.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 2110. Number of Smooth Descent Periods of a Stock - * https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/ - * Difficulty: Medium - * - * You are given an integer array prices representing the daily price history of a stock, - * where prices[i] is the stock price on the ith day. - * - * A smooth descent period of a stock consists of one or more contiguous days such that the - * price on each day is lower than the price on the preceding day by exactly 1. The first - * day of the period is exempted from this rule. - * - * Return the number of smooth descent periods. - */ - -/** - * @param {number[]} prices - * @return {number} - */ -var getDescentPeriods = function(prices) { - let result = 1; - let currentLength = 1; - - for (let i = 1; i < prices.length; i++) { - if (prices[i] === prices[i - 1] - 1) { - currentLength++; - } else { - currentLength = 1; - } - result += currentLength; - } - - return result; -}; diff --git a/solutions/2111-minimum-operations-to-make-the-array-k-increasing.js b/solutions/2111-minimum-operations-to-make-the-array-k-increasing.js deleted file mode 100644 index 8f861b84..00000000 --- a/solutions/2111-minimum-operations-to-make-the-array-k-increasing.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 2111. Minimum Operations to Make the Array K-Increasing - * https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/ - * Difficulty: Hard - * - * You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. - * - * The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where - * k <= i <= n-1. - * - * - For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: - * - arr[0] <= arr[2] (4 <= 5) - * - arr[1] <= arr[3] (1 <= 2) - * - arr[2] <= arr[4] (5 <= 6) - * - arr[3] <= arr[5] (2 <= 2) - * - However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because - * arr[0] > arr[3]). - * - * In one operation, you can choose an index i and change arr[i] into any positive integer. - * - * Return the minimum number of operations required to make the array K-increasing for the given k. - */ - -/** - * @param {number[]} arr - * @param {number} k - * @return {number} - */ -var kIncreasing = function(arr, k) { - let result = 0; - for (let i = 0; i < k; i++) { - const subsequence = []; - for (let j = i; j < arr.length; j += k) { - subsequence.push(arr[j]); - } - result += longestNonDecreasingSubsequence(subsequence); - } - - return result; - - function longestNonDecreasingSubsequence(nums) { - const tails = []; - for (const num of nums) { - let left = 0; - let right = tails.length; - while (left < right) { - const mid = Math.floor((left + right) / 2); - if (tails[mid] <= num) { - left = mid + 1; - } else { - right = mid; - } - } - tails[left] = num; - } - return nums.length - tails.length; - } -}; diff --git a/solutions/2115-find-all-possible-recipes-from-given-supplies.js b/solutions/2115-find-all-possible-recipes-from-given-supplies.js deleted file mode 100644 index a13ac28f..00000000 --- a/solutions/2115-find-all-possible-recipes-from-given-supplies.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 2115. Find All Possible Recipes from Given Supplies - * https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ - * Difficulty: Medium - * - * You have information about n different recipes. You are given a string array recipes and a 2D - * string array ingredients. The ith recipe has the name recipes[i], and you can create it if you - * have all the needed ingredients from ingredients[i]. A recipe can also be an ingredient for - * other recipes, i.e., ingredients[i] may contain a string that is in recipes. - * - * You are also given a string array supplies containing all the ingredients that you initially - * have, and you have an infinite supply of all of them. - * - * Return a list of all the recipes that you can create. You may return the answer in any order. - * - * Note that two recipes may contain each other in their ingredients. - */ - -/** - * @param {string[]} recipes - * @param {string[][]} ingredients - * @param {string[]} supplies - * @return {string[]} - */ -var findAllRecipes = function(recipes, ingredients, supplies) { - const available = new Set(supplies); - const recipeGraph = new Map(); - const inDegree = new Map(); - const queue = []; - const result = []; - - recipes.forEach((recipe, index) => { - inDegree.set(recipe, ingredients[index].length); - ingredients[index].forEach(ing => { - if (!recipeGraph.has(ing)) recipeGraph.set(ing, []); - recipeGraph.get(ing).push(recipe); - }); - }); - - available.forEach(supply => { - if (recipeGraph.has(supply)) { - recipeGraph.get(supply).forEach(recipe => { - const count = inDegree.get(recipe) - 1; - inDegree.set(recipe, count); - if (count === 0) queue.push(recipe); - }); - } - }); - - while (queue.length) { - const currentRecipe = queue.shift(); - result.push(currentRecipe); - if (recipeGraph.has(currentRecipe)) { - recipeGraph.get(currentRecipe).forEach(nextRecipe => { - const count = inDegree.get(nextRecipe) - 1; - inDegree.set(nextRecipe, count); - if (count === 0) queue.push(nextRecipe); - }); - } - } - - return result; -}; diff --git a/solutions/2117-abbreviating-the-product-of-a-range.js b/solutions/2117-abbreviating-the-product-of-a-range.js deleted file mode 100644 index 4334b25b..00000000 --- a/solutions/2117-abbreviating-the-product-of-a-range.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * 2117. Abbreviating the Product of a Range - * https://leetcode.com/problems/abbreviating-the-product-of-a-range/ - * Difficulty: Hard - * - * You are given two positive integers left and right with left <= right. Calculate the product of - * all integers in the inclusive range [left, right]. - * - * Since the product may be very large, you will abbreviate it following these steps: - * 1. Count all trailing zeros in the product and remove them. Let us denote this count as C. - * - For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546. - * 2. Denote the remaining number of digits in the product as d. If d > 10, then express the product - * as
... where 
 denotes the first 5 digits of the product, and  denotes the
- *    last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it
- *    unchanged.
- *    - For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as
- *      1234567.
- * 3. Finally, represent the product as a string "
...eC".
- *    - For example, 12345678987600000 will be represented as "12345...89876e5".
- *
- * Return a string denoting the abbreviated product of all integers in the inclusive range [left,
- * right].
- */
-
-/**
- * @param {number} left
- * @param {number} right
- * @return {string}
- */
-var abbreviateProduct = function(left, right) {
-  let zeros = 0;
-  let count2 = 0;
-  let count5 = 0;
-
-  for (let i = left; i <= right; i++) {
-    let n = i;
-    while (n % 2 === 0) {
-      count2++;
-      n = Math.floor(n / 2);
-    }
-    n = i;
-    while (n % 5 === 0) {
-      count5++;
-      n = Math.floor(n / 5);
-    }
-  }
-  zeros = Math.min(count2, count5);
-
-  let digits = 0;
-  for (let i = left; i <= right; i++) {
-    digits += Math.log10(i);
-  }
-  digits = Math.floor(digits) + 1;
-
-  if (digits - zeros <= 10) {
-    let product = 1n;
-    for (let i = left; i <= right; i++) {
-      product *= BigInt(i);
-    }
-    for (let i = 0; i < zeros; i++) {
-      product /= 10n;
-    }
-    return product.toString() + 'e' + zeros;
-  }
-
-  let prefix = 1;
-  for (let i = left; i <= right; i++) {
-    prefix *= i;
-    while (prefix >= 1e10) {
-      prefix /= 10;
-    }
-  }
-  prefix = prefix.toString().slice(0, 5);
-
-  let suffix = 1n;
-  for (let i = right; i >= left; i--) {
-    suffix = (suffix * BigInt(i));
-    while (suffix % 10n === 0n) {
-      suffix /= 10n;
-    }
-    suffix = suffix % (10n ** 15n);
-  }
-
-  suffix = suffix.toString();
-  while (suffix.length < 5) {
-    suffix = '0' + suffix;
-  }
-  suffix = suffix.slice(-5);
-
-  return prefix + '...' + suffix + 'e' + zeros;
-};
diff --git a/solutions/2119-a-number-after-a-double-reversal.js b/solutions/2119-a-number-after-a-double-reversal.js
deleted file mode 100644
index efc1d321..00000000
--- a/solutions/2119-a-number-after-a-double-reversal.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * 2119. A Number After a Double Reversal
- * https://leetcode.com/problems/a-number-after-a-double-reversal/
- * Difficulty: Easy
- *
- * Reversing an integer means to reverse all its digits.
- * - For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros
- *   are not retained.
- *
- * Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2.
- * Return true if reversed2 equals num. Otherwise return false.
- */
-
-/**
- * @param {number} num
- * @return {boolean}
- */
-var isSameAfterReversals = function(num) {
-  return num === 0 || num % 10 !== 0;
-};
diff --git a/solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js b/solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js
deleted file mode 100644
index 940ddc72..00000000
--- a/solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * 2120. Execution of All Suffix Instructions Staying in a Grid
- * https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/
- * Difficulty: Medium
- *
- * There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at
- * (n - 1, n - 1). You are given the integer n and an integer array startPos where
- * startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).
- *
- * You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the
- * robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).
- *
- * The robot can begin executing from any ith instruction in s. It executes the instructions one
- * by one towards the end of s but it stops if either of these conditions is met:
- * - The next instruction will move the robot off the grid.
- * - There are no more instructions left to execute.
- *
- * Return an array answer of length m where answer[i] is the number of instructions the robot can
- * execute if the robot begins executing from the ith instruction in s.
- */
-
-/**
- * @param {number} n
- * @param {number[]} startPos
- * @param {string} s
- * @return {number[]}
- */
-var executeInstructions = function(n, startPos, s) {
-  const m = s.length;
-  const result = new Array(m).fill(0);
-
-  for (let i = 0; i < m; i++) {
-    let row = startPos[0];
-    let col = startPos[1];
-    let steps = 0;
-
-    for (let j = i; j < m; j++) {
-      if (s[j] === 'L') col--;
-      else if (s[j] === 'R') col++;
-      else if (s[j] === 'U') row--;
-      else row++;
-
-      if (row < 0 || row >= n || col < 0 || col >= n) break;
-      steps++;
-    }
-
-    result[i] = steps;
-  }
-
-  return result;
-};
diff --git a/solutions/2121-intervals-between-identical-elements.js b/solutions/2121-intervals-between-identical-elements.js
deleted file mode 100644
index 3686726b..00000000
--- a/solutions/2121-intervals-between-identical-elements.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 2121. Intervals Between Identical Elements
- * https://leetcode.com/problems/intervals-between-identical-elements/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array of n integers arr.
- *
- * The interval between two elements in arr is defined as the absolute difference between their
- * indices. More formally, the interval between arr[i] and arr[j] is |i - j|.
- *
- * Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i]
- * and each element in arr with the same value as arr[i].
- *
- * Note: |x| is the absolute value of x.
- */
-
-/**
- * @param {number[]} arr
- * @return {number[]}
- */
-var getDistances = function(arr) {
-  const valueIndices = new Map();
-  const result = new Array(arr.length).fill(0);
-
-  for (let i = 0; i < arr.length; i++) {
-    if (!valueIndices.has(arr[i])) {
-      valueIndices.set(arr[i], []);
-    }
-    valueIndices.get(arr[i]).push(i);
-  }
-
-  for (const indices of valueIndices.values()) {
-    let prefixSum = 0;
-    for (let i = 1; i < indices.length; i++) {
-      prefixSum += indices[i] - indices[0];
-    }
-
-    result[indices[0]] = prefixSum;
-
-    for (let i = 1; i < indices.length; i++) {
-      const diff = indices[i] - indices[i - 1];
-      prefixSum += diff * (i - (indices.length - i));
-      result[indices[i]] = prefixSum;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2122-recover-the-original-array.js b/solutions/2122-recover-the-original-array.js
deleted file mode 100644
index 7b6030fb..00000000
--- a/solutions/2122-recover-the-original-array.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 2122. Recover the Original Array
- * https://leetcode.com/problems/recover-the-original-array/
- * Difficulty: Hard
- *
- * Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary
- * positive integer k and created two new 0-indexed integer arrays lower and higher in the
- * following manner:
- * 1. lower[i] = arr[i] - k, for every index i where 0 <= i < n
- * 2. higher[i] = arr[i] + k, for every index i where 0 <= i < n
- *
- * Unfortunately, Alice lost all three arrays. However, she remembers the integers that were
- * present in the arrays lower and higher, but not the array each integer belonged to. Help
- * Alice and recover the original array.
- *
- * Given an array nums consisting of 2n integers, where exactly n of the integers were present
- * in lower and the remaining in higher, return the original array arr. In case the answer is
- * not unique, return any valid array.
- *
- * Note: The test cases are generated such that there exists at least one valid array arr.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var recoverArray = function(nums) {
-  const n = nums.length / 2;
-  nums.sort((a, b) => a - b);
-
-  for (let i = 1; i < 2 * n; i++) {
-    const k = nums[i] - nums[0];
-    if (k <= 0 || k % 2 !== 0) continue;
-
-    const original = [];
-    const used = new Array(2 * n).fill(false);
-    let count = 0;
-
-    for (let left = 0, right = i; right < 2 * n && count < n; right++) {
-      while (left < right && used[left]) left++;
-      if (left >= right) continue;
-
-      if (nums[right] - nums[left] === k) {
-        original.push(nums[left] + k / 2);
-        used[left] = used[right] = true;
-        count++;
-        left++;
-      }
-    }
-
-    if (count === n) return original;
-  }
-
-  return [];
-};
diff --git a/solutions/2124-check-if-all-as-appears-before-all-bs.js b/solutions/2124-check-if-all-as-appears-before-all-bs.js
deleted file mode 100644
index 57f06772..00000000
--- a/solutions/2124-check-if-all-as-appears-before-all-bs.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * 2124. Check if All A's Appears Before All B's
- * https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/
- * Difficulty: Easy
- *
- * Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears
- * before every 'b' in the string. Otherwise, return false.
- */
-
-/**
- * @param {string} s
- * @return {boolean}
- */
-var checkString = function(s) {
-  let seen = false;
-
-  for (const char of s) {
-    if (char === 'b') seen = true;
-    else if (seen) return false;
-  }
-
-  return true;
-};
diff --git a/solutions/2125-number-of-laser-beams-in-a-bank.js b/solutions/2125-number-of-laser-beams-in-a-bank.js
deleted file mode 100644
index 58a8afb7..00000000
--- a/solutions/2125-number-of-laser-beams-in-a-bank.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2125. Number of Laser Beams in a Bank
- * https://leetcode.com/problems/number-of-laser-beams-in-a-bank/
- * Difficulty: Medium
- *
- * Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string
- * array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i]
- * represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1'
- * means the cell has a security device.
- *
- * There is one laser beam between any two security devices if both conditions are met:
- * - The two devices are located on two different rows: r1 and r2, where r1 < r2.
- * - For each row i where r1 < i < r2, there are no security devices in the ith row.
- *
- * Laser beams are independent, i.e., one beam does not interfere nor join with another.
- *
- * Return the total number of laser beams in the bank.
- */
-
-/**
- * @param {string[]} bank
- * @return {number}
- */
-var numberOfBeams = function(bank) {
-  let result = 0;
-  let prevDevices = 0;
-
-  for (const row of bank) {
-    let currentDevices = 0;
-    for (const cell of row) {
-      if (cell === '1') currentDevices++;
-    }
-    if (currentDevices > 0) {
-      result += prevDevices * currentDevices;
-      prevDevices = currentDevices;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2126-destroying-asteroids.js b/solutions/2126-destroying-asteroids.js
deleted file mode 100644
index 8c0ff17e..00000000
--- a/solutions/2126-destroying-asteroids.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2126. Destroying Asteroids
- * https://leetcode.com/problems/destroying-asteroids/
- * Difficulty: Medium
- *
- * You are given an integer mass, which represents the original mass of a planet. You are further
- * given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.
- *
- * You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass
- * of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed
- * and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.
- *
- * Return true if all asteroids can be destroyed. Otherwise, return false.
- */
-
-/**
- * @param {number} mass
- * @param {number[]} asteroids
- * @return {boolean}
- */
-var asteroidsDestroyed = function(mass, asteroids) {
-  asteroids.sort((a, b) => a - b);
-
-  let planetMass = BigInt(mass);
-  for (const asteroid of asteroids) {
-    if (planetMass < BigInt(asteroid)) return false;
-    planetMass += BigInt(asteroid);
-  }
-
-  return true;
-};
diff --git a/solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js b/solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js
deleted file mode 100644
index 296b3bd0..00000000
--- a/solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * 2131. Longest Palindrome by Concatenating Two Letter Words
- * https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
- * Difficulty: Medium
- *
- * You are given an array of strings words. Each element of words consists of two lowercase
- * English letters.
- *
- * Create the longest possible palindrome by selecting some elements from words and concatenating
- * them in any order. Each element can be selected at most once.
- *
- * Return the length of the longest palindrome that you can create. If it is impossible to create
- * any palindrome, return 0.
- *
- * A palindrome is a string that reads the same forward and backward.
- */
-
-/**
- * @param {string[]} words
- * @return {number}
- */
-var longestPalindrome = function(words) {
-  const map = new Map();
-  let length = 0;
-  let hasCenter = false;
-
-  for (const word of words) {
-    map.set(word, (map.get(word) || 0) + 1);
-  }
-
-  for (const word of map.keys()) {
-    const reverse = word[1] + word[0];
-
-    if (word === reverse) {
-      const count = map.get(word);
-      length += Math.floor(count / 2) * 4;
-      if (count % 2 === 1) hasCenter = true;
-    } else if (map.has(reverse)) {
-      const pairs = Math.min(map.get(word), map.get(reverse));
-      length += pairs * 4;
-      map.set(word, 0);
-      map.set(reverse, 0);
-    }
-  }
-
-  return hasCenter ? length + 2 : length;
-};
diff --git a/solutions/2132-stamping-the-grid.js b/solutions/2132-stamping-the-grid.js
deleted file mode 100644
index 3143e1e3..00000000
--- a/solutions/2132-stamping-the-grid.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * 2132. Stamping the Grid
- * https://leetcode.com/problems/stamping-the-grid/
- * Difficulty: Hard
- *
- * You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).
- *
- * You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that
- * they follow the given restrictions and requirements:
- * 1. Cover all the empty cells.
- * 2. Do not cover any of the occupied cells.
- * 3. We can put as many stamps as we want.
- * 4. Stamps can overlap with each other.
- * 5. Stamps are not allowed to be rotated.
- * 6. Stamps must stay completely inside the grid.
- *
- * Return true if it is possible to fit the stamps while following the given restrictions and
- * requirements. Otherwise, return false.
- */
-
-/**
- * @param {number[][]} grid
- * @param {number} stampHeight
- * @param {number} stampWidth
- * @return {boolean}
- */
-var possibleToStamp = function(grid, stampHeight, stampWidth) {
-  const rows = grid.length;
-  const cols = grid[0].length;
-  const prefixSum = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0));
-  const diff = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0));
-
-  for (let i = 0; i < rows; i++) {
-    for (let j = 0; j < cols; j++) {
-      prefixSum[i + 1][j + 1] = prefixSum[i + 1][j] + prefixSum[i][j + 1]
-        - prefixSum[i][j] + grid[i][j];
-    }
-  }
-
-  for (let i = 0; i <= rows - stampHeight; i++) {
-    for (let j = 0; j <= cols - stampWidth; j++) {
-      const x = i + stampHeight;
-      const y = j + stampWidth;
-      if (prefixSum[x][y] - prefixSum[x][j] - prefixSum[i][y] + prefixSum[i][j] === 0) {
-        diff[i][j]++;
-        diff[i][y]--;
-        diff[x][j]--;
-        diff[x][y]++;
-      }
-    }
-  }
-
-  const covered = new Array(rows).fill().map(() => new Array(cols).fill(0));
-  for (let i = 0; i < rows; i++) {
-    for (let j = 0; j < cols; j++) {
-      covered[i][j] = (i > 0 ? covered[i - 1][j] : 0)
-        + (j > 0 ? covered[i][j - 1] : 0)
-        - (i > 0 && j > 0 ? covered[i - 1][j - 1] : 0) + diff[i][j];
-      if (grid[i][j] === 0 && covered[i][j] === 0) return false;
-    }
-  }
-
-  return true;
-};
diff --git a/solutions/2133-check-if-every-row-and-column-contains-all-numbers.js b/solutions/2133-check-if-every-row-and-column-contains-all-numbers.js
deleted file mode 100644
index e8d6990a..00000000
--- a/solutions/2133-check-if-every-row-and-column-contains-all-numbers.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2133. Check if Every Row and Column Contains All Numbers
- * https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/
- * Difficulty: Easy
- *
- * An n x n matrix is valid if every row and every column contains all the integers from 1
- * to n (inclusive).
- *
- * Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise,
- * return false.
- */
-
-/**
- * @param {number[][]} matrix
- * @return {boolean}
- */
-var checkValid = function(matrix) {
-  const n = matrix.length;
-
-  for (let i = 0; i < n; i++) {
-    const rowSet = new Set();
-    const colSet = new Set();
-
-    for (let j = 0; j < n; j++) {
-      rowSet.add(matrix[i][j]);
-      colSet.add(matrix[j][i]);
-    }
-
-    if (rowSet.size !== n || colSet.size !== n) return false;
-  }
-
-  return true;
-};
diff --git a/solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js b/solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js
deleted file mode 100644
index 1105dced..00000000
--- a/solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2134. Minimum Swaps to Group All 1's Together II
- * https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/
- * Difficulty: Medium
- *
- * A swap is defined as taking two distinct positions in an array and swapping the values in them.
- *
- * A circular array is defined as an array where we consider the first element and the last element
- * to be adjacent.
- *
- * Given a binary circular array nums, return the minimum number of swaps required to group all
- * 1's present in the array together at any location.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minSwaps = function(nums) {
-  const onesCount = nums.reduce((sum, num) => sum + num, 0);
-  const n = nums.length;
-  let result = Infinity;
-  let currentZeros = 0;
-
-  for (let i = 0; i < onesCount; i++) {
-    if (nums[i] === 0) currentZeros++;
-  }
-
-  result = currentZeros;
-
-  for (let i = 1; i < n; i++) {
-    if (nums[(i - 1) % n] === 0) currentZeros--;
-    if (nums[(i + onesCount - 1) % n] === 0) currentZeros++;
-    result = Math.min(result, currentZeros);
-  }
-
-  return result;
-};
diff --git a/solutions/2135-count-words-obtained-after-adding-a-letter.js b/solutions/2135-count-words-obtained-after-adding-a-letter.js
deleted file mode 100644
index c7b08943..00000000
--- a/solutions/2135-count-words-obtained-after-adding-a-letter.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * 2135. Count Words Obtained After Adding a Letter
- * https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/
- * Difficulty: Medium
- *
- * You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists
- * of lowercase English letters only.
- *
- * For each string in targetWords, check if it is possible to choose a string from startWords and
- * perform a conversion operation on it to be equal to that from targetWords.
- *
- * The conversion operation is described in the following two steps:
- * 1. Append any lowercase letter that is not present in the string to its end.
- *    - For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but
- *      not 'a'. If 'd' is added, the resulting string will be "abcd".
- * 2. Rearrange the letters of the new string in any arbitrary order.
- *    - For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it
- *      can also be rearranged to "abcd" itself.
- *
- * Return the number of strings in targetWords that can be obtained by performing the operations
- * on any string of startWords.
- *
- * Note that you will only be verifying if the string in targetWords can be obtained from a string
- * in startWords by performing the operations. The strings in startWords do not actually change
- * during this process.
- */
-
-/**
- * @param {string[]} startWords
- * @param {string[]} targetWords
- * @return {number}
- */
-var wordCount = function(startWords, targetWords) {
-  const sortedStartWords = new Set(startWords.map(word => [...word].sort().join('')));
-  let result = 0;
-
-  for (const target of targetWords) {
-    const sortedTarget = [...target].sort().join('');
-    for (let i = 0; i < target.length; i++) {
-      const candidate = sortedTarget.slice(0, i) + sortedTarget.slice(i + 1);
-      if (sortedStartWords.has(candidate)) {
-        result++;
-        break;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2136-earliest-possible-day-of-full-bloom.js b/solutions/2136-earliest-possible-day-of-full-bloom.js
deleted file mode 100644
index e4a07b6c..00000000
--- a/solutions/2136-earliest-possible-day-of-full-bloom.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2136. Earliest Possible Day of Full Bloom
- * https://leetcode.com/problems/earliest-possible-day-of-full-bloom/
- * Difficulty: Hard
- *
- * You have n flower seeds. Every seed must be planted first before it can begin to grow, then
- * bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed
- * integer arrays plantTime and growTime, of length n each:
- * - plantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can
- *   work on planting exactly one seed. You do not have to work on planting the same seed on
- *   consecutive days, but the planting of a seed is not complete until you have worked plantTime[i]
- *   days on planting it in total.
- * - growTime[i] is the number of full days it takes the ith seed to grow after being completely
- *   planted. After the last day of its growth, the flower blooms and stays bloomed forever.
- *
- * From the beginning of day 0, you can plant the seeds in any order.
- *
- * Return the earliest possible day where all seeds are blooming.
- */
-
-/**
- * @param {number[]} plantTime
- * @param {number[]} growTime
- * @return {number}
- */
-var earliestFullBloom = function(plantTime, growTime) {
-  const seeds = plantTime.map((plant, index) => ({ plant, grow: growTime[index] }));
-  seeds.sort((a, b) => b.grow - a.grow);
-
-  let plantingDays = 0;
-  let result = 0;
-
-  for (const { plant, grow } of seeds) {
-    plantingDays += plant;
-    result = Math.max(result, plantingDays + grow);
-  }
-
-  return result;
-};
diff --git a/solutions/2138-divide-a-string-into-groups-of-size-k.js b/solutions/2138-divide-a-string-into-groups-of-size-k.js
deleted file mode 100644
index 24d0197f..00000000
--- a/solutions/2138-divide-a-string-into-groups-of-size-k.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 2138. Divide a String Into Groups of Size k
- * https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/
- * Difficulty: Easy
- *
- * A string s can be partitioned into groups of size k using the following procedure:
- * - The first group consists of the first k characters of the string, the second group consists
- *   of the next k characters of the string, and so on. Each element can be a part of exactly one
- *   group.
- * - For the last group, if the string does not have k characters remaining, a character fill is
- *   used to complete the group.
- *
- * Note that the partition is done so that after removing the fill character from the last group
- * (if it exists) and concatenating all the groups in order, the resultant string should be s.
- *
- * Given the string s, the size of each group k and the character fill, return a string array
- * denoting the composition of every group s has been divided into, using the above procedure.
- */
-
-/**
- * @param {string} s
- * @param {number} k
- * @param {character} fill
- * @return {string[]}
- */
-var divideString = function(s, k, fill) {
-  const paddedString = s + fill.repeat((k - s.length % k) % k);
-  const result = [];
-
-  for (let i = 0; i < paddedString.length; i += k) {
-    result.push(paddedString.slice(i, i + k));
-  }
-
-  return result;
-};
diff --git a/solutions/2139-minimum-moves-to-reach-target-score.js b/solutions/2139-minimum-moves-to-reach-target-score.js
deleted file mode 100644
index a074595f..00000000
--- a/solutions/2139-minimum-moves-to-reach-target-score.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2139. Minimum Moves to Reach Target Score
- * https://leetcode.com/problems/minimum-moves-to-reach-target-score/
- * Difficulty: Medium
- *
- * You are playing a game with integers. You start with the integer 1 and you want to reach
- * the integer target.
- *
- * In one move, you can either:
- * - Increment the current integer by one (i.e., x = x + 1).
- * - Double the current integer (i.e., x = 2 * x).
- *
- * You can use the increment operation any number of times, however, you can only use the double
- * operation at most maxDoubles times.
- *
- * Given the two integers target and maxDoubles, return the minimum number of moves needed to
- * reach target starting with 1.
- */
-
-/**
- * @param {number} target
- * @param {number} maxDoubles
- * @return {number}
- */
-var minMoves = function(target, maxDoubles) {
-  let moves = 0;
-  let current = target;
-
-  while (current > 1 && maxDoubles > 0) {
-    if (current % 2 === 0) {
-      current /= 2;
-      maxDoubles--;
-    } else {
-      current--;
-    }
-    moves++;
-  }
-
-  return moves + (current - 1);
-};
diff --git a/solutions/2140-solving-questions-with-brainpower.js b/solutions/2140-solving-questions-with-brainpower.js
deleted file mode 100644
index 5fc65820..00000000
--- a/solutions/2140-solving-questions-with-brainpower.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2140. Solving Questions With Brainpower
- * https://leetcode.com/problems/solving-questions-with-brainpower/
- * Difficulty: Medium
- *
- * You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri].
- *
- * The array describes the questions of an exam, where you have to process the questions in order
- * (i.e., starting from question 0) and make a decision whether to solve or skip each question.
- * Solving question i will earn you pointsi points but you will be unable to solve each of the next
- * brainpoweri questions. If you skip question i, you get to make the decision on the next question.
- *
- * For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]:
- * - If question 0 is solved, you will earn 3 points but you will be unable to solve questions
- *   1 and 2.
- * - If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you
- *   will be unable to solve questions 2 and 3.
- *
- * Return the maximum points you can earn for the exam.
- */
-
-/**
- * @param {number[][]} questions
- * @return {number}
- */
-var mostPoints = function(questions) {
-  const dp = new Array(questions.length + 1).fill(0);
-
-  for (let i = questions.length - 1; i >= 0; i--) {
-    const [points, brainpower] = questions[i];
-    const nextAvailable = Math.min(questions.length, i + brainpower + 1);
-    dp[i] = Math.max(points + dp[nextAvailable], dp[i + 1]);
-  }
-
-  return dp[0];
-};
diff --git a/solutions/2141-maximum-running-time-of-n-computers.js b/solutions/2141-maximum-running-time-of-n-computers.js
deleted file mode 100644
index b5f7b090..00000000
--- a/solutions/2141-maximum-running-time-of-n-computers.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2141. Maximum Running Time of N Computers
- * https://leetcode.com/problems/maximum-running-time-of-n-computers/
- * Difficulty: Hard
- *
- * You have n computers. You are given the integer n and a 0-indexed integer array batteries
- * where the ith battery can run a computer for batteries[i] minutes. You are interested in
- * running all n computers simultaneously using the given batteries.
- *
- * Initially, you can insert at most one battery into each computer. After that and at any
- * integer time moment, you can remove a battery from a computer and insert another battery
- * any number of times. The inserted battery can be a totally new battery or a battery from
- * another computer. You may assume that the removing and inserting processes take no time.
- *
- * Note that the batteries cannot be recharged.
- *
- * Return the maximum number of minutes you can run all the n computers simultaneously.
- */
-
-/**
- * @param {number} n
- * @param {number[]} batteries
- * @return {number}
- */
-var maxRunTime = function(n, batteries) {
-  let left = 1;
-  let right = Math.floor(batteries.reduce((sum, battery) => sum + battery, 0) / n);
-
-  while (left < right) {
-    const mid = Math.floor((left + right + 1) / 2);
-    const total = batteries.reduce((sum, battery) => sum + Math.min(battery, mid), 0);
-
-    if (total >= n * mid) {
-      left = mid;
-    } else {
-      right = mid - 1;
-    }
-  }
-
-  return left;
-};
diff --git a/solutions/2144-minimum-cost-of-buying-candies-with-discount.js b/solutions/2144-minimum-cost-of-buying-candies-with-discount.js
deleted file mode 100644
index 86eca1e2..00000000
--- a/solutions/2144-minimum-cost-of-buying-candies-with-discount.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2144. Minimum Cost of Buying Candies With Discount
- * https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/
- * Difficulty: Easy
- *
- * A shop is selling candies at a discount. For every two candies sold, the shop gives a
- * third candy for free.
- *
- * The customer can choose any candy to take away for free as long as the cost of the
- * chosen candy is less than or equal to the minimum cost of the two candies bought.
- *
- * - For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys
- *   candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the
- *   candy with cost 4.
- *
- * Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy,
- * return the minimum cost of buying all the candies.
- */
-
-/**
- * @param {number[]} cost
- * @return {number}
- */
-var minimumCost = function(cost) {
-  cost.sort((a, b) => b - a);
-  let result = 0;
-
-  for (let i = 0; i < cost.length; i += 3) {
-    result += cost[i] + (cost[i + 1] || 0);
-  }
-
-  return result;
-};
diff --git a/solutions/2145-count-the-hidden-sequences.js b/solutions/2145-count-the-hidden-sequences.js
deleted file mode 100644
index 48406074..00000000
--- a/solutions/2145-count-the-hidden-sequences.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2145. Count the Hidden Sequences
- * https://leetcode.com/problems/count-the-hidden-sequences/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array of n integers differences, which describes the differences
- * between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally,
- * call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].
- *
- * You are further given two integers lower and upper that describe the inclusive range of values
- * [lower, upper] that the hidden sequence can contain.
- *
- * - For example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a
- *   sequence of length 4 whose elements are in between 1 and 6 (inclusive).
- *   - [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.
- *   - [5, 6, 3, 7] is not possible since it contains an element greater than 6.
- *   - [1, 2, 3, 4] is not possible since the differences are not correct.
- *
- * Return the number of possible hidden sequences there are. If there are no possible sequences,
- * return 0.
- */
-
-/**
- * @param {number[]} differences
- * @param {number} lower
- * @param {number} upper
- * @return {number}
- */
-var numberOfArrays = function(differences, lower, upper) {
-  let minValue = 0;
-  let maxValue = 0;
-  let current = 0;
-
-  for (const diff of differences) {
-    current += diff;
-    minValue = Math.min(minValue, current);
-    maxValue = Math.max(maxValue, current);
-  }
-
-  const range = upper - lower;
-  const validRange = range - (maxValue - minValue);
-
-  return validRange >= 0 ? validRange + 1 : 0;
-};
diff --git a/solutions/2147-number-of-ways-to-divide-a-long-corridor.js b/solutions/2147-number-of-ways-to-divide-a-long-corridor.js
deleted file mode 100644
index e504b765..00000000
--- a/solutions/2147-number-of-ways-to-divide-a-long-corridor.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * 2147. Number of Ways to Divide a Long Corridor
- * https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/
- * Difficulty: Hard
- *
- * Along a long library corridor, there is a line of seats and decorative plants. You are given
- * a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S'
- * represents a seat and each 'P' represents a plant.
- *
- * One room divider has already been installed to the left of index 0, and another to the right
- * of index n - 1. Additional room dividers can be installed. For each position between indices
- * i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.
- *
- * Divide the corridor into non-overlapping sections, where each section has exactly two seats
- * with any number of plants. There may be multiple ways to perform the division. Two ways are
- * different if there is a position with a room divider installed in the first way but not in
- * the second way.
- *
- * Return the number of ways to divide the corridor. Since the answer may be very large, return
- * it modulo 109 + 7. If there is no way, return 0.
- */
-
-/**
- * @param {string} corridor
- * @return {number}
- */
-var numberOfWays = function(corridor) {
-  const MOD = 1e9 + 7;
-  let seatCount = 0;
-  let result = 1;
-  let lastPairEnd = -1;
-
-  for (let i = 0; i < corridor.length; i++) {
-    if (corridor[i] === 'S') {
-      seatCount++;
-    }
-  }
-  if (seatCount === 0 || seatCount % 2 !== 0) {
-    return 0;
-  }
-
-  seatCount = 0;
-
-  for (let i = 0; i < corridor.length; i++) {
-    if (corridor[i] === 'S') {
-      seatCount++;
-
-      if (seatCount % 2 === 0) {
-        lastPairEnd = i;
-      } else if (seatCount > 1) {
-        const plantsCount = i - lastPairEnd - 1;
-        result = (result * (plantsCount + 1)) % MOD;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js b/solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js
deleted file mode 100644
index 194880af..00000000
--- a/solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * 2148. Count Elements With Strictly Smaller and Greater Elements
- * https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/
- * Difficulty: Easy
- *
- * Given an integer array nums, return the number of elements that have both a strictly
- * smaller and a strictly greater element appear in nums.
- */
-
-/**
-* @param {number[]} nums
-* @return {number}
-*/
-var countElements = function(nums) {
-  let result = 0;
-
-  if (nums.length <= 2) return 0;
-  for (const num of nums) {
-    if (num > Math.min(...nums) && num < Math.max(...nums)) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2149-rearrange-array-elements-by-sign.js b/solutions/2149-rearrange-array-elements-by-sign.js
deleted file mode 100644
index 7979e5ef..00000000
--- a/solutions/2149-rearrange-array-elements-by-sign.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2149. Rearrange Array Elements by Sign
- * https://leetcode.com/problems/rearrange-array-elements-by-sign/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums of even length consisting of an equal number
- * of positive and negative integers.
- *
- * You should return the array of nums such that the the array follows the given conditions:
- * 1. Every consecutive pair of integers have opposite signs.
- * 2. For all integers with the same sign, the order in which they were present in nums is
- *    preserved.
- * 3. The rearranged array begins with a positive integer.
- *
- * Return the modified array after rearranging the elements to satisfy the aforementioned
- * conditions.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var rearrangeArray = function(nums) {
-  const positives = nums.filter(num => num > 0);
-  const negatives = nums.filter(num => num < 0);
-  const result = [];
-
-  for (let i = 0; i < positives.length; i++) {
-    result.push(positives[i], negatives[i]);
-  }
-
-  return result;
-};
diff --git a/solutions/2150-find-all-lonely-numbers-in-the-array.js b/solutions/2150-find-all-lonely-numbers-in-the-array.js
deleted file mode 100644
index 676badc6..00000000
--- a/solutions/2150-find-all-lonely-numbers-in-the-array.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2150. Find All Lonely Numbers in the Array
- * https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/
- * Difficulty: Medium
- *
- * You are given an integer array nums. A number x is lonely when it appears only once, and
- * no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
- *
- * Return all lonely numbers in nums. You may return the answer in any order.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var findLonely = function(nums) {
-  const map = new Map();
-
-  for (const num of nums) {
-    map.set(num, (map.get(num) || 0) + 1);
-  }
-
-  const result = [];
-  for (const [num, count] of map) {
-    if (count === 1 && !map.has(num - 1) && !map.has(num + 1)) {
-      result.push(num);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2151-maximum-good-people-based-on-statements.js b/solutions/2151-maximum-good-people-based-on-statements.js
deleted file mode 100644
index 9a5d71cd..00000000
--- a/solutions/2151-maximum-good-people-based-on-statements.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * 2151. Maximum Good People Based on Statements
- * https://leetcode.com/problems/maximum-good-people-based-on-statements/
- * Difficulty: Hard
- *
- * There are two types of persons:
- * - The good person: The person who always tells the truth.
- * - The bad person: The person who might tell the truth and might lie.
- *
- * You are given a 0-indexed 2D integer array statements of size n x n that represents the
- * statements made by n people about each other. More specifically, statements[i][j] could
- * be one of the following:
- * - 0 which represents a statement made by person i that person j is a bad person.
- * - 1 which represents a statement made by person i that person j is a good person.
- * - 2 represents that no statement is made by person i about person j.
- *
- * Additionally, no person ever makes a statement about themselves. Formally, we have that
- * statements[i][i] = 2 for all 0 <= i < n.
- *
- * Return the maximum number of people who can be good based on the statements made by the
- * n people.
- */
-
-/**
- * @param {number[][]} statements
- * @return {number}
- */
-var maximumGood = function(statements) {
-  const n = statements.length;
-  let result = 0;
-
-  backtrack(0, new Array(n).fill(false), 0);
-  return result;
-
-  function isValid(goodPeople) {
-    for (let i = 0; i < n; i++) {
-      if (!goodPeople[i]) continue;
-      for (let j = 0; j < n; j++) {
-        if (statements[i][j] === 0 && goodPeople[j]) return false;
-        if (statements[i][j] === 1 && !goodPeople[j]) return false;
-      }
-    }
-    return true;
-  }
-
-  function backtrack(index, goodPeople, goodCount) {
-    if (index === n) {
-      if (isValid(goodPeople)) {
-        result = Math.max(result, goodCount);
-      }
-      return;
-    }
-
-    goodPeople[index] = true;
-    backtrack(index + 1, goodPeople, goodCount + 1);
-    goodPeople[index] = false;
-    backtrack(index + 1, goodPeople, goodCount);
-  }
-};
diff --git a/solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js b/solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js
deleted file mode 100644
index 66db5b2f..00000000
--- a/solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * 2155. All Divisions With the Highest Score of a Binary Array
- * https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/
- * Difficulty: Medium
- *
- * You are given a 0-indexed binary array nums of length n. nums can be divided at index i
- * (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:
- * - numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright
- *   has all the elements of nums between index i and n - 1 (inclusive).
- * - If i == 0, numsleft is empty, while numsright has all the elements of nums.
- * - If i == n, numsleft has all the elements of nums, while numsright is empty.
- *
- * The division score of an index i is the sum of the number of 0's in numsleft and the number
- * of 1's in numsright.
- *
- * Return all distinct indices that have the highest possible division score. You may return
- * the answer in any order.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var maxScoreIndices = function(nums) {
-  const result = [0];
-  let leftZeros = 0;
-  let rightOnes = nums.reduce((sum, num) => sum + num, 0);
-  let maxScore = rightOnes;
-
-  for (let i = 0; i < nums.length; i++) {
-    leftZeros += nums[i] === 0 ? 1 : 0;
-    rightOnes -= nums[i];
-    const score = leftZeros + rightOnes;
-
-    if (score > maxScore) {
-      maxScore = score;
-      result.length = 0;
-      result.push(i + 1);
-    } else if (score === maxScore) {
-      result.push(i + 1);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2156-find-substring-with-given-hash-value.js b/solutions/2156-find-substring-with-given-hash-value.js
deleted file mode 100644
index a43f4a10..00000000
--- a/solutions/2156-find-substring-with-given-hash-value.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * 2156. Find Substring With Given Hash Value
- * https://leetcode.com/problems/find-substring-with-given-hash-value/
- * Difficulty: Hard
- *
- * The hash of a 0-indexed string s of length k, given integers p and m, is computed using
- * the following function:
- * - hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.
- *
- * Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.
- *
- * You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the
- * first substring of s of length k such that hash(sub, power, modulo) == hashValue.
- *
- * The test cases will be generated such that an answer always exists.
- *
- * A substring is a contiguous non-empty sequence of characters within a string.
- */
-
-/**
-* @param {string} s
-* @param {number} power
-* @param {number} modulo
-* @param {number} k
-* @param {number} hashValue
-* @return {string}
-*/
-var subStrHash = function(s, power, modulo, k, hashValue) {
-  power = BigInt(power);
-  modulo = BigInt(modulo);
-  hashValue = BigInt(hashValue);
-
-  const powers = new Array(k);
-  powers[0] = 1n;
-  for (let i = 1; i < k; i++) {
-    powers[i] = (powers[i - 1] * power) % modulo;
-  }
-
-  for (let start = 0; start <= s.length - k; start++) {
-    let hash = 0n;
-    for (let i = 0; i < k; i++) {
-      const charVal = BigInt(s.charCodeAt(start + i) - 'a'.charCodeAt(0) + 1);
-      hash = (hash + charVal * powers[i]) % modulo;
-    }
-    if (hash === hashValue) {
-      return s.substring(start, start + k);
-    }
-  }
-
-  return '';
-};
diff --git a/solutions/2157-groups-of-strings.js b/solutions/2157-groups-of-strings.js
deleted file mode 100644
index 8af51c12..00000000
--- a/solutions/2157-groups-of-strings.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/**
- * 2157. Groups of Strings
- * https://leetcode.com/problems/groups-of-strings/
- * Difficulty: Hard
- *
- * You are given a 0-indexed array of strings words. Each string consists of lowercase English
- * letters only. No letter occurs more than once in any string of words.
- *
- * Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained
- * from the set of letters of s1 by any one of the following operations:
- * - Adding exactly one letter to the set of the letters of s1.
- * - Deleting exactly one letter from the set of the letters of s1.
- * - Replacing exactly one letter from the set of the letters of s1 with any letter, including
- *   itself.
- *
- * The array words can be divided into one or more non-intersecting groups. A string belongs
- * to a group if any one of the following is true:
- * - It is connected to at least one other string of the group.
- * - It is the only string present in the group.
- *
- * Note that the strings in words should be grouped in such a manner that a string belonging
- * to a group cannot be connected to a string present in any other group. It can be proved
- * that such an arrangement is always unique.
- *
- * Return an array ans of size 2 where:
- * - ans[0] is the maximum number of groups words can be divided into, and
- * - ans[1] is the size of the largest group.
- */
-
-/**
- * @param {string[]} words
- * @return {number[]}
- */
-var groupStrings = function(words) {
-  const n = words.length;
-  const masks = words.map(word => {
-    let mask = 0;
-    for (let i = 0; i < word.length; i++) {
-      mask |= (1 << (word.charCodeAt(i) - 'a'.charCodeAt(0)));
-    }
-    return mask;
-  });
-  const uf = new UnionFind(n);
-  const maskToIndex = new Map();
-  for (let i = 0; i < n; i++) {
-    if (maskToIndex.has(masks[i])) {
-      uf.union(maskToIndex.get(masks[i]), i);
-    } else {
-      maskToIndex.set(masks[i], i);
-    }
-  }
-  const processed = new Set();
-
-  for (let i = 0; i < n; i++) {
-    const mask = masks[i];
-    if (processed.has(mask)) continue;
-    processed.add(mask);
-
-    for (let bit = 0; bit < 26; bit++) {
-      if ((mask & (1 << bit)) === 0) {
-        const newMask = mask | (1 << bit);
-        if (maskToIndex.has(newMask)) {
-          uf.union(i, maskToIndex.get(newMask));
-        }
-      }
-    }
-
-    for (let bit = 0; bit < 26; bit++) {
-      if ((mask & (1 << bit)) !== 0) {
-        const newMask = mask & ~(1 << bit);
-        if (maskToIndex.has(newMask)) {
-          uf.union(i, maskToIndex.get(newMask));
-        }
-      }
-    }
-
-    for (let remove = 0; remove < 26; remove++) {
-      if ((mask & (1 << remove)) !== 0) {
-        for (let add = 0; add < 26; add++) {
-          if ((mask & (1 << add)) === 0) {
-            const newMask = (mask & ~(1 << remove)) | (1 << add);
-            if (maskToIndex.has(newMask)) {
-              uf.union(i, maskToIndex.get(newMask));
-            }
-          }
-        }
-      }
-    }
-  }
-
-  return [uf.count, uf.getMaxSize()];
-};
-
-class UnionFind {
-  constructor(n) {
-    this.parent = Array(n).fill().map((_, i) => i);
-    this.rank = Array(n).fill(0);
-    this.count = n;
-    this.sizes = Array(n).fill(1);
-  }
-
-  find(x) {
-    if (this.parent[x] !== x) {
-      this.parent[x] = this.find(this.parent[x]);
-    }
-    return this.parent[x];
-  }
-
-  union(x, y) {
-    const rootX = this.find(x);
-    const rootY = this.find(y);
-
-    if (rootX === rootY) return false;
-
-    if (this.rank[rootX] < this.rank[rootY]) {
-      this.parent[rootX] = rootY;
-      this.sizes[rootY] += this.sizes[rootX];
-    } else if (this.rank[rootX] > this.rank[rootY]) {
-      this.parent[rootY] = rootX;
-      this.sizes[rootX] += this.sizes[rootY];
-    } else {
-      this.parent[rootY] = rootX;
-      this.rank[rootX]++;
-      this.sizes[rootX] += this.sizes[rootY];
-    }
-
-    this.count--;
-    return true;
-  }
-
-  getMaxSize() {
-    let maxSize = 0;
-    for (let i = 0; i < this.parent.length; i++) {
-      if (this.parent[i] === i) {
-        maxSize = Math.max(maxSize, this.sizes[i]);
-      }
-    }
-    return maxSize;
-  }
-}
diff --git a/solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js b/solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js
deleted file mode 100644
index fa3b9b86..00000000
--- a/solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * 2160. Minimum Sum of Four Digit Number After Splitting Digits
- * https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/
- * Difficulty: Easy
- *
- * You are given a positive integer num consisting of exactly four digits. Split num into two
- * new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in
- * new1 and new2, and all the digits found in num must be used.
- * - For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3.
- *   Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
- *
- * Return the minimum possible sum of new1 and new2.
- */
-
-/**
- * @param {number} num
- * @return {number}
- */
-var minimumSum = function(num) {
-  const digits = String(num).split('').map(Number).sort((a, b) => a - b);
-  return (digits[0] * 10 + digits[2]) + (digits[1] * 10 + digits[3]);
-};
diff --git a/solutions/2162-minimum-cost-to-set-cooking-time.js b/solutions/2162-minimum-cost-to-set-cooking-time.js
deleted file mode 100644
index e1c51c1b..00000000
--- a/solutions/2162-minimum-cost-to-set-cooking-time.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * 2162. Minimum Cost to Set Cooking Time
- * https://leetcode.com/problems/minimum-cost-to-set-cooking-time/
- * Difficulty: Medium
- *
- * A generic microwave supports cooking times for:
- * - at least 1 second.
- * - at most 99 minutes and 99 seconds.
- *
- * To set the cooking time, you push at most four digits. The microwave normalizes what you push
- * as four digits by prepending zeroes. It interprets the first two digits as the minutes and
- * the last two digits as the seconds. It then adds them up as the cooking time. For example,
- * - You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and
- *   54 seconds.
- * - You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds.
- * - You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds.
- * - You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds.
- *
- * You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger
- * is on the digit startAt. Moving the finger above any specific digit costs moveCost units of
- * fatigue. Pushing the digit below the finger once costs pushCost units of fatigue.
- *
- * There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are
- * interested in the way with the minimum cost.
- *
- * Return the minimum cost to set targetSeconds seconds of cooking time.
- *
- * Remember that one minute consists of 60 seconds.
- */
-
-/**
- * @param {number} startAt
- * @param {number} moveCost
- * @param {number} pushCost
- * @param {number} targetSeconds
- * @return {number}
- */
-var minCostSetTime = function(startAt, moveCost, pushCost, targetSeconds) {
-  const minutes1 = Math.floor(targetSeconds / 60);
-  const seconds1 = targetSeconds % 60;
-  let result = Infinity;
-
-  if (minutes1 <= 99) {
-    const digits1 = getDigits(minutes1, seconds1);
-    result = Math.min(result, calculateCost(digits1));
-  }
-
-  const minutes2 = Math.floor(targetSeconds / 60) - 1;
-  const seconds2 = targetSeconds % 60 + 60;
-  if (minutes2 >= 0 && minutes2 <= 99 && seconds2 <= 99) {
-    const digits2 = getDigits(minutes2, seconds2);
-    result = Math.min(result, calculateCost(digits2));
-  }
-
-  return result;
-
-  function calculateCost(digits) {
-    let totalCost = 0;
-    let currentDigit = startAt;
-
-    for (const digit of digits) {
-      if (digit !== currentDigit) {
-        totalCost += moveCost;
-        currentDigit = digit;
-      }
-      totalCost += pushCost;
-    }
-
-    return totalCost;
-  }
-
-  function getDigits(minutes, seconds) {
-    const result = [];
-
-    if (minutes > 0) {
-      if (minutes >= 10) {
-        result.push(Math.floor(minutes / 10));
-      }
-      result.push(minutes % 10);
-    }
-
-    if (minutes > 0 || seconds >= 10) {
-      result.push(Math.floor(seconds / 10));
-    }
-
-    result.push(seconds % 10);
-
-    return result;
-  }
-};
diff --git a/solutions/2164-sort-even-and-odd-indices-independently.js b/solutions/2164-sort-even-and-odd-indices-independently.js
deleted file mode 100644
index ed9322c6..00000000
--- a/solutions/2164-sort-even-and-odd-indices-independently.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * 2164. Sort Even and Odd Indices Independently
- * https://leetcode.com/problems/sort-even-and-odd-indices-independently/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums. Rearrange the values of nums according to the
- * following rules:
- * 1. Sort the values at odd indices of nums in non-increasing order.
- *    - For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values
- *      at odd indices 1 and 3 are sorted in non-increasing order.
- * 2. Sort the values at even indices of nums in non-decreasing order.
- *    - For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values
- *      at even indices 0 and 2 are sorted in non-decreasing order.
- *
- * Return the array formed after rearranging the values of nums.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var sortEvenOdd = function(nums) {
-  const evens = [];
-  const odds = [];
-
-  for (let i = 0; i < nums.length; i++) {
-    if (i % 2 === 0) {
-      evens.push(nums[i]);
-    } else {
-      odds.push(nums[i]);
-    }
-  }
-
-  evens.sort((a, b) => a - b);
-  odds.sort((a, b) => b - a);
-
-  const result = [];
-  let evenIndex = 0;
-  let oddIndex = 0;
-
-  for (let i = 0; i < nums.length; i++) {
-    if (i % 2 === 0) {
-      result.push(evens[evenIndex++]);
-    } else {
-      result.push(odds[oddIndex++]);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2165-smallest-value-of-the-rearranged-number.js b/solutions/2165-smallest-value-of-the-rearranged-number.js
deleted file mode 100644
index c3226062..00000000
--- a/solutions/2165-smallest-value-of-the-rearranged-number.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 2165. Smallest Value of the Rearranged Number
- * https://leetcode.com/problems/smallest-value-of-the-rearranged-number/
- * Difficulty: Medium
- *
- * You are given an integer num. Rearrange the digits of num such that its value is minimized
- * and it does not contain any leading zeros.
- *
- * Return the rearranged number with minimal value.
- *
- * Note that the sign of the number does not change after rearranging the digits.
- */
-
-/**
- * @param {number} num
- * @return {number}
- */
-var smallestNumber = function(num) {
-  const isNegative = num < 0;
-  const digits = Math.abs(num).toString().split('').map(Number);
-
-  if (isNegative) {
-    digits.sort((a, b) => b - a);
-    return -parseInt(digits.join(''), 10);
-  }
-
-  digits.sort((a, b) => a - b);
-  const firstNonZero = digits.findIndex(d => d !== 0);
-
-  if (firstNonZero === -1) return 0;
-
-  [digits[0], digits[firstNonZero]] = [digits[firstNonZero], digits[0]];
-  return parseInt(digits.join(''), 10);
-};
diff --git a/solutions/2166-design-bitset.js b/solutions/2166-design-bitset.js
deleted file mode 100644
index 155fe39b..00000000
--- a/solutions/2166-design-bitset.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * 2166. Design Bitset
- * https://leetcode.com/problems/design-bitset/
- * Difficulty: Medium
- *
- * A Bitset is a data structure that compactly stores bits.
- *
- * Implement the Bitset class:
- * - Bitset(int size) Initializes the Bitset with size bits, all of which are 0.
- * - void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was
- *   already 1, no change occurs.
- * - void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value
- *   was already 0, no change occurs.
- * - void flip() Flips the values of each bit in the Bitset. In other words, all bits with
- *   value 0 will now have value 1 and vice versa.
- * - boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it
- *   satisfies the condition, false otherwise.
- * - boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns
- *   true if it satisfies the condition, false otherwise.
- * - int count() Returns the total number of bits in the Bitset which have value 1.
- * - String toString() Returns the current composition of the Bitset. Note that in the
- *   resultant string, the character at the ith index should coincide with the value at
- *   the ith bit of the Bitset.
- */
-
-/**
- * @param {number} size
- */
-var Bitset = function(size) {
-  this.bits = new Uint8Array(size);
-  this.ones = 0;
-  this.flipped = false;
-};
-
-/**
- * @param {number} idx
- * @return {void}
- */
-Bitset.prototype.fix = function(idx) {
-  if (this.flipped) {
-    if (this.bits[idx] === 1) {
-      this.bits[idx] = 0;
-      this.ones++;
-    }
-  } else {
-    if (this.bits[idx] === 0) {
-      this.bits[idx] = 1;
-      this.ones++;
-    }
-  }
-};
-
-/**
- * @param {number} idx
- * @return {void}
- */
-Bitset.prototype.unfix = function(idx) {
-  if (this.flipped) {
-    if (this.bits[idx] === 0) {
-      this.bits[idx] = 1;
-      this.ones--;
-    }
-  } else {
-    if (this.bits[idx] === 1) {
-      this.bits[idx] = 0;
-      this.ones--;
-    }
-  }
-};
-
-/**
- * @return {void}
- */
-Bitset.prototype.flip = function() {
-  this.flipped = !this.flipped;
-  this.ones = this.bits.length - this.ones;
-};
-
-/**
- * @return {boolean}
- */
-Bitset.prototype.all = function() {
-  return this.ones === this.bits.length;
-};
-
-/**
- * @return {boolean}
- */
-Bitset.prototype.one = function() {
-  return this.ones > 0;
-};
-
-/**
- * @return {number}
- */
-Bitset.prototype.count = function() {
-  return this.ones;
-};
-
-/**
- * @return {string}
- */
-Bitset.prototype.toString = function() {
-  let result = '';
-  for (let i = 0; i < this.bits.length; i++) {
-    result += this.flipped ? 1 - this.bits[i] : this.bits[i];
-  }
-  return result;
-};
diff --git a/solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js b/solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js
deleted file mode 100644
index 4877a0de..00000000
--- a/solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2167. Minimum Time to Remove All Cars Containing Illegal Goods
- * https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/
- * Difficulty: Hard
- *
- * You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0'
- * denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car
- * does contain illegal goods.
- *
- * As the train conductor, you would like to get rid of all the cars containing illegal goods.
- * You can do any of the following three operations any number of times:
- * 1. Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time.
- * 2. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit
- *    of time.
- * 3. Remove a train car from anywhere in the sequence which takes 2 units of time.
- *
- * Return the minimum time to remove all the cars containing illegal goods.
- *
- * Note that an empty sequence of cars is considered to have no cars containing illegal goods.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var minimumTime = function(s) {
-  let leftCost = 0;
-  let result = s.length;
-
-  for (let i = 0; i < s.length; i++) {
-    leftCost = Math.min(leftCost + (s[i] === '1' ? 2 : 0), i + 1);
-    const rightCost = s.length - i - 1;
-    result = Math.min(result, leftCost + rightCost);
-  }
-
-  return result;
-};
diff --git a/solutions/2169-count-operations-to-obtain-zero.js b/solutions/2169-count-operations-to-obtain-zero.js
deleted file mode 100644
index 428bd42a..00000000
--- a/solutions/2169-count-operations-to-obtain-zero.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 2169. Count Operations to Obtain Zero
- * https://leetcode.com/problems/count-operations-to-obtain-zero/
- * Difficulty: Easy
- *
- * You are given two non-negative integers num1 and num2.
- *
- * In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1
- * from num2.
- * - For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and
- *   num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.
- *
- * Return the number of operations required to make either num1 = 0 or num2 = 0.
- */
-
-/**
- * @param {number} num1
- * @param {number} num2
- * @return {number}
- */
-var countOperations = function(num1, num2) {
-  let operations = 0;
-
-  while (num1 !== 0 && num2 !== 0) {
-    if (num1 >= num2) {
-      num1 -= num2;
-    } else {
-      num2 -= num1;
-    }
-    operations++;
-  }
-
-  return operations;
-};
diff --git a/solutions/2170-minimum-operations-to-make-the-array-alternating.js b/solutions/2170-minimum-operations-to-make-the-array-alternating.js
deleted file mode 100644
index 770b6d62..00000000
--- a/solutions/2170-minimum-operations-to-make-the-array-alternating.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * 2170. Minimum Operations to Make the Array Alternating
- * https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array nums consisting of n positive integers.
- *
- * The array nums is called alternating if:
- * - nums[i - 2] == nums[i], where 2 <= i <= n - 1.
- * - nums[i - 1] != nums[i], where 1 <= i <= n - 1.
- *
- * In one operation, you can choose an index i and change nums[i] into any positive integer.
- *
- * Return the minimum number of operations required to make the array alternating.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minimumOperations = function(nums) {
-  const evenFreq = new Map();
-  const oddFreq = new Map();
-
-  if (nums.length <= 1) return 0;
-  for (let i = 0; i < nums.length; i++) {
-    if (i % 2 === 0) {
-      evenFreq.set(nums[i], (evenFreq.get(nums[i]) || 0) + 1);
-    } else {
-      oddFreq.set(nums[i], (oddFreq.get(nums[i]) || 0) + 1);
-    }
-  }
-
-  const evenTop = [...evenFreq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 2);
-  const oddTop = [...oddFreq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 2);
-  const evenTotal = Math.ceil(nums.length / 2);
-  const oddTotal = Math.floor(nums.length / 2);
-  let minOps = nums.length;
-
-  for (const [evenNum, evenCount] of evenTop.length ? evenTop : [[0, 0]]) {
-    for (const [oddNum, oddCount] of oddTop.length ? oddTop : [[0, 0]]) {
-      if (evenNum !== oddNum || evenNum === 0) {
-        minOps = Math.min(minOps, (evenTotal - evenCount) + (oddTotal - oddCount));
-      }
-    }
-  }
-
-  return minOps === nums.length ? Math.min(evenTotal, oddTotal) : minOps;
-};
diff --git a/solutions/2171-removing-minimum-number-of-magic-beans.js b/solutions/2171-removing-minimum-number-of-magic-beans.js
deleted file mode 100644
index 23fd2236..00000000
--- a/solutions/2171-removing-minimum-number-of-magic-beans.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2171. Removing Minimum Number of Magic Beans
- * https://leetcode.com/problems/removing-minimum-number-of-magic-beans/
- * Difficulty: Medium
- *
- * You are given an array of positive integers beans, where each integer represents the number
- * of magic beans found in a particular magic bag.
- *
- * Remove any number of beans (possibly none) from each bag such that the number of beans in
- * each remaining non-empty bag (still containing at least one bean) is equal. Once a bean
- * has been removed from a bag, you are not allowed to return it to any of the bags.
- *
- * Return the minimum number of magic beans that you have to remove.
- */
-
-/**
- * @param {number[]} beans
- * @return {number}
- */
-var minimumRemoval = function(beans) {
-  const sortedBeans = beans.sort((a, b) => a - b);
-  const totalBeans = sortedBeans.reduce((sum, bean) => sum + bean, 0);
-  let result = totalBeans;
-  let remaining = totalBeans;
-
-  for (let i = 0; i < sortedBeans.length; i++) {
-    remaining -= sortedBeans[i];
-    const equalBags = sortedBeans.length - i;
-    result = Math.min(result, totalBeans - sortedBeans[i] * equalBags);
-  }
-
-  return result;
-};
diff --git a/solutions/2172-maximum-and-sum-of-array.js b/solutions/2172-maximum-and-sum-of-array.js
deleted file mode 100644
index 6c9020d6..00000000
--- a/solutions/2172-maximum-and-sum-of-array.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2172. Maximum AND Sum of Array
- * https://leetcode.com/problems/maximum-and-sum-of-array/
- * Difficulty: Hard
- *
- * You are given an integer array nums of length n and an integer numSlots such that
- * 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots.
- *
- * You have to place all n integers into the slots such that each slot contains at most
- * two numbers. The AND sum of a given placement is the sum of the bitwise AND of every
- * number with its respective slot number.
- * - For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into
- *   slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4.
- *
- * Return the maximum possible AND sum of nums given numSlots slots.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} numSlots
- * @return {number}
- */
-var maximumANDSum = function(nums, numSlots) {
-  const map = new Map();
-
-  return dp(0, new Array(numSlots).fill(0));
-
-  function dp(index, slots) {
-    if (index >= nums.length) return 0;
-
-    const key = `${index},${slots.join(',')}`;
-    if (map.has(key)) return map.get(key);
-
-    let result = 0;
-    for (let i = 0; i < numSlots; i++) {
-      if (slots[i] < 2) {
-        slots[i]++;
-        result = Math.max(result, (nums[index] & (i + 1)) + dp(index + 1, slots));
-        slots[i]--;
-      }
-    }
-
-    map.set(key, result);
-    return result;
-  }
-};
diff --git a/solutions/2176-count-equal-and-divisible-pairs-in-an-array.js b/solutions/2176-count-equal-and-divisible-pairs-in-an-array.js
deleted file mode 100644
index a0adb051..00000000
--- a/solutions/2176-count-equal-and-divisible-pairs-in-an-array.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 2176. Count Equal and Divisible Pairs in an Array
- * https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/
- * Difficulty: Easy
- *
- * Given a 0-indexed integer array nums of length n and an integer k, return the number of
- * pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var countPairs = function(nums, k) {
-  const frequencyMap = new Map();
-  let result = 0;
-
-  nums.forEach((num, index) => {
-    if (frequencyMap.has(num)) {
-      const values = frequencyMap.get(num);
-      values.forEach(prevIndex => {
-        if ((prevIndex * index) % k === 0) {
-          result++;
-        }
-      });
-      values.push(index);
-    } else {
-      frequencyMap.set(num, [index]);
-    }
-  });
-
-  return result;
-};
diff --git a/solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js b/solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js
deleted file mode 100644
index f77b1221..00000000
--- a/solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * 2177. Find Three Consecutive Integers That Sum to a Given Number
- * https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/
- * Difficulty: Medium
- *
- * Given an integer num, return three consecutive integers (as a sorted array) that sum to num.
- * If num cannot be expressed as the sum of three consecutive integers, return an empty array.
- */
-
-/**
- * @param {number} num
- * @return {number[]}
- */
-var sumOfThree = function(num) {
-  if (num % 3 !== 0) return [];
-
-  const middle = num / 3;
-  return [middle - 1, middle, middle + 1];
-};
diff --git a/solutions/2178-maximum-split-of-positive-even-integers.js b/solutions/2178-maximum-split-of-positive-even-integers.js
deleted file mode 100644
index 602b2ab7..00000000
--- a/solutions/2178-maximum-split-of-positive-even-integers.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2178. Maximum Split of Positive Even Integers
- * https://leetcode.com/problems/maximum-split-of-positive-even-integers/
- * Difficulty: Medium
- *
- * You are given an integer finalSum. Split it into a sum of a maximum number of unique
- * positive even integers.
- * - For example, given finalSum = 12, the following splits are valid (unique positive even
- *   integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them,
- *   (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split
- *   into (2 + 2 + 4 + 4) as all the numbers should be unique.
- *
- * Return a list of integers that represent a valid split containing a maximum number of
- * integers. If no valid split exists for finalSum, return an empty list. You may return
- * the integers in any order.
- */
-
-/**
- * @param {number} finalSum
- * @return {number[]}
- */
-var maximumEvenSplit = function(finalSum) {
-  if (finalSum % 2 !== 0) return [];
-
-  const result = [];
-  let current = 2;
-  let remaining = finalSum;
-
-  while (remaining >= current) {
-    if (remaining - current <= current) {
-      result.push(remaining);
-      return result;
-    }
-    result.push(current);
-    remaining -= current;
-    current += 2;
-  }
-
-  return result;
-};
diff --git a/solutions/2179-count-good-triplets-in-an-array.js b/solutions/2179-count-good-triplets-in-an-array.js
deleted file mode 100644
index 1046d371..00000000
--- a/solutions/2179-count-good-triplets-in-an-array.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * 2179. Count Good Triplets in an Array
- * https://leetcode.com/problems/count-good-triplets-in-an-array/
- * Difficulty: Hard
- *
- * You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations
- * of [0, 1, ..., n - 1].
- *
- * A good triplet is a set of 3 distinct values which are present in increasing order by position
- * both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in
- * nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z)
- * where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.
- *
- * Return the total number of good triplets.
- */
-
-/**
- * @param {number[]} nums1
- * @param {number[]} nums2
- * @return {number}
- */
-var goodTriplets = function(nums1, nums2) {
-  const length = nums1.length;
-  const pos1 = new Array(length);
-  const pos2 = new Array(length);
-
-  for (let i = 0; i < length; i++) {
-    pos1[nums1[i]] = i;
-    pos2[nums2[i]] = i;
-  }
-
-  const indices = new Array(length);
-  for (let i = 0; i < length; i++) {
-    indices[pos1[i]] = pos2[i];
-  }
-
-  const leftTree = new Array(length + 1).fill(0);
-  const rightTree = new Array(length + 1).fill(0);
-
-  let result = 0;
-  for (let i = length - 1; i >= 0; i--) {
-    const position = indices[i];
-    update(rightTree, position, 1);
-  }
-
-  for (let i = 0; i < length; i++) {
-    const position = indices[i];
-    update(rightTree, position, -1);
-    const smaller = query(leftTree, position);
-    const larger = query(rightTree, length - 1) - query(rightTree, position);
-    result += smaller * larger;
-    update(leftTree, position, 1);
-  }
-
-  return result;
-
-  function update(tree, index, delta) {
-    for (let i = index + 1; i <= length; i += i & -i) {
-      tree[i] += delta;
-    }
-  }
-
-  function query(tree, index) {
-    let sum = 0;
-    for (let i = index + 1; i > 0; i -= i & -i) {
-      sum += tree[i];
-    }
-    return sum;
-  }
-};
diff --git a/solutions/2180-count-integers-with-even-digit-sum.js b/solutions/2180-count-integers-with-even-digit-sum.js
deleted file mode 100644
index c1a077e6..00000000
--- a/solutions/2180-count-integers-with-even-digit-sum.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2180. Count Integers With Even Digit Sum
- * https://leetcode.com/problems/count-integers-with-even-digit-sum/
- * Difficulty: Easy
- *
- * Given a positive integer num, return the number of positive integers less than or equal to num
- * whose digit sums are even.
- *
- * The digit sum of a positive integer is the sum of all its digits.
- */
-
-/**
- * @param {number} num
- * @return {number}
- */
-var countEven = function(num) {
-  let result = 0;
-
-  for (let i = 1; i <= num; i++) {
-    let sum = 0;
-    let current = i;
-    while (current > 0) {
-      sum += current % 10;
-      current = Math.floor(current / 10);
-    }
-    if (sum % 2 === 0) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2181-merge-nodes-in-between-zeros.js b/solutions/2181-merge-nodes-in-between-zeros.js
deleted file mode 100644
index f5993c27..00000000
--- a/solutions/2181-merge-nodes-in-between-zeros.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2181. Merge Nodes in Between Zeros
- * https://leetcode.com/problems/merge-nodes-in-between-zeros/
- * Difficulty: Medium
- *
- * You are given the head of a linked list, which contains a series of integers separated
- * by 0's. The beginning and end of the linked list will have Node.val == 0.
- *
- * For every two consecutive 0's, merge all the nodes lying in between them into a single
- * node whose value is the sum of all the merged nodes. The modified list should not contain
- * any 0's.
- *
- * Return the head of the modified 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 {ListNode}
- */
-var mergeNodes = function(head) {
-  const result = new ListNode(0);
-  let current = result;
-  let sum = 0;
-
-  head = head.next;
-
-  while (head) {
-    if (head.val === 0) {
-      current.next = new ListNode(sum);
-      current = current.next;
-      sum = 0;
-    } else {
-      sum += head.val;
-    }
-    head = head.next;
-  }
-
-  return result.next;
-};
diff --git a/solutions/2183-count-array-pairs-divisible-by-k.js b/solutions/2183-count-array-pairs-divisible-by-k.js
deleted file mode 100644
index 96f923c4..00000000
--- a/solutions/2183-count-array-pairs-divisible-by-k.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2183. Count Array Pairs Divisible by K
- * https://leetcode.com/problems/count-array-pairs-divisible-by-k/
- * Difficulty: Hard
- *
- * Given a 0-indexed integer array nums of length n and an integer k, return the number
- * of pairs (i, j) such that:
- * - 0 <= i < j <= n - 1 and
- * - nums[i] * nums[j] is divisible by k.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var countPairs = function(nums, k) {
-  const map = new Map();
-  let pairs = 0;
-
-  for (const num of nums) {
-    const gcd1 = gcd(num, k);
-    for (const [gcd2, count] of map) {
-      if ((gcd1 * gcd2) % k === 0) {
-        pairs += count;
-      }
-    }
-    map.set(gcd1, (map.get(gcd1) || 0) + 1);
-  }
-
-  return pairs;
-};
-
-function gcd(a, b) {
-  while (b) {
-    [a, b] = [b, a % b];
-  }
-  return a;
-}
diff --git a/solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js b/solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js
deleted file mode 100644
index 2501cbd5..00000000
--- a/solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2186. Minimum Number of Steps to Make Two Strings Anagram II
- * https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/
- * Difficulty: Medium
- *
- * You are given two strings s and t. In one step, you can append any character to either s or t.
- *
- * Return the minimum number of steps to make s and t anagrams of each other.
- *
- * An anagram of a string is a string that contains the same characters with a different (or the
- * same) ordering.
- */
-
-/**
- * @param {string} s
- * @param {string} t
- * @return {number}
- */
-var minSteps = function(s, t) {
-  const charCount = new Array(26).fill(0);
-
-  for (const char of s) {
-    charCount[char.charCodeAt(0) - 97]++;
-  }
-
-  for (const char of t) {
-    charCount[char.charCodeAt(0) - 97]--;
-  }
-
-  let result = 0;
-  for (const count of charCount) {
-    result += Math.abs(count);
-  }
-
-  return result;
-};
diff --git a/solutions/2187-minimum-time-to-complete-trips.js b/solutions/2187-minimum-time-to-complete-trips.js
deleted file mode 100644
index 305712f8..00000000
--- a/solutions/2187-minimum-time-to-complete-trips.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2187. Minimum Time to Complete Trips
- * https://leetcode.com/problems/minimum-time-to-complete-trips/
- * Difficulty: Medium
- *
- * You are given an array time where time[i] denotes the time taken by the ith bus to complete
- * one trip.
- *
- * Each bus can make multiple trips successively; that is, the next trip can start immediately
- * after completing the current trip. Also, each bus operates independently; that is, the trips
- * of one bus do not influence the trips of any other bus.
- *
- * You are also given an integer totalTrips, which denotes the number of trips all buses should
- * make in total. Return the minimum time required for all buses to complete at least totalTrips
- * trips.
- */
-
-/**
- * @param {number[]} time
- * @param {number} totalTrips
- * @return {number}
- */
-var minimumTime = function(time, totalTrips) {
-  let left = 1;
-  let right = Math.min(...time) * totalTrips;
-
-  while (left < right) {
-    const mid = Math.floor((left + right) / 2);
-    const trips = time.reduce((sum, t) => sum + Math.floor(mid / t), 0);
-
-    if (trips >= totalTrips) {
-      right = mid;
-    } else {
-      left = mid + 1;
-    }
-  }
-
-  return left;
-};
diff --git a/solutions/2188-minimum-time-to-finish-the-race.js b/solutions/2188-minimum-time-to-finish-the-race.js
deleted file mode 100644
index fbce3d25..00000000
--- a/solutions/2188-minimum-time-to-finish-the-race.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * 2188. Minimum Time to Finish the Race
- * https://leetcode.com/problems/minimum-time-to-finish-the-race/
- * Difficulty: Hard
- *
- * You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that
- * the ith tire can finish its xth successive lap in fi * ri(x-1) seconds.
- * - For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds,
- *   its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc.
- *
- * You are also given an integer changeTime and an integer numLaps.
- *
- * The race consists of numLaps laps and you may start the race with any tire. You have an
- * unlimited supply of each tire and after every lap, you may change to any given tire (including
- * the current tire type) if you wait changeTime seconds.
- *
- * Return the minimum time to finish the race.
- */
-
-/**
- * @param {number[][]} tires
- * @param {number} changeTime
- * @param {number} numLaps
- * @return {number}
- */
-var minimumFinishTime = function(tires, changeTime, numLaps) {
-  const minTimes = new Array(18).fill(Infinity);
-  const bestTime = new Array(numLaps + 1).fill(Infinity);
-
-  for (const [baseTime, multiplier] of tires) {
-    let currentTime = baseTime;
-    let totalTime = baseTime;
-
-    for (let lap = 1; lap <= Math.min(numLaps, 17); lap++) {
-      if (currentTime > changeTime + baseTime) break;
-      minTimes[lap] = Math.min(minTimes[lap], totalTime);
-      currentTime *= multiplier;
-      totalTime += currentTime;
-    }
-  }
-
-  bestTime[0] = 0;
-
-  for (let lap = 1; lap <= numLaps; lap++) {
-    for (let prev = 1; prev <= Math.min(lap, 17); prev++) {
-      if (minTimes[prev] !== Infinity) {
-        bestTime[lap] = Math.min(
-          bestTime[lap],
-          bestTime[lap - prev] + minTimes[prev] + (lap === prev ? 0 : changeTime)
-        );
-      }
-    }
-  }
-
-  return bestTime[numLaps];
-};
diff --git a/solutions/2190-most-frequent-number-following-key-in-an-array.js b/solutions/2190-most-frequent-number-following-key-in-an-array.js
deleted file mode 100644
index b5485503..00000000
--- a/solutions/2190-most-frequent-number-following-key-in-an-array.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2190. Most Frequent Number Following Key In an Array
- * https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums. You are also given an integer key, which is
- * present in nums.
- *
- * For every unique integer target in nums, count the number of times target immediately follows
- * an occurrence of key in nums. In other words, count the number of indices i such that:
- * - 0 <= i <= nums.length - 2,
- * - nums[i] == key and,
- * - nums[i + 1] == target.
- *
- * Return the target with the maximum count. The test cases will be generated such that the target
- * with maximum count is unique.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} key
- * @return {number}
- */
-var mostFrequent = function(nums, key) {
-  const frequency = new Map();
-  let maxCount = 0;
-  let result = 0;
-
-  for (let i = 0; i < nums.length - 1; i++) {
-    if (nums[i] === key) {
-      const target = nums[i + 1];
-      const count = (frequency.get(target) || 0) + 1;
-      frequency.set(target, count);
-
-      if (count > maxCount) {
-        maxCount = count;
-        result = target;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2191-sort-the-jumbled-numbers.js b/solutions/2191-sort-the-jumbled-numbers.js
deleted file mode 100644
index 490e1d17..00000000
--- a/solutions/2191-sort-the-jumbled-numbers.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * 2191. Sort the Jumbled Numbers
- * https://leetcode.com/problems/sort-the-jumbled-numbers/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled
- * decimal system. mapping[i] = j means digit i should be mapped to digit j in this system.
- *
- * The mapped value of an integer is the new integer obtained by replacing each occurrence of digit
- * i in the integer with mapping[i] for all 0 <= i <= 9.
- *
- * You are also given another integer array nums. Return the array nums sorted in non-decreasing
- * order based on the mapped values of its elements.
- *
- * Notes:
- * - Elements with the same mapped values should appear in the same relative order as in the input.
- * - The elements of nums should only be sorted based on their mapped values and not be replaced by
- *   them.
- */
-
-/**
- * @param {number[]} mapping
- * @param {number[]} nums
- * @return {number[]}
- */
-var sortJumbled = function(mapping, nums) {
-  const mapped = nums.map((num, index) => {
-    let mappedNum = 0;
-    let temp = num;
-
-    if (temp === 0) {
-      mappedNum = mapping[0];
-    } else {
-      const digits = [];
-      while (temp > 0) {
-        digits.push(mapping[temp % 10]);
-        temp = Math.floor(temp / 10);
-      }
-      while (digits.length > 0) {
-        mappedNum = mappedNum * 10 + digits.pop();
-      }
-    }
-
-    return { original: num, mapped: mappedNum, index };
-  });
-
-  mapped.sort((a, b) => {
-    if (a.mapped === b.mapped) return a.index - b.index;
-    return a.mapped - b.mapped;
-  });
-
-  return mapped.map(item => item.original);
-};
diff --git a/solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js b/solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js
deleted file mode 100644
index 9eeb8509..00000000
--- a/solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 2192. All Ancestors of a Node in a Directed Acyclic Graph
- * https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/
- * Difficulty: Medium
- *
- * You are given a positive integer n representing the number of nodes of a Directed Acyclic
- * Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).
- *
- * You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there
- * is a unidirectional edge from fromi to toi in the graph.
- *
- * Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in
- * ascending order.
- *
- * A node u is an ancestor of another node v if u can reach v via a set of edges.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} edges
- * @return {number[][]}
- */
-var getAncestors = function(n, edges) {
-  const graph = Array.from({ length: n }, () => []);
-  const ancestors = Array.from({ length: n }, () => new Set());
-
-  for (const [from, to] of edges) {
-    graph[to].push(from);
-  }
-
-  for (let i = 0; i < n; i++) {
-    findAncestors(i);
-  }
-
-  return ancestors.map(set => [...set].sort((a, b) => a - b));
-
-  function findAncestors(node) {
-    if (ancestors[node].size > 0) return;
-
-    for (const parent of graph[node]) {
-      ancestors[node].add(parent);
-      findAncestors(parent);
-      for (const ancestor of ancestors[parent]) {
-        ancestors[node].add(ancestor);
-      }
-    }
-  }
-};
diff --git a/solutions/2193-minimum-number-of-moves-to-make-palindrome.js b/solutions/2193-minimum-number-of-moves-to-make-palindrome.js
deleted file mode 100644
index c25800e2..00000000
--- a/solutions/2193-minimum-number-of-moves-to-make-palindrome.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 2193. Minimum Number of Moves to Make Palindrome
- * https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/
- * Difficulty: Hard
- *
- * You are given a string s consisting only of lowercase English letters.
- *
- * In one move, you can select any two adjacent characters of s and swap them.
- *
- * Return the minimum number of moves needed to make s a palindrome.
- *
- * Note that the input will be generated such that s can always be converted to a palindrome.
- */
-
-/**
-* @param {string} s
-* @return {number}
-*/
-var minMovesToMakePalindrome = function(s) {
-  const chars = s.split('');
-  let moves = 0;
-
-  while (chars.length > 1) {
-    const matchIndex = chars.lastIndexOf(chars[0]);
-
-    if (matchIndex === 0) {
-      const middlePos = Math.floor(chars.length / 2);
-      moves += middlePos;
-      chars.splice(0, 1);
-    } else {
-      for (let i = matchIndex; i < chars.length - 1; i++) {
-        [chars[i], chars[i + 1]] = [chars[i + 1], chars[i]];
-        moves++;
-      }
-
-      chars.pop();
-      chars.shift();
-    }
-  }
-
-  return moves;
-};
diff --git a/solutions/2194-cells-in-a-range-on-an-excel-sheet.js b/solutions/2194-cells-in-a-range-on-an-excel-sheet.js
deleted file mode 100644
index 194c60cc..00000000
--- a/solutions/2194-cells-in-a-range-on-an-excel-sheet.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2194. Cells in a Range on an Excel Sheet
- * https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/
- * Difficulty: Easy
- *
- * A cell (r, c) of an excel sheet is represented as a string "" where:
- * -  denotes the column number c of the cell. It is represented by alphabetical letters.
- *   - For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on.
- * -  is the row number r of the cell. The rth row is represented by the integer r.
- *   - You are given a string s in the format ":", where  represents
- *     the column c1,  represents the row r1,  represents the column c2, and 
- *     represents the row r2, such that r1 <= r2 and c1 <= c2.
- *
- * Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should
- * be represented as strings in the format mentioned above and be sorted in non-decreasing order
- * first by columns and then by rows.
- */
-
-/**
- * @param {string} s
- * @return {string[]}
- */
-var cellsInRange = function(s) {
-  const result = [];
-  const startCol = s.charCodeAt(0);
-  const endCol = s.charCodeAt(3);
-  const startRow = parseInt(s[1], 10);
-  const endRow = parseInt(s[4], 10);
-
-  for (let col = startCol; col <= endCol; col++) {
-    for (let row = startRow; row <= endRow; row++) {
-      result.push(String.fromCharCode(col) + row);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2195-append-k-integers-with-minimal-sum.js b/solutions/2195-append-k-integers-with-minimal-sum.js
deleted file mode 100644
index bc873455..00000000
--- a/solutions/2195-append-k-integers-with-minimal-sum.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2195. Append K Integers With Minimal Sum
- * https://leetcode.com/problems/append-k-integers-with-minimal-sum/
- * Difficulty: Medium
- *
- * You are given an integer array nums and an integer k. Append k unique positive integers that do
- * not appear in nums to nums such that the resulting total sum is minimum.
- *
- * Return the sum of the k integers appended to nums.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var minimalKSum = function(nums, k) {
-  const sortedUnique = [...new Set(nums)].sort((a, b) => a - b);
-  let sum = BigInt(0);
-  let current = 1;
-  let i = 0;
-
-  while (k > 0 && i < sortedUnique.length) {
-    if (current < sortedUnique[i]) {
-      const count = Math.min(k, sortedUnique[i] - current);
-      sum += (BigInt(current) + BigInt(current + count - 1)) * BigInt(count) / BigInt(2);
-      k -= count;
-      current += count;
-    } else {
-      current = sortedUnique[i] + 1;
-      i++;
-    }
-  }
-
-  if (k > 0) {
-    sum += (BigInt(current) + BigInt(current + k - 1)) * BigInt(k) / BigInt(2);
-  }
-
-  return Number(sum);
-};
diff --git a/solutions/2196-create-binary-tree-from-descriptions.js b/solutions/2196-create-binary-tree-from-descriptions.js
deleted file mode 100644
index 67af6416..00000000
--- a/solutions/2196-create-binary-tree-from-descriptions.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * 2196. Create Binary Tree From Descriptions
- * https://leetcode.com/problems/create-binary-tree-from-descriptions/
- * Difficulty: Medium
- *
- * You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti]
- * indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
- * - If isLefti == 1, then childi is the left child of parenti.
- * - If isLefti == 0, then childi is the right child of parenti.
- *
- * Construct the binary tree described by descriptions and return its root.
- *
- * The test cases will be generated such that the binary tree is valid.
- */
-
-/**
- * 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[][]} descriptions
- * @return {TreeNode}
- */
-var createBinaryTree = function(descriptions) {
-  const nodes = new Map();
-  const children = new Set();
-
-  for (const [parent, child, isLeft] of descriptions) {
-    if (!nodes.has(parent)) {
-      nodes.set(parent, new TreeNode(parent));
-    }
-    if (!nodes.has(child)) {
-      nodes.set(child, new TreeNode(child));
-    }
-    children.add(child);
-    if (isLeft) {
-      nodes.get(parent).left = nodes.get(child);
-    } else {
-      nodes.get(parent).right = nodes.get(child);
-    }
-  }
-
-  for (const [val, node] of nodes) {
-    if (!children.has(val)) {
-      return node;
-    }
-  }
-
-  return null;
-};
diff --git a/solutions/2197-replace-non-coprime-numbers-in-array.js b/solutions/2197-replace-non-coprime-numbers-in-array.js
deleted file mode 100644
index 2bc8e2d5..00000000
--- a/solutions/2197-replace-non-coprime-numbers-in-array.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 2197. Replace Non-Coprime Numbers in Array
- * https://leetcode.com/problems/replace-non-coprime-numbers-in-array/
- * Difficulty: Hard
- *
- * You are given an array of integers nums. Perform the following steps:
- * 1. Find any two adjacent numbers in nums that are non-coprime.
- * 2. If no such numbers are found, stop the process.
- * 3. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).
- * 4. Repeat this process as long as you keep finding two adjacent non-coprime numbers.
- *
- * Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in
- * any arbitrary order will lead to the same result.
- *
- * The test cases are generated such that the values in the final array are less than or equal to
- * 108.
- *
- * Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common
- * Divisor of x and y.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var replaceNonCoprimes = function(nums) {
-  const result = [];
-
-  for (let num of nums) {
-    while (result.length > 0) {
-      const last = result[result.length - 1];
-      const gcdValue = gcd(last, num);
-      if (gcdValue === 1) break;
-      result.pop();
-      num = (last / gcdValue) * num;
-    }
-    result.push(num);
-  }
-
-  return result;
-};
-
-function gcd(a, b) {
-  while (b) {
-    [a, b] = [b, a % b];
-  }
-  return a;
-}
diff --git a/solutions/2200-find-all-k-distant-indices-in-an-array.js b/solutions/2200-find-all-k-distant-indices-in-an-array.js
deleted file mode 100644
index 5a2cd1bd..00000000
--- a/solutions/2200-find-all-k-distant-indices-in-an-array.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2200. Find All K-Distant Indices in an Array
- * https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums and two integers key and k. A k-distant index
- * is an index i of nums for which there exists at least one index j such that |i - j| <= k
- * and nums[j] == key.
- *
- * Return a list of all k-distant indices sorted in increasing order.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} key
- * @param {number} k
- * @return {number[]}
- */
-var findKDistantIndices = function(nums, key, k) {
-  const result = new Set();
-
-  for (let j = 0; j < nums.length; j++) {
-    if (nums[j] === key) {
-      for (let i = Math.max(0, j - k); i <= Math.min(nums.length - 1, j + k); i++) {
-        result.add(i);
-      }
-    }
-  }
-
-  return [...result].sort((a, b) => a - b);
-};
diff --git a/solutions/2201-count-artifacts-that-can-be-extracted.js b/solutions/2201-count-artifacts-that-can-be-extracted.js
deleted file mode 100644
index cd5f5627..00000000
--- a/solutions/2201-count-artifacts-that-can-be-extracted.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * 2201. Count Artifacts That Can Be Extracted
- * https://leetcode.com/problems/count-artifacts-that-can-be-extracted/
- * Difficulty: Medium
- *
- * There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer
- * n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular
- * artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried
- * in the subgrid where:
- * - (r1i, c1i) is the coordinate of the top-left cell of the ith artifact and
- * - (r2i, c2i) is the coordinate of the bottom-right cell of the ith artifact.
- *
- * You will excavate some cells of the grid and remove all the mud from them. If the cell has a
- * part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact
- * are uncovered, you can extract it.
- *
- * Given a 0-indexed 2D integer array dig where dig[i] = [ri, ci] indicates that you will excavate
- * the cell (ri, ci), return the number of artifacts that you can extract.
- *
- * The test cases are generated such that:
- * - No two artifacts overlap.
- * - Each artifact only covers at most 4 cells.
- * - The entries of dig are unique.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} artifacts
- * @param {number[][]} dig
- * @return {number}
- */
-var digArtifacts = function(n, artifacts, dig) {
-  const excavated = new Set();
-  let result = 0;
-
-  for (const [row, col] of dig) {
-    excavated.add(`${row},${col}`);
-  }
-
-  for (const [r1, c1, r2, c2] of artifacts) {
-    let allUncovered = true;
-
-    for (let r = r1; r <= r2; r++) {
-      for (let c = c1; c <= c2; c++) {
-        if (!excavated.has(`${r},${c}`)) {
-          allUncovered = false;
-          break;
-        }
-      }
-      if (!allUncovered) break;
-    }
-
-    if (allUncovered) result++;
-  }
-
-  return result;
-};
diff --git a/solutions/2202-maximize-the-topmost-element-after-k-moves.js b/solutions/2202-maximize-the-topmost-element-after-k-moves.js
deleted file mode 100644
index 8b1554b2..00000000
--- a/solutions/2202-maximize-the-topmost-element-after-k-moves.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 2202. Maximize the Topmost Element After K Moves
- * https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0]
- * is the topmost element of the pile.
- *
- * In one move, you can perform either of the following:
- * - If the pile is not empty, remove the topmost element of the pile.
- * - If there are one or more removed elements, add any one of them back onto the pile. This element
- *   becomes the new topmost element.
- *
- * You are also given an integer k, which denotes the total number of moves to be made.
- *
- * Return the maximum value of the topmost element of the pile possible after exactly k moves. In
- * case it is not possible to obtain a non-empty pile after k moves, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var maximumTop = function(nums, k) {
-  const n = nums.length;
-
-  if (n === 1 && k % 2 === 1) return -1;
-  if (k === 0) return nums[0];
-  if (k === 1) return n > 1 ? nums[1] : -1;
-
-  let result = 0;
-  for (let i = 0; i < Math.min(k - 1, n); i++) {
-    result = Math.max(result, nums[i]);
-  }
-
-  if (k < n) {
-    result = Math.max(result, nums[k]);
-  }
-
-  return result;
-};
diff --git a/solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js b/solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js
deleted file mode 100644
index 4ace48ff..00000000
--- a/solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * 2203. Minimum Weighted Subgraph With the Required Paths
- * https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/
- * Difficulty: Hard
- *
- * You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes
- * are numbered from 0 to n - 1.
- *
- * You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that
- * there exists a directed edge from fromi to toi with weight weighti.
- *
- * Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes
- * of the graph.
- *
- * Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from
- * both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist,
- * return -1.
- *
- * A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of
- * a subgraph is the sum of weights of its constituent edges.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} edges
- * @param {number} src1
- * @param {number} src2
- * @param {number} dest
- * @return {number}
- */
-var minimumWeight = function(n, edges, src1, src2, dest) {
-  const forwardGraph = Array.from({ length: n }, () => []);
-  const reverseGraph = Array.from({ length: n }, () => []);
-
-  for (const [from, to, weight] of edges) {
-    forwardGraph[from].push([to, weight]);
-    reverseGraph[to].push([from, weight]);
-  }
-
-  const distFromSrc1 = dijkstra(forwardGraph, src1);
-  const distFromSrc2 = dijkstra(forwardGraph, src2);
-  const distToDest = dijkstra(reverseGraph, dest);
-  let minWeight = Infinity;
-  for (let i = 0; i < n; i++) {
-    if (distFromSrc1[i] !== Infinity && distFromSrc2[i] !== Infinity
-        && distToDest[i] !== Infinity) {
-      minWeight = Math.min(minWeight, distFromSrc1[i] + distFromSrc2[i] + distToDest[i]);
-    }
-  }
-
-  return minWeight === Infinity ? -1 : minWeight;
-
-  function dijkstra(graph, start) {
-    const distances = new Array(n).fill(Infinity);
-    distances[start] = 0;
-    const pq = new PriorityQueue((a, b) => a[0] - b[0]);
-    pq.enqueue([0, start]);
-
-    while (!pq.isEmpty()) {
-      const [dist, node] = pq.dequeue();
-      if (dist > distances[node]) continue;
-
-      for (const [next, weight] of graph[node]) {
-        if (distances[next] > dist + weight) {
-          distances[next] = dist + weight;
-          pq.enqueue([distances[next], next]);
-        }
-      }
-    }
-
-    return distances;
-  }
-};
diff --git a/solutions/2206-divide-array-into-equal-pairs.js b/solutions/2206-divide-array-into-equal-pairs.js
deleted file mode 100644
index 6a2765e0..00000000
--- a/solutions/2206-divide-array-into-equal-pairs.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2206. Divide Array Into Equal Pairs
- * https://leetcode.com/problems/divide-array-into-equal-pairs/
- * Difficulty: Easy
- *
- * You are given an integer array nums consisting of 2 * n integers.
- *
- * You need to divide nums into n pairs such that:
- * - Each element belongs to exactly one pair.
- * - The elements present in a pair are equal.
- *
- * Return true if nums can be divided into n pairs, otherwise return false.
- */
-
-/**
- * @param {number[]} nums
- * @return {boolean}
- */
-/**
- * @param {number[]} nums
- * @return {boolean}
- */
-var divideArray = function(nums) {
-  const map = new Map();
-
-  for (const num of nums) {
-    map.set(num, (map.get(num) || 0) + 1);
-  }
-  for (const count of map.values()) {
-    if (count % 2 !== 0) {
-      return false;
-    }
-  }
-
-  return true;
-};
diff --git a/solutions/2207-maximize-number-of-subsequences-in-a-string.js b/solutions/2207-maximize-number-of-subsequences-in-a-string.js
deleted file mode 100644
index d7ad35a6..00000000
--- a/solutions/2207-maximize-number-of-subsequences-in-a-string.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2207. Maximize Number of Subsequences in a String
- * https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/
- * Difficulty: Medium
- *
- * You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both
- * of which consist of only lowercase English letters.
- *
- * You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the
- * character can be added even at the beginning or at the end of text.
- *
- * Return the maximum number of times pattern can occur as a subsequence of the modified text.
- *
- * A subsequence is a string that can be derived from another string by deleting some or no
- * characters without changing the order of the remaining characters.
- */
-
-/**
- * @param {string} text
- * @param {string} pattern
- * @return {number}
- */
-var maximumSubsequenceCount = function(text, pattern) {
-  const firstChar = pattern[0];
-  const secondChar = pattern[1];
-  let firstCount = 0;
-  let secondCount = 0;
-  let subsequences = 0;
-
-  for (const char of text) {
-    if (char === secondChar) {
-      subsequences += firstCount;
-      secondCount++;
-    }
-    if (char === firstChar) {
-      firstCount++;
-    }
-  }
-
-  return subsequences + Math.max(firstCount, secondCount);
-};
diff --git a/solutions/2209-minimum-white-tiles-after-covering-with-carpets.js b/solutions/2209-minimum-white-tiles-after-covering-with-carpets.js
deleted file mode 100644
index 08fb5fd3..00000000
--- a/solutions/2209-minimum-white-tiles-after-covering-with-carpets.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2209. Minimum White Tiles After Covering With Carpets
- * https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/
- * Difficulty: Hard
- *
- * You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:
- * - floor[i] = '0' denotes that the ith tile of the floor is colored black.
- * - On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.
- *
- * You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length
- * carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles
- * still visible is minimum. Carpets may overlap one another.
- *
- * Return the minimum number of white tiles still visible.
- */
-
-/**
- * @param {string} floor
- * @param {number} numCarpets
- * @param {number} carpetLen
- * @return {number}
- */
-var minimumWhiteTiles = function(floor, numCarpets, carpetLen) {
-  const n = floor.length;
-  const dp = Array.from({ length: n + 1 }, () => Array(numCarpets + 1).fill(0));
-
-  for (let i = 1; i <= n; i++) {
-    for (let j = 0; j <= numCarpets; j++) {
-      const skip = dp[i - 1][j] + (floor[i - 1] === '1' ? 1 : 0);
-      const cover = j > 0 ? dp[Math.max(0, i - carpetLen)][j - 1] : Infinity;
-      dp[i][j] = Math.min(skip, cover);
-    }
-  }
-
-  return dp[n][numCarpets];
-};
diff --git a/solutions/2210-count-hills-and-valleys-in-an-array.js b/solutions/2210-count-hills-and-valleys-in-an-array.js
deleted file mode 100644
index 388d78f5..00000000
--- a/solutions/2210-count-hills-and-valleys-in-an-array.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2210. Count Hills and Valleys in an Array
- * https://leetcode.com/problems/count-hills-and-valleys-in-an-array/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the
- * closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part
- * of a valley in nums if the closest non-equal neighbors of i are larger than nums[i].
- * Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].
- *
- * Note that for an index to be part of a hill or valley, it must have a non-equal neighbor
- * on both the left and right of the index.
- *
- * Return the number of hills and valleys in nums.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var countHillValley = function(nums) {
-  let count = 0;
-  let prev = nums[0];
-
-  for (let i = 1; i < nums.length - 1; i++) {
-    if (nums[i] === nums[i + 1]) continue;
-    const left = prev;
-    const right = nums[i + 1];
-
-    if ((nums[i] > left && nums[i] > right) || (nums[i] < left && nums[i] < right)) {
-      count++;
-    }
-
-    prev = nums[i];
-  }
-
-  return count;
-};
diff --git a/solutions/2211-count-collisions-on-a-road.js b/solutions/2211-count-collisions-on-a-road.js
deleted file mode 100644
index acbd8920..00000000
--- a/solutions/2211-count-collisions-on-a-road.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2211. Count Collisions on a Road
- * https://leetcode.com/problems/count-collisions-on-a-road/
- * Difficulty: Medium
- *
- * There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left
- * to right and each car is present at a unique point.
- *
- * You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R',
- * or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying
- * at its current point respectively. Each moving car has the same speed.
- *
- * The number of collisions can be calculated as follows:
- * - When two cars moving in opposite directions collide with each other, the number of collisions
- *   increases by 2.
- * - When a moving car collides with a stationary car, the number of collisions increases by 1.
- *
- * After a collision, the cars involved can no longer move and will stay at the point where they
- * collided. Other than that, cars cannot change their state or direction of motion.
- *
- * Return the total number of collisions that will happen on the road.
- */
-
-/**
- * @param {string} directions
- * @return {number}
- */
-var countCollisions = function(directions) {
-  let result = 0;
-  let left = 0;
-  let right = directions.length - 1;
-
-  while (left < directions.length && directions[left] === 'L') left++;
-  while (right >= 0 && directions[right] === 'R') right--;
-
-  for (let i = left; i <= right; i++) {
-    if (directions[i] !== 'S') result++;
-  }
-
-  return result;
-};
diff --git a/solutions/2212-maximum-points-in-an-archery-competition.js b/solutions/2212-maximum-points-in-an-archery-competition.js
deleted file mode 100644
index 2c09fc29..00000000
--- a/solutions/2212-maximum-points-in-an-archery-competition.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * 2212. Maximum Points in an Archery Competition
- * https://leetcode.com/problems/maximum-points-in-an-archery-competition/
- * Difficulty: Medium
- *
- * Alice and Bob are opponents in an archery competition. The competition has set the
- * following rules:
- * 1. Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.
- * 2. The points are then calculated as follows:
- *    1. The target has integer scoring sections ranging from 0 to 11 inclusive.
- *    2. For each section of the target with score k (in between 0 to 11), say Alice and Bob have
- *       shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points.
- *       If ak < bk, then Bob takes k points.
- *    3. However, if ak == bk == 0, then nobody takes k points.
- * - For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes
- *   11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot
- *   2 arrows on that same section, then Bob takes 11 points.
- *
- * You are given the integer numArrows and an integer array aliceArrows of size 12, which represents
- * the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize
- * the total number of points he can obtain.
- *
- * Return the array bobArrows which represents the number of arrows Bob shot on each scoring section
- * from 0 to 11. The sum of the values in bobArrows should equal numArrows.
- *
- * If there are multiple ways for Bob to earn the maximum total points, return any one of them.
- */
-
-/**
- * @param {number} numArrows
- * @param {number[]} aliceArrows
- * @return {number[]}
- */
-var maximumBobPoints = function(numArrows, aliceArrows) {
-  let maxScore = 0;
-  let bestConfig = new Array(12).fill(0);
-
-  backtrack(1, numArrows, 0, new Array(12).fill(0));
-  return bestConfig;
-
-  function backtrack(index, arrowsLeft, score, config) {
-    if (index === 12 || arrowsLeft === 0) {
-      if (score > maxScore) {
-        maxScore = score;
-        bestConfig = [...config];
-        bestConfig[0] += arrowsLeft;
-      }
-      return;
-    }
-
-    const needed = aliceArrows[index] + 1;
-    if (arrowsLeft >= needed) {
-      config[index] = needed;
-      backtrack(index + 1, arrowsLeft - needed, score + index, config);
-      config[index] = 0;
-    }
-
-    backtrack(index + 1, arrowsLeft, score, config);
-  }
-};
diff --git a/solutions/2213-longest-substring-of-one-repeating-character.js b/solutions/2213-longest-substring-of-one-repeating-character.js
deleted file mode 100644
index ca5e006d..00000000
--- a/solutions/2213-longest-substring-of-one-repeating-character.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * 2213. Longest Substring of One Repeating Character
- * https://leetcode.com/problems/longest-substring-of-one-repeating-character/
- * Difficulty: Hard
- *
- * You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of
- * length k and a 0-indexed array of integer indices queryIndices of length k, both of which are
- * used to describe k queries.
- *
- * The ith query updates the character in s at index queryIndices[i] to the character
- * queryCharacters[i].
- *
- * Return an array lengths of length k where lengths[i] is the length of the longest substring of
- * s consisting of only one repeating character after the ith query is performed.
- */
-
-/**
-* @param {string} s
-* @param {string} queryCharacters
-* @param {number[]} queryIndices
-* @return {number[]}
-*/
-var longestRepeating = function(s, queryCharacters, queryIndices) {
-  const chars = s.split('');
-  const n = chars.length;
-  const k = queryIndices.length;
-  const result = [];
-
-  class Node {
-    constructor() {
-      this.left = 0;
-      this.right = 0;
-      this.max = 0;
-      this.total = 0;
-    }
-  }
-
-  const tree = new Array(4 * n);
-  for (let i = 0; i < 4 * n; i++) {
-    tree[i] = new Node();
-  }
-
-  function buildTree(node, start, end) {
-    if (start === end) {
-      tree[node].left = 1;
-      tree[node].right = 1;
-      tree[node].max = 1;
-      tree[node].total = 1;
-      return;
-    }
-
-    const mid = Math.floor((start + end) / 2);
-    buildTree(2 * node, start, mid);
-    buildTree(2 * node + 1, mid + 1, end);
-
-    updateNode(node, start, end);
-  }
-
-  function updateNode(node, start, end) {
-    const leftChild = 2 * node;
-    const rightChild = 2 * node + 1;
-    const mid = Math.floor((start + end) / 2);
-
-    tree[node].total = tree[leftChild].total + tree[rightChild].total;
-
-    if (tree[leftChild].total === tree[leftChild].left
-        && mid + 1 <= end && chars[mid] === chars[mid + 1]) {
-      tree[node].left = tree[leftChild].total + tree[rightChild].left;
-    } else {
-      tree[node].left = tree[leftChild].left;
-    }
-
-    if (tree[rightChild].total === tree[rightChild].right
-        && mid >= start && chars[mid] === chars[mid + 1]) {
-      tree[node].right = tree[rightChild].total + tree[leftChild].right;
-    } else {
-      tree[node].right = tree[rightChild].right;
-    }
-
-    tree[node].max = Math.max(tree[leftChild].max, tree[rightChild].max);
-
-    if (mid >= start && mid + 1 <= end && chars[mid] === chars[mid + 1]) {
-      tree[node].max = Math.max(tree[node].max,
-        tree[leftChild].right + tree[rightChild].left);
-    }
-  }
-
-  function update(node, start, end, index) {
-    if (index < start || index > end) {
-      return;
-    }
-
-    if (start === end) {
-      return;
-    }
-
-    const mid = Math.floor((start + end) / 2);
-    update(2 * node, start, mid, index);
-    update(2 * node + 1, mid + 1, end, index);
-
-    updateNode(node, start, end);
-  }
-
-  buildTree(1, 0, n - 1);
-
-  for (let q = 0; q < k; q++) {
-    const index = queryIndices[q];
-    const newChar = queryCharacters[q];
-
-    chars[index] = newChar;
-    update(1, 0, n - 1, index);
-
-    result.push(tree[1].max);
-  }
-
-  return result;
-};
diff --git a/solutions/2216-minimum-deletions-to-make-array-beautiful.js b/solutions/2216-minimum-deletions-to-make-array-beautiful.js
deleted file mode 100644
index 7cb1012e..00000000
--- a/solutions/2216-minimum-deletions-to-make-array-beautiful.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2216. Minimum Deletions to Make Array Beautiful
- * https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums. The array nums is beautiful if:
- * - nums.length is even.
- * - nums[i] != nums[i + 1] for all i % 2 == 0.
- *
- * Note that an empty array is considered beautiful.
- *
- * You can delete any number of elements from nums. When you delete an element, all the elements
- * to the right of the deleted element will be shifted one unit to the left to fill the gap
- * created and all the elements to the left of the deleted element will remain unchanged.
- *
- * Return the minimum number of elements to delete from nums to make it beautiful.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minDeletion = function(nums) {
-  let result = 0;
-  let i = 0;
-
-  while (i < nums.length - 1) {
-    if (nums[i] === nums[i + 1]) {
-      result++;
-      i++;
-    } else {
-      i += 2;
-    }
-  }
-
-  if ((nums.length - result) % 2 !== 0) {
-    result++;
-  }
-
-  return result;
-};
diff --git a/solutions/2217-find-palindrome-with-fixed-length.js b/solutions/2217-find-palindrome-with-fixed-length.js
deleted file mode 100644
index 4e6a83aa..00000000
--- a/solutions/2217-find-palindrome-with-fixed-length.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2217. Find Palindrome With Fixed Length
- * https://leetcode.com/problems/find-palindrome-with-fixed-length/
- * Difficulty: Medium
- *
- * Given an integer array queries and a positive integer intLength, return an array answer where
- * answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1
- * if no such palindrome exists.
- *
- * A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have
- * leading zeros.
- */
-
-/**
- * @param {number[]} queries
- * @param {number} intLength
- * @return {number[]}
- */
-var kthPalindrome = function(queries, intLength) {
-  const halfLength = Math.ceil(intLength / 2);
-  const maxPalindromes = Math.pow(10, halfLength - 1) * 9;
-
-  return queries.map(generatePalindrome);
-
-  function generatePalindrome(query) {
-    if (query > maxPalindromes) return -1;
-
-    let firstHalf = Math.pow(10, halfLength - 1) + query - 1;
-    let result = firstHalf;
-
-    if (intLength % 2 === 1) firstHalf = Math.floor(firstHalf / 10);
-
-    while (firstHalf > 0) {
-      result = result * 10 + (firstHalf % 10);
-      firstHalf = Math.floor(firstHalf / 10);
-    }
-
-    return result;
-  }
-};
diff --git a/solutions/2218-maximum-value-of-k-coins-from-piles.js b/solutions/2218-maximum-value-of-k-coins-from-piles.js
deleted file mode 100644
index 743b4b17..00000000
--- a/solutions/2218-maximum-value-of-k-coins-from-piles.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2218. Maximum Value of K Coins From Piles
- * https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/
- * Difficulty: Hard
- *
- * There are n piles of coins on a table. Each pile consists of a positive number of coins of
- * assorted denominations.
- *
- * In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.
- *
- * Given a list piles, where piles[i] is a list of integers denoting the composition of the ith
- * pile from top to bottom, and a positive integer k, return the maximum total value of coins
- * you can have in your wallet if you choose exactly k coins optimally.
- */
-
-/**
- * @param {number[][]} piles
- * @param {number} k
- * @return {number}
- */
-var maxValueOfCoins = function(piles, k) {
-  const n = piles.length;
-  const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(-1));
-
-  return maximize(0, k);
-
-  function maximize(pileIndex, remainingCoins) {
-    if (pileIndex === n || remainingCoins === 0) return 0;
-    if (dp[pileIndex][remainingCoins] !== -1) return dp[pileIndex][remainingCoins];
-
-    let maxValue = maximize(pileIndex + 1, remainingCoins);
-    let currentSum = 0;
-
-    for (let i = 0; i < Math.min(piles[pileIndex].length, remainingCoins); i++) {
-      currentSum += piles[pileIndex][i];
-      maxValue = Math.max(
-        maxValue,
-        currentSum + maximize(pileIndex + 1, remainingCoins - (i + 1))
-      );
-    }
-
-    return dp[pileIndex][remainingCoins] = maxValue;
-  }
-};
diff --git a/solutions/2220-minimum-bit-flips-to-convert-number.js b/solutions/2220-minimum-bit-flips-to-convert-number.js
deleted file mode 100644
index 28e0a9da..00000000
--- a/solutions/2220-minimum-bit-flips-to-convert-number.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * 2220. Minimum Bit Flips to Convert Number
- * https://leetcode.com/problems/minimum-bit-flips-to-convert-number/
- * Difficulty: Easy
- *
- * A bit flip of a number x is choosing a bit in the binary representation of x and flipping it
- * from either 0 to 1 or 1 to 0.
- * - For example, for x = 7, the binary representation is 111 and we may choose any bit (including
- *   any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110,
- *   flip the second bit from the right to get 101, flip the fifth bit from the right (a leading
- *   zero) to get 10111, etc.
- *
- * Given two integers start and goal, return the minimum number of bit flips to convert start to
- * goal.
- */
-
-/**
- * @param {number} start
- * @param {number} goal
- * @return {number}
- */
-var minBitFlips = function(start, goal) {
-  return (start ^ goal).toString(2).replace(/0+/g, '').length;
-};
diff --git a/solutions/2221-find-triangular-sum-of-an-array.js b/solutions/2221-find-triangular-sum-of-an-array.js
deleted file mode 100644
index 3ef02fcd..00000000
--- a/solutions/2221-find-triangular-sum-of-an-array.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 2221. Find Triangular Sum of an Array
- * https://leetcode.com/problems/find-triangular-sum-of-an-array/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and
- * 9 (inclusive).
- *
- * The triangular sum of nums is the value of the only element present in nums after the
- * following process terminates:
- * 1. Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new
- *    0-indexed integer array newNums of length n - 1.
- * 2. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as
- *    (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.
- * 3. Replace the array nums with newNums.
- * 4. Repeat the entire process starting from step 1.
- *
- * Return the triangular sum of nums.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var triangularSum = function(nums) {
-  while (nums.length > 1) {
-    const updated = [];
-    for (let i = 0; i < nums.length - 1; i++) {
-      updated.push((nums[i] + nums[i + 1]) % 10);
-    }
-    nums = updated;
-  }
-  return nums[0];
-};
diff --git a/solutions/2222-number-of-ways-to-select-buildings.js b/solutions/2222-number-of-ways-to-select-buildings.js
deleted file mode 100644
index 012573fc..00000000
--- a/solutions/2222-number-of-ways-to-select-buildings.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * 2222. Number of Ways to Select Buildings
- * https://leetcode.com/problems/number-of-ways-to-select-buildings/
- * Difficulty: Medium
- *
- * You are given a 0-indexed binary string s which represents the types of buildings along
- * a street where:
- * - s[i] = '0' denotes that the ith building is an office and
- * - s[i] = '1' denotes that the ith building is a restaurant.
- *
- * As a city official, you would like to select 3 buildings for random inspection. However, to
- * ensure variety, no two consecutive buildings out of the selected buildings can be of the same
- * type.
- * - For example, given s = "001101", we cannot select the 1st, 3rd, and 5th buildings as that
- *   would form "011" which is not allowed due to having two consecutive buildings of the same type.
- *
- * Return the number of valid ways to select 3 buildings.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var numberOfWays = function(s) {
-  const prefixCounts = [[0, 0]];
-  let zeros = 0;
-  let ones = 0;
-
-  for (const char of s) {
-    if (char === '0') zeros++;
-    else ones++;
-    prefixCounts.push([zeros, ones]);
-  }
-
-  let result = 0;
-  for (let i = 1; i < s.length - 1; i++) {
-    if (s[i] === '0') {
-      const leftOnes = prefixCounts[i][1];
-      const rightOnes = prefixCounts[s.length][1] - prefixCounts[i + 1][1];
-      result += leftOnes * rightOnes;
-    } else {
-      const leftZeros = prefixCounts[i][0];
-      const rightZeros = prefixCounts[s.length][0] - prefixCounts[i + 1][0];
-      result += leftZeros * rightZeros;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2223-sum-of-scores-of-built-strings.js b/solutions/2223-sum-of-scores-of-built-strings.js
deleted file mode 100644
index 4b5110cc..00000000
--- a/solutions/2223-sum-of-scores-of-built-strings.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2223. Sum of Scores of Built Strings
- * https://leetcode.com/problems/sum-of-scores-of-built-strings/
- * Difficulty: Hard
- *
- * You are building a string s of length n one character at a time, prepending each new character
- * to the front of the string. The strings are labeled from 1 to n, where the string with length
- * i is labeled si.
- * - For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc.
- *
- * The score of si is the length of the longest common prefix between si and sn (Note that s == sn).
- *
- * Given the final string s, return the sum of the score of every si.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var sumScores = function(s) {
-  const n = s.length;
-  const z = new Array(n).fill(0);
-  let left = 0;
-  let right = 0;
-
-  for (let i = 1; i < n; i++) {
-    if (i <= right) {
-      z[i] = Math.min(right - i + 1, z[i - left]);
-    }
-    while (i + z[i] < n && s[z[i]] === s[i + z[i]]) {
-      z[i]++;
-    }
-    if (i + z[i] - 1 > right) {
-      left = i;
-      right = i + z[i] - 1;
-    }
-  }
-
-  return z.reduce((sum, val) => sum + val, n);
-};
diff --git a/solutions/2224-minimum-number-of-operations-to-convert-time.js b/solutions/2224-minimum-number-of-operations-to-convert-time.js
deleted file mode 100644
index 95b7a154..00000000
--- a/solutions/2224-minimum-number-of-operations-to-convert-time.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2224. Minimum Number of Operations to Convert Time
- * https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/
- * Difficulty: Easy
- *
- * You are given two strings current and correct representing two 24-hour times.
- *
- * 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00
- * and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
- *
- * In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform
- * this operation any number of times.
- *
- * Return the minimum number of operations needed to convert current to correct.
- */
-
-/**
- * @param {string} current
- * @param {string} correct
- * @return {number}
- */
-var convertTime = function(current, correct) {
-  const toMinutes = time => {
-    const [hours, minutes] = time.split(':').map(Number);
-    return hours * 60 + minutes;
-  };
-
-  let diff = toMinutes(correct) - toMinutes(current);
-  const increments = [60, 15, 5, 1];
-  let result = 0;
-
-  for (const increment of increments) {
-    result += Math.floor(diff / increment);
-    diff %= increment;
-  }
-
-  return result;
-};
diff --git a/solutions/2225-find-players-with-zero-or-one-losses.js b/solutions/2225-find-players-with-zero-or-one-losses.js
deleted file mode 100644
index 3182523e..00000000
--- a/solutions/2225-find-players-with-zero-or-one-losses.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2225. Find Players With Zero or One Losses
- * https://leetcode.com/problems/find-players-with-zero-or-one-losses/
- * Difficulty: Medium
- *
- * You are given an integer array matches where matches[i] = [winneri, loseri] indicates that
- * the player winneri defeated player loseri in a match.
- *
- * Return a list answer of size 2 where:
- * - answer[0] is a list of all players that have not lost any matches.
- * - answer[1] is a list of all players that have lost exactly one match.
- *
- * The values in the two lists should be returned in increasing order.
- *
- * Note:
- * - You should only consider the players that have played at least one match.
- * - The testcases will be generated such that no two matches will have the same outcome.
- */
-
-/**
- * @param {number[][]} matches
- * @return {number[][]}
- */
-var findWinners = function(matches) {
-  const lossCount = new Map();
-
-  for (const [winner, loser] of matches) {
-    lossCount.set(winner, lossCount.get(winner) || 0);
-    lossCount.set(loser, (lossCount.get(loser) || 0) + 1);
-  }
-
-  const noLosses = [];
-  const oneLoss = [];
-
-  for (const [player, losses] of lossCount) {
-    if (losses === 0) noLosses.push(player);
-    else if (losses === 1) oneLoss.push(player);
-  }
-
-  return [
-    noLosses.sort((a, b) => a - b),
-    oneLoss.sort((a, b) => a - b)
-  ];
-};
diff --git a/solutions/2226-maximum-candies-allocated-to-k-children.js b/solutions/2226-maximum-candies-allocated-to-k-children.js
deleted file mode 100644
index 98f340a4..00000000
--- a/solutions/2226-maximum-candies-allocated-to-k-children.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2226. Maximum Candies Allocated to K Children
- * https://leetcode.com/problems/maximum-candies-allocated-to-k-children/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array candies. Each element in the array denotes a pile of
- * candies of size candies[i]. You can divide each pile into any number of sub piles, but you
- * cannot merge two piles together.
- *
- * You are also given an integer k. You should allocate piles of candies to k children such that
- * each child gets the same number of candies. Each child can be allocated candies from only one
- * pile of candies and some piles of candies may go unused.
- *
- * Return the maximum number of candies each child can get.
- */
-
-/**
- * @param {number[]} candies
- * @param {number} k
- * @return {number}
- */
-var maximumCandies = function(candies, k) {
-  let left = 0;
-  let right = 1e7 + 1;
-
-  while (left + 1 !== right) {
-    const middle = Math.floor((left + right) / 2);
-    let piles = 0;
-    for (const candy of candies) {
-      piles += Math.floor(candy / middle);
-    }
-    if (piles >= k) {
-      left = middle;
-    } else {
-      right = middle;
-    }
-  }
-
-  return left;
-};
diff --git a/solutions/2227-encrypt-and-decrypt-strings.js b/solutions/2227-encrypt-and-decrypt-strings.js
deleted file mode 100644
index fd773ffb..00000000
--- a/solutions/2227-encrypt-and-decrypt-strings.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * 2227. Encrypt and Decrypt Strings
- * https://leetcode.com/problems/encrypt-and-decrypt-strings/
- * Difficulty: Hard
- *
- * You are given a character array keys containing unique characters and a string array values
- * containing strings of length 2. You are also given another string array dictionary that
- * contains all permitted original strings after decryption. You should implement a data structure
- * that can encrypt or decrypt a 0-indexed string.
- *
- * A string is encrypted with the following process:
- * 1. For each character c in the string, we find the index i satisfying keys[i] == c in keys.
- * 2. Replace c with values[i] in the string.
- *
- * Note that in case a character of the string is not present in keys, the encryption process cannot
- * be carried out, and an empty string "" is returned.
- *
- * A string is decrypted with the following process:
- * 1. For each substring s of length 2 occurring at an even index in the string, we find an i such
- *    that values[i] == s. If there are multiple valid i, we choose any one of them. This means a
- *    string could have multiple possible strings it can decrypt to.
- * 2. Replace s with keys[i] in the string.
- *
- * Implement the Encrypter class:
- * - Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class
- *   with keys, values, and dictionary.
- * - String encrypt(String word1) Encrypts word1 with the encryption process described above and
- *   returns the encrypted string.
- * - int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that
- *   also appear in dictionary.
- */
-
-/**
- * @param {character[]} keys
- * @param {string[]} values
- * @param {string[]} dictionary
- */
-var Encrypter = function(keys, values, dictionary) {
-  this.encryptMap = new Map();
-  this.validEncryptions = new Map();
-
-  for (let i = 0; i < keys.length; i++) {
-    this.encryptMap.set(keys[i], values[i]);
-  }
-
-  for (const word of dictionary) {
-    const encrypted = this.encrypt(word);
-    if (encrypted !== '') {
-      this.validEncryptions.set(encrypted, (this.validEncryptions.get(encrypted) || 0) + 1);
-    }
-  }
-};
-
-/**
- * @param {string} word1
- * @return {string}
- */
-Encrypter.prototype.encrypt = function(word1) {
-  let result = '';
-
-  for (const char of word1) {
-    if (!this.encryptMap.has(char)) {
-      return '';
-    }
-    result += this.encryptMap.get(char);
-  }
-
-  return result;
-};
-
-/**
- * @param {string} word2
- * @return {number}
- */
-Encrypter.prototype.decrypt = function(word2) {
-  return this.validEncryptions.get(word2) || 0;
-};
diff --git a/solutions/2232-minimize-result-by-adding-parentheses-to-expression.js b/solutions/2232-minimize-result-by-adding-parentheses-to-expression.js
deleted file mode 100644
index f32f3fd9..00000000
--- a/solutions/2232-minimize-result-by-adding-parentheses-to-expression.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * 2232. Minimize Result by Adding Parentheses to Expression
- * https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/
- * Difficulty: Medium
- *
- * You are given a 0-indexed string expression of the form "+" where 
- * and  represent positive integers.
- *
- * Add a pair of parentheses to expression such that after the addition of parentheses,
- * expression is a valid mathematical expression and evaluates to the smallest possible
- * value. The left parenthesis must be added to the left of '+' and the right parenthesis
- * must be added to the right of '+'.
- *
- * Return expression after adding a pair of parentheses such that expression evaluates to the
- * smallest possible value. If there are multiple answers that yield the same result, return
- * any of them.
- *
- * The input has been generated such that the original value of expression, and the value of
- * expression after adding any pair of parentheses that meets the requirements fits within
- * a signed 32-bit integer.
- */
-
-/**
- * @param {string} expression
- * @return {string}
- */
-var minimizeResult = function(expression) {
-  const plusIndex = expression.indexOf('+');
-  const left = expression.slice(0, plusIndex);
-  const right = expression.slice(plusIndex + 1);
-  let minValue = Infinity;
-  let result = '';
-
-  for (let i = 0; i < left.length; i++) {
-    for (let j = 1; j <= right.length; j++) {
-      const leftPrefix = i === 0 ? 1 : parseInt(left.slice(0, i));
-      const leftNum = parseInt(left.slice(i), 10);
-      const rightNum = parseInt(right.slice(0, j), 10);
-      const rightSuffix = j === right.length ? 1 : parseInt(right.slice(j), 10);
-      const value = leftPrefix * (leftNum + rightNum) * rightSuffix;
-
-      if (value < minValue) {
-        minValue = value;
-        result = `${left.slice(0, i)}(${left.slice(i)}+${right.slice(0, j)})${right.slice(j)}`;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2234-maximum-total-beauty-of-the-gardens.js b/solutions/2234-maximum-total-beauty-of-the-gardens.js
deleted file mode 100644
index 54985527..00000000
--- a/solutions/2234-maximum-total-beauty-of-the-gardens.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * 2234. Maximum Total Beauty of the Gardens
- * https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/
- * Difficulty: Hard
- *
- * Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total
- * beauty of all her gardens.
- *
- * You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number
- * of flowers already planted in the ith garden. Flowers that are already planted cannot be
- * removed. You are then given another integer newFlowers, which is the maximum number of
- * flowers that Alice can additionally plant. You are also given the integers target, full,
- * and partial.
- *
- * A garden is considered complete if it has at least target flowers. The total beauty of the
- * gardens is then determined as the sum of the following:
- * - The number of complete gardens multiplied by full.
- * - The minimum number of flowers in any of the incomplete gardens multiplied by partial.
- *   If there are no incomplete gardens, then this value will be 0.
- *
- * Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
- */
-
-/**
- * @param {number[]} flowers
- * @param {number} newFlowers
- * @param {number} target
- * @param {number} full
- * @param {number} partial
- * @return {number}
- */
-var maximumBeauty = function(flowers, newFlowers, target, full, partial) {
-  const n = flowers.length;
-  flowers.sort((a, b) => b - a);
-
-  const suffixCost = Array(n + 1).fill(0);
-  let lastUniqueIndex = n - 1;
-  let minIndex = n - 2;
-
-  for (; minIndex >= 0; --minIndex) {
-    if (flowers[minIndex] >= target) break;
-
-    const flowerDiff = flowers[minIndex] - flowers[minIndex + 1];
-    const gardenCount = n - lastUniqueIndex;
-    suffixCost[minIndex] = suffixCost[minIndex + 1] + flowerDiff * gardenCount;
-
-    if (suffixCost[minIndex] > newFlowers) break;
-
-    if (flowers[minIndex] !== flowers[minIndex - 1]) {
-      lastUniqueIndex = minIndex;
-    }
-  }
-
-  ++minIndex;
-
-  const remainingFlowersForMin = newFlowers - suffixCost[minIndex];
-  const gardenCountForMin = n - minIndex;
-  let minFlowerValue = Math.min(
-    target - 1,
-    flowers[minIndex] + Math.floor(remainingFlowersForMin / gardenCountForMin)
-  );
-
-  let result = 0;
-
-  for (let i = 0; i < n; ++i) {
-    if (flowers[i] >= target) {
-      continue;
-    }
-
-    const currentBeauty = i * full + minFlowerValue * partial;
-    result = Math.max(result, currentBeauty);
-
-    const flowersNeeded = target - flowers[i];
-    if (flowersNeeded > newFlowers) break;
-
-    newFlowers -= flowersNeeded;
-    flowers[i] = target;
-
-    while (
-      minIndex <= i || newFlowers < suffixCost[minIndex]
-      || (minIndex > 0 && flowers[minIndex] === flowers[minIndex - 1])
-    ) {
-      ++minIndex;
-    }
-
-    const updatedRemaining = newFlowers - suffixCost[minIndex];
-    const updatedGardenCount = n - minIndex;
-    minFlowerValue = Math.min(
-      target - 1,
-      flowers[minIndex] + Math.floor(updatedRemaining / updatedGardenCount)
-    );
-  }
-
-  if (flowers[n - 1] >= target) {
-    result = Math.max(result, n * full);
-  }
-
-  return result;
-};
diff --git a/solutions/2236-root-equals-sum-of-children.js b/solutions/2236-root-equals-sum-of-children.js
deleted file mode 100644
index fa9a3cd9..00000000
--- a/solutions/2236-root-equals-sum-of-children.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * 2236. Root Equals Sum of Children
- * https://leetcode.com/problems/root-equals-sum-of-children/
- * Difficulty: Easy
- *
- * You are given the root of a binary tree that consists of exactly 3 nodes: the root, its
- * left child, and its right child.
- *
- * Return true if the value of the root is equal to the sum of the values of its two children,
- * or false otherwise.
- */
-
-/**
- * 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 checkTree = function(root) {
-  return root.val === root.left.val + root.right.val;
-};
diff --git a/solutions/2239-find-closest-number-to-zero.js b/solutions/2239-find-closest-number-to-zero.js
deleted file mode 100644
index 56d07d8e..00000000
--- a/solutions/2239-find-closest-number-to-zero.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * 2239. Find Closest Number to Zero
- * https://leetcode.com/problems/find-closest-number-to-zero/
- * Difficulty: Easy
- *
- * Given an integer array nums of size n, return the number with the value closest to 0 in nums.
- * If there are multiple answers, return the number with the largest value.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var findClosestNumber = function(nums) {
-  let result = nums[0];
-  let minDistance = Math.abs(nums[0]);
-
-  for (const num of nums) {
-    const distance = Math.abs(num);
-    if (distance < minDistance || (distance === minDistance && num > result)) {
-      minDistance = distance;
-      result = num;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2240-number-of-ways-to-buy-pens-and-pencils.js b/solutions/2240-number-of-ways-to-buy-pens-and-pencils.js
deleted file mode 100644
index b55f1cff..00000000
--- a/solutions/2240-number-of-ways-to-buy-pens-and-pencils.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2240. Number of Ways to Buy Pens and Pencils
- * https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/
- * Difficulty: Medium
- *
- * You are given an integer total indicating the amount of money you have. You are also given
- * two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can
- * spend part or all of your money to buy multiple quantities (or none) of each kind of writing
- * utensil.
- *
- * Return the number of distinct ways you can buy some number of pens and pencils.
- */
-
-/**
- * @param {number} total
- * @param {number} cost1
- * @param {number} cost2
- * @return {number}
- */
-var waysToBuyPensPencils = function(total, cost1, cost2) {
-  let result = 0;
-  const maxPens = Math.floor(total / cost1);
-
-  for (let pens = 0; pens <= maxPens; pens++) {
-    const remaining = total - pens * cost1;
-    const pencils = Math.floor(remaining / cost2);
-    result += pencils + 1;
-  }
-
-  return result;
-};
diff --git a/solutions/2241-design-an-atm-machine.js b/solutions/2241-design-an-atm-machine.js
deleted file mode 100644
index 4a5afa87..00000000
--- a/solutions/2241-design-an-atm-machine.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * 2241. Design an ATM Machine
- * https://leetcode.com/problems/design-an-atm-machine/
- * Difficulty: Medium
- *
- * There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and
- * 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or
- * withdraw any amount of money.
- *
- * When withdrawing, the machine prioritizes using banknotes of larger values.
- * - For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote,
- *   and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.
- * - However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote,
- *   then the withdraw request will be rejected because the machine will first try to use the
- *   $500 banknote and then be unable to use banknotes to complete the remaining $100. Note
- *   that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.
- *
- * Implement the ATM class:
- * - ATM() Initializes the ATM object.
- * - void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100,
- *   $200, and $500.
- * - int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that
- *   will be handed to the user in the order $20, $50, $100, $200, and $500, and update the
- *   number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do
- *   not withdraw any banknotes in this case).
- */
-
-var ATM = function() {
-  this.denominations = [20, 50, 100, 200, 500];
-  this.notes = [0, 0, 0, 0, 0];
-};
-
-/**
- * @param {number[]} banknotesCount
- * @return {void}
- */
-ATM.prototype.deposit = function(banknotesCount) {
-  for (let i = 0; i < 5; i++) {
-    this.notes[i] += banknotesCount[i];
-  }
-};
-
-/**
- * @param {number} amount
- * @return {number[]}
- */
-ATM.prototype.withdraw = function(amount) {
-  const result = [0, 0, 0, 0, 0];
-  let remaining = amount;
-
-  for (let i = 4; i >= 0; i--) {
-    const count = Math.min(Math.floor(remaining / this.denominations[i]), this.notes[i]);
-    result[i] = count;
-    remaining -= count * this.denominations[i];
-  }
-
-  if (remaining !== 0) return [-1];
-
-  for (let i = 0; i < 5; i++) {
-    this.notes[i] -= result[i];
-  }
-
-  return result;
-};
diff --git a/solutions/2242-maximum-score-of-a-node-sequence.js b/solutions/2242-maximum-score-of-a-node-sequence.js
deleted file mode 100644
index b64c16ce..00000000
--- a/solutions/2242-maximum-score-of-a-node-sequence.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 2242. Maximum Score of a Node Sequence
- * https://leetcode.com/problems/maximum-score-of-a-node-sequence/
- * Difficulty: Hard
- *
- * There is an undirected graph with n nodes, numbered from 0 to n - 1.
- *
- * You are given a 0-indexed integer array scores of length n where scores[i] denotes the score
- * of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that
- * there exists an undirected edge connecting nodes ai and bi.
- *
- * A node sequence is valid if it meets the following conditions:
- * - There is an edge connecting every pair of adjacent nodes in the sequence.
- * - No node appears more than once in the sequence.
- *
- * The score of a node sequence is defined as the sum of the scores of the nodes in the sequence.
- *
- * Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists,
- * return -1.
- */
-
-/**
- * @param {number[]} scores
- * @param {number[][]} edges
- * @return {number}
- */
-var maximumScore = function(scores, edges) {
-  const n = scores.length;
-  const graph = new Array(n).fill().map(() => []);
-
-  for (const [a, b] of edges) {
-    graph[a].push(b);
-    graph[b].push(a);
-  }
-
-  for (let i = 0; i < n; i++) {
-    graph[i].sort((a, b) => scores[b] - scores[a]);
-    if (graph[i].length > 3) {
-      graph[i] = graph[i].slice(0, 3);
-    }
-  }
-
-  let result = -1;
-  for (const [a, b] of edges) {
-    for (const c of graph[a]) {
-      if (c === b) continue;
-      for (const d of graph[b]) {
-        if (d === a || d === c) continue;
-        result = Math.max(result, scores[a] + scores[b] + scores[c] + scores[d]);
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2243-calculate-digit-sum-of-a-string.js b/solutions/2243-calculate-digit-sum-of-a-string.js
deleted file mode 100644
index 293438ed..00000000
--- a/solutions/2243-calculate-digit-sum-of-a-string.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2243. Calculate Digit Sum of a String
- * https://leetcode.com/problems/calculate-digit-sum-of-a-string/
- * Difficulty: Easy
- *
- * You are given a string s consisting of digits and an integer k.
- *
- * A round can be completed if the length of s is greater than k. In one round, do the following:
- * 1. Divide s into consecutive groups of size k such that the first k characters are in the first
- *    group, the next k characters are in the second group, and so on. Note that the size of the
- *    last group can be smaller than k.
- * 2. Replace each group of s with a string representing the sum of all its digits. For example,
- *    "346" is replaced with "13" because 3 + 4 + 6 = 13.
- * 3. Merge consecutive groups together to form a new string. If the length of the string is greater
- *    than k, repeat from step 1.
- *
- * Return s after all rounds have been completed.
- */
-
-/**
- * @param {string} s
- * @param {number} k
- * @return {string}
- */
-var digitSum = function(s, k) {
-  while (s.length > k) {
-    let next = '';
-    for (let i = 0; i < s.length; i += k) {
-      const group = s.slice(i, i + k);
-      const sum = group.split('').reduce((acc, digit) => acc + Number(digit), 0);
-      next += sum;
-    }
-    s = next;
-  }
-  return s;
-};
diff --git a/solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js b/solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js
deleted file mode 100644
index 7f18ed32..00000000
--- a/solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * 2245. Maximum Trailing Zeros in a Cornered Path
- * https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/
- * Difficulty: Medium
- *
- * You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.
- *
- * A cornered path is defined as a set of adjacent cells with at most one turn. More specifically,
- * the path should exclusively move either horizontally or vertically up to the turn (if there is
- * one), without returning to a previously visited cell. After the turn, the path will then move
- * exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa,
- * also without returning to a previously visited cell.
- *
- * The product of a path is defined as the product of all the values in the path.
- *
- * Return the maximum number of trailing zeros in the product of a cornered path found in grid.
- *
- * Note:
- * - Horizontal movement means moving in either the left or right direction.
- * - Vertical movement means moving in either the up or down direction.
- */
-
-/**
- * @param {number[][]} grid
- * @return {number}
- */
-var maxTrailingZeros = function(grid) {
-  const m = grid.length;
-  const n = grid[0].length;
-
-  function countFactors(num) {
-    let count2 = 0;
-    let count5 = 0;
-
-    while (num % 2 === 0) {
-      count2++;
-      num = Math.floor(num / 2);
-    }
-
-    while (num % 5 === 0) {
-      count5++;
-      num = Math.floor(num / 5);
-    }
-
-    return [count2, count5];
-  }
-
-  const factors = new Array(m).fill().map(() => new Array(n).fill().map(() => [0, 0]));
-  for (let i = 0; i < m; i++) {
-    for (let j = 0; j < n; j++) {
-      factors[i][j] = countFactors(grid[i][j]);
-    }
-  }
-
-  const rowPrefix = new Array(m).fill().map(() => new Array(n + 1).fill().map(() => [0, 0]));
-  for (let i = 0; i < m; i++) {
-    for (let j = 0; j < n; j++) {
-      rowPrefix[i][j + 1][0] = rowPrefix[i][j][0] + factors[i][j][0];
-      rowPrefix[i][j + 1][1] = rowPrefix[i][j][1] + factors[i][j][1];
-    }
-  }
-
-  const colPrefix = new Array(m + 1).fill().map(() => new Array(n).fill().map(() => [0, 0]));
-  for (let j = 0; j < n; j++) {
-    for (let i = 0; i < m; i++) {
-      colPrefix[i + 1][j][0] = colPrefix[i][j][0] + factors[i][j][0];
-      colPrefix[i + 1][j][1] = colPrefix[i][j][1] + factors[i][j][1];
-    }
-  }
-
-  let maxZeros = 0;
-  for (let i = 0; i < m; i++) {
-    for (let j = 0; j < n; j++) {
-      const [count2, count5] = factors[i][j];
-
-      const leftUp = [
-        rowPrefix[i][j][0] + colPrefix[i][j][0],
-        rowPrefix[i][j][1] + colPrefix[i][j][1]
-      ];
-
-      const leftDown = [
-        rowPrefix[i][j][0] + (colPrefix[m][j][0] - colPrefix[i + 1][j][0]),
-        rowPrefix[i][j][1] + (colPrefix[m][j][1] - colPrefix[i + 1][j][1])
-      ];
-
-      const rightUp = [
-        (rowPrefix[i][n][0] - rowPrefix[i][j + 1][0]) + colPrefix[i][j][0],
-        (rowPrefix[i][n][1] - rowPrefix[i][j + 1][1]) + colPrefix[i][j][1]
-      ];
-
-      const rightDown = [
-        (rowPrefix[i][n][0] - rowPrefix[i][j + 1][0])
-          + (colPrefix[m][j][0] - colPrefix[i + 1][j][0]),
-        (rowPrefix[i][n][1] - rowPrefix[i][j + 1][1])
-          + (colPrefix[m][j][1] - colPrefix[i + 1][j][1])
-      ];
-
-      const paths = [
-        [leftUp[0] + count2, leftUp[1] + count5],
-        [leftDown[0] + count2, leftDown[1] + count5],
-        [rightUp[0] + count2, rightUp[1] + count5],
-        [rightDown[0] + count2, rightDown[1] + count5]
-      ];
-
-      for (const [path2, path5] of paths) {
-        maxZeros = Math.max(maxZeros, Math.min(path2, path5));
-      }
-    }
-  }
-
-  return maxZeros;
-};
diff --git a/solutions/2246-longest-path-with-different-adjacent-characters.js b/solutions/2246-longest-path-with-different-adjacent-characters.js
deleted file mode 100644
index 4eb8cb53..00000000
--- a/solutions/2246-longest-path-with-different-adjacent-characters.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * 2246. Longest Path With Different Adjacent Characters
- * https://leetcode.com/problems/longest-path-with-different-adjacent-characters/
- * Difficulty: Hard
- *
- * You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node
- * 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array
- * parent of size n, where parent[i] is the parent of node i. Since node 0 is the root,
- * parent[0] == -1.
- *
- * You are also given a string s of length n, where s[i] is the character assigned to node i.
- *
- * Return the length of the longest path in the tree such that no pair of adjacent nodes on the path
- * have the same character assigned to them.
- */
-
-/**
- * @param {number[]} parent
- * @param {string} s
- * @return {number}
- */
-var longestPath = function(parent, s) {
-  const n = parent.length;
-  const children = Array.from({ length: n }, () => []);
-  let result = 1;
-
-  for (let i = 1; i < n; i++) {
-    children[parent[i]].push(i);
-  }
-
-  findLongest(0);
-
-  return result;
-
-  function findLongest(node) {
-    let longest = 0;
-    let secondLongest = 0;
-
-    for (const child of children[node]) {
-      const length = findLongest(child);
-      if (s[child] !== s[node]) {
-        if (length > longest) {
-          secondLongest = longest;
-          longest = length;
-        } else if (length > secondLongest) {
-          secondLongest = length;
-        }
-      }
-    }
-
-    result = Math.max(result, longest + secondLongest + 1);
-    return longest + 1;
-  }
-};
diff --git a/solutions/2248-intersection-of-multiple-arrays.js b/solutions/2248-intersection-of-multiple-arrays.js
deleted file mode 100644
index fa162656..00000000
--- a/solutions/2248-intersection-of-multiple-arrays.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2248. Intersection of Multiple Arrays
- * https://leetcode.com/problems/intersection-of-multiple-arrays/
- * Difficulty: Easy
- *
- * Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers,
- * return the list of integers that are present in each array of nums sorted in ascending order.
- */
-
-/**
- * @param {number[][]} nums
- * @return {number[]}
- */
-var intersection = function(nums) {
-  const count = new Map();
-
-  for (const array of nums) {
-    for (const num of array) {
-      count.set(num, (count.get(num) || 0) + 1);
-    }
-  }
-
-  const result = [];
-  for (const [num, freq] of count) {
-    if (freq === nums.length) {
-      result.push(num);
-    }
-  }
-
-  return result.sort((a, b) => a - b);
-};
diff --git a/solutions/2249-count-lattice-points-inside-a-circle.js b/solutions/2249-count-lattice-points-inside-a-circle.js
deleted file mode 100644
index 2c762806..00000000
--- a/solutions/2249-count-lattice-points-inside-a-circle.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2249. Count Lattice Points Inside a Circle
- * https://leetcode.com/problems/count-lattice-points-inside-a-circle/
- * Difficulty: Medium
- *
- * Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi)
- * and radius ri of the ith circle drawn on a grid, return the number of lattice points that are
- * present inside at least one circle.
- *
- * Note:
- * - A lattice point is a point with integer coordinates.
- * - Points that lie on the circumference of a circle are also considered to be inside it.
- */
-
-/**
- * @param {number[][]} circles
- * @return {number}
- */
-var countLatticePoints = function(circles) {
-  const set = new Set();
-
-  for (const [x, y, r] of circles) {
-    for (let i = x - r; i <= x + r; i++) {
-      for (let j = y - r; j <= y + r; j++) {
-        if ((x - i) ** 2 + (y - j) ** 2 <= r ** 2) {
-          set.add(`${i},${j}`);
-        }
-      }
-    }
-  }
-
-  return set.size;
-};
diff --git a/solutions/2250-count-number-of-rectangles-containing-each-point.js b/solutions/2250-count-number-of-rectangles-containing-each-point.js
deleted file mode 100644
index 79ed186c..00000000
--- a/solutions/2250-count-number-of-rectangles-containing-each-point.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * 2250. Count Number of Rectangles Containing Each Point
- * https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/
- * Difficulty: Medium
- *
- * You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith
- * rectangle has a length of li and a height of hi. You are also given a 2D integer array points
- * where points[j] = [xj, yj] is a point with coordinates (xj, yj).
- *
- * The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right
- * corner point at (li, hi).
- *
- * Return an integer array count of length points.length where count[j] is the number of rectangles
- * that contain the jth point.
- *
- * The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points
- * that lie on the edges of a rectangle are also considered to be contained by that rectangle.
- */
-
-/**
- * @param {number[][]} rectangles
- * @param {number[][]} points
- * @return {number[]}
- */
-var countRectangles = function(rectangles, points) {
-  const rectByHeight = new Array(101).fill().map(() => []);
-
-  for (const [length, height] of rectangles) {
-    rectByHeight[height].push(length);
-  }
-
-  for (let h = 0; h <= 100; h++) {
-    rectByHeight[h].sort((a, b) => a - b);
-  }
-
-  const result = new Array(points.length).fill(0);
-  for (let i = 0; i < points.length; i++) {
-    const [x, y] = points[i];
-
-    for (let h = y; h <= 100; h++) {
-      const lengths = rectByHeight[h];
-
-      let left = 0;
-      let right = lengths.length - 1;
-      let insertPos = lengths.length;
-
-      while (left <= right) {
-        const mid = Math.floor((left + right) / 2);
-        if (lengths[mid] >= x) {
-          insertPos = mid;
-          right = mid - 1;
-        } else {
-          left = mid + 1;
-        }
-      }
-
-      result[i] += lengths.length - insertPos;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2251-number-of-flowers-in-full-bloom.js b/solutions/2251-number-of-flowers-in-full-bloom.js
deleted file mode 100644
index c9ae393f..00000000
--- a/solutions/2251-number-of-flowers-in-full-bloom.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2251. Number of Flowers in Full Bloom
- * https://leetcode.com/problems/number-of-flowers-in-full-bloom/
- * Difficulty: Hard
- *
- * You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means
- * the ith flower will be in full bloom from starti to endi (inclusive). You are also given a
- * 0-indexed integer array people of size n, where people[i] is the time that the ith person
- * will arrive to see the flowers.
- *
- * Return an integer array answer of size n, where answer[i] is the number of flowers that are
- * in full bloom when the ith person arrives.
- */
-
-/**
- * @param {number[][]} flowers
- * @param {number[]} people
- * @return {number[]}
- */
-var fullBloomFlowers = function(flowers, people) {
-  const events = [];
-  for (const [start, end] of flowers) {
-    events.push([start, 1]);
-    events.push([end + 1, -1]);
-  }
-  events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
-
-  const result = new Array(people.length).fill(0);
-  const peopleWithIndex = people.map((time, index) => [time, index]);
-  peopleWithIndex.sort((a, b) => a[0] - b[0]);
-
-  let bloomCount = 0;
-  let eventIndex = 0;
-  for (const [time, personIndex] of peopleWithIndex) {
-    while (eventIndex < events.length && events[eventIndex][0] <= time) {
-      bloomCount += events[eventIndex][1];
-      eventIndex++;
-    }
-    result[personIndex] = bloomCount;
-  }
-
-  return result;
-};
diff --git a/solutions/2255-count-prefixes-of-a-given-string.js b/solutions/2255-count-prefixes-of-a-given-string.js
deleted file mode 100644
index 25f3ecbf..00000000
--- a/solutions/2255-count-prefixes-of-a-given-string.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * 2255. Count Prefixes of a Given String
- * https://leetcode.com/problems/count-prefixes-of-a-given-string/
- * Difficulty: Easy
- *
- * You are given a string array words and a string s, where words[i] and s comprise only of
- * lowercase English letters.
- *
- * Return the number of strings in words that are a prefix of s.
- *
- * A prefix of a string is a substring that occurs at the beginning of the string. A substring
- * is a contiguous sequence of characters within a string.
- */
-
-/**
- * @param {string[]} words
- * @param {string} s
- * @return {number}
- */
-var countPrefixes = function(words, s) {
-  let result = 0;
-
-  for (const word of words) {
-    if (word.length <= s.length && s.startsWith(word)) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2256-minimum-average-difference.js b/solutions/2256-minimum-average-difference.js
deleted file mode 100644
index 8c7ebdde..00000000
--- a/solutions/2256-minimum-average-difference.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2256. Minimum Average Difference
- * https://leetcode.com/problems/minimum-average-difference/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums of length n.
- *
- * The average difference of the index i is the absolute difference between the average of the
- * first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages
- * should be rounded down to the nearest integer.
- *
- * Return the index with the minimum average difference. If there are multiple such indices,
- * return the smallest one.
- *
- * Note:
- * - The absolute difference of two numbers is the absolute value of their difference.
- * - The average of n elements is the sum of the n elements divided (integer division) by n.
- * - The average of 0 elements is considered to be 0.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minimumAverageDifference = function(nums) {
-  const n = nums.length;
-  let leftSum = 0;
-  let rightSum = nums.reduce((sum, num) => sum + num, 0);
-  let minDiff = Infinity;
-  let result = 0;
-
-  for (let i = 0; i < n; i++) {
-    leftSum += nums[i];
-    rightSum -= nums[i];
-    const leftAvg = Math.floor(leftSum / (i + 1));
-    const rightAvg = i === n - 1 ? 0 : Math.floor(rightSum / (n - i - 1));
-    const diff = Math.abs(leftAvg - rightAvg);
-
-    if (diff < minDiff) {
-      minDiff = diff;
-      result = i;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2257-count-unguarded-cells-in-the-grid.js b/solutions/2257-count-unguarded-cells-in-the-grid.js
deleted file mode 100644
index 87cbde16..00000000
--- a/solutions/2257-count-unguarded-cells-in-the-grid.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * 2257. Count Unguarded Cells in the Grid
- * https://leetcode.com/problems/count-unguarded-cells-in-the-grid/
- * Difficulty: Medium
- *
- * You are given two integers m and n representing a 0-indexed m x n grid. You are also given two
- * 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj]
- * represent the positions of the ith guard and jth wall respectively.
- *
- * A guard can see every cell in the four cardinal directions (north, east, south, or west) starting
- * from their position unless obstructed by a wall or another guard. A cell is guarded if there is
- * at least one guard that can see it.
- *
- * Return the number of unoccupied cells that are not guarded.
- */
-
-/**
- * @param {number} m
- * @param {number} n
- * @param {number[][]} guards
- * @param {number[][]} walls
- * @return {number}
- */
-var countUnguarded = function(m, n, guards, walls) {
-  const grid = Array.from({ length: m }, () => Array(n).fill(0));
-
-  for (const [row, col] of walls) {
-    grid[row][col] = 1;
-  }
-  for (const [row, col] of guards) {
-    grid[row][col] = 2;
-  }
-
-  for (const [row, col] of guards) {
-    for (let i = row - 1; i >= 0 && grid[i][col] !== 1 && grid[i][col] !== 2; i--) {
-      grid[i][col] = 3;
-    }
-    for (let i = row + 1; i < m && grid[i][col] !== 1 && grid[i][col] !== 2; i++) {
-      grid[i][col] = 3;
-    }
-    for (let j = col - 1; j >= 0 && grid[row][j] !== 1 && grid[row][j] !== 2; j--) {
-      grid[row][j] = 3;
-    }
-    for (let j = col + 1; j < n && grid[row][j] !== 1 && grid[row][j] !== 2; j++) {
-      grid[row][j] = 3;
-    }
-  }
-
-  let result = 0;
-  for (let i = 0; i < m; i++) {
-    for (let j = 0; j < n; j++) {
-      if (grid[i][j] === 0) {
-        result++;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2258-escape-the-spreading-fire.js b/solutions/2258-escape-the-spreading-fire.js
deleted file mode 100644
index 7e26720a..00000000
--- a/solutions/2258-escape-the-spreading-fire.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * 2258. Escape the Spreading Fire
- * https://leetcode.com/problems/escape-the-spreading-fire/
- * Difficulty: Hard
- *
- * You are given a 0-indexed 2D integer array grid of size m x n which represents a field.
- * Each cell has one of three values:
- * - 0 represents grass,
- * - 1 represents fire,
- * - 2 represents a wall that you and fire cannot pass through.
- *
- * You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the
- * bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After
- * your move, every fire cell will spread to all adjacent cells that are not walls.
- *
- * Return the maximum number of minutes that you can stay in your initial position before moving
- * while still safely reaching the safehouse. If this is impossible, return -1. If you can always
- * reach the safehouse regardless of the minutes stayed, return 109.
- *
- * Note that even if the fire spreads to the safehouse immediately after you have reached it, it
- * will be counted as safely reaching the safehouse.
- *
- * A cell is adjacent to another cell if the former is directly north, east, south, or west of the
- * latter (i.e., their sides are touching).
- */
-
-/**
- * @param {number[][]} grid
- * @return {number}
- */
-var maximumMinutes = function(grid) {
-  const m = grid.length;
-  const n = grid[0].length;
-  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
-  const MAX_ANSWER = 1000000000;
-
-  function isValid(x, y) {
-    return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] === 0;
-  }
-
-  function calculateFireTime() {
-    const fireTime = new Array(m).fill().map(() => new Array(n).fill(Infinity));
-    const queue = [];
-
-    for (let i = 0; i < m; i++) {
-      for (let j = 0; j < n; j++) {
-        if (grid[i][j] === 1) {
-          queue.push([i, j, 0]);
-          fireTime[i][j] = 0;
-        }
-      }
-    }
-
-    while (queue.length > 0) {
-      const [x, y, time] = queue.shift();
-
-      for (const [dx, dy] of directions) {
-        const nx = x + dx;
-        const ny = y + dy;
-
-        if (isValid(nx, ny) && fireTime[nx][ny] === Infinity) {
-          fireTime[nx][ny] = time + 1;
-          queue.push([nx, ny, time + 1]);
-        }
-      }
-    }
-
-    return fireTime;
-  }
-
-  function canReachSafehouse(delay) {
-    const fireTime = calculateFireTime();
-    const visited = new Array(m).fill().map(() => new Array(n).fill(false));
-    const queue = [[0, 0, delay]];
-    visited[0][0] = true;
-
-    while (queue.length > 0) {
-      const [x, y, time] = queue.shift();
-
-      for (const [dx, dy] of directions) {
-        const nx = x + dx;
-        const ny = y + dy;
-
-        if (!isValid(nx, ny) || visited[nx][ny]) continue;
-
-        if (nx === m - 1 && ny === n - 1) {
-          if (time + 1 <= fireTime[nx][ny] || fireTime[nx][ny] === Infinity) {
-            return true;
-          }
-        }
-
-        if (time + 1 < fireTime[nx][ny]) {
-          visited[nx][ny] = true;
-          queue.push([nx, ny, time + 1]);
-        }
-      }
-    }
-
-    return false;
-  }
-
-  let left = 0;
-  let right = MAX_ANSWER;
-  let result = -1;
-
-  while (left <= right) {
-    const mid = Math.floor((left + right) / 2);
-
-    if (canReachSafehouse(mid)) {
-      result = mid;
-      left = mid + 1;
-    } else {
-      right = mid - 1;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2259-remove-digit-from-number-to-maximize-result.js b/solutions/2259-remove-digit-from-number-to-maximize-result.js
deleted file mode 100644
index d9ee4397..00000000
--- a/solutions/2259-remove-digit-from-number-to-maximize-result.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2259. Remove Digit From Number to Maximize Result
- * https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/
- * Difficulty: Easy
- *
- * You are given a string number representing a positive integer and a character digit.
- *
- * Return the resulting string after removing exactly one occurrence of digit from number such that
- * the value of the resulting string in decimal form is maximized. The test cases are generated such
- * that digit occurs at least once in number.
- */
-
-/**
- * @param {string} number
- * @param {character} digit
- * @return {string}
- */
-var removeDigit = function(number, digit) {
-  let result = '';
-
-  for (let i = 0; i < number.length; i++) {
-    if (number[i] === digit) {
-      const candidate = number.slice(0, i) + number.slice(i + 1);
-      if (candidate > result) {
-        result = candidate;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2260-minimum-consecutive-cards-to-pick-up.js b/solutions/2260-minimum-consecutive-cards-to-pick-up.js
deleted file mode 100644
index 4463e10c..00000000
--- a/solutions/2260-minimum-consecutive-cards-to-pick-up.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * 2260. Minimum Consecutive Cards to Pick Up
- * https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/
- * Difficulty: Medium
- *
- * You are given an integer array cards where cards[i] represents the value of the ith card. A pair
- * of cards are matching if the cards have the same value.
- *
- * Return the minimum number of consecutive cards you have to pick up to have a pair of matching
- * cards among the picked cards. If it is impossible to have matching cards, return -1.
- */
-
-/**
- * @param {number[]} cards
- * @return {number}
- */
-var minimumCardPickup = function(cards) {
-  const map = new Map();
-  let minLength = Infinity;
-
-  for (let i = 0; i < cards.length; i++) {
-    if (map.has(cards[i])) {
-      minLength = Math.min(minLength, i - map.get(cards[i]) + 1);
-    }
-    map.set(cards[i], i);
-  }
-
-  return minLength === Infinity ? -1 : minLength;
-};
diff --git a/solutions/2261-k-divisible-elements-subarrays.js b/solutions/2261-k-divisible-elements-subarrays.js
deleted file mode 100644
index 72d781d1..00000000
--- a/solutions/2261-k-divisible-elements-subarrays.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2261. K Divisible Elements Subarrays
- * https://leetcode.com/problems/k-divisible-elements-subarrays/
- * Difficulty: Medium
- *
- * Given an integer array nums and two integers k and p, return the number of distinct subarrays,
- * which have at most k elements that are divisible by p.
- *
- * Two arrays nums1 and nums2 are said to be distinct if:
- * - They are of different lengths, or
- * - There exists at least one index i where nums1[i] != nums2[i].
- *
- * A subarray is defined as a non-empty contiguous sequence of elements in an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @param {number} p
- * @return {number}
- */
-var countDistinct = function(nums, k, p) {
-  const n = nums.length;
-  const seen = new Set();
-
-  for (let start = 0; start < n; start++) {
-    const subarray = [];
-    let divisibleCount = 0;
-
-    for (let end = start; end < n; end++) {
-      subarray.push(nums[end]);
-      if (nums[end] % p === 0) divisibleCount++;
-
-      if (divisibleCount <= k) {
-        seen.add(subarray.join(','));
-      }
-    }
-  }
-
-  return seen.size;
-};
diff --git a/solutions/2262-total-appeal-of-a-string.js b/solutions/2262-total-appeal-of-a-string.js
deleted file mode 100644
index 20c2e2c3..00000000
--- a/solutions/2262-total-appeal-of-a-string.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2262. Total Appeal of A String
- * https://leetcode.com/problems/total-appeal-of-a-string/
- * Difficulty: Hard
- *
- * The appeal of a string is the number of distinct characters found in the string.
- * - For example, the appeal of "abbca" is 3 because it has 3 distinct characters:
- *   'a', 'b', and 'c'.
- *
- * Given a string s, return the total appeal of all of its substrings.
- *
- * A substring is a contiguous sequence of characters within a string.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var appealSum = function(s) {
-  const n = s.length;
-  const lastSeen = new Array(26).fill(-1);
-  let result = 0;
-
-  for (let i = 0; i < n; i++) {
-    const charIndex = s.charCodeAt(i) - 97;
-    result += (i - lastSeen[charIndex]) * (n - i);
-    lastSeen[charIndex] = i;
-  }
-
-  return result;
-};
diff --git a/solutions/2264-largest-3-same-digit-number-in-string.js b/solutions/2264-largest-3-same-digit-number-in-string.js
deleted file mode 100644
index ef1df3a9..00000000
--- a/solutions/2264-largest-3-same-digit-number-in-string.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 2264. Largest 3-Same-Digit Number in String
- * https://leetcode.com/problems/largest-3-same-digit-number-in-string/
- * Difficulty: Easy
- *
- * You are given a string num representing a large integer. An integer is good if it meets
- * the following conditions:
- * - It is a substring of num with length 3.
- * - It consists of only one unique digit.
- *
- * Return the maximum good integer as a string or an empty string "" if no such integer exists.
- *
- * Note:
- * - A substring is a contiguous sequence of characters within a string.
- * - There may be leading zeroes in num or a good integer.
- */
-
-/**
- * @param {string} num
- * @return {string}
- */
-var largestGoodInteger = function(num) {
-  let result = '';
-
-  for (let i = 0; i <= num.length - 3; i++) {
-    const substring = num.slice(i, i + 3);
-    if (substring[0] === substring[1] && substring[1] === substring[2]) {
-      if (substring > result) {
-        result = substring;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2265-count-nodes-equal-to-average-of-subtree.js b/solutions/2265-count-nodes-equal-to-average-of-subtree.js
deleted file mode 100644
index 2e3f4cb5..00000000
--- a/solutions/2265-count-nodes-equal-to-average-of-subtree.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2265. Count Nodes Equal to Average of Subtree
- * https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/
- * Difficulty: Medium
- *
- * Given the root of a binary tree, return the number of nodes where the value of the node is
- * equal to the average of the values in its subtree.
- *
- * Note:
- * - The average of n elements is the sum of the n elements divided by n and rounded down to
- *   the nearest integer.
- * - A subtree of root is a tree consisting of root and all of its descendants.
- */
-
-/**
- * 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 averageOfSubtree = function(root) {
-  let count = 0;
-  traverse(root);
-  return count;
-
-  function traverse(node) {
-    if (!node) return [0, 0];
-
-    const [leftSum, leftCount] = traverse(node.left);
-    const [rightSum, rightCount] = traverse(node.right);
-    const totalSum = leftSum + rightSum + node.val;
-    const totalCount = leftCount + rightCount + 1;
-
-    if (Math.floor(totalSum / totalCount) === node.val) {
-      count++;
-    }
-
-    return [totalSum, totalCount];
-  }
-};
diff --git a/solutions/2266-count-number-of-texts.js b/solutions/2266-count-number-of-texts.js
deleted file mode 100644
index d2f9cf84..00000000
--- a/solutions/2266-count-number-of-texts.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * 2266. Count Number of Texts
- * https://leetcode.com/problems/count-number-of-texts/
- * Difficulty: Medium
- *
- * Alice is texting Bob using her phone. The mapping of digits to letters is shown in the
- * figure below.
- *
- * In order to add a letter, Alice has to press the key of the corresponding digit i times,
- * where i is the position of the letter in the key.
- * - For example, to add the letter 's', Alice has to press '7' four times. Similarly, to
- *   add the letter 'k', Alice has to press '5' twice.
- * - Note that the digits '0' and '1' do not map to any letters, so Alice does not use them.
- *
- * However, due to an error in transmission, Bob did not receive Alice's text message but
- * received a string of pressed keys instead.
- * - For example, when Alice sent the message "bob", Bob received the string "2266622".
- *
- * Given a string pressedKeys representing the string received by Bob, return the total
- * number of possible text messages Alice could have sent.
- *
- * Since the answer may be very large, return it modulo 109 + 7.
- */
-
-/**
- * @param {string} pressedKeys
- * @return {number}
- */
-var countTexts = function(pressedKeys) {
-  const mod = 1e9 + 7;
-  const maxGroup = pressedKeys.length;
-  const dp = new Array(maxGroup + 1).fill(0);
-  dp[0] = 1;
-
-  const map = new Map([
-    ['2', 3], ['3', 3], ['4', 3], ['5', 3],
-    ['6', 3], ['7', 4], ['8', 3], ['9', 4]
-  ]);
-
-  for (let i = 1; i <= maxGroup; i++) {
-    dp[i] = dp[i - 1];
-    if (i >= 2 && pressedKeys[i - 1] === pressedKeys[i - 2]) {
-      dp[i] = (dp[i] + dp[i - 2]) % mod;
-    }
-    if (i >= 3 && pressedKeys[i - 1] === pressedKeys[i - 2]
-        && pressedKeys[i - 2] === pressedKeys[i - 3]) {
-      dp[i] = (dp[i] + dp[i - 3]) % mod;
-    }
-    if (i >= 4 && pressedKeys[i - 1] === pressedKeys[i - 2]
-        && pressedKeys[i - 2] === pressedKeys[i - 3]
-        && pressedKeys[i - 3] === pressedKeys[i - 4] && map.get(pressedKeys[i - 1]) === 4) {
-      dp[i] = (dp[i] + dp[i - 4]) % mod;
-    }
-  }
-
-  return dp[maxGroup];
-};
diff --git a/solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js b/solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js
deleted file mode 100644
index 8dc163ed..00000000
--- a/solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * 2267. Check if There Is a Valid Parentheses String Path
- * https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/
- * Difficulty: Hard
- *
- * 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 an m x n matrix of parentheses grid. A valid parentheses string path in the grid
- * is a path satisfying all of the following conditions:
- * - The path starts from the upper left cell (0, 0).
- * - The path ends at the bottom-right cell (m - 1, n - 1).
- * - The path only ever moves down or right.
- * - The resulting parentheses string formed by the path is valid.
- *
- * Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
- */
-
-/**
-* @param {character[][]} grid
-* @return {boolean}
-*/
-var hasValidPath = function(grid) {
-  const m = grid.length;
-  const n = grid[0].length;
-
-  if ((m + n - 1) % 2 !== 0) {
-    return false;
-  }
-
-  if (grid[0][0] === ')' || grid[m - 1][n - 1] === '(') {
-    return false;
-  }
-
-  const visited = new Set();
-  return dfs(0, 0, 0);
-
-  function dfs(i, j, openCount) {
-    if (i >= m || j >= n || openCount < 0) {
-      return false;
-    }
-    openCount += grid[i][j] === '(' ? 1 : -1;
-    if (i === m - 1 && j === n - 1) {
-      return openCount === 0;
-    }
-    const key = `${i},${j},${openCount}`;
-    if (visited.has(key)) {
-      return false;
-    }
-    visited.add(key);
-
-    return dfs(i + 1, j, openCount) || dfs(i, j + 1, openCount);
-  }
-};
diff --git a/solutions/2269-find-the-k-beauty-of-a-number.js b/solutions/2269-find-the-k-beauty-of-a-number.js
deleted file mode 100644
index 3027e4d4..00000000
--- a/solutions/2269-find-the-k-beauty-of-a-number.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2269. Find the K-Beauty of a Number
- * https://leetcode.com/problems/find-the-k-beauty-of-a-number/
- * Difficulty: Easy
- *
- * The k-beauty of an integer num is defined as the number of substrings of num when it is
- * read as a string that meet the following conditions:
- * - It has a length of k.
- * - It is a divisor of num.
- *
- * Given integers num and k, return the k-beauty of num.
- *
- * Note:
- * - Leading zeros are allowed.
- * - 0 is not a divisor of any value.
- *
- * A substring is a contiguous sequence of characters in a string.
- */
-
-/**
- * @param {number} num
- * @param {number} k
- * @return {number}
- */
-var divisorSubstrings = function(num, k) {
-  const numStr = num.toString();
-  let result = 0;
-
-  for (let i = 0; i <= numStr.length - k; i++) {
-    const substring = parseInt(numStr.slice(i, i + k));
-    if (substring !== 0 && num % substring === 0) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2270-number-of-ways-to-split-array.js b/solutions/2270-number-of-ways-to-split-array.js
deleted file mode 100644
index f7ac5451..00000000
--- a/solutions/2270-number-of-ways-to-split-array.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2270. Number of Ways to Split Array
- * https://leetcode.com/problems/number-of-ways-to-split-array/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums of length n.
- *
- * nums contains a valid split at index i if the following are true:
- * - The sum of the first i + 1 elements is greater than or equal to the sum of the
- *   last n - i - 1 elements.
- * - There is at least one element to the right of i. That is, 0 <= i < n - 1.
- *
- * Return the number of valid splits in nums.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var waysToSplitArray = function(nums) {
-  const total = nums.reduce((a, b) => a + b);
-  let result = 0;
-
-  for (let i = 0, sum = 0; i < nums.length - 1; i++) {
-    sum += nums[i];
-    if (sum >= total - sum) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2271-maximum-white-tiles-covered-by-a-carpet.js b/solutions/2271-maximum-white-tiles-covered-by-a-carpet.js
deleted file mode 100644
index 0af443fc..00000000
--- a/solutions/2271-maximum-white-tiles-covered-by-a-carpet.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * 2271. Maximum White Tiles Covered by a Carpet
- * https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/
- * Difficulty: Medium
- *
- * You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile
- * j in the range li <= j <= ri is colored white.
- *
- * You are also given an integer carpetLen, the length of a single carpet that can be placed
- * anywhere.
- *
- * Return the maximum number of white tiles that can be covered by the carpet.
- */
-
-/**
- * @param {number[][]} tiles
- * @param {number} carpetLen
- * @return {number}
- */
-var maximumWhiteTiles = function(tiles, carpetLen) {
-  tiles.sort((a, b) => a[0] - b[0]);
-
-  let result = 0;
-  let covered = 0;
-  let j = 0;
-
-  for (let i = 0; i < tiles.length; i++) {
-    const carpetEnd = tiles[i][0] + carpetLen - 1;
-
-    while (j < tiles.length && tiles[j][0] <= carpetEnd) {
-      if (tiles[j][1] <= carpetEnd) {
-        covered += tiles[j][1] - tiles[j][0] + 1;
-        j++;
-      } else {
-        covered += carpetEnd - tiles[j][0] + 1;
-        result = Math.max(result, covered);
-        covered -= carpetEnd - tiles[j][0] + 1;
-        break;
-      }
-    }
-
-    result = Math.max(result, covered);
-
-    if (j === tiles.length) break;
-
-    covered -= tiles[i][1] - tiles[i][0] + 1;
-  }
-
-  return result;
-};
diff --git a/solutions/2272-substring-with-largest-variance.js b/solutions/2272-substring-with-largest-variance.js
deleted file mode 100644
index f11361c2..00000000
--- a/solutions/2272-substring-with-largest-variance.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * 2272. Substring With Largest Variance
- * https://leetcode.com/problems/substring-with-largest-variance/
- * Difficulty: Hard
- *
- * The variance of a string is defined as the largest difference between the number of occurrences
- * of any 2 characters present in the string. Note the two characters may or may not be the same.
- *
- * Given a string s consisting of lowercase English letters only, return the largest variance
- * possible among all substrings of s.
- *
- * A substring is a contiguous sequence of characters within a string.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var largestVariance = function(s) {
-  const map = new Set(s);
-  let result = 0;
-
-  for (const charA of map) {
-    for (const charB of map) {
-      if (charA === charB) continue;
-
-      let countA = 0;
-      let countB = 0;
-      let hasA = false;
-      let hasB = false;
-
-      for (const char of s) {
-        if (char === charA) {
-          countA++;
-          hasA = true;
-        }
-        if (char === charB) {
-          countB++;
-          hasB = true;
-        }
-
-        if (hasA && hasB) {
-          result = Math.max(result, Math.abs(countA - countB));
-        }
-
-        if (countA < countB) {
-          countA = 0;
-          countB = 0;
-          hasA = false;
-          hasB = false;
-        }
-      }
-
-      countA = 0;
-      countB = 0;
-      hasA = false;
-      hasB = false;
-
-      for (let i = s.length - 1; i >= 0; i--) {
-        if (s[i] === charA) {
-          countA++;
-          hasA = true;
-        }
-        if (s[i] === charB) {
-          countB++;
-          hasB = true;
-        }
-
-        if (hasA && hasB) {
-          result = Math.max(result, Math.abs(countA - countB));
-        }
-
-        if (countA < countB) {
-          countA = 0;
-          countB = 0;
-          hasA = false;
-          hasB = false;
-        }
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2273-find-resultant-array-after-removing-anagrams.js b/solutions/2273-find-resultant-array-after-removing-anagrams.js
deleted file mode 100644
index 8e0ef746..00000000
--- a/solutions/2273-find-resultant-array-after-removing-anagrams.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2273. Find Resultant Array After Removing Anagrams
- * https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/
- * Difficulty: Easy
- *
- * You are given a 0-indexed string array words, where words[i] consists of lowercase
- * English letters.
- *
- * In one operation, select any index i such that 0 < i < words.length and words[i - 1] and
- * words[i] are anagrams, and delete words[i] from words. Keep performing this operation as
- * long as you can select an index that satisfies the conditions.
- *
- * Return words after performing all operations. It can be shown that selecting the indices
- * for each operation in any arbitrary order will lead to the same result.
- *
- * An Anagram is a word or phrase formed by rearranging the letters of a different word or
- * phrase using all the original letters exactly once. For example, "dacb" is an anagram of
- * "abdc".
- */
-
-/**
- * @param {string[]} words
- * @return {string[]}
- */
-var removeAnagrams = function(words) {
-  const result = [words[0]];
-
-  for (let i = 1; i < words.length; i++) {
-    const prevSorted = result[result.length - 1].split('').sort().join('');
-    const currSorted = words[i].split('').sort().join('');
-
-    if (prevSorted !== currSorted) {
-      result.push(words[i]);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2274-maximum-consecutive-floors-without-special-floors.js b/solutions/2274-maximum-consecutive-floors-without-special-floors.js
deleted file mode 100644
index 6ccb00f4..00000000
--- a/solutions/2274-maximum-consecutive-floors-without-special-floors.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2274. Maximum Consecutive Floors Without Special Floors
- * https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/
- * Difficulty: Medium
- *
- * Alice manages a company and has rented some floors of a building as office space. Alice has
- * decided some of these floors should be special floors, used for relaxation only.
- *
- * You are given two integers bottom and top, which denote that Alice has rented all the floors
- * from bottom to top (inclusive). You are also given the integer array special, where special[i]
- * denotes a special floor that Alice has designated for relaxation.
- *
- * Return the maximum number of consecutive floors without a special floor.
- */
-
-/**
- * @param {number} bottom
- * @param {number} top
- * @param {number[]} special
- * @return {number}
- */
-var maxConsecutive = function(bottom, top, special) {
-  special.sort((a, b) => a - b);
-  let result = Math.max(special[0] - bottom, top - special[special.length - 1]);
-
-  for (let i = 1; i < special.length; i++) {
-    result = Math.max(result, special[i] - special[i - 1] - 1);
-  }
-
-  return result;
-};
diff --git a/solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js b/solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js
deleted file mode 100644
index e75f68d3..00000000
--- a/solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2275. Largest Combination With Bitwise AND Greater Than Zero
- * https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/
- * Difficulty: Medium
- *
- * The bitwise AND of an array nums is the bitwise AND of all integers in nums.
- * - For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
- * - Also, for nums = [7], the bitwise AND is 7.
- *
- * You are given an array of positive integers candidates. Compute the bitwise AND for all
- * possible combinations of elements in the candidates array.
- *
- * Return the size of the largest combination of candidates with a bitwise AND greater than 0.
- */
-
-/**
- * @param {number[]} candidates
- * @return {number}
- */
-var largestCombination = function(candidates) {
-  const bitCounts = new Array(32).fill(0);
-  let result = 0;
-
-  for (const num of candidates) {
-    for (let i = 0; i < 32; i++) {
-      if (num & (1 << i)) {
-        bitCounts[i]++;
-      }
-    }
-  }
-
-  for (const count of bitCounts) {
-    result = Math.max(result, count);
-  }
-
-  return result;
-};
diff --git a/solutions/2278-percentage-of-letter-in-string.js b/solutions/2278-percentage-of-letter-in-string.js
deleted file mode 100644
index fb3dfdbb..00000000
--- a/solutions/2278-percentage-of-letter-in-string.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * 2278. Percentage of Letter in String
- * https://leetcode.com/problems/percentage-of-letter-in-string/
- * Difficulty: Easy
- *
- * Given a string s and a character letter, return the percentage of characters in s that equal
- * letter rounded down to the nearest whole percent.
- */
-
-/**
- * @param {string} s
- * @param {character} letter
- * @return {number}
- */
-var percentageLetter = function(s, letter) {
-  return Math.floor((s.split('').filter(char => char === letter).length / s.length) * 100);
-};
diff --git a/solutions/2279-maximum-bags-with-full-capacity-of-rocks.js b/solutions/2279-maximum-bags-with-full-capacity-of-rocks.js
deleted file mode 100644
index 77d36c1a..00000000
--- a/solutions/2279-maximum-bags-with-full-capacity-of-rocks.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2279. Maximum Bags With Full Capacity of Rocks
- * https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/
- * Difficulty: Medium
- *
- * You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity
- * and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i]
- * rocks. You are also given an integer additionalRocks, the number of additional rocks you can
- * place in any of the bags.
- *
- * Return the maximum number of bags that could have full capacity after placing the additional
- * rocks in some bags.
- */
-
-/**
- * @param {number[]} capacity
- * @param {number[]} rocks
- * @param {number} additionalRocks
- * @return {number}
- */
-var maximumBags = function(capacity, rocks, additionalRocks) {
-  const remaining = capacity.map((cap, i) => cap - rocks[i]);
-  remaining.sort((a, b) => a - b);
-
-  let result = 0;
-  let rocksLeft = additionalRocks;
-
-  for (const needed of remaining) {
-    if (needed <= rocksLeft) {
-      result++;
-      rocksLeft -= needed;
-    } else {
-      break;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2280-minimum-lines-to-represent-a-line-chart.js b/solutions/2280-minimum-lines-to-represent-a-line-chart.js
deleted file mode 100644
index ff401c32..00000000
--- a/solutions/2280-minimum-lines-to-represent-a-line-chart.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2280. Minimum Lines to Represent a Line Chart
- * https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/
- * Difficulty: Medium
- *
- * You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates
- * the price of the stock on day dayi is pricei. A line chart is created from the array by
- * plotting the points on an XY plane with the X-axis representing the day and the Y-axis
- * representing the price and connecting adjacent points. One such example is shown below.
- *
- * Return the minimum number of lines needed to represent the line chart.
- */
-
-/**
- * @param {number[][]} stockPrices
- * @return {number}
- */
-var minimumLines = function(stockPrices) {
-  if (stockPrices.length <= 2) return stockPrices.length - 1;
-
-  stockPrices.sort((a, b) => a[0] - b[0]);
-
-  let lines = 1;
-  for (let i = 2; i < stockPrices.length; i++) {
-    const [x0, y0] = stockPrices[i - 2];
-    const [x1, y1] = stockPrices[i - 1];
-    const [x2, y2] = stockPrices[i];
-
-    const dx1 = BigInt(x1 - x0);
-    const dy1 = BigInt(y1 - y0);
-    const dx2 = BigInt(x2 - x1);
-    const dy2 = BigInt(y2 - y1);
-
-    if (dy1 * dx2 !== dy2 * dx1) lines++;
-  }
-
-  return lines;
-};
diff --git a/solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js b/solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js
deleted file mode 100644
index ea342877..00000000
--- a/solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * 2283. Check if Number Has Equal Digit Count and Digit Value
- * https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/
- * Difficulty: Easy
- *
- * You are given a 0-indexed string num of length n consisting of digits.
- *
- * Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num,
- * otherwise return false.
- */
-
-/**
- * @param {string} num
- * @return {boolean}
- */
-var digitCount = function(num) {
-  const frequency = new Array(10).fill(0);
-
-  for (const digit of num) {
-    frequency[digit]++;
-  }
-
-  for (let i = 0; i < num.length; i++) {
-    if (frequency[i] !== Number(num[i])) {
-      return false;
-    }
-  }
-
-  return true;
-};
diff --git a/solutions/2284-sender-with-largest-word-count.js b/solutions/2284-sender-with-largest-word-count.js
deleted file mode 100644
index d4c02260..00000000
--- a/solutions/2284-sender-with-largest-word-count.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2284. Sender With Largest Word Count
- * https://leetcode.com/problems/sender-with-largest-word-count/
- * Difficulty: Medium
- *
- * You have a chat log of n messages. You are given two string arrays messages and senders
- * where messages[i] is a message sent by senders[i].
- *
- * A message is list of words that are separated by a single space with no leading or trailing
- * spaces. The word count of a sender is the total number of words sent by the sender. Note
- * that a sender may send more than one message.
- *
- * Return the sender with the largest word count. If there is more than one sender with the
- * largest word count, return the one with the lexicographically largest name.
- *
- * Note:
- * - Uppercase letters come before lowercase letters in lexicographical order.
- * - "Alice" and "alice" are distinct.
- */
-
-/**
- * @param {string[]} messages
- * @param {string[]} senders
- * @return {string}
- */
-var largestWordCount = function(messages, senders) {
-  const map = new Map();
-  let maxWords = 0;
-  let result = '';
-
-  for (let i = 0; i < messages.length; i++) {
-    const wordCount = messages[i].split(' ').length;
-    const sender = senders[i];
-    const totalWords = (map.get(sender) || 0) + wordCount;
-    map.set(sender, totalWords);
-
-    if (totalWords > maxWords || (totalWords === maxWords && sender > result)) {
-      maxWords = totalWords;
-      result = sender;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2287-rearrange-characters-to-make-target-string.js b/solutions/2287-rearrange-characters-to-make-target-string.js
deleted file mode 100644
index 310eb5a2..00000000
--- a/solutions/2287-rearrange-characters-to-make-target-string.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2287. Rearrange Characters to Make Target String
- * https://leetcode.com/problems/rearrange-characters-to-make-target-string/
- * Difficulty: Easy
- *
- * You are given two 0-indexed strings s and target. You can take some letters from s and
- * rearrange them to form new strings.
- *
- * Return the maximum number of copies of target that can be formed by taking letters from
- * s and rearranging them.
- */
-
-/**
- * @param {string} s
- * @param {string} target
- * @return {number}
- */
-var rearrangeCharacters = function(s, target) {
-  const sourceFreq = new Array(26).fill(0);
-  const targetFreq = new Array(26).fill(0);
-
-  for (const char of s) {
-    sourceFreq[char.charCodeAt(0) - 97]++;
-  }
-
-  for (const char of target) {
-    targetFreq[char.charCodeAt(0) - 97]++;
-  }
-
-  let result = Infinity;
-  for (let i = 0; i < 26; i++) {
-    if (targetFreq[i] > 0) {
-      result = Math.min(result, Math.floor(sourceFreq[i] / targetFreq[i]));
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2288-apply-discount-to-prices.js b/solutions/2288-apply-discount-to-prices.js
deleted file mode 100644
index 4645204e..00000000
--- a/solutions/2288-apply-discount-to-prices.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2288. Apply Discount to Prices
- * https://leetcode.com/problems/apply-discount-to-prices/
- * Difficulty: Medium
- *
- * A sentence is a string of single-space separated words where each word can contain digits,
- * lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence
- * of digits preceded by a dollar sign.
- * - For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not.
- *
- * You are given a string sentence representing a sentence and an integer discount. For each
- * word representing a price, apply a discount of discount% on the price and update the word
- * in the sentence. All updated prices should be represented with exactly two decimal places.
- *
- * Return a string representing the modified sentence.
- *
- * Note that all prices will contain at most 10 digits.
- */
-
-/**
- * @param {string} sentence
- * @param {number} discount
- * @return {string}
- */
-var discountPrices = function(sentence, discount) {
-  const words = sentence.split(' ');
-  const discountFactor = 1 - discount / 100;
-
-  for (let i = 0; i < words.length; i++) {
-    if (words[i].startsWith('$') && /^[0-9]+$/.test(words[i].slice(1))) {
-      const price = parseInt(words[i].slice(1)) * discountFactor;
-      words[i] = `$${price.toFixed(2)}`;
-    }
-  }
-
-  return words.join(' ');
-};
diff --git a/solutions/2293-min-max-game.js b/solutions/2293-min-max-game.js
deleted file mode 100644
index b6952f9c..00000000
--- a/solutions/2293-min-max-game.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2293. Min Max Game
- * https://leetcode.com/problems/min-max-game/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums whose length is a power of 2.
- *
- * Apply the following algorithm on nums:
- * 1. Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed
- *    integer array newNums of length n / 2.
- * 2. For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as
- *    min(nums[2 * i], nums[2 * i + 1]).
- * 3. For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as
- *    max(nums[2 * i], nums[2 * i + 1]).
- * 4. Replace the array nums with newNums.
- * 5. Repeat the entire process starting from step 1.
- *
- * Return the last number that remains in nums after applying the algorithm.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minMaxGame = function(nums) {
-  let array = nums.slice();
-
-  while (array.length > 1) {
-    const newArray = new Array(array.length / 2);
-
-    for (let i = 0; i < newArray.length; i++) {
-      if (i % 2 === 0) {
-        newArray[i] = Math.min(array[2 * i], array[2 * i + 1]);
-      } else {
-        newArray[i] = Math.max(array[2 * i], array[2 * i + 1]);
-      }
-    }
-
-    array = newArray;
-  }
-
-  return array[0];
-};
diff --git a/solutions/2294-partition-array-such-that-maximum-difference-is-k.js b/solutions/2294-partition-array-such-that-maximum-difference-is-k.js
deleted file mode 100644
index 06cad3ae..00000000
--- a/solutions/2294-partition-array-such-that-maximum-difference-is-k.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 2294. Partition Array Such That Maximum Difference Is K
- * https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/
- * Difficulty: Medium
- *
- * You are given an integer array nums and an integer k. You may partition nums into one or more
- * subsequences such that each element in nums appears in exactly one of the subsequences.
- *
- * Return the minimum number of subsequences needed such that the difference between the maximum
- * and minimum values in each subsequence is at most k.
- *
- * A subsequence is a sequence that can be derived from another sequence by deleting some or no
- * elements without changing the order of the remaining elements.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var partitionArray = function(nums, k) {
-  nums.sort((a, b) => a - b);
-  let result = 1;
-  let minValue = nums[0];
-
-  for (let i = 1; i < nums.length; i++) {
-    if (nums[i] - minValue > k) {
-      result++;
-      minValue = nums[i];
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2295-replace-elements-in-an-array.js b/solutions/2295-replace-elements-in-an-array.js
deleted file mode 100644
index de3bbad0..00000000
--- a/solutions/2295-replace-elements-in-an-array.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2295. Replace Elements in an Array
- * https://leetcode.com/problems/replace-elements-in-an-array/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array nums that consists of n distinct positive integers.
- * Apply m operations to this array, where in the ith operation you replace the number
- * operations[i][0] with operations[i][1].
- *
- * It is guaranteed that in the ith operation:
- * - operations[i][0] exists in nums.
- * - operations[i][1] does not exist in nums.
- *
- * Return the array obtained after applying all the operations.
- */
-
-/**
- * @param {number[]} nums
- * @param {number[][]} operations
- * @return {number[]}
- */
-var arrayChange = function(nums, operations) {
-  const map = new Map();
-  for (let i = 0; i < nums.length; i++) {
-    map.set(nums[i], i);
-  }
-
-  for (const [oldVal, newVal] of operations) {
-    const index = map.get(oldVal);
-    nums[index] = newVal;
-    map.set(newVal, index);
-    map.delete(oldVal);
-  }
-
-  return nums;
-};
diff --git a/solutions/2296-design-a-text-editor.js b/solutions/2296-design-a-text-editor.js
deleted file mode 100644
index 6020598d..00000000
--- a/solutions/2296-design-a-text-editor.js
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * 2296. Design a Text Editor
- * https://leetcode.com/problems/design-a-text-editor/
- * Difficulty: Hard
- *
- * Design a text editor with a cursor that can do the following:
- * - Add text to where the cursor is.
- * - Delete text from where the cursor is (simulating the backspace key).
- * - Move the cursor either left or right.
- *
- * When deleting text, only characters to the left of the cursor will be deleted. The cursor
- * will also remain within the actual text and cannot be moved beyond it. More formally,
- * we have that 0 <= cursor.position <= currentText.length always holds.
- *
- * Implement the TextEditor class:
- * - TextEditor() Initializes the object with empty text.
- * - void addText(string text) Appends text to where the cursor is. The cursor ends to the
- *   right of text.
- * - int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number
- *   of characters actually deleted.
- * - string cursorLeft(int k) Moves the cursor to the left k times. Returns the last
- *   min(10, len) characters to the left of the cursor, where len is the number of characters
- *   to the left of the cursor.
- * - string cursorRight(int k) Moves the cursor to the right k times. Returns the last
- *   min(10, len) characters to the left of the cursor, where len is the number of characters
- *   to the left of the cursor.
- */
-
-var TextEditor = function() {
-  this.left = [];
-  this.right = [];
-};
-
-/**
- * @param {string} text
- * @return {void}
- */
-TextEditor.prototype.addText = function(text) {
-  for (const char of text) {
-    this.left.push(char);
-  }
-};
-
-/**
- * @param {number} k
- * @return {number}
- */
-TextEditor.prototype.deleteText = function(k) {
-  const deleteCount = Math.min(k, this.left.length);
-  for (let i = 0; i < deleteCount; i++) {
-    this.left.pop();
-  }
-  return deleteCount;
-};
-
-/**
- * @param {number} k
- * @return {string}
- */
-TextEditor.prototype.cursorLeft = function(k) {
-  for (let i = 0; i < k && this.left.length; i++) {
-    this.right.push(this.left.pop());
-  }
-  const start = Math.max(0, this.left.length - 10);
-  return this.left.slice(start).join('');
-};
-
-/**
- * @param {number} k
- * @return {string}
- */
-TextEditor.prototype.cursorRight = function(k) {
-  for (let i = 0; i < k && this.right.length; i++) {
-    this.left.push(this.right.pop());
-  }
-  const start = Math.max(0, this.left.length - 10);
-  return this.left.slice(start).join('');
-};
diff --git a/solutions/2299-strong-password-checker-ii.js b/solutions/2299-strong-password-checker-ii.js
deleted file mode 100644
index f96fac07..00000000
--- a/solutions/2299-strong-password-checker-ii.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2299. Strong Password Checker II
- * https://leetcode.com/problems/strong-password-checker-ii/
- * Difficulty: Easy
- *
- * A password is said to be strong if it satisfies all the following criteria:
- * - It has at least 8 characters.
- * - It contains at least one lowercase letter.
- * - It contains at least one uppercase letter.
- * - It contains at least one digit.
- * - It contains at least one special character. The special characters are the characters
- *   in the following string: "!@#$%^&*()-+".
- * - It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates
- *   this condition, but "aba" does not).
- *
- * Given a string password, return true if it is a strong password. Otherwise, return false.
- */
-
-/**
- * @param {string} password
- * @return {boolean}
- */
-var strongPasswordCheckerII = function(password) {
-  if (password.length < 8) return false;
-
-  let hasLower = false;
-  let hasUpper = false;
-  let hasDigit = false;
-  let hasSpecial = false;
-  const set = new Set(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+']);
-
-  for (let i = 0; i < password.length; i++) {
-    if (i > 0 && password[i] === password[i - 1]) return false;
-
-    const char = password[i];
-    if (/[a-z]/.test(char)) hasLower = true;
-    else if (/[A-Z]/.test(char)) hasUpper = true;
-    else if (/\d/.test(char)) hasDigit = true;
-    else if (set.has(char)) hasSpecial = true;
-  }
-
-  return hasLower && hasUpper && hasDigit && hasSpecial;
-};
diff --git a/solutions/2301-match-substring-after-replacement.js b/solutions/2301-match-substring-after-replacement.js
deleted file mode 100644
index fc7e5a91..00000000
--- a/solutions/2301-match-substring-after-replacement.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * 2301. Match Substring After Replacement
- * https://leetcode.com/problems/match-substring-after-replacement/
- * Difficulty: Hard
- *
- * You are given two strings s and sub. You are also given a 2D character array mappings where
- * mappings[i] = [oldi, newi] indicates that you may perform the following operation any number
- * of times:
- * - Replace a character oldi of sub with newi.
- *
- * Each character in sub cannot be replaced more than once.
- *
- * Return true if it is possible to make sub a substring of s by replacing zero or more characters
- * according to mappings. Otherwise, return false.
- *
- * A substring is a contiguous non-empty sequence of characters within a string.
- */
-
-/**
- * @param {string} s
- * @param {string} sub
- * @param {character[][]} mappings
- * @return {boolean}
- */
-var matchReplacement = function(s, sub, mappings) {
-  const map = new Map();
-
-  for (const [oldChar, newChar] of mappings) {
-    if (!map.has(oldChar)) {
-      map.set(oldChar, new Set());
-    }
-    map.get(oldChar).add(newChar);
-  }
-
-  const subLen = sub.length;
-  for (let i = 0; i <= s.length - subLen; i++) {
-    let isValid = true;
-    for (let j = 0; j < subLen; j++) {
-      const sChar = s[i + j];
-      const subChar = sub[j];
-      if (sChar !== subChar && (!map.has(subChar) || !map.get(subChar).has(sChar))) {
-        isValid = false;
-        break;
-      }
-    }
-    if (isValid) return true;
-  }
-
-  return false;
-};
diff --git a/solutions/2302-count-subarrays-with-score-less-than-k.js b/solutions/2302-count-subarrays-with-score-less-than-k.js
deleted file mode 100644
index 29aa7eda..00000000
--- a/solutions/2302-count-subarrays-with-score-less-than-k.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 2302. Count Subarrays With Score Less Than K
- * https://leetcode.com/problems/count-subarrays-with-score-less-than-k/
- * Difficulty: Hard
- *
- * The score of an array is defined as the product of its sum and its length.
- * - For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.
- *
- * Given a positive integer array nums and an integer k, return the number of non-empty subarrays
- * of nums whose score is strictly less than k.
- *
- * A subarray is a contiguous sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var countSubarrays = function(nums, k) {
-  let result = 0;
-  let currentSum = 0;
-  let left = 0;
-
-  for (let right = 0; right < nums.length; right++) {
-    currentSum += nums[right];
-    while (currentSum * (right - left + 1) >= k) {
-      currentSum -= nums[left];
-      left++;
-    }
-    result += right - left + 1;
-  }
-
-  return result;
-};
diff --git a/solutions/2303-calculate-amount-paid-in-taxes.js b/solutions/2303-calculate-amount-paid-in-taxes.js
deleted file mode 100644
index 6944f54b..00000000
--- a/solutions/2303-calculate-amount-paid-in-taxes.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2303. Calculate Amount Paid in Taxes
- * https://leetcode.com/problems/calculate-amount-paid-in-taxes/
- * Difficulty: Easy
- *
- * You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti]
- * means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti.
- * The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).
- *
- * Tax is calculated as follows:
- * - The first upper0 dollars earned are taxed at a rate of percent0.
- * - The next upper1 - upper0 dollars earned are taxed at a rate of percent1.
- * - The next upper2 - upper1 dollars earned are taxed at a rate of percent2.
- * - And so on.
- *
- * You are given an integer income representing the amount of money you earned. Return the
- * amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer
- * will be accepted.
- */
-
-/**
- * @param {number[][]} brackets
- * @param {number} income
- * @return {number}
- */
-var calculateTax = function(brackets, income) {
-  let result = 0;
-  let previousUpper = 0;
-
-  for (const [upper, percent] of brackets) {
-    if (income > previousUpper) {
-      const taxable = Math.min(income, upper) - previousUpper;
-      result += taxable * (percent / 100);
-      previousUpper = upper;
-    } else {
-      break;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2304-minimum-path-cost-in-a-grid.js b/solutions/2304-minimum-path-cost-in-a-grid.js
deleted file mode 100644
index eb1f10c4..00000000
--- a/solutions/2304-minimum-path-cost-in-a-grid.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 2304. Minimum Path Cost in a Grid
- * https://leetcode.com/problems/minimum-path-cost-in-a-grid/
- * Difficulty: Medium
- *
- * You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from
- * 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row.
- * That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells
- * (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from
- * cells in the last row.
- *
- * Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n,
- * where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j
- * of the next row. The cost of moving from cells in the last row of grid can be ignored.
- *
- * The cost of a path in grid is the sum of all values of cells visited plus the sum of costs
- * of all the moves made. Return the minimum cost of a path that starts from any cell in the
- * first row and ends at any cell in the last row.
- */
-
-/**
- * @param {number[][]} grid
- * @param {number[][]} moveCost
- * @return {number}
- */
-var minPathCost = function(grid, moveCost) {
-  const m = grid.length;
-  const n = grid[0].length;
-  const dp = Array.from({ length: m }, () => new Array(n).fill(Infinity));
-
-  for (let j = 0; j < n; j++) {
-    dp[0][j] = grid[0][j];
-  }
-
-  for (let i = 0; i < m - 1; i++) {
-    for (let j = 0; j < n; j++) {
-      const value = grid[i][j];
-      for (let k = 0; k < n; k++) {
-        dp[i + 1][k] = Math.min(
-          dp[i + 1][k],
-          dp[i][j] + grid[i + 1][k] + moveCost[value][k]
-        );
-      }
-    }
-  }
-
-  return Math.min(...dp[m - 1]);
-};
diff --git a/solutions/2305-fair-distribution-of-cookies.js b/solutions/2305-fair-distribution-of-cookies.js
deleted file mode 100644
index dffcb4a4..00000000
--- a/solutions/2305-fair-distribution-of-cookies.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2305. Fair Distribution of Cookies
- * https://leetcode.com/problems/fair-distribution-of-cookies/
- * Difficulty: Medium
- *
- * You are given an integer array cookies, where cookies[i] denotes the number of cookies in the
- * ith bag. You are also given an integer k that denotes the number of children to distribute
- * all the bags of cookies to. All the cookies in the same bag must go to the same child and
- * cannot be split up.
- *
- * The unfairness of a distribution is defined as the maximum total cookies obtained by a single
- * child in the distribution.
- *
- * Return the minimum unfairness of all distributions.
- */
-
-/**
- * @param {number[]} cookies
- * @param {number} k
- * @return {number}
- */
-var distributeCookies = function(cookies, k) {
-  const distribution = new Array(k).fill(0);
-  let result = Infinity;
-
-  distribute(0);
-
-  return result;
-
-  function distribute(index) {
-    if (index === cookies.length) {
-      result = Math.min(result, Math.max(...distribution));
-      return;
-    }
-
-    for (let i = 0; i < k; i++) {
-      distribution[i] += cookies[index];
-      if (distribution[i] < result) {
-        distribute(index + 1);
-      }
-      distribution[i] -= cookies[index];
-
-      if (distribution[i] === 0) break;
-    }
-  }
-};
diff --git a/solutions/2306-naming-a-company.js b/solutions/2306-naming-a-company.js
deleted file mode 100644
index bef81dfe..00000000
--- a/solutions/2306-naming-a-company.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2306. Naming a Company
- * https://leetcode.com/problems/naming-a-company/
- * Difficulty: Hard
- *
- * You are given an array of strings ideas that represents a list of names to be used in the
- * process of naming a company. The process of naming a company is as follows:
- * 1. Choose 2 distinct names from ideas, call them ideaA and ideaB.
- * 2. Swap the first letters of ideaA and ideaB with each other.
- * 3. If both of the new names are not found in the original ideas, then the name ideaA ideaB
- *    (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
- * 4. Otherwise, it is not a valid name.
- *
- * Return the number of distinct valid names for the company.
- */
-
-/**
- * @param {string[]} ideas
- * @return {number}
- */
-var distinctNames = function(ideas) {
-  const groups = Array.from({ length: 26 }, () => new Set());
-  let result = 0;
-
-  for (const idea of ideas) {
-    groups[idea.charCodeAt(0) - 97].add(idea.slice(1));
-  }
-
-  for (let i = 0; i < 25; i++) {
-    for (let j = i + 1; j < 26; j++) {
-      const mutualCount = [...groups[i]].filter(suffix => groups[j].has(suffix)).length;
-      result += 2 * (groups[i].size - mutualCount) * (groups[j].size - mutualCount);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2309-greatest-english-letter-in-upper-and-lower-case.js b/solutions/2309-greatest-english-letter-in-upper-and-lower-case.js
deleted file mode 100644
index b86b8f8b..00000000
--- a/solutions/2309-greatest-english-letter-in-upper-and-lower-case.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2309. Greatest English Letter in Upper and Lower Case
- * https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/
- * Difficulty: Easy
- *
- * Given a string of English letters s, return the greatest English letter which occurs as both
- * a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such
- * letter exists, return an empty string.
- *
- * An English letter b is greater than another letter a if b appears after a in the English
- * alphabet.
- */
-
-/**
- * @param {string} s
- * @return {string}
- */
-var greatestLetter = function(s) {
-  const lowerSet = new Set();
-  const upperSet = new Set();
-
-  for (const char of s) {
-    if (char >= 'a' && char <= 'z') {
-      lowerSet.add(char);
-    } else {
-      upperSet.add(char.toLowerCase());
-    }
-  }
-
-  let maxLetter = '';
-  for (const char of lowerSet) {
-    if (upperSet.has(char) && char > maxLetter) {
-      maxLetter = char;
-    }
-  }
-
-  return maxLetter.toUpperCase();
-};
diff --git a/solutions/2312-selling-pieces-of-wood.js b/solutions/2312-selling-pieces-of-wood.js
deleted file mode 100644
index 6edab3a0..00000000
--- a/solutions/2312-selling-pieces-of-wood.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2312. Selling Pieces of Wood
- * https://leetcode.com/problems/selling-pieces-of-wood/
- * Difficulty: Hard
- *
- * You are given two integers m and n that represent the height and width of a rectangular piece
- * of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei]
- * indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.
- *
- * To cut a piece of wood, you must make a vertical or horizontal cut across the entire height
- * or width of the piece to split it into two smaller pieces. After cutting a piece of wood into
- * some number of smaller pieces, you can sell pieces according to prices. You may sell multiple
- * pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood
- * makes a difference, so you cannot rotate a piece to swap its height and width.
- *
- * Return the maximum money you can earn after cutting an m x n piece of wood.
- *
- * Note that you can cut the piece of wood as many times as you want.
- */
-
-/**
- * @param {number} m
- * @param {number} n
- * @param {number[][]} prices
- * @return {number}
- */
-var sellingWood = function(m, n, prices) {
-  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
-
-  for (const [h, w, price] of prices) {
-    dp[h][w] = price;
-  }
-
-  for (let i = 1; i <= m; i++) {
-    for (let j = 1; j <= n; j++) {
-      for (let k = 1; k < i; k++) {
-        dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]);
-      }
-      for (let k = 1; k < j; k++) {
-        dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]);
-      }
-    }
-  }
-
-  return dp[m][n];
-};
diff --git a/solutions/2315-count-asterisks.js b/solutions/2315-count-asterisks.js
deleted file mode 100644
index 650055eb..00000000
--- a/solutions/2315-count-asterisks.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2315. Count Asterisks
- * https://leetcode.com/problems/count-asterisks/
- * Difficulty: Easy
- *
- * You are given a string s, where every two consecutive vertical bars '|' are grouped into
- * a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair,
- * and so forth.
- *
- * Return the number of '*' in s, excluding the '*' between each pair of '|'.
- *
- * Note that each '|' will belong to exactly one pair.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var countAsterisks = function(s) {
-  let isInsidePair = false;
-  let result = 0;
-
-  for (const char of s) {
-    if (char === '|') {
-      isInsidePair = !isInsidePair;
-    } else if (char === '*' && !isInsidePair) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js b/solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js
deleted file mode 100644
index 4de0c07b..00000000
--- a/solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
- * https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/
- * Difficulty: Medium
- *
- * You are given an integer n. There is an undirected graph with n nodes, numbered from 0
- * to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that
- * there exists an undirected edge connecting nodes ai and bi.
- *
- * Return the number of pairs of different nodes that are unreachable from each other.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} edges
- * @return {number}
- */
-var countPairs = function(n, edges) {
-  const graph = Array.from({ length: n }, () => []);
-  for (const [a, b] of edges) {
-    graph[a].push(b);
-    graph[b].push(a);
-  }
-
-  const visited = new Array(n).fill(false);
-  let result = 0;
-
-  let totalNodes = 0;
-  for (let node = 0; node < n; node++) {
-    if (!visited[node]) {
-      const componentSize = exploreComponent(node);
-      result += totalNodes * componentSize;
-      totalNodes += componentSize;
-    }
-  }
-
-  return result;
-
-  function exploreComponent(node) {
-    if (visited[node]) return 0;
-    visited[node] = true;
-    let size = 1;
-    for (const neighbor of graph[node]) {
-      size += exploreComponent(neighbor);
-    }
-    return size;
-  }
-};
diff --git a/solutions/2317-maximum-xor-after-operations.js b/solutions/2317-maximum-xor-after-operations.js
deleted file mode 100644
index 7049675b..00000000
--- a/solutions/2317-maximum-xor-after-operations.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * 2317. Maximum XOR After Operations
- * https://leetcode.com/problems/maximum-xor-after-operations/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums. In one operation, select any non-negative
- * integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).
- *
- * Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.
- *
- * Return the maximum possible bitwise XOR of all elements of nums after applying the operation
- * any number of times.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var maximumXOR = function(nums) {
-  let maxXor = 0;
-
-  for (const num of nums) {
-    maxXor |= num;
-  }
-
-  return maxXor;
-};
diff --git a/solutions/2318-number-of-distinct-roll-sequences.js b/solutions/2318-number-of-distinct-roll-sequences.js
deleted file mode 100644
index 5f67f5c0..00000000
--- a/solutions/2318-number-of-distinct-roll-sequences.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 2318. Number of Distinct Roll Sequences
- * https://leetcode.com/problems/number-of-distinct-roll-sequences/
- * Difficulty: Hard
- *
- * You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number
- * of distinct sequences of rolls possible such that the following conditions are satisfied:
- * 1. The greatest common divisor of any adjacent values in the sequence is equal to 1.
- * 2. There is at least a gap of 2 rolls between equal valued rolls. More formally, if the
- *    value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.
- *
- * Return the total number of distinct sequences possible. Since the answer may be very large,
- * return it modulo 109 + 7.
- *
- * Two sequences are considered distinct if at least one element is different.
- */
-
-/**
- * @param {number} n
- * @return {number}
- */
-var distinctSequences = function(n) {
-  const MOD = 1e9 + 7;
-  const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
-
-  const dp = new Array(n + 1)
-    .fill()
-    .map(() => new Array(7).fill().map(() => new Array(7).fill(0)));
-
-  for (let i = 1; i <= 6; i++) {
-    dp[1][i][0] = 1;
-  }
-
-  for (let len = 2; len <= n; len++) {
-    for (let curr = 1; curr <= 6; curr++) {
-      for (let prev = 0; prev <= 6; prev++) {
-        for (let prevPrev = 0; prevPrev <= 6; prevPrev++) {
-          if (dp[len - 1][prev][prevPrev] === 0) continue;
-          if (curr === prev || curr === prevPrev) continue;
-          if (prev !== 0 && gcd(curr, prev) !== 1) continue;
-          dp[len][curr][prev] = (dp[len][curr][prev] + dp[len - 1][prev][prevPrev]) % MOD;
-        }
-      }
-    }
-  }
-
-  let result = 0;
-  for (let curr = 1; curr <= 6; curr++) {
-    for (let prev = 0; prev <= 6; prev++) {
-      result = (result + dp[n][curr][prev]) % MOD;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2319-check-if-matrix-is-x-matrix.js b/solutions/2319-check-if-matrix-is-x-matrix.js
deleted file mode 100644
index ee45ca42..00000000
--- a/solutions/2319-check-if-matrix-is-x-matrix.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2319. Check if Matrix Is X-Matrix
- * https://leetcode.com/problems/check-if-matrix-is-x-matrix/
- * Difficulty: Easy
- *
- * A square matrix is said to be an X-Matrix if both of the following conditions hold:
- * 1. All the elements in the diagonals of the matrix are non-zero.
- * 2. All other elements are 0.
- *
- * Given a 2D integer array grid of size n x n representing a square matrix, return true if grid
- * is an X-Matrix. Otherwise, return false.
- */
-
-/**
- * @param {number[][]} grid
- * @return {boolean}
- */
-var checkXMatrix = function(grid) {
-  const size = grid.length;
-
-  for (let row = 0; row < size; row++) {
-    for (let col = 0; col < size; col++) {
-      const isDiagonal = row === col || row + col === size - 1;
-      const isNonZero = grid[row][col] !== 0;
-
-      if (isDiagonal && !isNonZero) return false;
-      if (!isDiagonal && isNonZero) return false;
-    }
-  }
-
-  return true;
-};
diff --git a/solutions/2320-count-number-of-ways-to-place-houses.js b/solutions/2320-count-number-of-ways-to-place-houses.js
deleted file mode 100644
index 39c28f72..00000000
--- a/solutions/2320-count-number-of-ways-to-place-houses.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 2320. Count Number of Ways to Place Houses
- * https://leetcode.com/problems/count-number-of-ways-to-place-houses/
- * Difficulty: Medium
- *
- * There is a street with n * 2 plots, where there are n plots on each side of the street. The plots
- * on each side are numbered from 1 to n. On each plot, a house can be placed.
- *
- * Return the number of ways houses can be placed such that no two houses are adjacent to each other
- * on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.
- *
- * Note that if a house is placed on the ith plot on one side of the street, a house can also be
- * placed on the ith plot on the other side of the street.
- */
-
-/**
- * @param {number} n
- * @return {number}
- */
-var countHousePlacements = function(n) {
-  const MOD = 1e9 + 7;
-  let empty = 1n;
-  let house = 1n;
-
-  for (let i = 2; i <= n; i++) {
-    const nextEmpty = (empty + house) % BigInt(MOD);
-    const nextHouse = empty;
-    empty = nextEmpty;
-    house = nextHouse;
-  }
-
-  const sideWays = (empty + house) % BigInt(MOD);
-  return Number((sideWays * sideWays) % BigInt(MOD));
-};
diff --git a/solutions/2321-maximum-score-of-spliced-array.js b/solutions/2321-maximum-score-of-spliced-array.js
deleted file mode 100644
index 3ecf5068..00000000
--- a/solutions/2321-maximum-score-of-spliced-array.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * 2321. Maximum Score Of Spliced Array
- * https://leetcode.com/problems/maximum-score-of-spliced-array/
- * Difficulty: Hard
- *
- * You are given two 0-indexed integer arrays nums1 and nums2, both of length n.
- *
- * You can choose two integers left and right where 0 <= left <= right < n and swap the subarray
- * nums1[left...right] with the subarray nums2[left...right].
- * - For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and
- *   right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].
- *
- * You may choose to apply the mentioned operation once or not do anything.
- *
- * The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum
- * of all the elements in the array arr.
- *
- * Return the maximum possible score.
- *
- * A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the
- * subarray that contains the elements of nums between indices left and right (inclusive).
- */
-
-/**
- * @param {number[]} nums1
- * @param {number[]} nums2
- * @return {number}
- */
-var maximumsSplicedArray = function(nums1, nums2) {
-  const length = nums1.length;
-  let sum1 = 0;
-  let sum2 = 0;
-
-  for (let i = 0; i < length; i++) {
-    sum1 += nums1[i];
-    sum2 += nums2[i];
-  }
-
-  let maxGain1 = 0;
-  let maxGain2 = 0;
-  let currGain1 = 0;
-  let currGain2 = 0;
-
-  for (let i = 0; i < length; i++) {
-    currGain1 = Math.max(0, currGain1 + nums2[i] - nums1[i]);
-    currGain2 = Math.max(0, currGain2 + nums1[i] - nums2[i]);
-    maxGain1 = Math.max(maxGain1, currGain1);
-    maxGain2 = Math.max(maxGain2, currGain2);
-  }
-
-  return Math.max(sum1 + maxGain1, sum2 + maxGain2);
-};
diff --git a/solutions/2322-minimum-score-after-removals-on-a-tree.js b/solutions/2322-minimum-score-after-removals-on-a-tree.js
deleted file mode 100644
index 4b0b6cd0..00000000
--- a/solutions/2322-minimum-score-after-removals-on-a-tree.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * 2322. Minimum Score After Removals on a Tree
- * https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/
- * Difficulty: Hard
- *
- * There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
- *
- * You are given a 0-indexed integer array nums of length n where nums[i] represents the value
- * of the ith node. You are also given a 2D integer array edges of length n - 1 where
- * edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
- *
- * Remove two distinct edges of the tree to form three connected components. For a pair of
- * removed edges, the following steps are defined:
- * 1. Get the XOR of all the values of the nodes for each of the three components respectively.
- * 2. The difference between the largest XOR value and the smallest XOR value is the score of
- *    the pair.
- * 3. For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3].
- *    The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR
- *    value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.
- *
- * Return the minimum score of any possible pair of edge removals on the given tree.
- */
-
-/**
-* @param {number[]} nums
-* @param {number[][]} edges
-* @return {number}
-*/
-var minimumScore = function(nums, edges) {
-  const n = nums.length;
-  const graph = Array.from({ length: n }, () => []);
-
-  for (const [a, b] of edges) {
-    graph[a].push(b);
-    graph[b].push(a);
-  }
-
-  const totalXor = nums.reduce((acc, num) => acc ^ num, 0);
-
-  const subtreeXor = new Array(n).fill(0);
-
-  const tin = new Array(n);
-  const tout = new Array(n);
-  let timer = 0;
-
-  function dfs(node, parent) {
-    tin[node] = timer++;
-    subtreeXor[node] = nums[node];
-
-    for (const neighbor of graph[node]) {
-      if (neighbor !== parent) {
-        dfs(neighbor, node);
-        subtreeXor[node] ^= subtreeXor[neighbor];
-      }
-    }
-
-    tout[node] = timer++;
-  }
-
-  dfs(0, -1);
-
-  function isAncestor(a, b) {
-    return tin[a] <= tin[b] && tout[a] >= tout[b];
-  }
-
-  let result = Infinity;
-  for (let i = 0; i < n - 1; i++) {
-    for (let j = i + 1; j < n - 1; j++) {
-      const edge1 = edges[i];
-      const edge2 = edges[j];
-
-      let node1;
-      if (isAncestor(edge1[0], edge1[1])) {
-        node1 = edge1[1];
-      } else {
-        node1 = edge1[0];
-      }
-      const subtree1 = subtreeXor[node1];
-
-      let node2;
-      if (isAncestor(edge2[0], edge2[1])) {
-        node2 = edge2[1];
-      } else {
-        node2 = edge2[0];
-      }
-      const subtree2 = subtreeXor[node2];
-
-      let component1;
-      let component2;
-      let component3;
-      if (isAncestor(node1, node2)) {
-        component1 = subtree2;
-        component2 = subtree1 ^ component1;
-        component3 = totalXor ^ subtree1;
-      } else if (isAncestor(node2, node1)) {
-        component1 = subtree1;
-        component2 = subtree2 ^ component1;
-        component3 = totalXor ^ subtree2;
-      } else {
-        component1 = subtree1;
-        component2 = subtree2;
-        component3 = totalXor ^ component1 ^ component2;
-      }
-
-      const maxXor = Math.max(component1, component2, component3);
-      const minXor = Math.min(component1, component2, component3);
-      result = Math.min(result, maxXor - minXor);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2325-decode-the-message.js b/solutions/2325-decode-the-message.js
deleted file mode 100644
index bde90e23..00000000
--- a/solutions/2325-decode-the-message.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2325. Decode the Message
- * https://leetcode.com/problems/decode-the-message/
- * Difficulty: Easy
- *
- * You are given the strings key and message, which represent a cipher key and a secret message,
- * respectively. The steps to decode message are as follows:
- * 1. Use the first appearance of all 26 lowercase English letters in key as the order of the
- *    substitution table.
- * 2. Align the substitution table with the regular English alphabet.
- * 3. Each letter in message is then substituted using the table.
- * 4. Spaces ' ' are transformed to themselves.
- * 5. For example, given key = "happy boy" (actual key would have at least one instance of each
- *    letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b',
- *    'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').
- *
- * Return the decoded message.
- */
-
-/**
- * @param {string} key
- * @param {string} message
- * @return {string}
- */
-var decodeMessage = function(key, message) {
-  const substitution = new Map();
-  let alphabetIndex = 0;
-
-  for (const char of key) {
-    if (char !== ' ' && !substitution.has(char)) {
-      substitution.set(char, String.fromCharCode(97 + alphabetIndex++));
-    }
-  }
-
-  let result = '';
-  for (const char of message) {
-    result += char === ' ' ? ' ' : substitution.get(char);
-  }
-
-  return result;
-};
diff --git a/solutions/2326-spiral-matrix-iv.js b/solutions/2326-spiral-matrix-iv.js
deleted file mode 100644
index 1fa98050..00000000
--- a/solutions/2326-spiral-matrix-iv.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * 2326. Spiral Matrix IV
- * https://leetcode.com/problems/spiral-matrix-iv/
- * Difficulty: Medium
- *
- * You are given two integers m and n, which represent the dimensions of a matrix.
- *
- * You are also given the head of a linked list of integers.
- *
- * Generate an m x n matrix that contains the integers in the linked list presented in spiral
- * order (clockwise), starting from the top-left of the matrix. If there are remaining empty
- * spaces, fill them with -1.
- *
- * Return the generated matrix.
- */
-
-/**
- * Definition for singly-linked list.
- * function ListNode(val, next) {
- *     this.val = (val===undefined ? 0 : val)
- *     this.next = (next===undefined ? null : next)
- * }
- */
-/**
- * @param {number} m
- * @param {number} n
- * @param {ListNode} head
- * @return {number[][]}
- */
-var spiralMatrix = function(m, n, head) {
-  const matrix = new Array(m).fill().map(() => new Array(n).fill(-1));
-  let top = 0;
-  let bottom = m - 1;
-  let left = 0;
-  let right = n - 1;
-  let current = head;
-
-  while (top <= bottom && left <= right && current) {
-    for (let col = left; col <= right && current; col++) {
-      matrix[top][col] = current.val;
-      current = current.next;
-    }
-    top++;
-
-    for (let row = top; row <= bottom && current; row++) {
-      matrix[row][right] = current.val;
-      current = current.next;
-    }
-    right--;
-
-    for (let col = right; col >= left && current; col--) {
-      matrix[bottom][col] = current.val;
-      current = current.next;
-    }
-    bottom--;
-
-    for (let row = bottom; row >= top && current; row--) {
-      matrix[row][left] = current.val;
-      current = current.next;
-    }
-    left++;
-  }
-
-  return matrix;
-};
diff --git a/solutions/2328-number-of-increasing-paths-in-a-grid.js b/solutions/2328-number-of-increasing-paths-in-a-grid.js
deleted file mode 100644
index f239c80c..00000000
--- a/solutions/2328-number-of-increasing-paths-in-a-grid.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * 2328. Number of Increasing Paths in a Grid
- * https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/
- * Difficulty: Hard
- *
- * You are given an m x n integer matrix grid, where you can move from a cell to any adjacent
- * cell in all 4 directions.
- *
- * Return the number of strictly increasing paths in the grid such that you can start from any
- * cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.
- *
- * Two paths are considered different if they do not have exactly the same sequence of visited
- * cells.
- */
-
-/**
- * @param {number[][]} grid
- * @return {number}
- */
-var countPaths = function(grid) {
-  const MOD = 1e9 + 7;
-  const rows = grid.length;
-  const cols = grid[0].length;
-  const cache = new Array(rows).fill().map(() => new Array(cols).fill(0));
-  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
-
-  function explore(row, col) {
-    if (cache[row][col]) return cache[row][col];
-
-    let paths = 1;
-    for (const [dr, dc] of directions) {
-      const newRow = row + dr;
-      const newCol = col + dc;
-      if (
-        newRow >= 0 && newRow < rows && newCol >= 0
-        && newCol < cols && grid[newRow][newCol] > grid[row][col]
-      ) {
-        paths = (paths + explore(newRow, newCol)) % MOD;
-      }
-    }
-
-    return cache[row][col] = paths;
-  }
-
-  let total = 0;
-  for (let i = 0; i < rows; i++) {
-    for (let j = 0; j < cols; j++) {
-      total = (total + explore(i, j)) % MOD;
-    }
-  }
-
-  return total;
-};
diff --git a/solutions/2331-evaluate-boolean-binary-tree.js b/solutions/2331-evaluate-boolean-binary-tree.js
deleted file mode 100644
index d6f4d851..00000000
--- a/solutions/2331-evaluate-boolean-binary-tree.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 2331. Evaluate Boolean Binary Tree
- * https://leetcode.com/problems/evaluate-boolean-binary-tree/
- * Difficulty: Easy
- *
- * You are given the root of a full binary tree with the following properties:
- * - Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.
- * - Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents
- *   the boolean AND.
- *
- * The evaluation of a node is as follows:
- * - If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.
- * - Otherwise, evaluate the node's two children and apply the boolean operation of its value with
- *   the children's evaluations.
- *
- * Return the boolean result of evaluating the root node.
- *
- * A full binary tree is a binary tree where each node has either 0 or 2 children.
- *
- * A leaf node is a node that has zero 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 {boolean}
- */
-var evaluateTree = function(root) {
-  if (!root.left && !root.right) return root.val === 1;
-
-  const leftResult = evaluateTree(root.left);
-  const rightResult = evaluateTree(root.right);
-
-  return root.val === 2 ? leftResult || rightResult : leftResult && rightResult;
-};
diff --git a/solutions/2334-subarray-with-elements-greater-than-varying-threshold.js b/solutions/2334-subarray-with-elements-greater-than-varying-threshold.js
deleted file mode 100644
index 789a5ff3..00000000
--- a/solutions/2334-subarray-with-elements-greater-than-varying-threshold.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2334. Subarray With Elements Greater Than Varying Threshold
- * https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/
- * Difficulty: Hard
- *
- * You are given an integer array nums and an integer threshold.
- *
- * Find any subarray of nums of length k such that every element in the subarray is greater
- * than threshold / k.
- *
- * Return the size of any such subarray. If there is no such subarray, return -1.
- *
- * A subarray is a contiguous non-empty sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} threshold
- * @return {number}
- */
-var validSubarraySize = function(nums, threshold) {
-  const n = nums.length;
-  const stack = [];
-  const nextSmaller = new Array(n).fill(n);
-  const prevSmaller = new Array(n).fill(-1);
-
-  for (let i = 0; i < n; i++) {
-    while (stack.length && nums[stack[stack.length - 1]] >= nums[i]) {
-      nextSmaller[stack.pop()] = i;
-    }
-    if (stack.length) prevSmaller[i] = stack[stack.length - 1];
-    stack.push(i);
-  }
-
-  for (let i = 0; i < n; i++) {
-    const k = nextSmaller[i] - prevSmaller[i] - 1;
-    if (k > 0 && nums[i] > threshold / k) {
-      return k;
-    }
-  }
-
-  return -1;
-};
diff --git a/solutions/2337-move-pieces-to-obtain-a-string.js b/solutions/2337-move-pieces-to-obtain-a-string.js
deleted file mode 100644
index 64f29a9a..00000000
--- a/solutions/2337-move-pieces-to-obtain-a-string.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2337. Move Pieces to Obtain a String
- * https://leetcode.com/problems/move-pieces-to-obtain-a-string/
- * Difficulty: Medium
- *
- * You are given two strings start and target, both of length n. Each string consists only of
- * the characters 'L', 'R', and '_' where:
- * - The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if
- *   there is a blank space directly to its left, and a piece 'R' can move to the right only if
- *   there is a blank space directly to its right.
- * - The character '_' represents a blank space that can be occupied by any of the 'L' or 'R'
- *   pieces.
- *
- * Return true if it is possible to obtain the string target by moving the pieces of the string
- * start any number of times. Otherwise, return false.
- */
-
-/**
- * @param {string} start
- * @param {string} target
- * @return {boolean}
- */
-var canChange = function(start, target) {
-  const pieces = [];
-  const targetPieces = [];
-
-  for (let i = 0; i < start.length; i++) {
-    if (start[i] !== '_') pieces.push([start[i], i]);
-    if (target[i] !== '_') targetPieces.push([target[i], i]);
-  }
-
-  if (pieces.length !== targetPieces.length) return false;
-
-  for (let i = 0; i < pieces.length; i++) {
-    if (pieces[i][0] !== targetPieces[i][0]) return false;
-    if (pieces[i][0] === 'L' && pieces[i][1] < targetPieces[i][1]) return false;
-    if (pieces[i][0] === 'R' && pieces[i][1] > targetPieces[i][1]) return false;
-  }
-
-  return true;
-};
diff --git a/solutions/2338-count-the-number-of-ideal-arrays.js b/solutions/2338-count-the-number-of-ideal-arrays.js
deleted file mode 100644
index dab7d4bc..00000000
--- a/solutions/2338-count-the-number-of-ideal-arrays.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * 2338. Count the Number of Ideal Arrays
- * https://leetcode.com/problems/count-the-number-of-ideal-arrays/
- * Difficulty: Hard
- *
- * You are given two integers n and maxValue, which are used to describe an ideal array.
- *
- * A 0-indexed integer array arr of length n is considered ideal if the following conditions hold:
- * - Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.
- * - Every arr[i] is divisible by arr[i - 1], for 0 < i < n.
- *
- * Return the number of distinct ideal arrays of length n. Since the answer may be very large,
- * return it modulo 109 + 7.
- */
-
-/**
- * @param {number} n
- * @param {number} maxValue
- * @return {number}
- */
-var idealArrays = function(n, maxValue) {
-  const MOD = 1e9 + 7;
-  const MAX_N = 10010;
-  const MAX_P = 15;
-
-  const c = Array.from({ length: MAX_N + MAX_P }, () =>
-    new Array(MAX_P + 1).fill(0)
-  );
-  const sieve = new Array(MAX_N).fill(0);
-  const ps = Array.from({ length: MAX_N }, () => []);
-
-  for (let i = 2; i < MAX_N; i++) {
-    if (sieve[i] === 0) {
-      for (let j = i; j < MAX_N; j += i) {
-        if (sieve[j] === 0) {
-          sieve[j] = i;
-        }
-      }
-    }
-  }
-
-  for (let i = 2; i < MAX_N; i++) {
-    let x = i;
-    while (x > 1) {
-      const p = sieve[x];
-      let cnt = 0;
-      while (x % p === 0) {
-        x = Math.floor(x / p);
-        cnt++;
-      }
-      ps[i].push(cnt);
-    }
-  }
-
-  c[0][0] = 1;
-  for (let i = 1; i < MAX_N + MAX_P; i++) {
-    c[i][0] = 1;
-    for (let j = 1; j <= Math.min(i, MAX_P); j++) {
-      c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % MOD;
-    }
-  }
-
-  let ans = 0n;
-  for (let x = 1; x <= maxValue; x++) {
-    let mul = 1n;
-    for (const p of ps[x]) {
-      mul = (mul * BigInt(c[n + p - 1][p])) % BigInt(MOD);
-    }
-    ans = (ans + mul) % BigInt(MOD);
-  }
-
-  return Number(ans);
-};
diff --git a/solutions/2341-maximum-number-of-pairs-in-array.js b/solutions/2341-maximum-number-of-pairs-in-array.js
deleted file mode 100644
index 2cdcce2c..00000000
--- a/solutions/2341-maximum-number-of-pairs-in-array.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 2341. Maximum Number of Pairs in Array
- * https://leetcode.com/problems/maximum-number-of-pairs-in-array/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums. In one operation, you may do the following:
- * - Choose two integers in nums that are equal.
- * - Remove both integers from nums, forming a pair.
- *
- * The operation is done on nums as many times as possible.
- *
- * Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that
- * are formed and answer[1] is the number of leftover integers in nums after doing the operation
- * as many times as possible.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var numberOfPairs = function(nums) {
-  const frequency = new Map();
-  let pairs = 0;
-
-  for (const num of nums) {
-    frequency.set(num, (frequency.get(num) || 0) + 1);
-    if (frequency.get(num) === 2) {
-      pairs++;
-      frequency.set(num, 0);
-    }
-  }
-
-  const leftovers = nums.length - pairs * 2;
-  return [pairs, leftovers];
-};
diff --git a/solutions/2347-best-poker-hand.js b/solutions/2347-best-poker-hand.js
deleted file mode 100644
index 586dcda2..00000000
--- a/solutions/2347-best-poker-hand.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2347. Best Poker Hand
- * https://leetcode.com/problems/best-poker-hand/
- * Difficulty: Easy
- *
- * You are given an integer array ranks and a character array suits. You have 5 cards where the
- * ith card has a rank of ranks[i] and a suit of suits[i].
- *
- * The following are the types of poker hands you can make from best to worst:
- * 1. "Flush": Five cards of the same suit.
- * 2. "Three of a Kind": Three cards of the same rank.
- * 3. "Pair": Two cards of the same rank.
- * 4. "High Card": Any single card.
- *
- * Return a string representing the best type of poker hand you can make with the given cards.
- *
- * Note that the return values are case-sensitive.
- */
-
-/**
- * @param {number[]} ranks
- * @param {character[]} suits
- * @return {string}
- */
-var bestHand = function(ranks, suits) {
-  const suitCount = new Map();
-  const rankCount = new Map();
-
-  for (let i = 0; i < 5; i++) {
-    suitCount.set(suits[i], (suitCount.get(suits[i]) || 0) + 1);
-    rankCount.set(ranks[i], (rankCount.get(ranks[i]) || 0) + 1);
-  }
-
-  if (suitCount.size === 1) return 'Flush';
-
-  const maxRankCount = Math.max(...rankCount.values());
-  if (maxRankCount >= 3) return 'Three of a Kind';
-  if (maxRankCount === 2) return 'Pair';
-
-  return 'High Card';
-};
diff --git a/solutions/2348-number-of-zero-filled-subarrays.js b/solutions/2348-number-of-zero-filled-subarrays.js
deleted file mode 100644
index fa93ec19..00000000
--- a/solutions/2348-number-of-zero-filled-subarrays.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * 2348. Number of Zero-Filled Subarrays
- * https://leetcode.com/problems/number-of-zero-filled-subarrays/
- * Difficulty: Medium
- *
- * Given an integer array nums, return the number of subarrays filled with 0.
- *
- * A subarray is a contiguous non-empty sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var zeroFilledSubarray = function(nums) {
-  let result = 0;
-  let zeroCount = 0;
-
-  for (const num of nums) {
-    if (num === 0) {
-      zeroCount++;
-      result += zeroCount;
-    } else {
-      zeroCount = 0;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2350-shortest-impossible-sequence-of-rolls.js b/solutions/2350-shortest-impossible-sequence-of-rolls.js
deleted file mode 100644
index ea27a604..00000000
--- a/solutions/2350-shortest-impossible-sequence-of-rolls.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2350. Shortest Impossible Sequence of Rolls
- * https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/
- * Difficulty: Hard
- *
- * You are given an integer array rolls of length n and an integer k. You roll a k sided dice
- * numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
- *
- * Return the length of the shortest sequence of rolls so that there's no such subsequence in rolls.
- *
- * A sequence of rolls of length len is the result of rolling a k sided dice len times.
- */
-
-/**
- * @param {number[]} rolls
- * @param {number} k
- * @return {number}
- */
-var shortestSequence = function(rolls, k) {
-  const set = new Set();
-  let sequences = 0;
-
-  for (const roll of rolls) {
-    set.add(roll);
-    if (set.size === k) {
-      sequences++;
-      set.clear();
-    }
-  }
-
-  return sequences + 1;
-};
diff --git a/solutions/2351-first-letter-to-appear-twice.js b/solutions/2351-first-letter-to-appear-twice.js
deleted file mode 100644
index b5fff8f5..00000000
--- a/solutions/2351-first-letter-to-appear-twice.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * 2351. First Letter to Appear Twice
- * https://leetcode.com/problems/first-letter-to-appear-twice/
- * Difficulty: Easy
- *
- * Given a string s consisting of lowercase English letters, return the first letter
- * to appear twice.
- *
- * Note:
- * - A letter a appears twice before another letter b if the second occurrence of a is before
- *   the second occurrence of b.
- * - s will contain at least one letter that appears twice.
- */
-
-/**
- * @param {string} s
- * @return {character}
- */
-var repeatedCharacter = function(s) {
-  const set = new Set();
-
-  for (const char of s) {
-    if (set.has(char)) return char;
-    set.add(char);
-  }
-};
diff --git a/solutions/2354-number-of-excellent-pairs.js b/solutions/2354-number-of-excellent-pairs.js
deleted file mode 100644
index bf60424a..00000000
--- a/solutions/2354-number-of-excellent-pairs.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2354. Number of Excellent Pairs
- * https://leetcode.com/problems/number-of-excellent-pairs/
- * Difficulty: Hard
- *
- * You are given a 0-indexed positive integer array nums and a positive integer k.
- *
- * A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:
- * - Both the numbers num1 and num2 exist in the array nums.
- * - The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal
- *   to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.
- *
- * Return the number of distinct excellent pairs.
- *
- * Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example,
- * (1, 2) and (2, 1) are distinct.
- *
- * Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least
- * one occurrence of num1 in the array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var countExcellentPairs = function(nums, k) {
-  const map = new Map();
-  const set = new Set(nums);
-
-  for (const num of set) {
-    const bits = num.toString(2).split('0').join('').length;
-    map.set(bits, (map.get(bits) || 0) + 1);
-  }
-
-  let result = 0;
-  for (const [i, countI] of map) {
-    for (const [j, countJ] of map) {
-      if (i + j >= k) {
-        result += countI * countJ;
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2358-maximum-number-of-groups-entering-a-competition.js b/solutions/2358-maximum-number-of-groups-entering-a-competition.js
deleted file mode 100644
index 2637927b..00000000
--- a/solutions/2358-maximum-number-of-groups-entering-a-competition.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2358. Maximum Number of Groups Entering a Competition
- * https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/
- * Difficulty: Medium
- *
- * You are given a positive integer array grades which represents the grades of students in
- * a university. You would like to enter all these students into a competition in ordered
- * non-empty groups, such that the ordering meets the following conditions:
- * - The sum of the grades of students in the ith group is less than the sum of the grades of
- *   students in the (i + 1)th group, for all groups (except the last).
- * - The total number of students in the ith group is less than the total number of students
- *   in the (i + 1)th group, for all groups (except the last).
- *
- * Return the maximum number of groups that can be formed.
- */
-
-/**
- * @param {number[]} grades
- * @return {number}
- */
-var maximumGroups = function(grades) {
-  let result = 0;
-  let studentsUsed = 0;
-
-  while (studentsUsed + result + 1 <= grades.length) {
-    result++;
-    studentsUsed += result;
-  }
-
-  return result;
-};
diff --git a/solutions/2359-find-closest-node-to-given-two-nodes.js b/solutions/2359-find-closest-node-to-given-two-nodes.js
deleted file mode 100644
index c048153f..00000000
--- a/solutions/2359-find-closest-node-to-given-two-nodes.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 2359. Find Closest Node to Given Two Nodes
- * https://leetcode.com/problems/find-closest-node-to-given-two-nodes/
- * Difficulty: Medium
- *
- * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at
- * most one outgoing edge.
- *
- * The graph is represented with a given 0-indexed array edges of size n, indicating that there
- * is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then
- * edges[i] == -1.
- *
- * You are also given two integers node1 and node2.
- *
- * Return the index of the node that can be reached from both node1 and node2, such that the maximum
- * between the distance from node1 to that node, and from node2 to that node is minimized. If there
- * are multiple answers, return the node with the smallest index, and if no possible answer exists,
- * return -1.
- *
- * Note that edges may contain cycles.
- */
-
-/**
- * @param {number[]} edges
- * @param {number} node1
- * @param {number} node2
- * @return {number}
- */
-var closestMeetingNode = function(edges, node1, node2) {
-  const n = edges.length;
-  const dist1 = new Array(n).fill(Infinity);
-  const dist2 = new Array(n).fill(Infinity);
-
-  computeDistances(node1, dist1);
-  computeDistances(node2, dist2);
-
-  let minDist = Infinity;
-  let result = -1;
-
-  for (let i = 0; i < n; i++) {
-    if (dist1[i] !== Infinity && dist2[i] !== Infinity) {
-      const maxDist = Math.max(dist1[i], dist2[i]);
-      if (maxDist < minDist) {
-        minDist = maxDist;
-        result = i;
-      }
-    }
-  }
-
-  return result;
-
-  function computeDistances(start, distances) {
-    let current = start;
-    let steps = 0;
-    const visited = new Set();
-
-    while (current !== -1 && !visited.has(current)) {
-      distances[current] = steps++;
-      visited.add(current);
-      current = edges[current];
-    }
-  }
-};
diff --git a/solutions/2360-longest-cycle-in-a-graph.js b/solutions/2360-longest-cycle-in-a-graph.js
deleted file mode 100644
index 6da96750..00000000
--- a/solutions/2360-longest-cycle-in-a-graph.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * 2360. Longest Cycle in a Graph
- * https://leetcode.com/problems/longest-cycle-in-a-graph/
- * Difficulty: Hard
- *
- * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at
- * most one outgoing edge.
- *
- * The graph is represented with a given 0-indexed array edges of size n, indicating that
- * there is a directed edge from node i to node edges[i]. If there is no outgoing edge from
- * node i, then edges[i] == -1.
- *
- * Return the length of the longest cycle in the graph. If no cycle exists, return -1.
- *
- * A cycle is a path that starts and ends at the same node.
- */
-
-/**
- * @param {number[]} edges
- * @return {number}
- */
-var longestCycle = function(edges) {
-  const n = edges.length;
-  const visited = new Array(n).fill(false);
-  let result = -1;
-
-  for (let i = 0; i < n; i++) {
-    if (!visited[i]) {
-      findCycle(i, 0, []);
-    }
-  }
-
-  return result;
-
-  function findCycle(node, steps, path) {
-    if (visited[node]) {
-      const cycleStart = path.indexOf(node);
-      if (cycleStart !== -1) {
-        result = Math.max(result, steps - cycleStart);
-      }
-      return;
-    }
-
-    visited[node] = true;
-    path.push(node);
-
-    if (edges[node] !== -1) {
-      findCycle(edges[node], steps + 1, path);
-    }
-
-    path.pop();
-  }
-};
diff --git a/solutions/2363-merge-similar-items.js b/solutions/2363-merge-similar-items.js
deleted file mode 100644
index da16c478..00000000
--- a/solutions/2363-merge-similar-items.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2363. Merge Similar Items
- * https://leetcode.com/problems/merge-similar-items/
- * Difficulty: Easy
- *
- * You are given two 2D integer arrays, items1 and items2, representing two sets of items.
- * Each array items has the following properties:
- * - items[i] = [valuei, weighti] where valuei represents the value and weighti represents
- *   the weight of the ith item.
- * - The value of each item in items is unique.
- *
- * Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of
- * weights of all items with value valuei.
- *
- * Note: ret should be returned in ascending order by value.
- */
-
-/**
- * @param {number[][]} items1
- * @param {number[][]} items2
- * @return {number[][]}
- */
-var mergeSimilarItems = function(items1, items2) {
-  const map = new Map();
-
-  for (const [value, weight] of items1) {
-    map.set(value, (map.get(value) || 0) + weight);
-  }
-
-  for (const [value, weight] of items2) {
-    map.set(value, (map.get(value) || 0) + weight);
-  }
-
-  const merged = [];
-  for (const [value, weight] of map) {
-    merged.push([value, weight]);
-  }
-
-  return merged.sort((a, b) => a[0] - b[0]);
-};
diff --git a/solutions/2365-task-scheduler-ii.js b/solutions/2365-task-scheduler-ii.js
deleted file mode 100644
index 166fdfdf..00000000
--- a/solutions/2365-task-scheduler-ii.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2365. Task Scheduler II
- * https://leetcode.com/problems/task-scheduler-ii/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array of positive integers tasks, representing tasks that need
- * to be completed in order, where tasks[i] represents the type of the ith task.
- *
- * You are also given a positive integer space, which represents the minimum number of days
- * that must pass after the completion of a task before another task of the same type can be
- * performed.
- *
- * Each day, until all tasks have been completed, you must either:
- * - Complete the next task from tasks, or
- * - Take a break.
- *
- * Return the minimum number of days needed to complete all tasks.
- */
-
-/**
- * @param {number[]} tasks
- * @param {number} space
- * @return {number}
- */
-var taskSchedulerII = function(tasks, space) {
-  const map = new Map();
-  let result = 0;
-
-  for (const task of tasks) {
-    result++;
-    if (map.has(task)) {
-      const lastDay = map.get(task);
-      if (result - lastDay <= space) {
-        result = lastDay + space + 1;
-      }
-    }
-    map.set(task, result);
-  }
-
-  return result;
-};
diff --git a/solutions/2366-minimum-replacements-to-sort-the-array.js b/solutions/2366-minimum-replacements-to-sort-the-array.js
deleted file mode 100644
index 422d21f6..00000000
--- a/solutions/2366-minimum-replacements-to-sort-the-array.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2366. Minimum Replacements to Sort the Array
- * https://leetcode.com/problems/minimum-replacements-to-sort-the-array/
- * Difficulty: Hard
- *
- * You are given a 0-indexed integer array nums. In one operation you can replace any element
- * of the array with any two elements that sum to it.
- * - For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4
- *   and convert nums to [5,2,4,7].
- *
- * Return the minimum number of operations to make an array that is sorted in non-decreasing order.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minimumReplacement = function(nums) {
-  let result = 0;
-  let prev = nums[nums.length - 1];
-
-  for (let i = nums.length - 2; i >= 0; i--) {
-    if (nums[i] > prev) {
-      const splits = Math.ceil(nums[i] / prev);
-      result += splits - 1;
-      prev = Math.floor(nums[i] / splits);
-    } else {
-      prev = nums[i];
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2367-number-of-arithmetic-triplets.js b/solutions/2367-number-of-arithmetic-triplets.js
deleted file mode 100644
index 21c02a86..00000000
--- a/solutions/2367-number-of-arithmetic-triplets.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 2367. Number of Arithmetic Triplets
- * https://leetcode.com/problems/number-of-arithmetic-triplets/
- * Difficulty: Easy
- *
- * You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff.
- * A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
- * - i < j < k,
- * - nums[j] - nums[i] == diff, and
- * - nums[k] - nums[j] == diff.
- *
- * Return the number of unique arithmetic triplets.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} diff
- * @return {number}
- */
-var arithmeticTriplets = function(nums, diff) {
-  let result = 0;
-
-  for (let j = 1; j < nums.length - 1; j++) {
-    let i = j - 1;
-    let k = j + 1;
-
-    while (i >= 0 && nums[j] - nums[i] <= diff) {
-      if (nums[j] - nums[i] === diff) {
-        while (k < nums.length && nums[k] - nums[j] <= diff) {
-          if (nums[k] - nums[j] === diff) {
-            result++;
-          }
-          k++;
-        }
-      }
-      i--;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2368-reachable-nodes-with-restrictions.js b/solutions/2368-reachable-nodes-with-restrictions.js
deleted file mode 100644
index 1ecd0821..00000000
--- a/solutions/2368-reachable-nodes-with-restrictions.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2368. Reachable Nodes With Restrictions
- * https://leetcode.com/problems/reachable-nodes-with-restrictions/
- * Difficulty: Medium
- *
- * There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
- *
- * You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates
- * that there is an edge between nodes ai and bi in the tree. You are also given an integer
- * array restricted which represents restricted nodes.
- *
- * Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.
- *
- * Note that node 0 will not be a restricted node.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} edges
- * @param {number[]} restricted
- * @return {number}
- */
-var reachableNodes = function(n, edges, restricted) {
-  const graph = Array(n).fill().map(() => []);
-  const restrictedSet = new Set(restricted);
-  const visited = new Set();
-
-  for (const [u, v] of edges) {
-    graph[u].push(v);
-    graph[v].push(u);
-  }
-
-  explore(0);
-  return visited.size;
-
-  function explore(node) {
-    if (visited.has(node) || restrictedSet.has(node)) return;
-    visited.add(node);
-    for (const neighbor of graph[node]) {
-      explore(neighbor);
-    }
-  }
-};
diff --git a/solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js b/solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js
deleted file mode 100644
index be0e9844..00000000
--- a/solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2369. Check if There is a Valid Partition For The Array
- * https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums. You have to partition the array into one or
- * more contiguous subarrays.
- *
- * We call a partition of the array valid if each of the obtained subarrays satisfies one of
- * the following conditions:
- * 1. The subarray consists of exactly 2, equal elements. For example, the subarray [2,2] is good.
- * 2. The subarray consists of exactly 3, equal elements. For example, the subarray [4,4,4] is good.
- * 3. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference
- *    between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray
- *    [1,3,5] is not.
- *
- * Return true if the array has at least one valid partition. Otherwise, return false.
- */
-
-/**
- * @param {number[]} nums
- * @return {boolean}
- */
-var validPartition = function(nums) {
-  const n = nums.length;
-  const dp = new Array(n + 1).fill(false);
-  dp[0] = true;
-
-  for (let i = 2; i <= n; i++) {
-    if (nums[i - 1] === nums[i - 2]) {
-      dp[i] = dp[i] || dp[i - 2];
-    }
-    if (i >= 3) {
-      if (nums[i - 1] === nums[i - 2] && nums[i - 2] === nums[i - 3]) {
-        dp[i] = dp[i] || dp[i - 3];
-      }
-      if (nums[i - 1] === nums[i - 2] + 1 && nums[i - 2] === nums[i - 3] + 1) {
-        dp[i] = dp[i] || dp[i - 3];
-      }
-    }
-  }
-
-  return dp[n];
-};
diff --git a/solutions/2370-longest-ideal-subsequence.js b/solutions/2370-longest-ideal-subsequence.js
deleted file mode 100644
index c07e27f9..00000000
--- a/solutions/2370-longest-ideal-subsequence.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2370. Longest Ideal Subsequence
- * https://leetcode.com/problems/longest-ideal-subsequence/
- * Difficulty: Medium
- *
- * You are given a string s consisting of lowercase letters and an integer k. We call a string
- * t ideal if the following conditions are satisfied:
- * - t is a subsequence of the string s.
- * - The absolute difference in the alphabet order of every two adjacent letters in t is less
- *   than or equal to k.
- *
- * Return the length of the longest ideal string.
- *
- * A subsequence is a string that can be derived from another string by deleting some or no
- * characters without changing the order of the remaining characters.
- *
- * Note that the alphabet order is not cyclic. For example, the absolute difference in the
- * alphabet order of 'a' and 'z' is 25, not 1.
- */
-
-/**
- * @param {string} s
- * @param {number} k
- * @return {number}
- */
-var longestIdealString = function(s, k) {
-  const dp = new Array(26).fill(0);
-  let result = 0;
-
-  for (const char of s) {
-    const idx = char.charCodeAt(0) - 97;
-    let currentMax = 0;
-
-    for (let i = Math.max(0, idx - k); i <= Math.min(25, idx + k); i++) {
-      currentMax = Math.max(currentMax, dp[i]);
-    }
-
-    dp[idx] = currentMax + 1;
-    result = Math.max(result, dp[idx]);
-  }
-
-  return result;
-};
diff --git a/solutions/2373-largest-local-values-in-a-matrix.js b/solutions/2373-largest-local-values-in-a-matrix.js
deleted file mode 100644
index 46a65c45..00000000
--- a/solutions/2373-largest-local-values-in-a-matrix.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2373. Largest Local Values in a Matrix
- * https://leetcode.com/problems/largest-local-values-in-a-matrix/
- * Difficulty: Easy
- *
- * You are given an n x n integer matrix grid.
- *
- * Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:
- * - maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around
- *   row i + 1 and column j + 1.
- *
- * In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
- *
- * Return the generated matrix.
- */
-
-/**
- * @param {number[][]} grid
- * @return {number[][]}
- */
-var largestLocal = function(grid) {
-  const n = grid.length;
-  const result = new Array(n - 2).fill().map(() => new Array(n - 2).fill(0));
-
-  for (let i = 0; i < n - 2; i++) {
-    for (let j = 0; j < n - 2; j++) {
-      let maxVal = 0;
-      for (let r = i; r < i + 3; r++) {
-        for (let c = j; c < j + 3; c++) {
-          maxVal = Math.max(maxVal, grid[r][c]);
-        }
-      }
-      result[i][j] = maxVal;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2374-node-with-highest-edge-score.js b/solutions/2374-node-with-highest-edge-score.js
deleted file mode 100644
index b8597422..00000000
--- a/solutions/2374-node-with-highest-edge-score.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2374. Node With Highest Edge Score
- * https://leetcode.com/problems/node-with-highest-edge-score/
- * Difficulty: Medium
- *
- * You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has
- * exactly one outgoing edge.
- *
- * The graph is represented by a given 0-indexed integer array edges of length n, where edges[i]
- * indicates that there is a directed edge from node i to node edges[i].
- *
- * The edge score of a node i is defined as the sum of the labels of all the nodes that have an
- * edge pointing to i.
- *
- * Return the node with the highest edge score. If multiple nodes have the same edge score, return
- * the node with the smallest index.
- */
-
-/**
- * @param {number[]} edges
- * @return {number}
- */
-var edgeScore = function(edges) {
-  const scores = new Array(edges.length).fill(0);
-
-  for (let i = 0; i < edges.length; i++) {
-    scores[edges[i]] += i;
-  }
-  let maxScore = 0;
-  let result = 0;
-  for (let i = 0; i < scores.length; i++) {
-    if (scores[i] > maxScore) {
-      maxScore = scores[i];
-      result = i;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js b/solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js
deleted file mode 100644
index 76994936..00000000
--- a/solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2379. Minimum Recolors to Get K Consecutive Black Blocks
- * https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/
- * Difficulty: Easy
- *
- * You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B',
- * representing the color of the ith block. The characters 'W' and 'B' denote the colors white
- * and black, respectively.
- *
- * You are also given an integer k, which is the desired number of consecutive black blocks.
- *
- * In one operation, you can recolor a white block such that it becomes a black block.
- *
- * Return the minimum number of operations needed such that there is at least one occurrence
- * of k consecutive black blocks.
- */
-
-/**
- * @param {string} blocks
- * @param {number} k
- * @return {number}
- */
-var minimumRecolors = function(blocks, k) {
-  let count = 0;
-
-  for (let i = 0; i < k; i++) {
-    if (blocks[i] === 'W') count++;
-  }
-
-  let result = count;
-
-  for (let i = k; i < blocks.length; i++) {
-    if (blocks[i] === 'W') count++;
-    if (blocks[i - k] === 'W') count--;
-    result = Math.min(result, count);
-  }
-
-  return result;
-};
diff --git a/solutions/2380-time-needed-to-rearrange-a-binary-string.js b/solutions/2380-time-needed-to-rearrange-a-binary-string.js
deleted file mode 100644
index d85d2234..00000000
--- a/solutions/2380-time-needed-to-rearrange-a-binary-string.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2380. Time Needed to Rearrange a Binary String
- * https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/
- * Difficulty: Medium
- *
- * You are given a binary string s. In one second, all occurrences of "01" are simultaneously
- * replaced with "10". This process repeats until no occurrences of "01" exist.
- *
- * Return the number of seconds needed to complete this process.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var secondsToRemoveOccurrences = function(s) {
-  const binary = s.split('');
-  let result = 0;
-
-  while (binary.join('').includes('01')) {
-    for (let i = 0; i < binary.length - 1; i++) {
-      if (binary[i] === '0' && binary[i + 1] === '1') {
-        binary[i] = '1';
-        binary[i + 1] = '0';
-        i++;
-      }
-    }
-    result++;
-  }
-
-  return result;
-};
diff --git a/solutions/2382-maximum-segment-sum-after-removals.js b/solutions/2382-maximum-segment-sum-after-removals.js
deleted file mode 100644
index 78065c5e..00000000
--- a/solutions/2382-maximum-segment-sum-after-removals.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * 2382. Maximum Segment Sum After Removals
- * https://leetcode.com/problems/maximum-segment-sum-after-removals/
- * Difficulty: Hard
- *
- * You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For
- * the ith query, the element in nums at the index removeQueries[i] is removed, splitting
- * nums into different segments.
- *
- * A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum
- * of every element in a segment.
- *
- * Return an integer array answer, of length n, where answer[i] is the maximum segment sum after
- * applying the ith removal.
- *
- * Note: The same index will not be removed more than once.
- */
-
-/**
- * @param {number[]} nums
- * @param {number[]} removeQueries
- * @return {number[]}
- */
-var maximumSegmentSum = function(nums, removeQueries) {
-  const n = nums.length;
-  const result = new Array(n);
-  const prefixSum = new Array(n + 1).fill(0);
-  const parents = new Array(n).fill(-1);
-  const sizes = new Array(n).fill(0);
-  const sums = new Array(n).fill(0);
-  let maxSum = 0;
-
-  for (let i = 0; i < n; i++) {
-    prefixSum[i + 1] = prefixSum[i] + nums[i];
-  }
-
-  for (let i = n - 1; i >= 0; i--) {
-    result[i] = maxSum;
-    const index = removeQueries[i];
-
-    parents[index] = index;
-    sizes[index] = 1;
-    sums[index] = nums[index];
-
-    if (index > 0 && parents[index - 1] !== -1) {
-      const leftRoot = findRoot(parents, index - 1);
-      const segmentSum = sums[leftRoot] + sums[index];
-
-      parents[index] = leftRoot;
-      sizes[leftRoot] += sizes[index];
-      sums[leftRoot] = segmentSum;
-    }
-
-    if (index < n - 1 && parents[index + 1] !== -1) {
-      const root = findRoot(parents, index);
-      const rightRoot = findRoot(parents, index + 1);
-
-      if (root !== rightRoot) {
-        const segmentSum = sums[root] + sums[rightRoot];
-
-        if (sizes[root] < sizes[rightRoot]) {
-          parents[root] = rightRoot;
-          sizes[rightRoot] += sizes[root];
-          sums[rightRoot] = segmentSum;
-        } else {
-          parents[rightRoot] = root;
-          sizes[root] += sizes[rightRoot];
-          sums[root] = segmentSum;
-        }
-      }
-    }
-
-    maxSum = Math.max(maxSum, sums[findRoot(parents, index)]);
-  }
-
-  return result;
-};
-
-function findRoot(parents, x) {
-  if (parents[x] !== x) {
-    parents[x] = findRoot(parents, parents[x]);
-  }
-  return parents[x];
-}
diff --git a/solutions/2383-minimum-hours-of-training-to-win-a-competition.js b/solutions/2383-minimum-hours-of-training-to-win-a-competition.js
deleted file mode 100644
index 0699fdcc..00000000
--- a/solutions/2383-minimum-hours-of-training-to-win-a-competition.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 2383. Minimum Hours of Training to Win a Competition
- * https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/
- * Difficulty: Easy
- *
- * You are entering a competition, and are given two positive integers initialEnergy and
- * initialExperience denoting your initial energy and initial experience respectively.
- *
- * You are also given two 0-indexed integer arrays energy and experience, both of length n.
- *
- * You will face n opponents in order. The energy and experience of the ith opponent is
- * denoted by energy[i] and experience[i] respectively. When you face an opponent, you need
- * to have both strictly greater experience and energy to defeat them and move to the next
- * opponent if available.
- *
- * Defeating the ith opponent increases your experience by experience[i], but decreases your
- * energy by energy[i].
- *
- * Before starting the competition, you can train for some number of hours. After each hour
- * of training, you can either choose to increase your initial experience by one, or increase
- * your initial energy by one.
- *
- * Return the minimum number of training hours required to defeat all n opponents.
- */
-
-/**
- * @param {number} initialEnergy
- * @param {number} initialExperience
- * @param {number[]} energy
- * @param {number[]} experience
- * @return {number}
- */
-var minNumberOfHours = function(initialEnergy, initialExperience, energy, experience) {
-  let energyNeeded = 0;
-  let experienceNeeded = 0;
-  let currentEnergy = initialEnergy;
-  let currentExperience = initialExperience;
-
-  for (let i = 0; i < energy.length; i++) {
-    if (currentEnergy <= energy[i]) {
-      const deficit = energy[i] - currentEnergy + 1;
-      energyNeeded += deficit;
-      currentEnergy += deficit;
-    }
-    if (currentExperience <= experience[i]) {
-      const deficit = experience[i] - currentExperience + 1;
-      experienceNeeded += deficit;
-      currentExperience += deficit;
-    }
-    currentEnergy -= energy[i];
-    currentExperience += experience[i];
-  }
-
-  return energyNeeded + experienceNeeded;
-};
diff --git a/solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js b/solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js
deleted file mode 100644
index 00bd2ddd..00000000
--- a/solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * 2385. Amount of Time for Binary Tree to Be Infected
- * https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/
- * Difficulty: Medium
- *
- * You are given the root of a binary tree with unique values, and an integer start.
- * At minute 0, an infection starts from the node with value start.
- *
- * Each minute, a node becomes infected if:
- * - The node is currently uninfected.
- * - The node is adjacent to an infected node.
- *
- * Return the number of minutes needed for the entire tree to be infected.
- */
-
-/**
- * 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} start
- * @return {number}
- */
-var amountOfTime = function(root, start) {
-  const graph = new Map();
-  const queue = [start];
-  const visited = new Set([start]);
-  let result = -1;
-
-  buildGraph(root, null);
-
-  while (queue.length) {
-    result++;
-    const levelSize = queue.length;
-    for (let i = 0; i < levelSize; i++) {
-      const current = queue.shift();
-      for (const neighbor of graph.get(current) || []) {
-        if (!visited.has(neighbor)) {
-          visited.add(neighbor);
-          queue.push(neighbor);
-        }
-      }
-    }
-  }
-
-  return result;
-
-  function buildGraph(node, parent) {
-    if (!node) return;
-    if (!graph.has(node.val)) graph.set(node.val, []);
-    if (parent) graph.get(node.val).push(parent.val);
-    if (node.left) {
-      graph.get(node.val).push(node.left.val);
-      graph.set(node.left.val, graph.get(node.left.val) || []);
-      graph.get(node.left.val).push(node.val);
-    }
-    if (node.right) {
-      graph.get(node.val).push(node.right.val);
-      graph.set(node.right.val, graph.get(node.right.val) || []);
-      graph.get(node.right.val).push(node.val);
-    }
-    buildGraph(node.left, node);
-    buildGraph(node.right, node);
-  }
-};
diff --git a/solutions/2389-longest-subsequence-with-limited-sum.js b/solutions/2389-longest-subsequence-with-limited-sum.js
deleted file mode 100644
index a498b7c8..00000000
--- a/solutions/2389-longest-subsequence-with-limited-sum.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 2389. Longest Subsequence With Limited Sum
- * https://leetcode.com/problems/longest-subsequence-with-limited-sum/
- * Difficulty: Easy
- *
- * You are given an integer array nums of length n, and an integer array queries of length m.
- *
- * Return an array answer of length m where answer[i] is the maximum size of a subsequence that
- * you can take from nums such that the sum of its elements is less than or equal to queries[i].
- *
- * 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[]} queries
- * @return {number[]}
- */
-var answerQueries = function(nums, queries) {
-  nums.sort((a, b) => a - b);
-  const prefixSums = [0];
-  for (const num of nums) {
-    prefixSums.push(prefixSums.at(-1) + num);
-  }
-
-  const result = new Array(queries.length);
-  for (let i = 0; i < queries.length; i++) {
-    let left = 0;
-    let right = nums.length;
-    while (left < right) {
-      const mid = Math.floor((left + right + 1) / 2);
-      if (prefixSums[mid] <= queries[i]) {
-        left = mid;
-      } else {
-        right = mid - 1;
-      }
-    }
-    result[i] = left;
-  }
-
-  return result;
-};
diff --git a/solutions/2391-minimum-amount-of-time-to-collect-garbage.js b/solutions/2391-minimum-amount-of-time-to-collect-garbage.js
deleted file mode 100644
index bbddfc01..00000000
--- a/solutions/2391-minimum-amount-of-time-to-collect-garbage.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * 2391. Minimum Amount of Time to Collect Garbage
- * https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment
- * of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G'
- * representing one unit of metal, paper and glass garbage respectively. Picking up one unit of
- * any type of garbage takes 1 minute.
- *
- * You are also given a 0-indexed integer array travel where travel[i] is the number of minutes
- * needed to go from house i to house i + 1.
- *
- * There are three garbage trucks in the city, each responsible for picking up one type of garbage.
- * Each garbage truck starts at house 0 and must visit each house in order; however, they do not
- * need to visit every house.
- *
- * Only one garbage truck may be used at any given moment. While one truck is driving or picking up
- * garbage, the other two trucks cannot do anything.
- *
- * Return the minimum number of minutes needed to pick up all the garbage.
- */
-
-/**
- * @param {string[]} garbage
- * @param {number[]} travel
- * @return {number}
- */
-var garbageCollection = function(garbage, travel) {
-  let result = 0;
-  const lastHouse = {'M': 0, 'P': 0, 'G': 0};
-
-  for (let i = 0; i < garbage.length; i++) {
-    result += garbage[i].length;
-    for (const type of garbage[i]) {
-      lastHouse[type] = i;
-    }
-  }
-
-  const prefixTravel = [0];
-  for (const time of travel) {
-    prefixTravel.push(prefixTravel.at(-1) + time);
-  }
-
-  Object.keys(lastHouse).forEach(type => {
-    result += prefixTravel[lastHouse[type]];
-  });
-
-  return result;
-};
diff --git a/solutions/2392-build-a-matrix-with-conditions.js b/solutions/2392-build-a-matrix-with-conditions.js
deleted file mode 100644
index b55cdd0f..00000000
--- a/solutions/2392-build-a-matrix-with-conditions.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * 2392. Build a Matrix With Conditions
- * https://leetcode.com/problems/build-a-matrix-with-conditions/
- * Difficulty: Hard
- *
- * You are given a positive integer k. You are also given:
- * - a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
- * - a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
- *
- * The two arrays contain integers from 1 to k.
- *
- * You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once.
- * The remaining cells should have the value 0.
- *
- * The matrix should also satisfy the following conditions:
- * - The number abovei should appear in a row that is strictly above the row at which the number
- *   belowi appears for all i from 0 to n - 1.
- * - The number lefti should appear in a column that is strictly left of the column at which the
- *   number righti appears for all i from 0 to m - 1.
- *
- * Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
- */
-
-/**
- * @param {number} k
- * @param {number[][]} rowConditions
- * @param {number[][]} colConditions
- * @return {number[][]}
- */
-var buildMatrix = function(k, rowConditions, colConditions) {
-  const rowOrder = helper(rowConditions, k);
-  if (!rowOrder.length) return [];
-
-  const colOrder = helper(colConditions, k);
-  if (!colOrder.length) return [];
-
-  const matrix = Array.from({ length: k }, () => new Array(k).fill(0));
-  const rowIndex = new Array(k + 1).fill(0);
-  const colIndex = new Array(k + 1).fill(0);
-
-  for (let i = 0; i < k; i++) {
-    rowIndex[rowOrder[i]] = i;
-    colIndex[colOrder[i]] = i;
-  }
-
-  for (let num = 1; num <= k; num++) {
-    matrix[rowIndex[num]][colIndex[num]] = num;
-  }
-
-  return matrix;
-
-  function helper(edges, size) {
-    const graph = Array.from({ length: size + 1 }, () => []);
-    const inDegree = new Array(size + 1).fill(0);
-    for (const [u, v] of edges) {
-      graph[u].push(v);
-      inDegree[v]++;
-    }
-
-    const queue = [];
-    for (let i = 1; i <= size; i++) {
-      if (inDegree[i] === 0) queue.push(i);
-    }
-
-    const order = [];
-    while (queue.length) {
-      const node = queue.shift();
-      order.push(node);
-      for (const next of graph[node]) {
-        if (--inDegree[next] === 0) queue.push(next);
-      }
-    }
-
-    return order.length === size ? order : [];
-  }
-};
diff --git a/solutions/2395-find-subarrays-with-equal-sum.js b/solutions/2395-find-subarrays-with-equal-sum.js
deleted file mode 100644
index 9b4ec520..00000000
--- a/solutions/2395-find-subarrays-with-equal-sum.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 2395. Find Subarrays With Equal Sum
- * https://leetcode.com/problems/find-subarrays-with-equal-sum/
- * Difficulty: Easy
- *
- * Given a 0-indexed integer array nums, determine whether there exist two subarrays of length
- * 2 with equal sum. Note that the two subarrays must begin at different indices.
- *
- * Return true if these subarrays exist, and false otherwise.
- *
- * A subarray is a contiguous non-empty sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @return {boolean}
- */
-var findSubarrays = function(nums) {
-  const set = new Set();
-
-  for (let i = 0; i < nums.length - 1; i++) {
-    const sum = nums[i] + nums[i + 1];
-    if (set.has(sum)) return true;
-    set.add(sum);
-  }
-
-  return false;
-};
diff --git a/solutions/2397-maximum-rows-covered-by-columns.js b/solutions/2397-maximum-rows-covered-by-columns.js
deleted file mode 100644
index 0fa68a2b..00000000
--- a/solutions/2397-maximum-rows-covered-by-columns.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * 2397. Maximum Rows Covered by Columns
- * https://leetcode.com/problems/maximum-rows-covered-by-columns/
- * Difficulty: Medium
- *
- * You are given an m x n binary matrix matrix and an integer numSelect.
- *
- * Your goal is to select exactly numSelect distinct columns from matrix such that you cover
- * as many rows as possible.
- *
- * A row is considered covered if all the 1's in that row are also part of a column that you
- * have selected. If a row does not have any 1s, it is also considered covered.
- *
- * More formally, let us consider selected = {c1, c2, ...., cnumSelect} as the set of columns
- * selected by you. A row i is covered by selected if:
- * - For each cell where matrix[i][j] == 1, the column j is in selected.
- * - Or, no cell in row i has a value of 1.
- *
- * Return the maximum number of rows that can be covered by a set of numSelect columns.
- */
-
-/**
- * @param {number[][]} matrix
- * @param {number} numSelect
- * @return {number}
- */
-var maximumRows = function(matrix, numSelect) {
-  const rows = matrix.length;
-  const cols = matrix[0].length;
-  let result = 0;
-
-  backtrack(0, 0, 0);
-
-  return result;
-
-  function countCovered(selected) {
-    let covered = 0;
-    for (let i = 0; i < rows; i++) {
-      let isCovered = true;
-      for (let j = 0; j < cols; j++) {
-        if (matrix[i][j] === 1 && !(selected & (1 << j))) {
-          isCovered = false;
-          break;
-        }
-      }
-      if (isCovered) covered++;
-    }
-    return covered;
-  }
-
-  function backtrack(index, selected, count) {
-    if (count === numSelect) {
-      result = Math.max(result, countCovered(selected));
-      return;
-    }
-    if (index >= cols || cols - index + count < numSelect) return;
-
-    backtrack(index + 1, selected | (1 << index), count + 1);
-    backtrack(index + 1, selected, count);
-  }
-};
diff --git a/solutions/2399-check-distances-between-same-letters.js b/solutions/2399-check-distances-between-same-letters.js
deleted file mode 100644
index 7f977d1e..00000000
--- a/solutions/2399-check-distances-between-same-letters.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2399. Check Distances Between Same Letters
- * https://leetcode.com/problems/check-distances-between-same-letters/
- * Difficulty: Easy
- *
- * You are given a 0-indexed string s consisting of only lowercase English letters, where each
- * letter in s appears exactly twice. You are also given a 0-indexed integer array distance of
- * length 26.
- *
- * Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1,
- * 'c' -> 2, ... , 'z' -> 25).
- *
- * In a well-spaced string, the number of letters between the two occurrences of the ith letter
- * is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.
- *
- * Return true if s is a well-spaced string, otherwise return false.
- */
-
-/**
- * @param {string} s
- * @param {number[]} distance
- * @return {boolean}
- */
-var checkDistances = function(s, distance) {
-  const map = new Map();
-
-  for (let i = 0; i < s.length; i++) {
-    const char = s[i];
-    if (map.has(char)) {
-      map.get(char).push(i);
-    } else {
-      map.set(char, [i]);
-    }
-  }
-
-  for (const [char, positions] of map) {
-    const letterIndex = char.charCodeAt(0) - 'a'.charCodeAt(0);
-    if (positions[1] - positions[0] - 1 !== distance[letterIndex]) {
-      return false;
-    }
-  }
-
-  return true;
-};
diff --git a/solutions/2401-longest-nice-subarray.js b/solutions/2401-longest-nice-subarray.js
deleted file mode 100644
index 6f423321..00000000
--- a/solutions/2401-longest-nice-subarray.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2401. Longest Nice Subarray
- * https://leetcode.com/problems/longest-nice-subarray/
- * Difficulty: Medium
- *
- * You are given an array nums consisting of positive integers.
- *
- * We call a subarray of nums nice if the bitwise AND of every pair of elements that are in
- * different positions in the subarray is equal to 0.
- *
- * Return the length of the longest nice subarray.
- *
- * A subarray is a contiguous part of an array.
- *
- * Note that subarrays of length 1 are always considered nice.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var longestNiceSubarray = function(nums) {
-  let result = 1;
-  let left = 0;
-  let usedBits = 0;
-
-  for (let right = 0; right < nums.length; right++) {
-    while ((usedBits & nums[right]) !== 0) {
-      usedBits ^= nums[left];
-      left++;
-    }
-    usedBits |= nums[right];
-    result = Math.max(result, right - left + 1);
-  }
-
-  return result;
-};
diff --git a/solutions/2404-most-frequent-even-element.js b/solutions/2404-most-frequent-even-element.js
deleted file mode 100644
index e5fcd0c6..00000000
--- a/solutions/2404-most-frequent-even-element.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2404. Most Frequent Even Element
- * https://leetcode.com/problems/most-frequent-even-element/
- * Difficulty: Easy
- *
- * Given an integer array nums, return the most frequent even element.
- *
- * If there is a tie, return the smallest one. If there is no such element, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var mostFrequentEven = function(nums) {
-  const map = new Map();
-  let maxCount = 0;
-  let result = -1;
-
-  for (const num of nums) {
-    if (num % 2 === 0) {
-      const count = (map.get(num) || 0) + 1;
-      map.set(num, count);
-      if (count > maxCount || (count === maxCount && num < result)) {
-        maxCount = count;
-        result = num;
-      }
-    }
-  }
-
-  return result;
-};
-
diff --git a/solutions/2405-optimal-partition-of-string.js b/solutions/2405-optimal-partition-of-string.js
deleted file mode 100644
index eb2849bc..00000000
--- a/solutions/2405-optimal-partition-of-string.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 2405. Optimal Partition of String
- * https://leetcode.com/problems/optimal-partition-of-string/
- * Difficulty: Medium
- *
- * Given a string s, partition the string into one or more substrings such that the characters
- * in each substring are unique. That is, no letter appears in a single substring more than once.
- *
- * Return the minimum number of substrings in such a partition.
- *
- * Note that each character should belong to exactly one substring in a partition.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var partitionString = function(s) {
-  const set = new Set();
-  let result = 1;
-
-  for (const char of s) {
-    if (set.has(char)) {
-      set.clear();
-      result++;
-    }
-    set.add(char);
-  }
-
-  return result;
-};
diff --git a/solutions/2409-count-days-spent-together.js b/solutions/2409-count-days-spent-together.js
deleted file mode 100644
index 1047ab0b..00000000
--- a/solutions/2409-count-days-spent-together.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 2409. Count Days Spent Together
- * https://leetcode.com/problems/count-days-spent-together/
- * Difficulty: Easy
- *
- * Alice and Bob are traveling to Rome for separate business meetings.
- *
- * You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in
- * the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city
- * from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the
- * format "MM-DD", corresponding to the month and day of the date.
- *
- * Return the total number of days that Alice and Bob are in Rome together.
- *
- * You can assume that all dates occur in the same calendar year, which is not a leap year. Note
- * that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30,
- * 31, 30, 31].
- */
-
-/**
- * @param {string} arriveAlice
- * @param {string} leaveAlice
- * @param {string} arriveBob
- * @param {string} leaveBob
- * @return {number}
- */
-var countDaysTogether = function(arriveAlice, leaveAlice, arriveBob, leaveBob) {
-  const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
-
-  function toDays(date) {
-    const [month, day] = date.split('-').map(Number);
-    let totalDays = 0;
-    for (let i = 0; i < month - 1; i++) {
-      totalDays += daysInMonth[i];
-    }
-    return totalDays + day;
-  }
-
-  const aliceStart = toDays(arriveAlice);
-  const aliceEnd = toDays(leaveAlice);
-  const bobStart = toDays(arriveBob);
-  const bobEnd = toDays(leaveBob);
-
-  const overlapStart = Math.max(aliceStart, bobStart);
-  const overlapEnd = Math.min(aliceEnd, bobEnd);
-
-  return Math.max(0, overlapEnd - overlapStart + 1);
-};
diff --git a/solutions/2410-maximum-matching-of-players-with-trainers.js b/solutions/2410-maximum-matching-of-players-with-trainers.js
deleted file mode 100644
index 885db445..00000000
--- a/solutions/2410-maximum-matching-of-players-with-trainers.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 2410. Maximum Matching of Players With Trainers
- * https://leetcode.com/problems/maximum-matching-of-players-with-trainers/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array players, where players[i] represents the ability of
- * the ith player. You are also given a 0-indexed integer array trainers, where trainers[j]
- * represents the training capacity of the jth trainer.
- *
- * The ith player can match with the jth trainer if the player's ability is less than or equal
- * to the trainer's training capacity. Additionally, the ith player can be matched with at most
- * one trainer, and the jth trainer can be matched with at most one player.
- *
- * Return the maximum number of matchings between players and trainers that satisfy these
- * conditions.
- */
-
-/**
- * @param {number[]} players
- * @param {number[]} trainers
- * @return {number}
- */
-var matchPlayersAndTrainers = function(players, trainers) {
-  players.sort((a, b) => a - b);
-  trainers.sort((a, b) => a - b);
-
-  let result = 0;
-  for (let j = 0; result < players.length && j < trainers.length; j++) {
-    if (trainers[j] >= players[result]) {
-      result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js b/solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js
deleted file mode 100644
index 784cf5d2..00000000
--- a/solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2411. Smallest Subarrays With Maximum Bitwise OR
- * https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array nums of length n, consisting of non-negative integers. For
- * each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty
- * subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.
- * - In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find
- *   the smallest subarray starting at i, such that bitwise OR of this subarray is equal to
- *   max(Bik) where i <= k <= n - 1.
- *
- * The bitwise OR of an array is the bitwise OR of all the numbers in it.
- *
- * Return an integer array answer of size n where answer[i] is the length of the minimum sized
- * subarray starting at i with maximum bitwise OR.
- *
- * A subarray is a contiguous non-empty sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var smallestSubarrays = function(nums) {
-  const n = nums.length;
-  const result = new Array(n).fill(1);
-  const bitPositions = new Array(32).fill(0);
-
-  for (let i = n - 1; i >= 0; i--) {
-    for (let bit = 0; bit < 32; bit++) {
-      if (nums[i] & (1 << bit)) {
-        bitPositions[bit] = i;
-      }
-    }
-
-    let maxIndex = i;
-    for (let bit = 0; bit < 32; bit++) {
-      maxIndex = Math.max(maxIndex, bitPositions[bit]);
-    }
-
-    result[i] = maxIndex - i + 1;
-  }
-
-  return result;
-};
diff --git a/solutions/2412-minimum-money-required-before-transactions.js b/solutions/2412-minimum-money-required-before-transactions.js
deleted file mode 100644
index 240ca6ca..00000000
--- a/solutions/2412-minimum-money-required-before-transactions.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 2412. Minimum Money Required Before Transactions
- * https://leetcode.com/problems/minimum-money-required-before-transactions/
- * Difficulty: Hard
- *
- * You are given a 0-indexed 2D integer array transactions, where
- * transactions[i] = [costi, cashbacki].
- *
- * The array describes transactions, where each transaction must be completed exactly once
- * in some order. At any given moment, you have a certain amount of money. In order to
- * complete transaction i, money >= costi must hold true. After performing a transaction,
- * money becomes money - costi + cashbacki.
- *
- * Return the minimum amount of money required before any transaction so that all of the
- * transactions can be completed regardless of the order of the transactions.
- */
-
-/**
- * @param {number[][]} transactions
- * @return {number}
- */
-var minimumMoney = function(transactions) {
-  let totalLoss = 0;
-  let maxCost = 0;
-
-  for (const [cost, cashback] of transactions) {
-    if (cost > cashback) {
-      totalLoss += cost - cashback;
-      maxCost = Math.max(maxCost, cashback);
-    } else {
-      maxCost = Math.max(maxCost, cost);
-    }
-  }
-
-  return totalLoss + maxCost;
-};
diff --git a/solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js b/solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js
deleted file mode 100644
index afb44c82..00000000
--- a/solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2414. Length of the Longest Alphabetical Continuous Substring
- * https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/
- * Difficulty: Medium
- *
- * An alphabetical continuous string is a string consisting of consecutive letters in the alphabet.
- * In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".
- * - For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not.
- *
- * Given a string s consisting of lowercase letters only, return the length of the longest
- * alphabetical continuous substring.
- */
-
-/**
- * @param {string} s
- * @return {number}
- */
-var longestContinuousSubstring = function(s) {
-  let result = 1;
-  let currentLength = 1;
-
-  for (let i = 1; i < s.length; i++) {
-    if (s.charCodeAt(i) - s.charCodeAt(i - 1) === 1) {
-      currentLength++;
-      result = Math.max(result, currentLength);
-    } else {
-      currentLength = 1;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2415-reverse-odd-levels-of-binary-tree.js b/solutions/2415-reverse-odd-levels-of-binary-tree.js
deleted file mode 100644
index 9c70383b..00000000
--- a/solutions/2415-reverse-odd-levels-of-binary-tree.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * 2415. Reverse Odd Levels of Binary Tree
- * https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/
- * Difficulty: Medium
- *
- * Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.
- * - For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should
- *   become [18,29,11,7,4,3,1,2].
- *
- * Return the root of the reversed tree.
- *
- * A binary tree is perfect if all parent nodes have two children and all leaves are on the same
- * level.
- *
- * The level of a node is the number of edges along the path between it and the root 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 {TreeNode}
- */
-var reverseOddLevels = function(root) {
-  reverseLevel([root], 0);
-  return root;
-
-  function reverseLevel(nodes, level) {
-    if (!nodes.length) return;
-
-    if (level % 2 === 1) {
-      for (let i = 0, j = nodes.length - 1; i < j; i++, j--) {
-        [nodes[i].val, nodes[j].val] = [nodes[j].val, nodes[i].val];
-      }
-    }
-
-    const nextLevel = [];
-    for (const node of nodes) {
-      if (node.left) nextLevel.push(node.left);
-      if (node.right) nextLevel.push(node.right);
-    }
-
-    reverseLevel(nextLevel, level + 1);
-  }
-};
diff --git a/solutions/2416-sum-of-prefix-scores-of-strings.js b/solutions/2416-sum-of-prefix-scores-of-strings.js
deleted file mode 100644
index 45d3a184..00000000
--- a/solutions/2416-sum-of-prefix-scores-of-strings.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * 2416. Sum of Prefix Scores of Strings
- * https://leetcode.com/problems/sum-of-prefix-scores-of-strings/
- * Difficulty: Hard
- *
- * You are given an array words of size n consisting of non-empty strings.
- *
- * We define the score of a string term as the number of strings words[i] such that term is
- * a prefix of words[i].
- * - For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since
- *   "ab" is a prefix of both "ab" and "abc".
- *
- * Return an array answer of size n where answer[i] is the sum of scores of every non-empty
- * prefix of words[i].
- *
- * Note that a string is considered as a prefix of itself.
- */
-
-/**
- * @param {string[]} words
- * @return {number[]}
- */
-var sumPrefixScores = function(words) {
-  class TrieNode {
-    constructor() {
-      this.children = new Map();
-      this.count = 0;
-    }
-  }
-
-  const root = new TrieNode();
-
-  for (const word of words) {
-    let node = root;
-    for (const char of word) {
-      if (!node.children.has(char)) {
-        node.children.set(char, new TrieNode());
-      }
-      node = node.children.get(char);
-      node.count++;
-    }
-  }
-
-  const result = [];
-  for (const word of words) {
-    let node = root;
-    let score = 0;
-    for (const char of word) {
-      node = node.children.get(char);
-      score += node.count;
-    }
-    result.push(score);
-  }
-
-  return result;
-};
diff --git a/solutions/2418-sort-the-people.js b/solutions/2418-sort-the-people.js
deleted file mode 100644
index c0477a6a..00000000
--- a/solutions/2418-sort-the-people.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * 2418. Sort the People
- * https://leetcode.com/problems/sort-the-people/
- * Difficulty: Easy
- *
- * You are given an array of strings names, and an array heights that consists of distinct
- * positive integers. Both arrays are of length n.
- *
- * For each index i, names[i] and heights[i] denote the name and height of the ith person.
- *
- * Return names sorted in descending order by the people's heights.
- */
-
-/**
- * @param {string[]} names
- * @param {number[]} heights
- * @return {string[]}
- */
-var sortPeople = function(names, heights) {
-  const people = names.map((name, index) => ({name, height: heights[index]}));
-  people.sort((a, b) => b.height - a.height);
-  return people.map(person => person.name);
-};
diff --git a/solutions/2419-longest-subarray-with-maximum-bitwise-and.js b/solutions/2419-longest-subarray-with-maximum-bitwise-and.js
deleted file mode 100644
index c6a26711..00000000
--- a/solutions/2419-longest-subarray-with-maximum-bitwise-and.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 2419. Longest Subarray With Maximum Bitwise AND
- * https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/
- * Difficulty: Medium
- *
- * You are given an integer array nums of size n.
- *
- * Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
- * - In other words, let k be the maximum value of the bitwise AND of any subarray of nums.
- *   Then, only subarrays with a bitwise AND equal to k should be considered.
- *
- * Return the length of the longest such subarray.
- *
- * The bitwise AND of an array is the bitwise AND of all the numbers in it.
- *
- * A subarray is a contiguous sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var longestSubarray = function(nums) {
-  const maxValue = Math.max(...nums);
-  let result = 0;
-  let currentLength = 0;
-
-  for (const num of nums) {
-    if (num === maxValue) {
-      currentLength++;
-      result = Math.max(result, currentLength);
-    } else {
-      currentLength = 0;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2421-number-of-good-paths.js b/solutions/2421-number-of-good-paths.js
deleted file mode 100644
index c0f7d606..00000000
--- a/solutions/2421-number-of-good-paths.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * 2421. Number of Good Paths
- * https://leetcode.com/problems/number-of-good-paths/
- * Difficulty: Hard
- *
- * There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes
- * numbered from 0 to n - 1 and exactly n - 1 edges.
- *
- * You are given a 0-indexed integer array vals of length n where vals[i] denotes the value
- * of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi]
- * denotes that there exists an undirected edge connecting nodes ai and bi.
- *
- * A good path is a simple path that satisfies the following conditions:
- * 1. The starting node and the ending node have the same value.
- * 2. All nodes between the starting node and the ending node have values less than or equal
- *    to the starting node (i.e. the starting node's value should be the maximum value along
- *    the path).
- *
- * Return the number of distinct good paths.
- *
- * Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is
- * considered to be the same as 1 -> 0. A single node is also considered as a valid path.
- */
-
-/**
- * @param {number[]} vals
- * @param {number[][]} edges
- * @return {number}
- */
-var numberOfGoodPaths = function(vals, edges) {
-  const n = vals.length;
-  const graph = Array.from({length: n}, () => []);
-  for (const [u, v] of edges) {
-    graph[u].push(v);
-    graph[v].push(u);
-  }
-
-  const parent = new Array(n).fill(-1);
-  const rank = new Array(n).fill(0);
-  function find(x) {
-    if (parent[x] === -1) return x;
-    return parent[x] = find(parent[x]);
-  }
-
-  function union(x, y) {
-    let px = find(x);
-    let py = find(y);
-    if (px === py) return;
-    if (rank[px] < rank[py]) [px, py] = [py, px];
-    parent[py] = px;
-    if (rank[px] === rank[py]) rank[px]++;
-  }
-
-  const valueGroups = new Map();
-  for (let i = 0; i < n; i++) {
-    if (!valueGroups.has(vals[i])) {
-      valueGroups.set(vals[i], []);
-    }
-    valueGroups.get(vals[i]).push(i);
-  }
-
-  let result = 0;
-  for (const value of [...valueGroups.keys()].sort((a, b) => a - b)) {
-    const nodes = valueGroups.get(value);
-
-    for (const node of nodes) {
-      for (const neighbor of graph[node]) {
-        if (vals[neighbor] <= value) {
-          union(node, neighbor);
-        }
-      }
-    }
-
-    const groupCount = new Map();
-    for (const node of nodes) {
-      const root = find(node);
-      groupCount.set(root, (groupCount.get(root) || 0) + 1);
-    }
-
-    for (const count of groupCount.values()) {
-      result += (count * (count + 1)) / 2;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2426-number-of-pairs-satisfying-inequality.js b/solutions/2426-number-of-pairs-satisfying-inequality.js
deleted file mode 100644
index e24957fd..00000000
--- a/solutions/2426-number-of-pairs-satisfying-inequality.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * 2426. Number of Pairs Satisfying Inequality
- * https://leetcode.com/problems/number-of-pairs-satisfying-inequality/
- * Difficulty: Hard
- *
- * You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an
- * integer diff. Find the number of pairs (i, j) such that:
- * - 0 <= i < j <= n - 1 and
- * - nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
- *
- * Return the number of pairs that satisfy the conditions.
- */
-
-/**
- * @param {number[]} nums1
- * @param {number[]} nums2
- * @param {number} diff
- * @return {number}
- */
-var numberOfPairs = function(nums1, nums2, diff) {
-  const n = nums1.length;
-  const differences = new Array(n);
-  for (let i = 0; i < n; i++) {
-    differences[i] = nums1[i] - nums2[i];
-  }
-  let result = 0;
-  mergeSort(0, n);
-  return result;
-
-  function mergeSort(left, right) {
-    if (right - left <= 1) return;
-
-    const mid = Math.floor((left + right) / 2);
-    mergeSort(left, mid);
-    mergeSort(mid, right);
-
-    let i = left;
-    let j = mid;
-    while (i < mid && j < right) {
-      if (differences[i] <= differences[j] + diff) {
-        result += right - j;
-        i++;
-      } else {
-        j++;
-      }
-    }
-
-    const sorted = new Array(right - left);
-    let k = 0;
-    i = left;
-    j = mid;
-    while (i < mid && j < right) {
-      if (differences[i] <= differences[j]) {
-        sorted[k++] = differences[i++];
-      } else {
-        sorted[k++] = differences[j++];
-      }
-    }
-    while (i < mid) sorted[k++] = differences[i++];
-    while (j < right) sorted[k++] = differences[j++];
-
-    for (let p = 0; p < sorted.length; p++) {
-      differences[left + p] = sorted[p];
-    }
-  }
-};
diff --git a/solutions/2428-maximum-sum-of-an-hourglass.js b/solutions/2428-maximum-sum-of-an-hourglass.js
deleted file mode 100644
index f6cb5a39..00000000
--- a/solutions/2428-maximum-sum-of-an-hourglass.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 2428. Maximum Sum of an Hourglass
- * https://leetcode.com/problems/maximum-sum-of-an-hourglass/
- * Difficulty: Medium
- *
- * You are given an m x n integer matrix grid.
- *
- * We define an hourglass as a part of the matrix with the following form.
- *
- * Return the maximum sum of the elements of an hourglass.
- *
- * Note that an hourglass cannot be rotated and must be entirely contained within the matrix.
- */
-
-/**
- * @param {number[][]} grid
- * @return {number}
- */
-var maxSum = function(grid) {
-  let result = 0;
-  const rows = grid.length;
-  const cols = grid[0].length;
-
-  for (let i = 0; i <= rows - 3; i++) {
-    for (let j = 0; j <= cols - 3; j++) {
-      const hourglassSum = grid[i][j] + grid[i][j+1] + grid[i][j+2] + grid[i+1][j+1]
-        + grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2];
-      result = Math.max(result, hourglassSum);
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2432-the-employee-that-worked-on-the-longest-task.js b/solutions/2432-the-employee-that-worked-on-the-longest-task.js
deleted file mode 100644
index acab1a87..00000000
--- a/solutions/2432-the-employee-that-worked-on-the-longest-task.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2432. The Employee That Worked on the Longest Task
- * https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/
- * Difficulty: Easy
- *
- * There are n employees, each with a unique id from 0 to n - 1.
- *
- * You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:
- * - idi is the id of the employee that worked on the ith task, and
- * - leaveTimei is the time at which the employee finished the ith task. All the values
- *   leaveTimei are unique.
- *
- * Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th
- * task starts at time 0.
- *
- * Return the id of the employee that worked the task with the longest time. If there is a tie
- * between two or more employees, return the smallest id among them.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} logs
- * @return {number}
- */
-var hardestWorker = function(n, logs) {
-  let maxDuration = 0;
-  let result = n;
-  let startTime = 0;
-
-  for (const [employeeId, endTime] of logs) {
-    const duration = endTime - startTime;
-    if (duration > maxDuration || (duration === maxDuration && employeeId < result)) {
-      maxDuration = duration;
-      result = employeeId;
-    }
-    startTime = endTime;
-  }
-
-  return result;
-};
diff --git a/solutions/2433-find-the-original-array-of-prefix-xor.js b/solutions/2433-find-the-original-array-of-prefix-xor.js
deleted file mode 100644
index 0f41ebeb..00000000
--- a/solutions/2433-find-the-original-array-of-prefix-xor.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 2433. Find The Original Array of Prefix Xor
- * https://leetcode.com/problems/find-the-original-array-of-prefix-xor/
- * Difficulty: Medium
- *
- * You are given an integer array pref of size n. Find and return the array arr of size
- * n that satisfies:
- * - pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
- *
- * Note that ^ denotes the bitwise-xor operation.
- *
- * It can be proven that the answer is unique.
- */
-
-/**
- * @param {number[]} pref
- * @return {number[]}
- */
-var findArray = function(pref) {
-  const result = new Array(pref.length);
-  result[0] = pref[0];
-
-  for (let i = 1; i < pref.length; i++) {
-    result[i] = pref[i] ^ pref[i - 1];
-  }
-
-  return result;
-};
diff --git a/solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js b/solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
deleted file mode 100644
index 430e0fa6..00000000
--- a/solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * 2434. Using a Robot to Print the Lexicographically Smallest String
- * https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/
- * Difficulty: Medium
- *
- * You are given a string s and a robot that currently holds an empty string t. Apply one of the
- * following operations until s and t are both empty:
- * - Remove the first character of a string s and give it to the robot. The robot will append
- *   this character to the string t.
- * - Remove the last character of a string t and give it to the robot. The robot will write
- *   this character on paper.
- *
- * Return the lexicographically smallest string that can be written on the paper.
- */
-
-/**
- * @param {string} s
- * @return {string}
- */
-var robotWithString = function(s) {
-  const charCount = Array(26).fill(0);
-  for (const char of s) {
-    charCount[char.charCodeAt(0) - 97]++;
-  }
-
-  const stack = [];
-  let minCharIndex = 0;
-  let result = '';
-
-  for (const char of s) {
-    stack.push(char);
-    charCount[char.charCodeAt(0) - 97]--;
-
-    while (minCharIndex < 26 && charCount[minCharIndex] === 0) {
-      minCharIndex++;
-    }
-
-    while (stack.length
-      && (minCharIndex === 26 || stack[stack.length - 1].charCodeAt(0) - 97 <= minCharIndex)) {
-      result += stack.pop();
-    }
-  }
-
-  while (stack.length) {
-    result += stack.pop();
-  }
-
-  return result;
-};
diff --git a/solutions/2444-count-subarrays-with-fixed-bounds.js b/solutions/2444-count-subarrays-with-fixed-bounds.js
deleted file mode 100644
index e672554c..00000000
--- a/solutions/2444-count-subarrays-with-fixed-bounds.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2444. Count Subarrays With Fixed Bounds
- * https://leetcode.com/problems/count-subarrays-with-fixed-bounds/
- * Difficulty: Hard
- *
- * You are given an integer array nums and two integers minK and maxK.
- *
- * A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
- * - The minimum value in the subarray is equal to minK.
- * - The maximum value in the subarray is equal to maxK.
- * - Return the number of fixed-bound subarrays.
- *
- * A subarray is a contiguous part of an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} minK
- * @param {number} maxK
- * @return {number}
- */
-var countSubarrays = function(nums, minK, maxK) {
-  let result = 0;
-
-  for (let i = 0, minIndex = -1, maxIndex = -1, invalidIndex = -1; i < nums.length; i++) {
-    if (nums[i] < minK || nums[i] > maxK) {
-      invalidIndex = i;
-    }
-    if (nums[i] === minK) {
-      minIndex = i;
-    }
-    if (nums[i] === maxK) {
-      maxIndex = i;
-    }
-    result += Math.max(0, Math.min(minIndex, maxIndex) - invalidIndex);
-  }
-
-  return result;
-};
diff --git a/solutions/2503-maximum-number-of-points-from-grid-queries.js b/solutions/2503-maximum-number-of-points-from-grid-queries.js
deleted file mode 100644
index 5503adc7..00000000
--- a/solutions/2503-maximum-number-of-points-from-grid-queries.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * 2503. Maximum Number of Points From Grid Queries
- * https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/
- * Difficulty: Hard
- *
- * You are given an m x n integer matrix grid and an array queries of size k.
- *
- * Find an array answer of size k such that for each integer queries[i] you start in the top left
- * cell of the matrix and repeat the following process:
- * - If queries[i] is strictly greater than the value of the current cell that you are in, then
- *   you get one point if it is your first time visiting this cell, and you can move to any adjacent
- *   cell in all 4 directions: up, down, left, and right.
- * - Otherwise, you do not get any points, and you end this process.
- *
- * After the process, answer[i] is the maximum number of points you can get. Note that for each
- * query you are allowed to visit the same cell multiple times.
- *
- * Return the resulting array answer.
- */
-
-/**
- * @param {number[][]} grid
- * @param {number[]} queries
- * @return {number[]}
- */
-var maxPoints = function(grid, queries) {
-  const rows = grid.length;
-  const cols = grid[0].length;
-  const result = new Array(queries.length);
-  const sortedQueries = queries
-    .map((value, index) => ({ value, index }))
-    .sort((a, b) => a.value - b.value);
-  const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];
-  const queue = new MinPriorityQueue(([row, col]) => grid[row][col]);
-  const visited = new Set();
-
-  queue.enqueue([0, 0]);
-  visited.add('0,0');
-
-  let queryIndex = 0;
-  let points = 0;
-  while (queue.size()) {
-    const [row, col] = queue.dequeue();
-    const currentValue = grid[row][col];
-    while (queryIndex < sortedQueries.length && currentValue >= sortedQueries[queryIndex].value) {
-      result[sortedQueries[queryIndex].index] = points;
-      queryIndex++;
-    }
-    if (queryIndex === sortedQueries.length) break;
-    points++;
-    for (const [rowOffset, colOffset] of directions) {
-      const nextRow = row + rowOffset;
-      const nextCol = col + colOffset;
-      const positionKey = `${nextRow},${nextCol}`;
-      if (nextRow >= 0 && nextRow < rows && nextCol >= 0 && nextCol < cols
-          && !visited.has(positionKey)) {
-        visited.add(positionKey);
-        queue.enqueue([nextRow, nextCol]);
-      }
-    }
-  }
-  while (queryIndex < sortedQueries.length) {
-    result[sortedQueries[queryIndex].index] = points;
-    queryIndex++;
-  }
-
-  return result;
-};
diff --git a/solutions/2523-closest-prime-numbers-in-range.js b/solutions/2523-closest-prime-numbers-in-range.js
deleted file mode 100644
index 9deec025..00000000
--- a/solutions/2523-closest-prime-numbers-in-range.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2523. Closest Prime Numbers in Range
- * https://leetcode.com/problems/closest-prime-numbers-in-range/
- * Difficulty: Medium
- *
- * Given two positive integers left and right, find the two integers num1 and num2 such that:
- * - left <= num1 < num2 <= right
- * - Both num1 and num2 are prime numbers.
- * - num2 - num1 is the minimum amongst all other pairs satisfying the above conditions.
- *
- * Return the positive integer array ans = [num1, num2]. If there are multiple pairs satisfying
- * these conditions, return the one with the smallest num1 value. If no such numbers exist,
- * return [-1, -1].
- */
-
-/**
- * @param {number} left
- * @param {number} right
- * @return {number[]}
- */
-var closestPrimes = function(left, right) {
-  const group = new Uint8Array(right + 1).fill(1);
-  let result = [-1, -1];
-
-  group[0] = group[1] = 0;
-  for (let i = 2; i * i <= right; i++) {
-    if (group[i]) {
-      for (let j = i * i; j <= right; j += i) {
-        group[j] = 0;
-      }
-    }
-  }
-  for (let i = Math.max(2, left), prev = -1, min = Infinity; i <= right; i++) {
-    if (group[i]) {
-      if (prev !== -1 && i - prev < min) {
-        min = i - prev;
-        result = [prev, i];
-      }
-      prev = i;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2537-count-the-number-of-good-subarrays.js b/solutions/2537-count-the-number-of-good-subarrays.js
deleted file mode 100644
index 40d4799b..00000000
--- a/solutions/2537-count-the-number-of-good-subarrays.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 2537. Count the Number of Good Subarrays
- * https://leetcode.com/problems/count-the-number-of-good-subarrays/
- * Difficulty: Medium
- *
- * Given an integer array nums and an integer k, return the number of good subarrays of nums.
- *
- * A subarray arr is good if there are at least k pairs of indices (i, j) such that i < j
- * and arr[i] == arr[j].
- *
- * A subarray is a contiguous non-empty sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var countGood = function(nums, k) {
-  const frequency = new Map();
-  let result = 0;
-  let currentPairs = 0;
-  let left = 0;
-
-  for (let right = 0; right < nums.length; right++) {
-    const num = nums[right];
-    const prevCount = frequency.get(num) || 0;
-    currentPairs += prevCount;
-    frequency.set(num, prevCount + 1);
-
-    while (currentPairs >= k) {
-      result += nums.length - right;
-      const leftNum = nums[left];
-      const leftCount = frequency.get(leftNum);
-      currentPairs -= leftCount - 1;
-      frequency.set(leftNum, leftCount - 1);
-      left++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2551-put-marbles-in-bags.js b/solutions/2551-put-marbles-in-bags.js
deleted file mode 100644
index c2bfa6d4..00000000
--- a/solutions/2551-put-marbles-in-bags.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2551. Put Marbles in Bags
- * https://leetcode.com/problems/put-marbles-in-bags/
- * Difficulty: Hard
- *
- * You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight
- * of the ith marble. You are also given the integer k.
- *
- * Divide the marbles into the k bags according to the following rules:
- * - No bag is empty.
- * - If the ith marble and jth marble are in a bag, then all marbles with an index between the ith
- *   and jth indices should also be in that same bag.
- * - If a bag consists of all the marbles with an index from i to j inclusively, then the cost of
- *   the bag is weights[i] + weights[j].
- *
- * The score after distributing the marbles is the sum of the costs of all the k bags.
- *
- * Return the difference between the maximum and minimum scores among marble distributions.
- */
-
-/**
- * @param {number[]} weights
- * @param {number} k
- * @return {number}
- */
-var putMarbles = function(weights, k) {
-  const n = weights.length;
-  if (k === n) return 0;
-
-  const pairSums = [];
-  for (let i = 0; i < n - 1; i++) {
-    pairSums.push(weights[i] + weights[i + 1]);
-  }
-
-  pairSums.sort((a, b) => a - b);
-
-  let minScore = 0;
-  let maxScore = 0;
-
-  for (let i = 0; i < k - 1; i++) {
-    minScore += pairSums[i];
-    maxScore += pairSums[n - 2 - i];
-  }
-
-  return maxScore - minScore;
-};
diff --git a/solutions/2559-count-vowel-strings-in-ranges.js b/solutions/2559-count-vowel-strings-in-ranges.js
deleted file mode 100644
index 80d61e6a..00000000
--- a/solutions/2559-count-vowel-strings-in-ranges.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 2559. Count Vowel Strings in Ranges
- * https://leetcode.com/problems/count-vowel-strings-in-ranges/
- * Difficulty: Medium
- *
- * You are given a 0-indexed array of strings words and a 2D array of integers queries.
- *
- * Each query queries[i] = [li, ri] asks us to find the number of strings present at the
- * indices ranging from li to ri (both inclusive) of words that start and end with a vowel.
- *
- * Return an array ans of size queries.length, where ans[i] is the answer to the ith query.
- *
- * Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'.
- */
-
-/**
- * @param {string[]} words
- * @param {number[][]} queries
- * @return {number[]}
- */
-var vowelStrings = function(words, queries) {
-  const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
-  const prefix = [0];
-  for (let i = 0; i < words.length; i++) {
-    prefix[i + 1] = prefix[i] + (vowels.has(words[i][0]) && vowels.has(words[i].at(-1)));
-  }
-  return queries.map(([l, r]) => prefix[r + 1] - prefix[l]);
-};
diff --git a/solutions/2560-house-robber-iv.js b/solutions/2560-house-robber-iv.js
deleted file mode 100644
index 07c9a9a3..00000000
--- a/solutions/2560-house-robber-iv.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * 2560. House Robber IV
- * https://leetcode.com/problems/house-robber-iv/
- * Difficulty: Medium
- *
- * There are several consecutive houses along a street, each of which has some money inside.
- * There is also a robber, who wants to steal money from the homes, but he refuses to steal
- * from adjacent homes.
- *
- * The capability of the robber is the maximum amount of money he steals from one house of
- * all the houses he robbed.
- *
- * You are given an integer array nums representing how much money is stashed in each house.
- * More formally, the ith house from the left has nums[i] dollars.
- *
- * You are also given an integer k, representing the minimum number of houses the robber will
- * steal from. It is always possible to steal at least k houses.
- *
- * Return the minimum capability of the robber out of all the possible ways to steal at least
- * k houses.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var minCapability = function(nums, k) {
-  let left = Math.min(...nums);
-  let right = Math.max(...nums);
-
-  while (left < right) {
-    const mid = Math.floor((left + right) / 2);
-
-    if (canRob(nums, mid, k)) {
-      right = mid;
-    } else {
-      left = mid + 1;
-    }
-  }
-
-  return left;
-};
-
-function canRob(nums, capability, k) {
-  let count = 0;
-  let i = 0;
-
-  while (i < nums.length) {
-    if (nums[i] <= capability) {
-      count++;
-      i += 2;
-    } else {
-      i++;
-    }
-  }
-
-  return count >= k;
-}
diff --git a/solutions/2563-count-the-number-of-fair-pairs.js b/solutions/2563-count-the-number-of-fair-pairs.js
deleted file mode 100644
index bcacc7b3..00000000
--- a/solutions/2563-count-the-number-of-fair-pairs.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * 2563. Count the Number of Fair Pairs
- * https://leetcode.com/problems/count-the-number-of-fair-pairs/
- * Difficulty: Medium
- *
- * Given a 0-indexed integer array nums of size n and two integers lower and upper, return the
- * number of fair pairs.
- *
- * A pair (i, j) is fair if:
- * - 0 <= i < j < n, and
- * - lower <= nums[i] + nums[j] <= upper
- */
-
-/**
- * @param {number[]} nums
- * @param {number} lower
- * @param {number} upper
- * @return {number}
- */
-var countFairPairs = function(nums, lower, upper) {
-  let result = 0;
-
-  nums.sort((a, b) => a - b);
-
-  for (let i = 0; i < nums.length - 1; i++) {
-    const minTarget = lower - nums[i];
-    const maxTarget = upper - nums[i];
-
-    const first = findFirstValidIndex(i + 1, minTarget);
-    const last = findFirstValidIndex(i + 1, maxTarget + 1) - 1;
-
-    if (first <= last) {
-      result += last - first + 1;
-    }
-  }
-
-  return result;
-
-  function findFirstValidIndex(start, target) {
-    let left = start;
-    let right = nums.length - 1;
-    let index = nums.length;
-
-    while (left <= right) {
-      const mid = Math.floor((left + right) / 2);
-      if (nums[mid] >= target) {
-        index = mid;
-        right = mid - 1;
-      } else {
-        left = mid + 1;
-      }
-    }
-
-    return index;
-  }
-};
diff --git a/solutions/2579-count-total-number-of-colored-cells.js b/solutions/2579-count-total-number-of-colored-cells.js
deleted file mode 100644
index 6727bfb3..00000000
--- a/solutions/2579-count-total-number-of-colored-cells.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * 2579. Count Total Number of Colored Cells
- * https://leetcode.com/problems/count-total-number-of-colored-cells/
- * Difficulty: Medium
- *
- * There exists an infinitely large two-dimensional grid of uncolored unit cells.
- * You are given a positive integer n, indicating that you must do the following
- * routine for n minutes:
- * - At the first minute, color any arbitrary unit cell blue.
- * - Every minute thereafter, color blue every uncolored cell that touches a blue cell.
- *
- * Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
- */
-
-/**
- * @param {number} n
- * @return {number}
- */
-var coloredCells = function(n) {
-  return 1 + 2 * n * (n - 1);
-};
diff --git a/solutions/2594-minimum-time-to-repair-cars.js b/solutions/2594-minimum-time-to-repair-cars.js
deleted file mode 100644
index 478ac4f2..00000000
--- a/solutions/2594-minimum-time-to-repair-cars.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * 2594. Minimum Time to Repair Cars
- * https://leetcode.com/problems/minimum-time-to-repair-cars/
- * Difficulty: Medium
- *
- * You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank
- * of the ith mechanic. A mechanic with a rank r can repair n cars in r * n2 minutes.
- *
- * You are also given an integer cars representing the total number of cars waiting in the garage
- * to be repaired.
- *
- * Return the minimum time taken to repair all the cars.
- *
- * Note: All the mechanics can repair the cars simultaneously.
- */
-
-/**
- * @param {number[]} ranks
- * @param {number} cars
- * @return {number}
- */
-var repairCars = function(ranks, cars) {
-  let left = 1;
-  let right = Math.min(...ranks) * cars * cars;
-
-  while (left < right) {
-    const mid = Math.floor((left + right) / 2);
-    if (verify(mid)) {
-      right = mid;
-    } else {
-      left = mid + 1;
-    }
-  }
-
-  return left;
-
-  function verify(time) {
-    let totalCars = 0;
-    for (const rank of ranks) {
-      totalCars += Math.floor(Math.sqrt(time / rank));
-      if (totalCars >= cars) return true;
-    }
-    return false;
-  }
-};
diff --git a/solutions/2615-sum-of-distances.js b/solutions/2615-sum-of-distances.js
deleted file mode 100644
index 470c10cf..00000000
--- a/solutions/2615-sum-of-distances.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 2615. Sum of Distances
- * https://leetcode.com/problems/sum-of-distances/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums. There exists an array arr of length nums.length,
- * where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there
- * is no such j, set arr[i] to be 0.
- *
- * Return the array arr.
- */
-
-/**
- * @param {number[]} nums
- * @return {number[]}
- */
-var distance = function(nums) {
-  const valueIndices = new Map();
-  const result = new Array(nums.length).fill(0);
-
-  for (let i = 0; i < nums.length; i++) {
-    if (!valueIndices.has(nums[i])) {
-      valueIndices.set(nums[i], []);
-    }
-    valueIndices.get(nums[i]).push(i);
-  }
-
-  for (const indices of valueIndices.values()) {
-    let prefixSum = 0;
-    for (let i = 1; i < indices.length; i++) {
-      prefixSum += indices[i] - indices[0];
-    }
-
-    result[indices[0]] = prefixSum;
-
-    for (let i = 1; i < indices.length; i++) {
-      const diff = indices[i] - indices[i - 1];
-      prefixSum += diff * (i - (indices.length - i));
-      result[indices[i]] = prefixSum;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2624-snail-traversal.js b/solutions/2624-snail-traversal.js
deleted file mode 100644
index 2ff26d6d..00000000
--- a/solutions/2624-snail-traversal.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 2624. Snail Traversal
- * https://leetcode.com/problems/snail-traversal/
- * Difficulty: Medium
- *
- * Write code that enhances all arrays such that you can call the snail(rowsCount,
- * colsCount) method that transforms the 1D array into a 2D array organised in the
- * pattern known as snail traversal order. Invalid input values should output an
- * empty array. If rowsCount * colsCount !== nums.length, the input is considered invalid.
- *
- * Snail traversal order starts at the top left cell with the first value of the
- * current array. It then moves through the entire first column from top to bottom,
- * followed by moving to the next column on the right and traversing it from bottom
- * to top. This pattern continues, alternating the direction of traversal with each
- * column, until the entire current array is covered. For example, when given the
- * input array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15]
- * with rowsCount = 5 and colsCount = 4, the desired output matrix is shown below.
- * Note that iterating the matrix following the arrows corresponds to the order
- * of numbers in the original array.
- */
-
-/**
- * @param {number} rowsCount
- * @param {number} colsCount
- * @return {Array>}
- */
-Array.prototype.snail = function(rowsCount, colsCount) {
-  if (rowsCount * colsCount !== this.length) return [];
-
-  const result = Array.from({ length: rowsCount }, () => []);
-  let index = 0;
-
-  for (let col = 0; col < colsCount; col++) {
-    if (col % 2 === 0) {
-      for (let row = 0; row < rowsCount; row++) {
-        result[row][col] = this[index++];
-      }
-    } else {
-      for (let row = rowsCount - 1; row >= 0; row--) {
-        result[row][col] = this[index++];
-      }
-    }
-  }
-
-  return result;
-}
diff --git a/solutions/2666-allow-one-function-call.js b/solutions/2666-allow-one-function-call.js
deleted file mode 100644
index 93bb604d..00000000
--- a/solutions/2666-allow-one-function-call.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * 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/solutions/2685-count-the-number-of-complete-components.js b/solutions/2685-count-the-number-of-complete-components.js
deleted file mode 100644
index eccc890e..00000000
--- a/solutions/2685-count-the-number-of-complete-components.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * 2685. Count the Number of Complete Components
- * https://leetcode.com/problems/count-the-number-of-complete-components/
- * Difficulty: Medium
- *
- * You are given an integer n. There is an undirected graph with n vertices, numbered from 0
- * to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that
- * there exists an undirected edge connecting vertices ai and bi.
- *
- * Return the number of complete connected components of the graph.
- *
- * A connected component is a subgraph of a graph in which there exists a path between any
- * two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the
- * subgraph.
- *
- * A connected component is said to be complete if there exists an edge between every pair of
- * its vertices.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} edges
- * @return {number}
- */
-var countCompleteComponents = function(n, edges) {
-  const adjacencyList = Array.from({ length: n }, () => new Set());
-  edges.forEach(([a, b]) => {
-    adjacencyList[a].add(b);
-    adjacencyList[b].add(a);
-  });
-
-  const visited = new Set();
-  let result = 0;
-
-  function exploreComponent(vertex) {
-    const component = new Set([vertex]);
-    const queue = [vertex];
-    visited.add(vertex);
-
-    while (queue.length) {
-      const current = queue.shift();
-      adjacencyList[current].forEach(neighbor => {
-        if (!visited.has(neighbor)) {
-          component.add(neighbor);
-          queue.push(neighbor);
-          visited.add(neighbor);
-        }
-      });
-    }
-    return component;
-  }
-
-  function isComplete(component) {
-    const size = component.size;
-    return [...component].every(vertex =>
-      adjacencyList[vertex].size === size - 1
-        && [...adjacencyList[vertex]].every(neighbor => component.has(neighbor))
-    );
-  }
-
-  for (let vertex = 0; vertex < n; vertex++) {
-    if (!visited.has(vertex)) {
-      const component = exploreComponent(vertex);
-      if (isComplete(component)) result++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2722-join-two-arrays-by-id.js b/solutions/2722-join-two-arrays-by-id.js
deleted file mode 100644
index 5e81dde1..00000000
--- a/solutions/2722-join-two-arrays-by-id.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 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/solutions/2780-minimum-index-of-a-valid-split.js b/solutions/2780-minimum-index-of-a-valid-split.js
deleted file mode 100644
index 8ad20e0d..00000000
--- a/solutions/2780-minimum-index-of-a-valid-split.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * 2780. Minimum Index of a Valid Split
- * https://leetcode.com/problems/minimum-index-of-a-valid-split/
- * Difficulty: Medium
- *
- * An element x of an integer array arr of length m is dominant if more than half the elements
- * of arr have a value of x.
- *
- * You are given a 0-indexed integer array nums of length n with one dominant element.
- *
- * You can split nums at an index i into two arrays nums[0, ..., i] and nums[i + 1, ..., n - 1],
- * but the split is only valid if:
- * - 0 <= i < n - 1
- * - nums[0, ..., i], and nums[i + 1, ..., n - 1] have the same dominant element.
- *
- * Here, nums[i, ..., j] denotes the subarray of nums starting at index i and ending at index j,
- * both ends being inclusive. Particularly, if j < i then nums[i, ..., j] denotes an empty subarray.
- *
- * Return the minimum index of a valid split. If no valid split exists, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minimumIndex = function(nums) {
-  const map = new Map();
-
-  for (const num of nums) {
-    map.set(num, (map.get(num) || 0) + 1);
-  }
-
-  let dominantElement;
-  for (const [num, count] of map) {
-    if (count * 2 > nums.length) {
-      dominantElement = num;
-      break;
-    }
-  }
-
-  let leftCount = 0;
-  for (let i = 0; i < nums.length - 1; i++) {
-    leftCount += nums[i] === dominantElement ? 1 : 0;
-    const rightCount = map.get(dominantElement) - leftCount;
-
-    if (leftCount * 2 > i + 1 && rightCount * 2 > nums.length - i - 1) {
-      return i;
-    }
-  }
-
-  return -1;
-};
diff --git a/solutions/2799-count-complete-subarrays-in-an-array.js b/solutions/2799-count-complete-subarrays-in-an-array.js
deleted file mode 100644
index 1ba19bb5..00000000
--- a/solutions/2799-count-complete-subarrays-in-an-array.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 2799. Count Complete Subarrays in an Array
- * https://leetcode.com/problems/count-complete-subarrays-in-an-array/
- * Difficulty: Medium
- *
- * You are given an array nums consisting of positive integers.
- *
- * We call a subarray of an array complete if the following condition is satisfied:
- * - The number of distinct elements in the subarray is equal to the number of distinct
- *   elements in the whole array.
- *
- * Return the number of complete subarrays.
- *
- * A subarray is a contiguous non-empty part of an array.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var countCompleteSubarrays = function(nums) {
-  const totalDistinct = new Set(nums).size;
-  const frequency = new Map();
-  let completeCount = 0;
-  let left = 0;
-
-  for (let right = 0; right < nums.length; right++) {
-    frequency.set(nums[right], (frequency.get(nums[right]) || 0) + 1);
-
-    while (frequency.size === totalDistinct) {
-      completeCount += nums.length - right;
-      const leftNum = nums[left];
-      frequency.set(leftNum, frequency.get(leftNum) - 1);
-      if (frequency.get(leftNum) === 0) {
-        frequency.delete(leftNum);
-      }
-      left++;
-    }
-  }
-
-  return completeCount;
-};
diff --git a/solutions/2818-apply-operations-to-maximize-score.js b/solutions/2818-apply-operations-to-maximize-score.js
deleted file mode 100644
index a239cff0..00000000
--- a/solutions/2818-apply-operations-to-maximize-score.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * 2818. Apply Operations to Maximize Score
- * https://leetcode.com/problems/apply-operations-to-maximize-score/
- * Difficulty: Hard
- *
- * You are given an array nums of n positive integers and an integer k.
- *
- * Initially, you start with a score of 1. You have to maximize your score by applying the following
- * operation at most k times:
- * - Choose any non-empty subarray nums[l, ..., r] that you haven't chosen previously.
- * - Choose an element x of nums[l, ..., r] with the highest prime score. If multiple such elements
- *   exist, choose the one with the smallest index.
- * - Multiply your score by x.
- *
- * Here, nums[l, ..., r] denotes the subarray of nums starting at index l and ending at the index
- * r, both ends being inclusive.
- *
- * The prime score of an integer x is equal to the number of distinct prime factors of x. For
- * example, the prime score of 300 is 3 since 300 = 2 * 2 * 3 * 5 * 5.
- *
- * Return the maximum possible score after applying at most k operations.
- *
- * Since the answer may be large, return it modulo 109 + 7.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var maximumScore = function(nums, k) {
-  const MOD = 1000000007n;
-  const MAX = 100000;
-  const powerCache = {};
-
-  const primeScores = new Array(MAX + 1).fill(0);
-  for (let prime = 2; prime <= MAX; prime++) {
-    if (primeScores[prime] > 0) continue;
-    for (let multiple = prime; multiple <= MAX; multiple += prime) {
-      primeScores[multiple]++;
-    }
-  }
-
-  const elements = nums.map(num => [num, primeScores[num], 1]);
-
-  const stack = [-1];
-  const n = elements.length;
-
-  for (let i = 0; i <= n; i++) {
-    while (
-      stack.length > 1 && (i === n || elements[stack[stack.length - 1]][1] < elements[i][1])
-    ) {
-      const current = stack.pop();
-      elements[current][2] = (i - current) * (current - stack[stack.length - 1]);
-    }
-
-    stack.push(i);
-  }
-
-  elements.sort((a, b) => b[0] - a[0]);
-
-  let result = 1n;
-  let remainingOps = k;
-
-  for (let i = 0; remainingOps > 0; i++) {
-    const usedOps = Math.min(remainingOps, elements[i][2]);
-    remainingOps -= usedOps;
-
-    const cacheKey = `${elements[i][0]},${usedOps}`;
-    let power;
-
-    if (cacheKey in powerCache) {
-      power = powerCache[cacheKey];
-    } else {
-      let base = BigInt(elements[i][0]);
-      let exp = usedOps;
-      power = 1n;
-
-      while (exp > 0) {
-        if (exp & 1) {
-          power = (power * base) % MOD;
-        }
-        exp >>= 1;
-        base = (base * base) % MOD;
-      }
-
-      powerCache[cacheKey] = power;
-    }
-
-    result = (result * power) % MOD;
-  }
-
-  return Number(result);
-};
diff --git a/solutions/2843-count-symmetric-integers.js b/solutions/2843-count-symmetric-integers.js
deleted file mode 100644
index d9f472ac..00000000
--- a/solutions/2843-count-symmetric-integers.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 2843. Count Symmetric Integers
- * https://leetcode.com/problems/count-symmetric-integers/
- * Difficulty: Easy
- *
- * You are given two positive integers low and high.
- *
- * An integer x consisting of 2 * n digits is symmetric if the sum of the first n digits of x is
- * equal to the sum of the last n digits of x. Numbers with an odd number of digits are never
- * symmetric.
- *
- * Return the number of symmetric integers in the range [low, high].
- */
-
-/**
- * @param {number} low
- * @param {number} high
- * @return {number}
- */
-var countSymmetricIntegers = function(low, high) {
-  let result = 0;
-
-  for (let number = low; number <= high; number++) {
-    if (isSymmetric(number)) result++;
-  }
-
-  return result;
-
-  function isSymmetric(number) {
-    const digits = number.toString().split('');
-    const length = digits.length;
-    if (length % 2 !== 0) return false;
-    const mid = length / 2;
-    const firstHalfSum = digits.slice(0, mid).reduce((sum, digit) => sum + Number(digit), 0);
-    const secondHalfSum = digits.slice(mid).reduce((sum, digit) => sum + Number(digit), 0);
-
-    return firstHalfSum === secondHalfSum;
-  }
-};
diff --git a/solutions/2845-count-of-interesting-subarrays.js b/solutions/2845-count-of-interesting-subarrays.js
deleted file mode 100644
index 841f4b24..00000000
--- a/solutions/2845-count-of-interesting-subarrays.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 2845. Count of Interesting Subarrays
- * https://leetcode.com/problems/count-of-interesting-subarrays/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums, an integer modulo, and an integer k.
- *
- * Your task is to find the count of subarrays that are interesting.
- *
- * A subarray nums[l..r] is interesting if the following condition holds:
- * - Let cnt be the number of indices i in the range [l, r] such that nums[i] % modulo == k.
- *   Then, cnt % modulo == k.
- *
- * Return an integer denoting the count of interesting subarrays.
- *
- * Note: A subarray is a contiguous non-empty sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} modulo
- * @param {number} k
- * @return {number}
- */
-var countInterestingSubarrays = function(nums, modulo, k) {
-  const prefixCounts = new Map([[0, 1]]);
-  let currentSum = 0;
-  let result = 0;
-
-  for (const num of nums) {
-    currentSum = (currentSum + (num % modulo === k ? 1 : 0)) % modulo;
-    result += prefixCounts.get((currentSum - k + modulo) % modulo) || 0;
-    prefixCounts.set(currentSum, (prefixCounts.get(currentSum) || 0) + 1);
-  }
-
-  return result;
-};
diff --git a/solutions/2873-maximum-value-of-an-ordered-triplet-i.js b/solutions/2873-maximum-value-of-an-ordered-triplet-i.js
deleted file mode 100644
index f9aa3686..00000000
--- a/solutions/2873-maximum-value-of-an-ordered-triplet-i.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 2873. Maximum Value of an Ordered Triplet I
- * https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-i/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums.
- *
- * Return the maximum value over all triplets of indices (i, j, k) such that i < j < k.
- * If all such triplets have a negative value, return 0.
- *
- * The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var maximumTripletValue = function(nums) {
-  let result = 0;
-
-  for (let i = 0; i < nums.length - 2; i++) {
-    for (let j = i + 1; j < nums.length - 1; j++) {
-      const diff = nums[i] - nums[j];
-      if (diff <= 0) continue;
-      for (let k = j + 1; k < nums.length; k++) {
-        result = Math.max(result, diff * nums[k]);
-      }
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2874-maximum-value-of-an-ordered-triplet-ii.js b/solutions/2874-maximum-value-of-an-ordered-triplet-ii.js
deleted file mode 100644
index 8894a753..00000000
--- a/solutions/2874-maximum-value-of-an-ordered-triplet-ii.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * 2874. Maximum Value of an Ordered Triplet II
- * https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-ii/
- * Difficulty: Medium
- *
- * You are given a 0-indexed integer array nums.
- *
- * Return the maximum value over all triplets of indices (i, j, k) such that i < j < k. If all
- * such triplets have a negative value, return 0.
- *
- * The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var maximumTripletValue = function(nums) {
-  let result = 0;
-  let maxNum = nums[0];
-  let maxDiff = 0;
-
-  for (let i = 1; i < nums.length; i++) {
-    result = Math.max(result, maxDiff * nums[i]);
-    maxDiff = Math.max(maxDiff, maxNum - nums[i]);
-    maxNum = Math.max(maxNum, nums[i]);
-  }
-
-  return result;
-};
diff --git a/solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js b/solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js
deleted file mode 100644
index b4df7c52..00000000
--- a/solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2900. Longest Unequal Adjacent Groups Subsequence I
- * https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i/
- * Difficulty: Easy
- *
- * You are given a string array words and a binary array groups both of length n, where words[i]
- * is associated with groups[i].
- *
- * Your task is to select the longest alternating subsequence from words. A subsequence of words
- * is alternating if for any two consecutive strings in the sequence, their corresponding elements
- * in the binary array groups differ. Essentially, you are to choose strings such that adjacent
- * elements have non-matching corresponding bits in the groups array.
- *
- * Formally, you need to find the longest subsequence of an array of indices [0, 1, ..., n - 1]
- * denoted as [i0, i1, ..., ik-1], such that groups[ij] != groups[ij+1] for each 0 <= j < k - 1
- * and then find the words corresponding to these indices.
- *
- * Return the selected subsequence. If there are multiple answers, return any of them.
- *
- * Note: The elements in words are distinct.
- */
-
-/**
- * @param {string[]} words
- * @param {number[]} groups
- * @return {string[]}
- */
-var getLongestSubsequence = function(words, groups) {
-  const result = [words[0]];
-  let lastGroup = groups[0];
-
-  for (let i = 1; i < words.length; i++) {
-    if (groups[i] !== lastGroup) {
-      result.push(words[i]);
-      lastGroup = groups[i];
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js b/solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js
deleted file mode 100644
index 1a290423..00000000
--- a/solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * 2901. Longest Unequal Adjacent Groups Subsequence II
- * https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-ii/
- * Difficulty: Medium
- *
- * You are given a string array words, and an array groups, both arrays having length n.
- *
- * The hamming distance between two strings of equal length is the number of positions at which the
- * corresponding characters are different.
- *
- * You need to select the longest subsequence from an array of indices [0, 1, ..., n - 1], such
- * that for the subsequence denoted as [i0, i1, ..., ik-1] having length k, the following holds:
- * - For adjacent indices in the subsequence, their corresponding groups are unequal, i.e.,
- *   groups[ij] != groups[ij+1], for each j where 0 < j + 1 < k.
- * - words[ij] and words[ij+1] are equal in length, and the hamming distance between them is 1,
- *   where 0 < j + 1 < k, for all indices in the subsequence.
- *
- * Return a string array containing the words corresponding to the indices (in order) in the
- * selected subsequence. If there are multiple answers, return any of them.
- *
- * Note: strings in words may be unequal in length.
- */
-
-/**
- * @param {string[]} words
- * @param {number[]} groups
- * @return {string[]}
- */
-var getWordsInLongestSubsequence = function(words, groups) {
-  const n = words.length;
-  const dp = new Array(n).fill(1);
-  const prev = new Array(n).fill(-1);
-  let maxLen = 1;
-  let lastIndex = 0;
-
-  for (let i = 1; i < n; i++) {
-    for (let j = 0; j < i; j++) {
-      if (groups[i] !== groups[j] && helper(words[i], words[j])) {
-        if (dp[j] + 1 > dp[i]) {
-          dp[i] = dp[j] + 1;
-          prev[i] = j;
-        }
-      }
-    }
-    if (dp[i] > maxLen) {
-      maxLen = dp[i];
-      lastIndex = i;
-    }
-  }
-
-  const result = [];
-  while (lastIndex !== -1) {
-    result.push(words[lastIndex]);
-    lastIndex = prev[lastIndex];
-  }
-
-  return result.reverse();
-
-  function helper(s1, s2) {
-    if (s1.length !== s2.length) return false;
-    let diff = 0;
-    for (let i = 0; i < s1.length; i++) {
-      if (s1[i] !== s2[i]) diff++;
-      if (diff > 1) return false;
-    }
-    return diff === 1;
-  }
-};
diff --git a/solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js b/solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js
deleted file mode 100644
index 15ea4af7..00000000
--- a/solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros
- * https://leetcode.com/problems/minimum-equal-sum-of-two-arrays-after-replacing-zeros/
- * Difficulty: Medium
- *
- * You are given two arrays nums1 and nums2 consisting of positive integers.
- *
- * You have to replace all the 0's in both arrays with strictly positive integers such that the
- * sum of elements of both arrays becomes equal.
- *
- * Return the minimum equal sum you can obtain, or -1 if it is impossible.
- */
-
-/**
- * @param {number[]} nums1
- * @param {number[]} nums2
- * @return {number}
- */
-var minSum = function(nums1, nums2) {
-  let sum1 = 0;
-  let zeros1 = 0;
-  for (const num of nums1) {
-    sum1 += num;
-    if (num === 0) zeros1++;
-  }
-
-  let sum2 = 0;
-  let zeros2 = 0;
-  for (const num of nums2) {
-    sum2 += num;
-    if (num === 0) zeros2++;
-  }
-
-  const minSum1 = sum1 + zeros1;
-  const minSum2 = sum2 + zeros2;
-
-  if (minSum1 > sum2 && zeros2 === 0 || minSum2 > sum1 && zeros1 === 0) return -1;
-
-  return Math.max(minSum1, minSum2);
-};
diff --git a/solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js b/solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js
deleted file mode 100644
index 1a67fad9..00000000
--- a/solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 2962. Count Subarrays Where Max Element Appears at Least K Times
- * https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/
- * Difficulty: Medium
- *
- * You are given an integer array nums and a positive integer k.
- *
- * Return the number of subarrays where the maximum element of nums appears at least k times in
- * that subarray.
- *
- * A subarray is a contiguous sequence of elements within an array.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var countSubarrays = function(nums, k) {
-  const maxNum = Math.max(...nums);
-  let maxCount = 0;
-  let left = 0;
-  let result = 0;
-
-  for (let right = 0; right < nums.length; right++) {
-    if (nums[right] === maxNum) maxCount++;
-    while (maxCount >= k) {
-      result += nums.length - right;
-      if (nums[left] === maxNum) maxCount--;
-      left++;
-    }
-  }
-
-  return result;
-};
diff --git a/solutions/2965-find-missing-and-repeated-values.js b/solutions/2965-find-missing-and-repeated-values.js
deleted file mode 100644
index c45f7c09..00000000
--- a/solutions/2965-find-missing-and-repeated-values.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * 2965. Find Missing and Repeated Values
- * https://leetcode.com/problems/find-missing-and-repeated-values/
- * Difficulty: Easy
- *
- * You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2].
- * Each integer appears exactly once except a which appears twice and b which is missing. The task
- * is to find the repeating and missing numbers a and b.
- *
- * Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.
- */
-
-/**
- * @param {number[][]} grid
- * @return {number[]}
- */
-var findMissingAndRepeatedValues = function(grid) {
-  const sum = grid.flat().reduce((a, b) => a + b, 0);
-  const expectedSum = (grid.length * grid.length * (grid.length * grid.length + 1)) / 2;
-  const repeated = sum - [...new Set(grid.flat())].reduce((a, b) => a + b, 0);
-  return [repeated, expectedSum - sum + repeated];
-};
diff --git a/solutions/2999-count-the-number-of-powerful-integers.js b/solutions/2999-count-the-number-of-powerful-integers.js
deleted file mode 100644
index 88b524b6..00000000
--- a/solutions/2999-count-the-number-of-powerful-integers.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * 2999. Count the Number of Powerful Integers
- * https://leetcode.com/problems/count-the-number-of-powerful-integers/
- * Difficulty: Hard
- *
- * You are given three integers start, finish, and limit. You are also given a 0-indexed string
- * s representing a positive integer.
- *
- * A positive integer x is called powerful if it ends with s (in other words, s is a suffix of x)
- * and each digit in x is at most limit.
- *
- * Return the total number of powerful integers in the range [start..finish].
- *
- * A string x is a suffix of a string y if and only if x is a substring of y that starts from
- * some index (including 0) in y and extends to the index y.length - 1. For example, 25 is a
- * suffix of 5125 whereas 512 is not.
- */
-
-/**
- * @param {number} start
- * @param {number} finish
- * @param {number} limit
- * @param {string} suffix
- * @return {number}
- */
-var numberOfPowerfulInt = function(start, finish, limit, suffix) {
-  start--;
-  const startCount = countValidNums(start, limit, suffix);
-  const finishCount = countValidNums(finish, limit, suffix);
-  return finishCount - startCount;
-
-  function countValidNums(number, maxDigit, suffix) {
-    const suffixNum = parseInt(suffix);
-    const suffixMod = 10 ** suffix.length;
-    const suffixPart = number % suffixMod;
-    let baseNum = Math.floor(number / suffixMod);
-    if (suffixPart < suffixNum) baseNum--;
-
-    if (baseNum <= 0) return baseNum + 1;
-
-    const digitStr = baseNum.toString();
-    let count = digitStr.charCodeAt(0) - 48;
-    let isExact = 1;
-
-    if (count > maxDigit) {
-      return (maxDigit + 1) ** digitStr.length;
-    }
-
-    for (let i = 1; i < digitStr.length; i++) {
-      count *= (maxDigit + 1);
-      if (isExact) {
-        const currentDigit = digitStr.charCodeAt(i) - 48;
-        if (currentDigit > maxDigit) {
-          isExact = 0;
-          count += maxDigit + 1;
-        } else {
-          count += currentDigit;
-        }
-      }
-    }
-
-    return count + isExact;
-  }
-};
diff --git a/solutions/3024-type-of-triangle.js b/solutions/3024-type-of-triangle.js
deleted file mode 100644
index 0a62411d..00000000
--- a/solutions/3024-type-of-triangle.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * 3024. Type of Triangle
- * https://leetcode.com/problems/type-of-triangle/
- * Difficulty: Easy
- *
- * You are given a 0-indexed integer array nums of size 3 which can form the sides of a triangle.
- * - A triangle is called equilateral if it has all sides of equal length.
- * - A triangle is called isosceles if it has exactly two sides of equal length.
- * - A triangle is called scalene if all its sides are of different lengths.
- *
- * Return a string representing the type of triangle that can be formed or "none" if it cannot
- * form a triangle.
- */
-
-/**
- * @param {number[]} nums
- * @return {string}
- */
-var triangleType = function(nums) {
-  const [sideA, sideB, sideC] = nums.sort((a, b) => a - b);
-
-  if (sideA + sideB <= sideC) return 'none';
-  if (sideA === sideB && sideB === sideC) return 'equilateral';
-  if (sideA === sideB || sideB === sideC) return 'isosceles';
-
-  return 'scalene';
-};
diff --git a/solutions/3068-find-the-maximum-sum-of-node-values.js b/solutions/3068-find-the-maximum-sum-of-node-values.js
deleted file mode 100644
index 27666217..00000000
--- a/solutions/3068-find-the-maximum-sum-of-node-values.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * 3068. Find the Maximum Sum of Node Values
- * https://leetcode.com/problems/find-the-maximum-sum-of-node-values/
- * Difficulty: Hard
- *
- * There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed
- * 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an
- * edge between nodes ui and vi in the tree. You are also given a positive integer k, and a
- * 0-indexed array of non-negative integers nums of length n, where nums[i] represents the
- * value of the node numbered i.
- *
- * Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the
- * following operation any number of times (including zero) on the tree:
- * - Choose any edge [u, v] connecting the nodes u and v, and update their values as follows:
- *   - nums[u] = nums[u] XOR k
- *   - nums[v] = nums[v] XOR k
- *
- * Return the maximum possible sum of the values Alice can achieve by performing the operation
- * any number of times.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @param {number[][]} edges
- * @return {number}
- */
-var maximumValueSum = function(nums, k, edges) {
-  let totalSum = 0;
-  let minChange = Infinity;
-  let changeCount = 0;
-
-  for (const num of nums) {
-    const xored = num ^ k;
-    const change = xored - num;
-
-    if (change > 0) {
-      totalSum += xored;
-      changeCount++;
-    } else {
-      totalSum += num;
-    }
-
-    minChange = Math.min(minChange, Math.abs(change));
-  }
-
-  if (changeCount % 2 === 0) {
-    return totalSum;
-  }
-
-  return totalSum - minChange;
-};
diff --git a/solutions/3108-minimum-cost-walk-in-weighted-graph.js b/solutions/3108-minimum-cost-walk-in-weighted-graph.js
deleted file mode 100644
index daa3b8a5..00000000
--- a/solutions/3108-minimum-cost-walk-in-weighted-graph.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * 3108. Minimum Cost Walk in Weighted Graph
- * https://leetcode.com/problems/minimum-cost-walk-in-weighted-graph/
- * Difficulty: Hard
- *
- * There is an undirected weighted graph with n vertices labeled from 0 to n - 1.
- *
- * You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that
- * there is an edge between vertices ui and vi with a weight of wi.
- *
- * A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex,
- * and each edge connects the vertex that comes before it and the vertex that comes after it.
- * It's important to note that a walk may visit the same edge or vertex more than once.
- *
- * The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the
- * weights of the edges traversed during the walk. In other words, if the sequence of edge weights
- * encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2
- * & ... & wk, where & denotes the bitwise AND operator.
- *
- * You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find
- * the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no
- * such walk, the answer is -1.
- *
- * Return the array answer, where answer[i] denotes the minimum cost of a walk for query i.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} edges
- * @param {number[][]} query
- * @return {number[]}
- */
-var minimumCost = function(n, edges, query) {
-  const parent = new Array(n).fill().map((_, i) => i);
-  const costs = new Array(n).fill(2 ** 17 - 1);
-
-  for (const [u, v, w] of edges) {
-    const [p1, p2] = [find(u), find(v)];
-    parent[p1] = p2;
-    costs[p1] = costs[p2] = costs[p1] & costs[p2] & w;
-  }
-
-  for (let i = 0; i < n; i++) {
-    parent[i] = find(i);
-  }
-
-  return query.map(([s, t]) => {
-    if (s === t) return 0;
-    return parent[s] === parent[t] ? costs[parent[s]] : -1;
-  });
-
-  function find(key) {
-    if (parent[key] !== key) {
-      parent[key] = find(parent[key]);
-    }
-    return parent[key];
-  }
-};
diff --git a/solutions/3169-count-days-without-meetings.js b/solutions/3169-count-days-without-meetings.js
deleted file mode 100644
index cd97771c..00000000
--- a/solutions/3169-count-days-without-meetings.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 3169. Count Days Without Meetings
- * https://leetcode.com/problems/count-days-without-meetings/
- * Difficulty: Medium
- *
- * You are given a positive integer days representing the total number of days an employee is
- * available for work (starting from day 1). You are also given a 2D array meetings of size n
- * where, meetings[i] = [start_i, end_i] represents the starting and ending days of meeting
- * i (inclusive).
- *
- * Return the count of days when the employee is available for work but no meetings are scheduled.
- *
- * Note: The meetings may overlap.
- */
-
-/**
- * @param {number} days
- * @param {number[][]} meetings
- * @return {number}
- */
-var countDays = function(days, meetings) {
-  meetings.sort((a, b) => a[0] - b[0]);
-
-  let result = 0;
-  let currentEnd = 0;
-
-  for (const [start, end] of meetings) {
-    if (start > currentEnd + 1) {
-      result += start - currentEnd - 1;
-    }
-    currentEnd = Math.max(currentEnd, end);
-  }
-
-  if (currentEnd < days) {
-    result += days - currentEnd;
-  }
-
-  return result;
-};
diff --git a/solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js b/solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js
deleted file mode 100644
index 7ee13752..00000000
--- a/solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * 3191. Minimum Operations to Make Binary Array Elements Equal to One I
- * https://leetcode.com/problems/minimum-operations-to-make-binary-array-elements-equal-to-one-i/
- * Difficulty: Medium
- *
- * You are given a binary array nums.
- *
- * You can do the following operation on the array any number of times (possibly zero):
- * - Choose any 3 consecutive elements from the array and flip all of them.
- *
- * Flipping an element means changing its value from 0 to 1, and from 1 to 0.
- *
- * Return the minimum number of operations required to make all elements in nums equal to 1.
- * If it is impossible, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var minOperations = function(nums) {
-  const result = [...nums];
-  let operations = 0;
-
-  for (let i = 0; i < nums.length - 2; i++) {
-    if (result[i] === 0) {
-      result[i] ^= 1;
-      result[i + 1] ^= 1;
-      result[i + 2] ^= 1;
-      operations++;
-    }
-  }
-
-  return result.every(num => num === 1) ? operations : -1;
-};
diff --git a/solutions/3208-alternating-groups-ii.js b/solutions/3208-alternating-groups-ii.js
deleted file mode 100644
index 6d4be0de..00000000
--- a/solutions/3208-alternating-groups-ii.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * 3208. Alternating Groups II
- * https://leetcode.com/problems/alternating-groups-ii/
- * Difficulty: Medium
- *
- * There is a circle of red and blue tiles. You are given an array of integers colors and
- * an integer k. The color of tile i is represented by colors[i]:
- * - colors[i] == 0 means that tile i is red.
- *  -colors[i] == 1 means that tile i is blue.
- *
- * An alternating group is every k contiguous tiles in the circle with alternating colors
- * (each tile in the group except the first and last one has a different color from its
- * left and right tiles).
- *
- * Return the number of alternating groups.
- *
- * Note that since colors represents a circle, the first and the last tiles are considered
- * to be next to each other.
- */
-
-/**
- * @param {number[]} colors
- * @param {number} k
- * @return {number}
- */
-var numberOfAlternatingGroups = function(colors, k) {
-  const extended = colors.concat(colors.slice(0, k - 1));
-  let result = 0;
-  let invalid = 0;
-
-  for (let i = 1; i < k; i++) {
-    if (extended[i] === extended[i - 1]) {
-      invalid++;
-    }
-  }
-  if (invalid === 0) {
-    result++;
-  }
-  for (let i = 1; i < colors.length; i++) {
-    if (extended[i] === extended[i - 1]) invalid--;
-    if (extended[i + k - 1] === extended[i + k - 2]) invalid++;
-    if (invalid === 0) result++;
-  }
-
-  return result;
-};
diff --git a/solutions/3272-find-the-count-of-good-integers.js b/solutions/3272-find-the-count-of-good-integers.js
deleted file mode 100644
index fd636f11..00000000
--- a/solutions/3272-find-the-count-of-good-integers.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * 3272. Find the Count of Good Integers
- * https://leetcode.com/problems/find-the-count-of-good-integers/
- * Difficulty: Hard
- *
- * You are given two positive integers n and k.
- *
- * An integer x is called k-palindromic if:
- * - x is a palindrome.
- * - x is divisible by k.
- *
- * An integer is called good if its digits can be rearranged to form a k-palindromic integer.
- * For example, for k = 2, 2020 can be rearranged to form the k-palindromic integer 2002,
- * whereas 1010 cannot be rearranged to form a k-palindromic integer.
- *
- * Return the count of good integers containing n digits.
- *
- * Note that any integer must not have leading zeros, neither before nor after rearrangement.
- * For example, 1010 cannot be rearranged to form 101.
- */
-
-/**
- * @param {number} n
- * @param {number} k
- * @return {number}
- */
-function countGoodIntegers(n, k) {
-  if (n === 1) return Math.floor(9 / k);
-
-  let result = 0;
-  const halfLength = Math.ceil(n / 2);
-  const start = Math.pow(10, halfLength - 1);
-  const end = Math.pow(10, halfLength);
-
-  const seen = new Set();
-  for (let i = start; i < end; i++) {
-    const palindromeStr = generatePalindrome(i);
-    if (palindromeStr.length !== n) continue;
-    const num = parseInt(palindromeStr);
-    if (num % k !== 0) continue;
-
-    const sortedDigits = palindromeStr.split('').sort().join('');
-    if (seen.has(sortedDigits)) continue;
-    seen.add(sortedDigits);
-
-    result += calculateArrangements(palindromeStr);
-  }
-
-  return result;
-
-  function generatePalindrome(firstHalf) {
-    const str = firstHalf.toString();
-    const isOdd = n % 2 === 1;
-    return isOdd
-      ? str + str.slice(0, -1).split('').reverse().join('')
-      : str + str.split('').reverse().join('');
-  }
-
-  function calculateArrangements(numStr) {
-    const freq = new Map();
-    for (const digit of numStr) {
-      freq.set(digit, (freq.get(digit) || 0) + 1);
-    }
-    const total = multinomial(n, freq);
-    if (!freq.has('0')) return total;
-
-    freq.set('0', freq.get('0') - 1);
-    if (freq.get('0') === 0) freq.delete('0');
-    return total - multinomial(n - 1, freq);
-  }
-
-  function multinomial(length, freq) {
-    const numerator = factorial(length);
-    let denominator = 1;
-    for (const count of freq.values()) {
-      denominator *= factorial(count);
-    }
-    return numerator / denominator;
-  }
-
-  function factorial(num) {
-    let res = 1;
-    for (let i = 2; i <= num; i++) res *= i;
-    return res;
-  }
-}
diff --git a/solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js b/solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js
deleted file mode 100644
index 7e8f635d..00000000
--- a/solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 3306. Count of Substrings Containing Every Vowel and K Consonants II
- * https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/
- * Difficulty: Medium
- *
- * You are given a string word and a non-negative integer k.
- *
- * Return the total number of substrings of word that contain every vowel ('a', 'e', 'i', 'o', and
- * 'u') at least once and exactly k consonants.
- */
-
-/**
- * @param {string} word
- * @param {number} k
- * @return {number}
- */
-function countOfSubstrings(word, k) {
-  return helper(word, k) - helper(word, k - 1);
-
-  function helper(word, k) {
-    const vowels = { a: 0, e: 0, i: 0, o: 0, u: 0 };
-    let count = 0;
-    let left = 0;
-    let consonants = k;
-
-    for (let right = 0; right < word.length; right++) {
-      const character = word[right];
-      if (character in vowels) {
-        vowels[character]++;
-      } else {
-        consonants--;
-      }
-
-      while (vowels.a > 0 && vowels.e > 0 && vowels.i > 0 && vowels.o > 0
-             && vowels.u > 0 && consonants < 0) {
-        const leftCharacter = word[left];
-        if (leftCharacter in vowels) {
-          vowels[leftCharacter]--;
-        } else {
-          consonants++;
-        }
-        left++;
-      }
-      count += right - left + 1;
-    }
-    return count;
-  }
-}
diff --git a/solutions/3335-total-characters-in-string-after-transformations-i.js b/solutions/3335-total-characters-in-string-after-transformations-i.js
deleted file mode 100644
index e62e76ea..00000000
--- a/solutions/3335-total-characters-in-string-after-transformations-i.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * 3335. Total Characters in String After Transformations I
- * https://leetcode.com/problems/total-characters-in-string-after-transformations-i/
- * Difficulty: Medium
- *
- * You are given a string s and an integer t, representing the number of transformations to
- * perform. In one transformation, every character in s is replaced according to the following
- * rules:
- * - If the character is 'z', replace it with the string "ab".
- * - Otherwise, replace it with the next character in the alphabet. For example, 'a' is replaced
- *   with 'b', 'b' is replaced with 'c', and so on.
- *
- * Return the length of the resulting string after exactly t transformations.
- *
- * Since the answer may be very large, return it modulo 109 + 7.
- */
-
-/**
- * @param {string} s
- * @param {number} t
- * @return {number}
- */
-var lengthAfterTransformations = function(s, t) {
-  const MOD = 1e9 + 7;
-  const freq = new Array(26).fill(0);
-
-  for (const char of s) {
-    freq[char.charCodeAt(0) - 97]++;
-  }
-
-  for (let i = 0; i < t; i++) {
-    const newFreq = new Array(26).fill(0);
-    for (let j = 0; j < 25; j++) {
-      newFreq[j + 1] = freq[j];
-    }
-    newFreq[0] = (newFreq[0] + freq[25]) % MOD;
-    newFreq[1] = (newFreq[1] + freq[25]) % MOD;
-    freq.splice(0, 26, ...newFreq);
-  }
-
-  let result = 0;
-  for (const count of freq) {
-    result = (result + count) % MOD;
-  }
-
-  return result;
-};
diff --git a/solutions/3337-total-characters-in-string-after-transformations-ii.js b/solutions/3337-total-characters-in-string-after-transformations-ii.js
deleted file mode 100644
index 91d4d6aa..00000000
--- a/solutions/3337-total-characters-in-string-after-transformations-ii.js
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * 3337. Total Characters in String After Transformations II
- * https://leetcode.com/problems/total-characters-in-string-after-transformations-ii/
- * Difficulty: Hard
- *
- * You are given a string s consisting of lowercase English letters, an integer t representing
- * the number of transformations to perform, and an array nums of size 26. In one transformation,
- * every character in s is replaced according to the following rules:
- * - Replace s[i] with the next nums[s[i] - 'a'] consecutive characters in the alphabet. For
- *   example, if s[i] = 'a' and nums[0] = 3, the character 'a' transforms into the next 3
- *   consecutive characters ahead of it, which results in "bcd".
- * - The transformation wraps around the alphabet if it exceeds 'z'. For example, if s[i] = 'y'
- *   and nums[24] = 3, the character 'y' transforms into the next 3 consecutive characters ahead
- *   of it, which results in "zab".
- *
- * Return the length of the resulting string after exactly t transformations.
- *
- * Since the answer may be very large, return it modulo 109 + 7.
- */
-
-/**
- * @param {string} s
- * @param {number} t
- * @param {number[]} nums
- * @return {number}
- */
-var lengthAfterTransformations = function(s, t, nums) {
-  const MOD = 1000000007n;
-  const freq = new Array(26).fill(0n);
-
-  for (const char of s) {
-    freq[char.charCodeAt(0) - 97]++;
-  }
-
-  const matrix = new Array(26).fill().map(() => new Array(26).fill(0n));
-  for (let i = 0; i < 26; i++) {
-    for (let j = 0; j < nums[i]; j++) {
-      matrix[(i + j + 1) % 26][i] = 1n;
-    }
-  }
-
-  const finalMatrix = matrixPower(matrix, t);
-  let total = 0n;
-
-  for (let i = 0; i < 26; i++) {
-    let sum = 0n;
-    for (let j = 0; j < 26; j++) {
-      sum = (sum + finalMatrix[i][j] * freq[j]) % MOD;
-    }
-    total = (total + sum) % MOD;
-  }
-
-  return Number(total);
-
-  function matrixMultiply(a, b) {
-    const result = new Array(26).fill().map(() => new Array(26).fill(0n));
-    for (let i = 0; i < 26; i++) {
-      for (let j = 0; j < 26; j++) {
-        for (let k = 0; k < 26; k++) {
-          result[i][j] = (result[i][j] + a[i][k] * b[k][j]) % MOD;
-        }
-      }
-    }
-    return result;
-  }
-
-  function matrixPower(mat, power) {
-    let result = new Array(26).fill().map(() => new Array(26).fill(0n));
-    for (let i = 0; i < 26; i++) result[i][i] = 1n;
-
-    while (power > 0) {
-      if (power & 1) result = matrixMultiply(result, mat);
-      mat = matrixMultiply(mat, mat);
-      power >>= 1;
-    }
-    return result;
-  }
-};
diff --git a/solutions/3341-find-minimum-time-to-reach-last-room-i.js b/solutions/3341-find-minimum-time-to-reach-last-room-i.js
deleted file mode 100644
index fae5957b..00000000
--- a/solutions/3341-find-minimum-time-to-reach-last-room-i.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 3341. Find Minimum Time to Reach Last Room I
- * https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/
- * Difficulty: Medium
- *
- * There is a dungeon with n x m rooms arranged as a grid.
- *
- * You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum
- * time in seconds when you can start moving to that room. You start from the room (0, 0) at
- * time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes exactly
- * one second.
- *
- * Return the minimum time to reach the room (n - 1, m - 1).
- *
- * Two rooms are adjacent if they share a common wall, either horizontally or vertically.
- */
-
-/**
- * @param {number[][]} moveTime
- * @return {number}
- */
-var minTimeToReach = function(moveTime) {
-  const rows = moveTime.length;
-  const cols = moveTime[0].length;
-  const distances = Array.from({ length: rows }, () => new Array(cols).fill(Infinity));
-  const pq = new PriorityQueue((a, b) => a[0] - b[0]);
-  pq.enqueue([0, 0, 0]);
-  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
-
-  distances[0][0] = 0;
-
-  while (!pq.isEmpty()) {
-    const [time, row, col] = pq.dequeue();
-
-    if (row === rows - 1 && col === cols - 1) return time;
-
-    if (time > distances[row][col]) continue;
-
-    for (const [dr, dc] of directions) {
-      const newRow = row + dr;
-      const newCol = col + dc;
-
-      if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue;
-
-      const newTime = Math.max(time, moveTime[newRow][newCol]) + 1;
-
-      if (newTime < distances[newRow][newCol]) {
-        distances[newRow][newCol] = newTime;
-        pq.enqueue([newTime, newRow, newCol]);
-      }
-    }
-  }
-
-  return distances[rows - 1][cols - 1];
-};
diff --git a/solutions/3342-find-minimum-time-to-reach-last-room-ii.js b/solutions/3342-find-minimum-time-to-reach-last-room-ii.js
deleted file mode 100644
index 24c9fc5a..00000000
--- a/solutions/3342-find-minimum-time-to-reach-last-room-ii.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * 3342. Find Minimum Time to Reach Last Room II
- * https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii/
- * Difficulty: Medium
- *
- * There is a dungeon with n x m rooms arranged as a grid.
- *
- * You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum
- * time in seconds when you can start moving to that room. You start from the room (0, 0) at
- * time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes one
- * second for one move and two seconds for the next, alternating between the two.
- *
- * Return the minimum time to reach the room (n - 1, m - 1).
- *
- * Two rooms are adjacent if they share a common wall, either horizontally or vertically.
- */
-
-/**
- * @param {number[][]} moveTime
- * @return {number}
- */
-var minTimeToReach = function(moveTime) {
-  const rows = moveTime.length;
-  const cols = moveTime[0].length;
-  const distances = Array.from({ length: rows }, () => new Array(cols).fill(Infinity));
-  const pq = new PriorityQueue((a, b) => a[0] - b[0]);
-  pq.enqueue([0, 0, 0, 0]);
-  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
-
-  distances[0][0] = 0;
-
-  while (!pq.isEmpty()) {
-    const [time, row, col, moveCount] = pq.dequeue();
-
-    if (row === rows - 1 && col === cols - 1) return time;
-
-    if (time > distances[row][col]) continue;
-
-    for (const [dr, dc] of directions) {
-      const newRow = row + dr;
-      const newCol = col + dc;
-
-      if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue;
-
-      const moveCost = moveCount % 2 === 0 ? 1 : 2;
-      const startTime = Math.max(time, moveTime[newRow][newCol]);
-      const newTime = startTime + moveCost;
-
-      if (newTime < distances[newRow][newCol]) {
-        distances[newRow][newCol] = newTime;
-        pq.enqueue([newTime, newRow, newCol, moveCount + 1]);
-      }
-    }
-  }
-
-  return distances[rows - 1][cols - 1];
-};
diff --git a/solutions/3343-count-number-of-balanced-permutations.js b/solutions/3343-count-number-of-balanced-permutations.js
deleted file mode 100644
index 0e27eae1..00000000
--- a/solutions/3343-count-number-of-balanced-permutations.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * 3343. Count Number of Balanced Permutations
- * https://leetcode.com/problems/count-number-of-balanced-permutations/
- * Difficulty: Hard
- *
- * You are given a string num. A string of digits is called balanced if the sum of the digits
- * at even indices is equal to the sum of the digits at odd indices.
- *
- * Return the number of distinct permutations of num that are balanced.
- *
- * Since the answer may be very large, return it modulo 109 + 7.
- *
- * A permutation is a rearrangement of all the characters of a string.
- */
-
-/**
- * @param {string} num
- * @return {number}
- */
-var countBalancedPermutations = function(num) {
-  const MOD = 1e9 + 7;
-  const n = num.length;
-  const digitCounts = new Array(10).fill(0);
-  let totalSum = 0;
-
-  for (const char of num) {
-    const digit = parseInt(char);
-    digitCounts[digit]++;
-    totalSum += digit;
-  }
-
-  if (totalSum % 2) return 0;
-
-  const memo = new Map();
-
-  function combination(n, r) {
-    if (r > n) return 0;
-    if (r === 0 || r === n) return 1;
-    if (r > n - r) r = n - r;
-
-    let result = 1n;
-    for (let i = 0; i < r; i++) {
-      result = result * BigInt(n - i) / BigInt(i + 1);
-    }
-    return Number(result % BigInt(MOD));
-  }
-
-  function exploreDigits(digit, oddSlots, evenSlots, targetBalance) {
-    if (oddSlots === 0 && evenSlots === 0 && targetBalance === 0) return 1;
-    if (digit < 0 || oddSlots < 0 || evenSlots < 0 || targetBalance < 0) return 0;
-
-    const key = `${digit},${oddSlots},${evenSlots},${targetBalance}`;
-    if (memo.has(key)) return memo.get(key);
-
-    let result = 0;
-    for (let oddCount = 0; oddCount <= digitCounts[digit]; oddCount++) {
-      const evenCount = digitCounts[digit] - oddCount;
-      const ways = (BigInt(combination(oddSlots, oddCount))
-        * BigInt(combination(evenSlots, evenCount))) % BigInt(MOD);
-      const next = BigInt(exploreDigits(digit - 1, oddSlots - oddCount,
-        evenSlots - evenCount, targetBalance - digit * oddCount));
-      result = (result + Number((ways * next) % BigInt(MOD))) % MOD;
-    }
-
-    memo.set(key, result);
-    return result;
-  }
-
-  return exploreDigits(9, n - Math.floor(n / 2), Math.floor(n / 2), totalSum / 2);
-};
diff --git a/solutions/3355-zero-array-transformation-i.js b/solutions/3355-zero-array-transformation-i.js
deleted file mode 100644
index 21b9bc13..00000000
--- a/solutions/3355-zero-array-transformation-i.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 3355. Zero Array Transformation I
- * https://leetcode.com/problems/zero-array-transformation-i/
- * Difficulty: Medium
- *
- * You are given an integer array nums of length n and a 2D array queries, where
- * queries[i] = [li, ri].
- *
- * For each queries[i]:
- * - Select a subset of indices within the range [li, ri] in nums.
- * - Decrement the values at the selected indices by 1.
- *
- * A Zero Array is an array where all elements are equal to 0.
- *
- * Return true if it is possible to transform nums into a Zero Array after processing all the
- * queries sequentially, otherwise return false.
- */
-
-/**
- * @param {number[]} nums
- * @param {number[][]} queries
- * @return {boolean}
- */
-var isZeroArray = function(nums, queries) {
-  const maxDecrements = new Array(nums.length).fill(0);
-
-  for (const [left, right] of queries) {
-    maxDecrements[left]++;
-    if (right + 1 < nums.length) {
-      maxDecrements[right + 1]--;
-    }
-  }
-
-  let currentDecrements = 0;
-  for (let i = 0; i < nums.length; i++) {
-    currentDecrements += maxDecrements[i];
-    if (nums[i] > currentDecrements) {
-      return false;
-    }
-  }
-
-  return true;
-};
diff --git a/solutions/3356-zero-array-transformation-ii.js b/solutions/3356-zero-array-transformation-ii.js
deleted file mode 100644
index 59c4b9e4..00000000
--- a/solutions/3356-zero-array-transformation-ii.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * 3356. Zero Array Transformation II
- * https://leetcode.com/problems/zero-array-transformation-ii/
- * Difficulty: Medium
- *
- * You are given an integer array nums of length n and a 2D array queries where
- * queries[i] = [li, ri, vali].
- *
- * Each queries[i] represents the following action on nums:
- * - Decrement the value at each index in the range [li, ri] in nums by at most vali.
- * - The amount by which each value is decremented can be chosen independently for each index.
- *
- * A Zero Array is an array with all its elements equal to 0.
- *
- * Return the minimum possible non-negative value of k, such that after processing the first
- * k queries in sequence, nums becomes a Zero Array. If no such k exists, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @param {number[][]} queries
- * @return {number}
- */
-var minZeroArray = function(nums, queries) {
-  const diff = new Array(nums.length + 1).fill(0);
-  const total = nums.reduce((sum, num) => sum + num, 0);
-  let left = 0;
-  let right = queries.length - 1;
-  let result = -1;
-
-  if (total === 0) {
-    return 0;
-  }
-
-  while (left <= right) {
-    const mid = Math.floor((left + right) / 2);
-    if (canZeroOut(mid)) {
-      result = mid + 1;
-      right = mid - 1;
-    } else {
-      left = mid + 1;
-    }
-  }
-
-  return result;
-
-  function canZeroOut(k) {
-    const tempDiff = new Array(nums.length + 1).fill(0);
-    for (let i = 0; i <= k; i++) {
-      const [left, right, val] = queries[i];
-      tempDiff[left] += val;
-      if (right + 1 < nums.length) tempDiff[right + 1] -= val;
-    }
-
-    let current = 0;
-    let reduction = 0;
-    for (let i = 0; i < nums.length; i++) {
-      current = Math.max(0, current + tempDiff[i]);
-      reduction += Math.min(nums[i], current);
-      if (reduction >= total) return true;
-    }
-    return reduction >= total;
-  }
-};
diff --git a/solutions/3362-zero-array-transformation-iii.js b/solutions/3362-zero-array-transformation-iii.js
deleted file mode 100644
index f6d979bb..00000000
--- a/solutions/3362-zero-array-transformation-iii.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * 3362. Zero Array Transformation III
- * https://leetcode.com/problems/zero-array-transformation-iii/
- * Difficulty: Medium
- *
- * You are given an integer array nums of length n and a 2D array queries where
- * queries[i] = [li, ri].
- *
- * Each queries[i] represents the following action on nums:
- * - Decrement the value at each index in the range [li, ri] in nums by at most 1.
- * - The amount by which the value is decremented can be chosen independently for each index.
- *
- * A Zero Array is an array with all its elements equal to 0.
- *
- * Return the maximum number of elements that can be removed from queries, such that nums can
- * still be converted to a zero array using the remaining queries. If it is not possible to
- * convert nums to a zero array, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @param {number[][]} queries
- * @return {number}
- */
-var maxRemoval = function(nums, queries) {
-  queries.sort((a, b) => a[0] - b[0]);
-  const endIndexHeap = new MaxPriorityQueue();
-  const expiredQueries = new Array(nums.length + 1).fill(0);
-  let operationCount = 0;
-  let queryIndex = 0;
-
-  for (let numIndex = 0; numIndex < nums.length; numIndex++) {
-    operationCount -= expiredQueries[numIndex];
-
-    while (queryIndex < queries.length && queries[queryIndex][0] === numIndex) {
-      endIndexHeap.push(queries[queryIndex][1]);
-      queryIndex++;
-    }
-
-    while (
-      operationCount < nums[numIndex] && !endIndexHeap.isEmpty() && endIndexHeap.front() >= numIndex
-    ) {
-      operationCount++;
-      expiredQueries[endIndexHeap.pop() + 1]++;
-    }
-
-    if (operationCount < nums[numIndex]) {
-      return -1;
-    }
-  }
-
-  return endIndexHeap.size();
-};
diff --git a/solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js b/solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js
deleted file mode 100644
index 4ea40bf6..00000000
--- a/solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 3375. Minimum Operations to Make Array Values Equal to K
- * https://leetcode.com/problems/minimum-operations-to-make-array-values-equal-to-k/
- * Difficulty: Easy
- *
- * You are given an integer array nums and an integer k.
- *
- * An integer h is called valid if all values in the array that are strictly greater than
- * h are identical.
- *
- * For example, if nums = [10, 8, 10, 8], a valid integer is h = 9 because all nums[i] > 9
- * are equal to 10, but 5 is not a valid integer.
- *
- * You are allowed to perform the following operation on nums:
- * - Select an integer h that is valid for the current values in nums.
- * - For each index i where nums[i] > h, set nums[i] to h.
- *
- * Return the minimum number of operations required to make every element in nums equal to k.
- * If it is impossible to make all elements equal to k, return -1.
- */
-
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number}
- */
-var minOperations = function(nums, k) {
-  if (nums.some(x => x < k)) return -1;
-
-  const uniqueAbove = [...new Set(nums.filter(x => x > k))].sort((a, b) => b - a);
-  if (uniqueAbove.length === 0) return 0;
-
-  let result = 0;
-  let current = uniqueAbove.slice();
-
-  while (current.length > 0) {
-    const threshold = current[0] - 1;
-    current = current.filter(x => x <= threshold);
-    result++;
-    if (current.every(x => x === k)) break;
-  }
-
-  return result;
-};
diff --git a/solutions/3394-check-if-grid-can-be-cut-into-sections.js b/solutions/3394-check-if-grid-can-be-cut-into-sections.js
deleted file mode 100644
index 7175b79f..00000000
--- a/solutions/3394-check-if-grid-can-be-cut-into-sections.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 3394. Check if Grid can be Cut into Sections
- * https://leetcode.com/problems/check-if-grid-can-be-cut-into-sections/
- * Difficulty: Medium
- *
- * You are given an integer n representing the dimensions of an n x n grid, with the origin at the
- * bottom-left corner of the grid. You are also given a 2D array of coordinates rectangles, where
- * rectangles[i] is in the form [startx, starty, endx, endy], representing a rectangle on the grid.
- * Each rectangle is defined as follows:
- * - (startx, starty): The bottom-left corner of the rectangle.
- * - (endx, endy): The top-right corner of the rectangle.
- *
- * Note that the rectangles do not overlap. Your task is to determine if it is possible to make
- * either two horizontal or two vertical cuts on the grid such that:
- * - Each of the three resulting sections formed by the cuts contains at least one rectangle.
- * - Every rectangle belongs to exactly one section.
- *
- * Return true if such cuts can be made; otherwise, return false.
- */
-
-/**
- * @param {number} n
- * @param {number[][]} rectangles
- * @return {boolean}
- */
-var checkValidCuts = function(n, rectangles) {
-  return canPartition(rectangles.map(r => [r[0], r[2]]))
-    || canPartition(rectangles.map(r => [r[1], r[3]]));
-};
-
-function canPartition(intervals, cuts = 0) {
-  intervals.sort(([start1, end1], [start2, end2]) => start1 - start2 || end2 - end1);
-  let maxReach = intervals[0][1];
-  for (let i = 1; i < intervals.length; i++) {
-    if (intervals[i][0] >= maxReach && ++cuts === 2) return true;
-    maxReach = Math.max(intervals[i][1], maxReach);
-  }
-  return false;
-}
diff --git a/solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js b/solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js
deleted file mode 100644
index bd801d33..00000000
--- a/solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * 3461. Check If Digits Are Equal in String After Operations I
- * https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-i/
- * Difficulty: Easy
- *
- * You are given a string s consisting of digits. Perform the following operation repeatedly
- * until the string has exactly two digits:
- * - For each pair of consecutive digits in s, starting from the first digit, calculate a new
- *   digit as the sum of the two digits modulo 10.
- * - Replace s with the sequence of newly calculated digits, maintaining the order in which
- *   they are computed.
- *
- * Return true if the final two digits in s are the same; otherwise, return false.
- */
-
-/**
- * @param {string} s
- * @return {boolean}
- */
-var hasSameDigits = function(s) {
-  while (s.length > 2) {
-    let next = '';
-    for (let i = 0; i < s.length - 1; i++) {
-      next += (parseInt(s[i]) + parseInt(s[i + 1])) % 10;
-    }
-    s = next;
-  }
-  return s[0] === s[1];
-};
diff --git a/solutions/3462-maximum-sum-with-at-most-k-elements.js b/solutions/3462-maximum-sum-with-at-most-k-elements.js
deleted file mode 100644
index aafcd08f..00000000
--- a/solutions/3462-maximum-sum-with-at-most-k-elements.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * 3462. Maximum Sum With at Most K Elements
- * https://leetcode.com/problems/maximum-sum-with-at-most-k-elements/
- * Difficulty: Medium
- *
- * You are given a 2D integer matrix grid of size n x m, an integer array limits of length n, and
- * an integer k. The task is to find the maximum sum of at most k elements from the matrix grid
- * such that:
- * - The number of elements taken from the ith row of grid does not exceed limits[i].
- *
- * Return the maximum sum.
- */
-
-/**
- * @param {number[][]} grid
- * @param {number[]} limits
- * @param {number} k
- * @return {number}
- */
-var maxSum = function(grid, limits, k) {
-  const result = [];
-  grid.forEach((row, i) => {
-    result.push(...row.slice().sort((a, b) => b - a).slice(0, limits[i]));
-  });
-  return result.sort((a, b) => b - a).slice(0, k).reduce((sum, num) => sum + num, 0);
-};
diff --git a/solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js b/solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js
deleted file mode 100644
index 6315d00c..00000000
--- a/solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 3463. Check If Digits Are Equal in String After Operations II
- * https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-ii/
- * Difficulty: Hard
- *
- * You are given a string s consisting of digits. Perform the following operation repeatedly until
- * the string has exactly two digits:
- * - For each pair of consecutive digits in s, starting from the first digit, calculate a new digit
- *   as the sum of the two digits modulo 10.
- * - Replace s with the sequence of newly calculated digits, maintaining the order in which they
- *   are computed.
- *
- * Return true if the final two digits in s are the same; otherwise, return false.
- */
-
-/**
- * @param {string} s
- * @return {boolean}
- */
-var hasSameDigits = function(s) {
-  const n = s.length;
-  const binomialMod2 = (k, n) => (k & n) === k ? 1 : 0;
-  const binomialMod5 = (k, n) => {
-    if (k > n) return 0;
-    let result = 1;
-    const pascalMod5 = [
-      [1, 0, 0, 0, 0],
-      [1, 1, 0, 0, 0],
-      [1, 2, 1, 0, 0],
-      [1, 3, 3, 1, 0],
-      [1, 4, 1, 4, 1]
-    ];
-
-    while (k > 0 || n > 0) {
-      const ki = k % 5;
-      const ni = n % 5;
-      if (ki > ni) return 0;
-      result = (result * pascalMod5[ni][ki]) % 5;
-      k = Math.floor(k / 5);
-      n = Math.floor(n / 5);
-    }
-    return result;
-  };
-
-  const binomialMod10 = (k, n) => {
-    const mod2 = binomialMod2(k, n);
-    const mod5 = binomialMod5(k, n);
-    for (let i = 0; i < 10; i++) {
-      if (i % 2 === mod2 && i % 5 === mod5) return i;
-    }
-    return 0;
-  };
-
-  let sum1 = 0;
-  let sum2 = 0;
-  for (let i = 0; i <= n - 2; i++) {
-    const coeff = binomialMod10(i, n - 2);
-    sum1 = (sum1 + coeff * +s[i]) % 10;
-    sum2 = (sum2 + coeff * +s[i + 1]) % 10;
-  }
-
-  return sum1 === sum2;
-};
diff --git a/solutions/3464-maximize-the-distance-between-points-on-a-square.js b/solutions/3464-maximize-the-distance-between-points-on-a-square.js
deleted file mode 100644
index 47428649..00000000
--- a/solutions/3464-maximize-the-distance-between-points-on-a-square.js
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * 3464. Maximize the Distance Between Points on a Square
- * https://leetcode.com/problems/maximize-the-distance-between-points-on-a-square/
- * Difficulty: Hard
- *
- * You are given an integer side, representing the edge length of a square with corners
- * at (0, 0), (0, side), (side, 0), and (side, side) on a Cartesian plane.
- *
- * You are also given a positive integer k and a 2D integer array points, where
- * points[i] = [xi, yi] represents the coordinate of a point lying on the boundary of
- * the square.
- *
- * You need to select k elements among points such that the minimum Manhattan distance
- * between any two points is maximized.
- *
- * Return the maximum possible minimum Manhattan distance between the selected k points.
- *
- * The Manhattan Distance between two cells (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.
- */
-
-/**
- * @param {number} squareSide
- * @param {number[][]} coordinates
- * @param {number} pointsToPlace
- * @return {number}
- */
-var maxDistance = function(squareSide, coordinates, pointsToPlace) {
-  const pointCount = coordinates.length;
-  const positions = new Array(pointCount);
-
-  for (let i = 0; i < pointCount; i++) {
-    const [x, y] = coordinates[i];
-    positions[i] = y === 0 ? x : x === squareSide
-      ? squareSide + y
-      : y === squareSide
-        ? 2 * squareSide + (squareSide - x)
-        : 3 * squareSide + (squareSide - y);
-  }
-  positions.sort((a, b) => a - b);
-
-  const perimeter = 4 * squareSide;
-  const extendedPositions = new Array(pointCount * 2);
-  for (let i = 0; i < pointCount; i++) {
-    extendedPositions[i] = positions[i];
-    extendedPositions[i + pointCount] = positions[i] + perimeter;
-  }
-
-  let result = 0;
-  let maxDistance = 2 * squareSide;
-  while (result < maxDistance) {
-    const midDistance = Math.floor((result + maxDistance + 1) / 2);
-    if (canPlaceAtDistance(midDistance)) result = midDistance;
-    else maxDistance = midDistance - 1;
-  }
-  return result;
-
-  function canPlaceAtDistance(distance) {
-    for (let start = 0; start < pointCount; start++) {
-      let current = start;
-      let lastPos = extendedPositions[start];
-      const limit = start + pointCount;
-      let valid = true;
-
-      for (let placed = 1; placed < pointsToPlace; placed++) {
-        const nextTarget = lastPos + distance;
-        let left = current + 1;
-        let right = limit;
-
-        while (left < right) {
-          const mid = Math.floor((left + right) / 2);
-          if (extendedPositions[mid] < nextTarget) left = mid + 1;
-          else right = mid;
-        }
-
-        if (left === limit) {
-          valid = false;
-          break;
-        }
-        current = left;
-        lastPos = extendedPositions[current];
-      }
-
-      if (valid && extendedPositions[start] + perimeter - lastPos >= distance) {
-        return true;
-      }
-    }
-    return false;
-  }
-};