id int64 1 2.61k | slug stringlengths 3 79 | title stringlengths 3 79 | difficulty stringclasses 3
values | content stringlengths 230 5.69k | javascript stringlengths 27 3.86k |
|---|---|---|---|---|---|
1 | two-sum | Two Sum | 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.
**Example 1:**
**Input:** nums... |
```javascript
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
}
```
... |
2 | add-two-numbers | Add Two Numbers | 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 ... |
```javascript
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val);
this.next = (next===undefined ? null : next);
};
function addTwoNumbers(l1, l2) {
const dummy = new ListNode(0);
let current = dummy;
let carry = 0;
while (l1 || l2 || carry) {
let sum = (l1 ? l1.... |
3 | longest-substring-without-repeating-characters | Longest Substring Without Repeating Characters | Medium | Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with t... |
```javascript
function lengthOfLongestSubstring(s) {
let left = 0, right = 0, maxLength = 0;
const characters = new Set();
while (right < s.length) {
if (!characters.has(s.charAt(right))) {
characters.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + ... |
4 | median-of-two-sorted-arrays | Median of Two Sorted Arrays | Hard | Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is ... |
```javascript
function findMedianSortedArrays(nums1, nums2) {
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1);
}
const x = nums1.length;
const y = nums2.length;
let low = 0;
let high = x;
while (low <= high) {
const partitionX = M... |
5 | longest-palindromic-substring | Longest Palindromic Substring | Medium | Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only dig... |
```javascript
function longestPalindromicSubstring(s) {
let n = s.length;
if (n === 0) return "";
let start = 0, maxLength = 1;
for (let i = 0; i < n; ++i) {
let l = i, r = i;
while (r < n - 1 && s[r] === s[r + 1])
r++;
i = r;
while (l > 0 && r < n - 1 && s[l - 1] === s[r + 1]) {
... |
6 | zigzag-conversion | Zigzag Conversion | Medium | The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this co... |
```javascript
function convert(s, numRows) {
if (numRows === 1 || numRows >= s.length) return s;
let rows = new Array(numRows).fill("");
let curRow = 0;
let goingDown = false;
for (let c of s) {
rows[curRow] += c;
if (curRow === 0 || curRow === numRows - 1) goingDown = !goingD... |
7 | reverse-integer | Reverse Integer | Medium | Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
... |
```javascript
function reverse(x) {
let sign = x < 0 ? -1 : 1;
x = Math.abs(x);
let res = 0;
while (x !== 0) {
res = res * 10 + x % 10;
x = Math.floor(x / 10);
}
res *= sign;
return (res < -(2 ** 31) || res > 2 ** 31 - 1) ? 0 : res;
}
```
The algorithm initializ... |
8 | string-to-integer-atoi | String to Integer (atoi) | Medium | Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
The algorithm for `myAtoi(string s)` is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is `'-'` or `... |
```javascript
function myAtoi(s) {
let result = 0, i = 0, sign = 1;
while (s[i] === ' ') i++;
if (s[i] === '-' || s[i] === '+') sign = (s[i++] === '+') ? 1 : -1;
while (!isNaN(s[i]) && s[i] !== ' ') {
result = result * 10 + parseInt(s[i++], 10);
if (result * sign > 2147483647) retur... |
9 | palindrome-number | Palindrome Number | Easy | Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, i... |
```javascript
function isPalindrome(x) {
if (x < 0) return false;
let original = x, reversed = 0;
while (x > 0) {
reversed = reversed * 10 + x % 10;
x = Math.floor(x / 10);
}
return original === reversed;
}
```
Here is the algorithm:
1. If the integer is negative, imm... |
10 | regular-expression-matching | Regular Expression Matching | Hard | Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:... |
```javascript
function isMatch(s, p) {
const m = s.length, n = p.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false));
dp[0][0] = true;
for (let j = 1; j <= n; j++) {
if (p[j - 1] === '*' && dp[0][j - 2]) {
dp[0][j] = true;
}
}
for (... |
11 | container-with-most-water | Container With Most Water | Medium | You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water... |
```javascript
function maxArea(height) {
let max_area = 0, left = 0, right = height.length - 1;
while (left < right) {
max_area = Math.max(max_area, Math.min(height[left], height[right]) * (right - left));
if (height[left] < height[right]) {
left++;
} else {
... |
12 | integer-to-roman | Integer to Roman | Medium | Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
**Symbol** **Value**
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, `2` is written as `II` in Roman numeral, just two one's adde... |
```javascript
function intToRoman(num) {
const romans = [
[1000, "M"], [900, "CM"], [500, "D"],
[400, "CD"], [100, "C"], [90, "XC"],
[50, "L"], [40, "XL"], [10, "X"],
[9, "IX"], [5, "V"], [4, "IV"], [1, "I"]
];
let roman = "";
for (const [value, symbol] of romans) {... |
13 | roman-to-integer | Roman to Integer | Easy | Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
**Symbol** **Value**
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, `2` is written as `II` in Roman numeral, just two ones added... |
```javascript
function romanToInt(s) {
const romanValues = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000};
let total = 0;
let prevValue = 0;
for (let i = 0; i < s.length; i++) {
let currValue = romanValues[s[i]];
if (currValue > prevValue)
total += cu... |
14 | longest-common-prefix | Longest Common Prefix | Easy | Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string `" "`.
**Example 1:**
**Input:** strs = \[ "flower ", "flow ", "flight "\]
**Output:** "fl "
**Example 2:**
**Input:** strs = \[ "dog ", "racecar ", "car "\]
**Output:** " "... |
```javascript
function longestCommonPrefix(strs) {
if (strs.length === 0) return "";
for (let i = 0; i < strs[0].length; ++i) {
const c = strs[0][i];
for (let j = 1; j < strs.length; ++j) {
if (i === strs[j].length || strs[j][i] !== c) {
return strs[0].substr(0,... |
15 | 3sum | 3Sum | 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.
**Example 1:**
**Input:** nums = \[-1,0,1,2,-1,-4\]
**Output:** \[\[-1,-1,2\],\[-1,0... |
```javascript
function threeSum(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]) {
let j = i + 1, k = nums.length - 1;
while (j < k) {
const sum = nums[i] + nums[j] +... |
16 | 3sum-closest | 3Sum Closest | Medium | Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** ... |
```javascript
function threeSumClosest(nums, target) {
nums.sort((a, b) => a - b);
let closest = nums[0] + nums[1] + nums[2];
for (let i = 0; i < nums.length - 2; ++i) {
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
let sum = nums[i] + nums[le... |
17 | letter-combinations-of-a-phone-number | Letter Combinations of a Phone Number | Medium | Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** di... |
```javascript
function letterCombinations(digits) {
if (digits.length === 0) return [];
let phone = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
let result = [""];
for (let i = 0; i < digits.length; i++) {
let digit = digits[i];
let temp = [];
for (let ... |
18 | 4sum | 4Sum | Medium | Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Examp... |
```javascript
function fourSum(nums, target) {
nums.sort((a, b) => a - b);
let result = [];
for (let i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
for (let j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] === nums[j - 1]) ... |
19 | remove-nth-node-from-end-of-list | Remove Nth Node From End of List | Medium | Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**C... |
```javascript
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
function removeNthFromEnd(head, n) {
let first = head;
let second = head;
for (let i = 0; i < n; i++) {
first = first.next;
}
if (first === null) {... |
20 | valid-parentheses | Valid Parentheses | Easy | Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corres... |
```javascript
function isValid(s) {
const stack = [];
for (const c of s) {
if (c === '(' || c === '{' || c === '[') {
stack.push(c);
} else {
if (!stack.length) return false;
if (c === ')' && stack[stack.length - 1] !== '(') return false;
if ... |
21 | merge-two-sorted-lists | Merge Two Sorted Lists | Easy | You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:**... |
```javascript
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
function mergeTwoLists(list1, list2) {
if (list1 === null) return list2;
if (list2 === null) return list1;
if (list1.val < list2.val) {
list1.next = mer... |
22 | generate-parentheses | Generate Parentheses | Medium | Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_.
**Example 1:**
**Input:** n = 3
**Output:** \["((()))","(()())","(())()","()(())","()()()"\]
**Example 2:**
**Input:** n = 1
**Output:** \["()"\]
**Constraints:**
* `1 <= n <= 8` |
```javascript
function generateParenthesis(n) {
function generateParenthesisHelper(open, close, current, result) {
if (open === 0 && close === 0) {
result.push(current);
return;
}
if (open > 0) {
generateParenthesisHelper(open - 1, close + 1, current ... |
23 | merge-k-sorted-lists | Merge k Sorted Lists | Hard | You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.
_Merge all the linked-lists into one sorted linked-list and return it._
**Example 1:**
**Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\]
**Output:** \[1,1,2,3,4,4,5,6\]
**Explanation:** The linked-lists are:
\[
1->4... |
```javascript
class ListNode {
constructor(val=0, next=null) {
this.val = val;
this.next = next;
}
}
function mergeKLists(lists) {
if(lists.length === 0) return null;
while(lists.length > 1){
lists.push(merge2Lists(lists.shift(), lists.shift()));
}
return lists[0];
... |
24 | swap-nodes-in-pairs | Swap Nodes in Pairs | 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.)
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** head = \[\]
**Output:** \[\... |
```javascript
function swapPairs(head) {
if (!head || !head.next) return head;
let second = head.next;
head.next = swapPairs(second.next);
second.next = head;
return second;
}
```
The algorithm uses recursion to solve the problem. It starts by checking if the list has remaining pairs... |
25 | reverse-nodes-in-k-group | Reverse Nodes in k-Group | Hard | Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is.
You may not alt... |
```javascript
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
function reverseKGroup(head, k) {
if (!head || k === 1) return head;
let len = 0;
let cur = head;
while (cur) {
len++;
cur = cur.next;
}
... |
26 | remove-duplicates-from-sorted-array | Remove Duplicates from Sorted Array | Easy | Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_... |
```javascript
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
```
We use two pointers `i` and `j`. `i` s... |
27 | remove-element | Remove Element | Easy | Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`.
Consider the number of elements in `nu... |
```javascript
function removeElement(nums, val) {
let i = 0;
for (let j = 0; j < nums.length; j++) {
if (nums[j] !== val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
```
The algorithm uses two pointers approach. The pointer `i` maintains the position w... |
28 | find-the-index-of-the-first-occurrence-in-a-string | Find the Index of the First Occurrence in a String | Easy | Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`.
**Example 1:**
**Input:** haystack = "sadbutsad ", needle = "sad "
**Output:** 0
**Explanation:** "sad " occurs at index 0 and 6.
The first occurrence is at ... |
```javascript
function strStr(haystack, needle) {
if (needle === '') return 0;
let index = haystack.indexOf(needle);
return index;
}
```
The algorithm searches for the first occurrence of the `needle` string in the `haystack` string. First, it checks if the `needle` is empty, and if it is, it... |
29 | divide-two-integers | Divide Two Integers | Medium | Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`.
Return _the... |
```javascript
function divide(dividend, divisor) {
if (dividend === -Math.pow(2, 31) && divisor === -1) {
return Math.pow(2, 31) - 1;
}
const sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;
let dvd = Math.abs(dividend);
let dvs = Math.abs(divisor);
let ans = 0;
while (dvd >= ... |
30 | substring-with-concatenation-of-all-words | Substring with Concatenation of All Words | Hard | You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**.
A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated.
* For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abef... |
```javascript
function findSubstring(s, words) {
if (!s || !words || words.length === 0) return [];
const word_count = new Map();
for (const word of words) {
word_count.set(word, (word_count.get(word) || 0) + 1);
}
const word_length = words[0].length;
const total_words = words.len... |
31 | next-permutation | Next Permutation | Medium | A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order.
* For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`.
The **next permutation** of an array of integers is the next le... |
```javascript
function nextPermutation(nums) {
let n = nums.length, k = n - 2, l;
while(k >= 0 && nums[k] >= nums[k + 1]) k--;
if(k < 0) {
nums.sort((a, b) => a - b);
} else {
for (l = n - 1; l > k; l--) {
if (nums[l] > nums[k]) break;
}
[nums[k], nums[l... |
32 | longest-valid-parentheses | Longest Valid Parentheses | Hard | Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_.
**Example 1:**
**Input:** s = "(() "
**Output:** 2
**Explanation:** The longest valid parentheses substring is "() ".
**Example 2:**
**Input:** s = ")()()) "
**Output:** ... |
```javascript
function longestValidParentheses(s) {
const n = s.length;
let result = 0;
const st = [];
for (let i = 0; i < n; ++i) {
if (s[i] === '(') {
st.push(i);
} else {
if (st.length > 0 && s[st[st.length - 1]] === '(') {
st.pop();
... |
33 | search-in-rotated-sorted-array | Search in Rotated Sorted Array | 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]]` ... |
```javascript
function search(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
let mid = left + Math.floor((right - left) / 2);
if (nums[mid] === target) {
return mid;
}
if (nums[mid] >= nums[left]) {
if (target >= nums[l... |
34 | find-first-and-last-position-of-element-in-sorted-array | Find First and Last Position of Element in Sorted Array | Medium | Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
*... |
```javascript
function searchRange(nums, target) {
let start = -1, end = -1;
let left = 0, right = nums.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid ... |
35 | search-insert-position | Search Insert Position | Easy | Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Exa... |
```javascript
function searchInsert(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
let mid = left + Math.floor((right - left) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
r... |
36 | valid-sudoku | Valid Sudoku | Medium | Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain... |
```javascript
function isValidSudoku(board) {
let seen = new Set();
for(let i = 0; i < 9; i++) {
for(let j = 0; j < 9; j++) {
let current_val = board[i][j];
if(current_val !== '.') {
let row = `${current_val} in row ${i}`;
let col = `${cu... |
37 | sudoku-solver | Sudoku Solver | Hard | Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly onc... |
```javascript
function isValid(board, row, col, c) {
for (let i = 0; i < 9; i++) {
if (board[i][col] === c) return false;
if (board[row][i] === c) return false;
if (board[3 * Math.floor(row / 3) + Math.floor(i / 3)][3 * Math.floor(col / 3) + i % 3] === c) return false;
}
return ... |
38 | count-and-say | Count and Say | Medium | The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, spli... |
```javascript
function countAndSay(n) {
if (n === 1) return "1";
let previous = countAndSay(n - 1);
let result = "";
let count = 1;
for (let i = 1; i < previous.length; i++) {
if (previous[i] === previous[i - 1]) {
count++;
} else {
result += count.toStri... |
39 | combination-sum | Combination Sum | Medium | Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of... |
```javascript
function combinationSum(candidates, target) {
function findCombinations(startIndex, remaining) {
if (remaining === 0) {
return [[]];
}
if (startIndex === candidates.length || remaining < 0) {
return [];
}
let result = [];
re... |
40 | combination-sum-ii | Combination Sum II | Medium | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.... |
```javascript
function combinationSum2(candidates, target) {
const result = [];
candidates.sort((a, b) => a - b);
combine(candidates, target, 0, [], result);
return result;
}
function combine(candidates, target, start, current, result) {
if (target === 0) {
result.push([...current]);
... |
41 | first-missing-positive | First Missing Positive | Hard | Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:*... |
```javascript
function firstMissingPositive(nums) {
let n = nums.length;
for(let i = 0; i < n; i++) {
while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i]) {
let temp = nums[i];
nums[i] = nums[temp - 1];
nums[temp - 1] = temp;
}
}
f... |
42 | trapping-rain-water | Trapping Rain Water | 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.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,... |
```javascript
function trap(height) {
const n = height.length;
let left = 0, right = n - 1, maxLeft = 0, maxRight = 0, water = 0;
while (left < right) {
if (height[left] <= height[right]) {
maxLeft = Math.max(maxLeft, height[left]);
water += maxLeft - height[left];
... |
43 | multiply-strings | Multiply Strings | Medium | Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string.
**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly.
**Example 1:**
**Input:** num1 = "2", num2 = "3"
**Output:** "6"
**Ex... |
```javascript
function multiply(num1, num2) {
let m = num1.length, n = num2.length;
let pos = new Array(m + n).fill(0);
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
let mult = (num1[i] - '0') * (num2[j] - '0');
let p1 = i + j, p2 = i + j + 1... |
44 | wildcard-matching | Wildcard Matching | Hard | Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Exam... |
```javascript
function isMatch(s, p) {
let m = s.length,
n = p.length;
let i = 0,
j = 0,
asterisk = -1,
match = 0;
while (i < m) {
if (j < n && (s[i] === p[j] || p[j] === '?')) {
i++;
j++;
} else if (j < n && p[j] === '*') {
... |
45 | jump-game-ii | Jump Game II | Medium | You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i +... |
```javascript
function jump(nums) {
let jumps = 0, currentEnd = 0, currentFarthest = 0;
for (let i = 0; i < nums.length - 1; i++) {
currentFarthest = Math.max(currentFarthest, i + nums[i]);
if (i === currentEnd) {
jumps++;
currentEnd = currentFarthest;
}
... |
46 | permutations | Permutations | Medium | Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\... |
```javascript
function permute(nums) {
const results = [];
helper(nums, 0, results);
return results;
}
function helper(nums, index, results) {
if (index === nums.length - 1) {
results.push(nums.slice());
return;
}
for (let i = index; i < nums.length; i++) {
[nums[index], nums[i]] = [nums[... |
47 | permutations-ii | Permutations II | Medium | Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,... |
```javascript
function permuteUnique(nums) {
nums.sort((a, b) => a - b);
const result = [];
const visited = new Array(nums.length).fill(false);
function backtrack(tempList) {
if (tempList.length === nums.length) {
result.push([...tempList]);
return;
}
... |
48 | rotate-image | Rotate Image | Medium | You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotati... |
```javascript
function rotate(matrix) {
let n = matrix.length;
for (let i = 0; i < Math.floor(n / 2); i++) {
for (let j = i; j < n - i - 1; j++) {
let temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
... |
49 | group-anagrams | Group Anagrams | 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.
**Example 1:**
**Input:** strs = \["eat","tea","tan... |
```javascript
function groupAnagrams(strs) {
const anagramMap = new Map();
for (const str of strs) {
const key = str.split('').sort().join('');
if (!anagramMap.has(key)) {
anagramMap.set(key, []);
}
anagramMap.get(key).push(str);
}
return Array.from(an... |
50 | powx-n | Pow(x, n) | Medium | Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`).
**Example 1:**
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000
**Example 2:**
**Input:** x = 2.10000, n = 3
**Output:** 9.26100
**Example 3:**
**Input:** x = 2.00000, n = -2
**... |
```javascript
function myPow(x, n) {
if (n === 0) return 1;
if (n < 0) {
x = 1 / x;
n = -n;
}
let result = 1;
let currentProduct = x;
for (let i = n; i > 0; i = Math.floor(i / 2)) {
if (i % 2 === 1) {
result *= currentProduct;
}
currentPro... |
51 | n-queens | N-Queens | Hard | The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-... |
```javascript
function solveNQueens(n) {
function isSafe(board, row, col) {
for (let i = 0; i < col; i++)
if (board[row][i] == 'Q') return false;
for (let i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 'Q') return false;
for (let i = row, j = col; i < n && j >= 0; i++, j... |
52 | n-queens-ii | N-Queens II | Hard | The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions ... |
```javascript
function isSafe(cols, row) {
let col = cols.length;
for (let i = 0; i < cols.length; i++) {
if (cols[i] === row || Math.abs(i - col) === Math.abs(cols[i] - row)) {
return false;
}
}
return true;
}
function backtrack(n, cols) {
if (cols.length === n) {
... |
53 | maximum-subarray | Maximum Subarray | Medium | Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_.
**Example 1:**
**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** The subarray \... |
```javascript
function maxSubArray(nums) {
let max_sum = nums[0];
let current_sum = max_sum;
for (let i = 1; i < nums.length; i++) {
current_sum = Math.max(current_sum + nums[i], nums[i]);
max_sum = Math.max(max_sum, current_sum);
}
return max_sum;
}
```
The algorithm... |
54 | spiral-matrix | Spiral Matrix | Medium | Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Const... |
```javascript
function spiralOrder(matrix) {
const result = [];
if (!matrix.length) return result;
let m = matrix.length, n = matrix[0].length;
let rowStart = 0, colStart = 0, rowEnd = m - 1, colEnd = n - 1;
while (rowStart <= rowEnd && colStart <= colEnd) {
for (let i = colStart; i <=... |
55 | jump-game | Jump Game | Medium | You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** t... |
```javascript
function canJump(nums) {
let maxReach = 0;
for (let i = 0; i < nums.length; ++i) {
if (i > maxReach) return false;
maxReach = Math.max(maxReach, i + nums[i]);
}
return true;
}
```
The algorithm iterates through the `nums` array, keeping track of the maximum re... |
56 | merge-intervals | Merge Intervals | Medium | Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\... |
```javascript
function merge(intervals) {
if (intervals.length === 0) return [];
intervals.sort((a, b) => a[0] - b[0]);
const result = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
if (result[result.length - 1][1] >= intervals[i][0]) {
result[result.length - 1][... |
57 | insert-interval | Insert Interval | Medium | You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another i... |
```javascript
function insert(intervals, newInterval) {
const result = [];
let start_pos = 0;
while (start_pos < intervals.length && intervals[start_pos][1] < newInterval[0]) {
result.push(intervals[start_pos]);
start_pos++;
}
while (start_pos < intervals.length && intervals[s... |
58 | length-of-last-word | Length of Last Word | Easy | Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
**Input:** s = "Hello World "
**Output:** 5
**Explanation:** The last word is "World " with length 5.
**Example 2:**
... |
```javascript
function lengthOfLastWord(s) {
let length = 0;
let tail = s.length - 1;
while (tail >= 0 && s[tail] === ' ') tail--;
while (tail >= 0 && s[tail] !== ' ') {
length++;
tail--;
}
return length;
}
```
The algorithm for finding the length of the last word i... |
59 | spiral-matrix-ii | Spiral Matrix II | Medium | Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20` |
```javascript
function generateMatrix(n) {
const matrix = Array.from({ length: n }, () => new Array(n).fill(0));
let value = 1, top = 0, bottom = n - 1, left = 0, right = n - 1;
while (value <= n * n) {
for (let i = left; i <= right; i++) {
matrix[top][i] = value++;
}
... |
60 | permutation-sequence | Permutation Sequence | Hard | The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
1. `"123 "`
2. `"132 "`
3. `"213 "`
4. `"231 "`
5. `"312 "`
6. `"321 "`
Given `n` and `k`, return the `kth` permutation sequence.
**Exa... |
```javascript
function getPermutation(n, k) {
const factorials = [1];
const nums = [...Array(n)].map((_, i) => i + 1);
let result = '';
for (let i = 1; i < n; i++) {
factorials[i] = factorials[i - 1] * i;
}
k--;
for (let i = n; i >= 1; i--) {
const index = Math.floor(... |
61 | rotate-list | Rotate List | Medium | Given the `head` of a linked list, rotate the list to the right by `k` places.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[4,5,1,2,3\]
**Example 2:**
**Input:** head = \[0,1,2\], k = 4
**Output:** \[2,0,1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 500]`.
* ... |
```javascript
class ListNode {
constructor(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
}
function rotateRight(head, k) {
if (!head || !head.next || k === 0) return head;
let current = head;
let len = 1;
while (cu... |
62 | unique-paths | Unique Paths | Medium | There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the nu... |
```javascript
function uniquePaths(m, n) {
const dp = Array.from({ length: m }, () => Array(n).fill(1));
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
```
The idea is to use dyn... |
63 | unique-paths-ii | Unique Paths II | Medium | You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as ... |
```javascript
function uniquePathsWithObstacles(grid) {
const m = grid.length;
const n = grid[0].length;
if (grid[0][0] === 1) return 0;
grid[0][0] = 1;
for (let i = 1; i < m; ++i) {
grid[i][0] = (grid[i][0] === 0 && grid[i - 1][0] === 1) ? 1 : 0;
}
for (let i = 1; i < n; ++i) ... |
64 | minimum-path-sum | Minimum Path Sum | Medium | Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanat... |
```javascript
function minPathSum(grid) {
let m = grid.length, n = grid[0].length;
for(let i = 1; i < m; i++)
grid[i][0] += grid[i - 1][0];
for(let i = 1; i < n; i++)
grid[0][i] += grid[0][i - 1];
for(let i = 1; i < m; i++){
for(let j = 1; j < n; j... |
65 | valid-number | Valid Number | Hard | A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the... |
```javascript
function isNumber(s) {
const pattern = /^[-+]?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(e[-+]?[0-9]+)?$/;
return pattern.test(s);
}
```
The algorithm utilizes regular expressions to match the input string against a pattern that defines a valid number. The regular expression in this case has ... |
66 | plus-one | Plus One | Easy | You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
Increment the large integer by one and re... |
```javascript
function plusOne(digits) {
let n = digits.length;
for(let i = n - 1; i >= 0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
digits.unshift(1);
return digits;
}
```
We start by iterating through ... |
67 | add-binary | Add Binary | Easy | Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` chara... |
```javascript
function addBinary(a, b) {
let result = "";
let i = a.length - 1, j = b.length - 1, carry = 0;
while (i >= 0 || j >= 0 || carry) {
if (i >= 0) carry += parseInt(a[i--], 10);
if (j >= 0) carry += parseInt(b[j--], 10);
result = (carry % 2) + result;
carry = M... |
68 | text-justification | Text Justification | Hard | Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that ea... |
```javascript
function fullJustify(words, maxWidth) {
const result = [];
let idx = 0;
while (idx < words.length) {
let totalChars = words[idx].length;
let last = idx + 1;
while (last < words.length) {
if (totalChars + 1 + words[last].length > maxWidth) break;
... |
69 | sqrtx | Sqrt(x) | Easy | Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.
**Example 1:**
... |
```javascript
function mySqrt(x) {
if (x === 0 || x === 1) return x;
let start = 1, end = x, ans;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (mid * mid === x) return mid;
if (mid * mid < x) {
start = mid + 1;
ans = mid;
} e... |
70 | climbing-stairs | Climbing Stairs | Easy | You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
... |
```javascript
function climbStairs(n) {
if(n <= 2) return n;
let a = 1, b = 2, c;
for(let i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
```
This problem can be solved using dynamic programming. The number of ways to reach the top can be calculate... |
71 | simplify-path | Simplify Path | Medium | Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level,... |
```javascript
function simplifyPath(path) {
let stack = [];
let parts = path.split("/");
for (let part of parts) {
if (!part || part === ".") continue;
if (part === "..") {
if (stack.length) stack.pop();
} else {
stack.push(part);
}
}
re... |
72 | edit-distance | Edit Distance | Hard | Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**O... |
```javascript
function minDistance(word1, word2) {
const m = word1.length;
const n = word2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i === 0) {
dp[i][j] = j... |
73 | set-matrix-zeroes | Set Matrix Zeroes | Medium | Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**In... |
```javascript
function setZeroes(matrix) {
let rows = matrix.length;
let cols = matrix[0].length;
let firstRow = false;
let firstCol = false;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (matrix[i][j] === 0) {
if (i === 0) firstRow =... |
74 | search-a-2d-matrix | Search a 2D Matrix | Medium | You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
... |
```javascript
function searchMatrix(matrix, target) {
const m = matrix.length;
const n = matrix[0].length;
let l = 0, r = m * n - 1;
while (l <= r) {
const mid = l+ Math.floor((r - l) / 2);
const midVal = matrix[Math.floor(mid / n)][mid % n];
if (midVal === target) {
... |
75 | sort-colors | Sort Colors | Medium | Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers `0`, `1`, and `2` to represent the color red, white,... |
```javascript
function sortColors(nums) {
let red = 0, white = 0, blue = nums.length - 1;
while (white <= blue) {
if (nums[white] === 0) {
[nums[red], nums[white]] = [nums[white], nums[red]];
red++;
white++;
} else if (nums[white] === 1) {
whi... |
76 | minimum-window-substring | Minimum Window Substring | 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 tha... |
```javascript
function minWindow(s, t) {
const need = new Map();
const window = new Map();
for (const c of t) {
need.set(c, (need.get(c) || 0) + 1);
}
let left = 0, right = 0;
let valid = 0;
let start = 0, length = Infinity;
while (right < s.length) {
const c ... |
77 | combinations | Combinations | Medium | Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combin... |
```javascript
function combine(n, k) {
const result = [];
backtrack(n, k, 1, [], result);
return result;
}
function backtrack(n, k, start, current, result) {
if (current.length === k) {
result.push([...current]);
return;
}
for (let i = start; i <= n; i++) {
current... |
78 | subsets | Subsets | Medium | Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
... |
```javascript
function subsets(nums) {
let result = [];
let n = nums.length;
let num_subsets = 1 << n;
for (let i = 0; i < num_subsets; ++i) {
let subset = [];
for (let j = 0; j < n; ++j) {
if (i & (1 << j)) {
subset.push(nums[j]);
}
... |
79 | word-search | Word Search | Medium | Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
**Example 1:**... |
```javascript
function exist(board, word) {
const m = board.length;
const n = board[0].length;
function dfs(i, j, k) {
if (i < 0 || i === m || j < 0 || j === n || board[i][j] !== word[k])
return false;
if (k === word.length - 1)
return true;
con... |
80 | remove-duplicates-from-sorted-array-ii | Remove Duplicates from Sorted Array II | Medium | Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**.
Since it is impossible to change the len... |
```javascript
function removeDuplicates(nums) {
let i = 0;
for (let num of nums) {
if (i < 2 || num > nums[i - 2]) {
nums[i++] = num;
}
}
return i;
}
```
The algorithm uses a two-pointer technique. The variable `i` represents the pointer to the position in the a... |
81 | search-in-rotated-sorted-array-ii | Search in Rotated Sorted Array II | Medium | There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nu... |
```javascript
function search(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (nums[mid] === target) return true;
if (nums[mid] === nums[left]) {
left++;
} else if (nums[mid] > ... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 34