id
int64
1
3.63k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
Kotlin
class Solution { fun multiply(num1: String, num2: String): String { if (num1 == "0" || num2 == "0") return "0" val chars_1 = num1.toCharArray().reversedArray() val chars_2 = num2.toCharArray().reversedArray() val result = mutableListOf<Int>() chars_1.forEachIndexed { i, c1 -> val multiplier_1 = c1 - '0' var over = 0 var index = 0 fun sum(product: Int = 0): Unit { while (index >= result.size) { result.add(0) } val value = product + over + result[index] result[index] = value % 10 over = value / 10 return } chars_2.forEachIndexed { j, c2 -> index = i + j val multiplier_2 = c2 - '0' sum(multiplier_1 * multiplier_2) } while (over > 0) { index++ sum() } } return result.reversed().joinToString("") } }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
PHP
class Solution { /** * @param string $num1 * @param string $num2 * @return string */ function multiply($num1, $num2) { $length1 = strlen($num1); $length2 = strlen($num2); $product = array_fill(0, $length1 + $length2, 0); for ($i = $length1 - 1; $i >= 0; $i--) { for ($j = $length2 - 1; $j >= 0; $j--) { $digit1 = intval($num1[$i]); $digit2 = intval($num2[$j]); $temp = $digit1 * $digit2 + $product[$i + $j + 1]; $product[$i + $j + 1] = $temp % 10; $carry = intval($temp / 10); $product[$i + $j] += $carry; } } $result = implode('', $product); $result = ltrim($result, '0'); return $result === '' ? '0' : $result; } }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
Python
class Solution: def multiply(self, num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" m, n = len(num1), len(num2) arr = [0] * (m + n) for i in range(m - 1, -1, -1): a = int(num1[i]) for j in range(n - 1, -1, -1): b = int(num2[j]) arr[i + j + 1] += a * b for i in range(m + n - 1, 0, -1): arr[i - 1] += arr[i] // 10 arr[i] %= 10 i = 0 if arr[0] else 1 return "".join(str(x) for x in arr[i:])
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
Rust
impl Solution { pub fn multiply(num1: String, num2: String) -> String { if num1 == "0" || num2 == "0" { return String::from("0"); } let (num1, num2) = (num1.as_bytes(), num2.as_bytes()); let (n, m) = (num1.len(), num2.len()); let mut res = vec![]; for i in 0..n { let a = num1[n - i - 1] - b'0'; let mut sum = 0; let mut j = 0; while j < m || sum != 0 { if i + j == res.len() { res.push(0); } let b = num2.get(m - j - 1).unwrap_or(&b'0') - b'0'; sum += a * b + res[i + j]; res[i + j] = sum % 10; sum /= 10; j += 1; } } res.into_iter() .rev() .map(|v| char::from(v + b'0')) .collect() } }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
TypeScript
function multiply(num1: string, num2: string): string { if (num1 === '0' || num2 === '0') { return '0'; } const m: number = num1.length; const n: number = num2.length; const arr: number[] = Array(m + n).fill(0); for (let i: number = m - 1; i >= 0; i--) { const a: number = +num1[i]; for (let j: number = n - 1; j >= 0; j--) { const b: number = +num2[j]; arr[i + j + 1] += a * b; } } for (let i: number = arr.length - 1; i > 0; i--) { arr[i - 1] += Math.floor(arr[i] / 10); arr[i] %= 10; } let i: number = 0; while (i < arr.length && arr[i] === 0) { i++; } return arr.slice(i).join(''); }
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
C++
class Solution { public: bool isMatch(string s, string p) { int m = s.size(), n = p.size(); int f[m + 1][n + 1]; memset(f, -1, sizeof(f)); function<bool(int, int)> dfs = [&](int i, int j) { if (i >= m) { return j >= n || (p[j] == '*' && dfs(i, j + 1)); } if (j >= n) { return false; } if (f[i][j] != -1) { return f[i][j] == 1; } if (p[j] == '*') { f[i][j] = dfs(i + 1, j) || dfs(i, j + 1) ? 1 : 0; } else { f[i][j] = (p[j] == '?' || s[i] == p[j]) && dfs(i + 1, j + 1) ? 1 : 0; } return f[i][j] == 1; }; return dfs(0, 0); } };
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
C#
public class Solution { private bool?[,] f; private char[] s; private char[] p; private int m; private int n; public bool IsMatch(string s, string p) { this.s = s.ToCharArray(); this.p = p.ToCharArray(); m = s.Length; n = p.Length; f = new bool?[m, n]; return Dfs(0, 0); } private bool Dfs(int i, int j) { if (i >= m) { return j >= n || (p[j] == '*' && Dfs(i, j + 1)); } if (j >= n) { return false; } if (f[i, j] != null) { return f[i, j].Value; } if (p[j] == '*') { f[i, j] = Dfs(i + 1, j) || Dfs(i + 1, j + 1) || Dfs(i, j + 1); } else { f[i, j] = (p[j] == '?' || s[i] == p[j]) && Dfs(i + 1, j + 1); } return f[i, j].Value; } }
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
Go
func isMatch(s string, p string) bool { m, n := len(s), len(p) f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } var dfs func(i, j int) bool dfs = func(i, j int) bool { if i >= m { return j >= n || p[j] == '*' && dfs(i, j+1) } if j >= n { return false } if f[i][j] != 0 { return f[i][j] == 1 } f[i][j] = 2 ok := false if p[j] == '*' { ok = dfs(i+1, j) || dfs(i+1, j+1) || dfs(i, j+1) } else { ok = (p[j] == '?' || s[i] == p[j]) && dfs(i+1, j+1) } if ok { f[i][j] = 1 } return ok } return dfs(0, 0) }
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
Java
class Solution { private Boolean[][] f; private char[] s; private char[] p; private int m; private int n; public boolean isMatch(String s, String p) { this.s = s.toCharArray(); this.p = p.toCharArray(); m = s.length(); n = p.length(); f = new Boolean[m][n]; return dfs(0, 0); } private boolean dfs(int i, int j) { if (i >= m) { return j >= n || (p[j] == '*' && dfs(i, j + 1)); } if (j >= n) { return false; } if (f[i][j] != null) { return f[i][j]; } if (p[j] == '*') { f[i][j] = dfs(i + 1, j) || dfs(i + 1, j + 1) || dfs(i, j + 1); } else { f[i][j] = (p[j] == '?' || s[i] == p[j]) && dfs(i + 1, j + 1); } return f[i][j]; } }
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
PHP
class Solution { /** * @param string $s * @param string $p * @return boolean */ function isMatch($s, $p) { $lengthS = strlen($s); $lengthP = strlen($p); $dp = []; for ($i = 0; $i <= $lengthS; $i++) { $dp[$i] = array_fill(0, $lengthP + 1, false); } $dp[0][0] = true; for ($i = 1; $i <= $lengthP; $i++) { if ($p[$i - 1] == '*') { $dp[0][$i] = $dp[0][$i - 1]; } } for ($i = 1; $i <= $lengthS; $i++) { for ($j = 1; $j <= $lengthP; $j++) { if ($p[$j - 1] == '?' || $s[$i - 1] == $p[$j - 1]) { $dp[$i][$j] = $dp[$i - 1][$j - 1]; } elseif ($p[$j - 1] == '*') { $dp[$i][$j] = $dp[$i][$j - 1] || $dp[$i - 1][$j]; } } } return $dp[$lengthS][$lengthP]; } }
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
Python
class Solution: def isMatch(self, s: str, p: str) -> bool: @cache def dfs(i: int, j: int) -> bool: if i >= len(s): return j >= len(p) or (p[j] == "*" and dfs(i, j + 1)) if j >= len(p): return False if p[j] == "*": return dfs(i + 1, j) or dfs(i + 1, j + 1) or dfs(i, j + 1) return (p[j] == "?" or s[i] == p[j]) and dfs(i + 1, j + 1) return dfs(0, 0)
44
Wildcard Matching
Hard
<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;?&#39;</code> Matches any single character.</li> <li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot; <strong>Output:</strong> true <strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot; <strong>Output:</strong> false <strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li> </ul>
Greedy; Recursion; String; Dynamic Programming
TypeScript
function isMatch(s: string, p: string): boolean { const m = s.length; const n = p.length; const f: number[][] = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => -1), ); const dfs = (i: number, j: number): boolean => { if (i >= m) { return j >= n || (p[j] === '*' && dfs(i, j + 1)); } if (j >= n) { return false; } if (f[i][j] !== -1) { return f[i][j] === 1; } if (p[j] === '*') { f[i][j] = dfs(i + 1, j) || dfs(i, j + 1) ? 1 : 0; } else { f[i][j] = (p[j] === '?' || s[i] === p[j]) && dfs(i + 1, j + 1) ? 1 : 0; } return f[i][j] === 1; }; return dfs(0, 0); }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
C
int jump(int* nums, int numsSize) { int ans = 0; int mx = 0; int last = 0; for (int i = 0; i < numsSize - 1; ++i) { mx = (mx > i + nums[i]) ? mx : (i + nums[i]); if (last == i) { ++ans; last = mx; } } return ans; }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
C++
class Solution { public: int jump(vector<int>& nums) { int ans = 0, mx = 0, last = 0; for (int i = 0; i < nums.size() - 1; ++i) { mx = max(mx, i + nums[i]); if (last == i) { ++ans; last = mx; } } return ans; } };
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
C#
public class Solution { public int Jump(int[] nums) { int ans = 0, mx = 0, last = 0; for (int i = 0; i < nums.Length - 1; ++i) { mx = Math.Max(mx, i + nums[i]); if (last == i) { ++ans; last = mx; } } return ans; } }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
Go
func jump(nums []int) (ans int) { mx, last := 0, 0 for i, x := range nums[:len(nums)-1] { mx = max(mx, i+x) if last == i { ans++ last = mx } } return }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
Java
class Solution { public int jump(int[] nums) { int ans = 0, mx = 0, last = 0; for (int i = 0; i < nums.length - 1; ++i) { mx = Math.max(mx, i + nums[i]); if (last == i) { ++ans; last = mx; } } return ans; } }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
PHP
class Solution { /** * @param Integer[] $nums * @return Integer */ function jump($nums) { $ans = 0; $mx = 0; $last = 0; for ($i = 0; $i < count($nums) - 1; $i++) { $mx = max($mx, $i + $nums[$i]); if ($last == $i) { $ans++; $last = $mx; } } return $ans; } }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
Python
class Solution: def jump(self, nums: List[int]) -> int: ans = mx = last = 0 for i, x in enumerate(nums[:-1]): mx = max(mx, i + x) if last == i: ans += 1 last = mx return ans
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
Rust
impl Solution { pub fn jump(nums: Vec<i32>) -> i32 { let mut ans = 0; let mut mx = 0; let mut last = 0; for i in 0..(nums.len() - 1) { mx = mx.max(i as i32 + nums[i]); if last == i as i32 { ans += 1; last = mx; } } ans } }
45
Jump Game II
Medium
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p> <p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p> <ul> <li><code>0 &lt;= j &lt;= nums[i]</code> and</li> <li><code>i + j &lt; n</code></li> </ul> <p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,0,1,4] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li> </ul>
Greedy; Array; Dynamic Programming
TypeScript
function jump(nums: number[]): number { let [ans, mx, last] = [0, 0, 0]; for (let i = 0; i < nums.length - 1; ++i) { mx = Math.max(mx, i + nums[i]); if (last === i) { ++ans; last = mx; } } return ans; }
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
C++
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { int n = nums.size(); vector<vector<int>> ans; vector<int> t(n); vector<bool> vis(n); auto dfs = [&](this auto&& dfs, int i) -> void { if (i == n) { ans.emplace_back(t); return; } for (int j = 0; j < n; ++j) { if (!vis[j]) { vis[j] = true; t[i] = nums[j]; dfs(i + 1); vis[j] = false; } } }; dfs(0); return ans; } };
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
C#
public class Solution { public IList<IList<int>> Permute(int[] nums) { var ans = new List<IList<int>>(); var t = new List<int>(); var vis = new bool[nums.Length]; dfs(nums, 0, t, vis, ans); return ans; } private void dfs(int[] nums, int i, IList<int> t, bool[] vis, IList<IList<int>> ans) { if (i >= nums.Length) { ans.Add(new List<int>(t)); return; } for (int j = 0; j < nums.Length; ++j) { if (!vis[j]) { vis[j] = true; t.Add(nums[j]); dfs(nums, i + 1, t, vis, ans); t.RemoveAt(t.Count - 1); vis[j] = false; } } } }
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
Go
func permute(nums []int) (ans [][]int) { n := len(nums) t := make([]int, n) vis := make([]bool, n) var dfs func(int) dfs = func(i int) { if i == n { ans = append(ans, slices.Clone(t)) return } for j, x := range nums { if !vis[j] { vis[j] = true t[i] = x dfs(i + 1) vis[j] = false } } } dfs(0) return }
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
Java
class Solution { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); private boolean[] vis; private int[] nums; public List<List<Integer>> permute(int[] nums) { this.nums = nums; vis = new boolean[nums.length]; dfs(0); return ans; } private void dfs(int i) { if (i == nums.length) { ans.add(new ArrayList<>(t)); return; } for (int j = 0; j < nums.length; ++j) { if (!vis[j]) { vis[j] = true; t.add(nums[j]); dfs(i + 1); t.remove(t.size() - 1); vis[j] = false; } } } }
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
JavaScript
/** * @param {number[]} nums * @return {number[][]} */ var permute = function (nums) { const n = nums.length; const ans = []; const vis = Array(n).fill(false); const t = Array(n).fill(0); const dfs = i => { if (i >= n) { ans.push(t.slice()); return; } for (let j = 0; j < n; ++j) { if (!vis[j]) { vis[j] = true; t[i] = nums[j]; dfs(i + 1); vis[j] = false; } } }; dfs(0); return ans; };
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
Python
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def dfs(i: int): if i >= n: ans.append(t[:]) return for j, x in enumerate(nums): if not vis[j]: vis[j] = True t[i] = x dfs(i + 1) vis[j] = False n = len(nums) vis = [False] * n t = [0] * n ans = [] dfs(0) return ans
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
Rust
impl Solution { pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> { let n = nums.len(); let mut ans = Vec::new(); let mut t = vec![0; n]; let mut vis = vec![false; n]; fn dfs( nums: &Vec<i32>, n: usize, t: &mut Vec<i32>, vis: &mut Vec<bool>, ans: &mut Vec<Vec<i32>>, i: usize, ) { if i == n { ans.push(t.clone()); return; } for j in 0..n { if !vis[j] { vis[j] = true; t[i] = nums[j]; dfs(nums, n, t, vis, ans, i + 1); vis[j] = false; } } } dfs(&nums, n, &mut t, &mut vis, &mut ans, 0); ans } }
46
Permutations
Medium
<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword="permutation-array">permutations</span>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [[0,1],[1,0]] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 6</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Backtracking
TypeScript
function permute(nums: number[]): number[][] { const n = nums.length; const ans: number[][] = []; const vis: boolean[] = Array(n).fill(false); const t: number[] = Array(n).fill(0); const dfs = (i: number) => { if (i >= n) { ans.push(t.slice()); return; } for (let j = 0; j < n; ++j) { if (!vis[j]) { vis[j] = true; t[i] = nums[j]; dfs(i + 1); vis[j] = false; } } }; dfs(0); return ans; }
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
C++
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { ranges::sort(nums); int n = nums.size(); vector<vector<int>> ans; vector<int> t(n); vector<bool> vis(n); auto dfs = [&](this auto&& dfs, int i) { if (i == n) { ans.emplace_back(t); return; } for (int j = 0; j < n; ++j) { if (vis[j] || (j && nums[j] == nums[j - 1] && !vis[j - 1])) { continue; } t[i] = nums[j]; vis[j] = true; dfs(i + 1); vis[j] = false; } }; dfs(0); return ans; } };
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
C#
public class Solution { private List<IList<int>> ans = new List<IList<int>>(); private List<int> t = new List<int>(); private int[] nums; private bool[] vis; public IList<IList<int>> PermuteUnique(int[] nums) { Array.Sort(nums); int n = nums.Length; vis = new bool[n]; this.nums = nums; dfs(0); return ans; } private void dfs(int i) { if (i == nums.Length) { ans.Add(new List<int>(t)); return; } for (int j = 0; j < nums.Length; ++j) { if (vis[j] || (j > 0 && nums[j] == nums[j - 1] && !vis[j - 1])) { continue; } vis[j] = true; t.Add(nums[j]); dfs(i + 1); t.RemoveAt(t.Count - 1); vis[j] = false; } } }
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
Go
func permuteUnique(nums []int) (ans [][]int) { slices.Sort(nums) n := len(nums) t := make([]int, n) vis := make([]bool, n) var dfs func(int) dfs = func(i int) { if i == n { ans = append(ans, slices.Clone(t)) return } for j := 0; j < n; j++ { if vis[j] || (j > 0 && nums[j] == nums[j-1] && !vis[j-1]) { continue } vis[j] = true t[i] = nums[j] dfs(i + 1) vis[j] = false } } dfs(0) return }
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
Java
class Solution { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); private int[] nums; private boolean[] vis; public List<List<Integer>> permuteUnique(int[] nums) { Arrays.sort(nums); this.nums = nums; vis = new boolean[nums.length]; dfs(0); return ans; } private void dfs(int i) { if (i == nums.length) { ans.add(new ArrayList<>(t)); return; } for (int j = 0; j < nums.length; ++j) { if (vis[j] || (j > 0 && nums[j] == nums[j - 1] && !vis[j - 1])) { continue; } t.add(nums[j]); vis[j] = true; dfs(i + 1); vis[j] = false; t.remove(t.size() - 1); } } }
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
JavaScript
/** * @param {number[]} nums * @return {number[][]} */ var permuteUnique = function (nums) { nums.sort((a, b) => a - b); const n = nums.length; const ans = []; const t = Array(n); const vis = Array(n).fill(false); const dfs = i => { if (i === n) { ans.push(t.slice()); return; } for (let j = 0; j < n; ++j) { if (vis[j] || (j > 0 && nums[j] === nums[j - 1] && !vis[j - 1])) { continue; } t[i] = nums[j]; vis[j] = true; dfs(i + 1); vis[j] = false; } }; dfs(0); return ans; };
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
Python
class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: def dfs(i: int): if i == n: ans.append(t[:]) return for j in range(n): if vis[j] or (j and nums[j] == nums[j - 1] and not vis[j - 1]): continue t[i] = nums[j] vis[j] = True dfs(i + 1) vis[j] = False n = len(nums) nums.sort() ans = [] t = [0] * n vis = [False] * n dfs(0) return ans
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
Rust
impl Solution { pub fn permute_unique(mut nums: Vec<i32>) -> Vec<Vec<i32>> { nums.sort(); let n = nums.len(); let mut ans = Vec::new(); let mut t = vec![0; n]; let mut vis = vec![false; n]; fn dfs( nums: &Vec<i32>, t: &mut Vec<i32>, vis: &mut Vec<bool>, ans: &mut Vec<Vec<i32>>, i: usize, ) { if i == nums.len() { ans.push(t.clone()); return; } for j in 0..nums.len() { if vis[j] || (j > 0 && nums[j] == nums[j - 1] && !vis[j - 1]) { continue; } t[i] = nums[j]; vis[j] = true; dfs(nums, t, vis, ans, i + 1); vis[j] = false; } } dfs(&nums, &mut t, &mut vis, &mut ans, 0); ans } }
47
Permutations II
Medium
<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [[1,1,2], [1,2,1], [2,1,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 8</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Backtracking; Sorting
TypeScript
function permuteUnique(nums: number[]): number[][] { nums.sort((a, b) => a - b); const n = nums.length; const ans: number[][] = []; const t: number[] = Array(n); const vis: boolean[] = Array(n).fill(false); const dfs = (i: number) => { if (i === n) { ans.push(t.slice()); return; } for (let j = 0; j < n; ++j) { if (vis[j] || (j > 0 && nums[j] === nums[j - 1] && !vis[j - 1])) { continue; } t[i] = nums[j]; vis[j] = true; dfs(i + 1); vis[j] = false; } }; dfs(0); return ans; }
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
C++
class Solution { public: void rotate(vector<vector<int>>& matrix) { int n = matrix.size(); for (int i = 0; i < n >> 1; ++i) { for (int j = 0; j < n; ++j) { swap(matrix[i][j], matrix[n - i - 1][j]); } } for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { swap(matrix[i][j], matrix[j][i]); } } } };
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
C#
public class Solution { public void Rotate(int[][] matrix) { int n = matrix.Length; for (int i = 0; i < n >> 1; ++i) { for (int j = 0; j < n; ++j) { int t = matrix[i][j]; matrix[i][j] = matrix[n - i - 1][j]; matrix[n - i - 1][j] = t; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { int t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; } } } }
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
Go
func rotate(matrix [][]int) { n := len(matrix) for i := 0; i < n>>1; i++ { for j := 0; j < n; j++ { matrix[i][j], matrix[n-i-1][j] = matrix[n-i-1][j], matrix[i][j] } } for i := 0; i < n; i++ { for j := 0; j < i; j++ { matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] } } }
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
Java
class Solution { public void rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n >> 1; ++i) { for (int j = 0; j < n; ++j) { int t = matrix[i][j]; matrix[i][j] = matrix[n - i - 1][j]; matrix[n - i - 1][j] = t; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { int t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; } } } }
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
JavaScript
/** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ var rotate = function (matrix) { matrix.reverse(); for (let i = 0; i < matrix.length; ++i) { for (let j = 0; j < i; ++j) { [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; } } };
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
Python
class Solution: def rotate(self, matrix: List[List[int]]) -> None: n = len(matrix) for i in range(n >> 1): for j in range(n): matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j] for i in range(n): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
Rust
impl Solution { pub fn rotate(matrix: &mut Vec<Vec<i32>>) { let n = matrix.len(); for i in 0..n / 2 { for j in 0..n { let t = matrix[i][j]; matrix[i][j] = matrix[n - i - 1][j]; matrix[n - i - 1][j] = t; } } for i in 0..n { for j in 0..i { let t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; } } } }
48
Rotate Image
Medium
<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p> <p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat1.jpg" style="width: 500px; height: 188px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0048.Rotate%20Image/images/mat2.jpg" style="width: 500px; height: 201px;" /> <pre> <strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] <strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 20</code></li> <li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li> </ul>
Array; Math; Matrix
TypeScript
/** Do not return anything, modify matrix in-place instead. */ function rotate(matrix: number[][]): void { matrix.reverse(); for (let i = 0; i < matrix.length; ++i) { for (let j = 0; j < i; ++j) { const t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; } } }
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
C++
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> d; for (auto& s : strs) { string k = s; sort(k.begin(), k.end()); d[k].emplace_back(s); } vector<vector<string>> ans; for (auto& [_, v] : d) ans.emplace_back(v); return ans; } };
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
C#
using System.Collections.Generic; public class Comparer : IEqualityComparer<string> { public bool Equals(string left, string right) { if (left.Length != right.Length) return false; var leftCount = new int[26]; foreach (var ch in left) { ++leftCount[ch - 'a']; } var rightCount = new int[26]; foreach (var ch in right) { var index = ch - 'a'; if (++rightCount[index] > leftCount[index]) return false; } return true; } public int GetHashCode(string obj) { var hashCode = 0; for (int i = 0; i < obj.Length; ++i) { hashCode ^= 1 << (obj[i] - 'a'); } return hashCode; } } public class Solution { public IList<IList<string>> GroupAnagrams(string[] strs) { var dict = new Dictionary<string, List<string>>(new Comparer()); foreach (var str in strs) { List<string> list; if (!dict.TryGetValue(str, out list)) { list = new List<string>(); dict.Add(str, list); } list.Add(str); } foreach (var list in dict.Values) { list.Sort(); } return new List<IList<string>>(dict.Values); } }
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
Go
func groupAnagrams(strs []string) (ans [][]string) { d := map[string][]string{} for _, s := range strs { t := []byte(s) sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) k := string(t) d[k] = append(d[k], s) } for _, v := range d { ans = append(ans, v) } return }
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
Java
class Solution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> d = new HashMap<>(); for (String s : strs) { char[] t = s.toCharArray(); Arrays.sort(t); String k = String.valueOf(t); d.computeIfAbsent(k, key -> new ArrayList<>()).add(s); } return new ArrayList<>(d.values()); } }
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
Python
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = defaultdict(list) for s in strs: k = ''.join(sorted(s)) d[k].append(s) return list(d.values())
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
Rust
use std::collections::HashMap; impl Solution { pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> { let mut map = HashMap::new(); for s in strs { let key = { let mut arr = s.chars().collect::<Vec<char>>(); arr.sort(); arr.iter().collect::<String>() }; let val = map.entry(key).or_insert(vec![]); val.push(s); } map.into_iter().map(|(_, v)| v).collect() } }
49
Group Anagrams
Medium
<p>Given an array of strings <code>strs</code>, group the <span data-keyword="anagram">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li> <li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li> <li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;&quot;]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strs = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= strs[i].length &lt;= 100</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sorting
TypeScript
function groupAnagrams(strs: string[]): string[][] { const d: Map<string, string[]> = new Map(); for (const s of strs) { const k = s.split('').sort().join(''); if (!d.has(k)) { d.set(k, []); } d.get(k)!.push(s); } return Array.from(d.values()); }
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
C++
class Solution { public: double myPow(double x, int n) { auto qpow = [](double a, long long n) { double ans = 1; for (; n; n >>= 1) { if (n & 1) { ans *= a; } a *= a; } return ans; }; return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long long) n); } };
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
C#
public class Solution { public double MyPow(double x, int n) { return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); } private double qpow(double a, long n) { double ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans *= a; } a *= a; } return ans; } }
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
Go
func myPow(x float64, n int) float64 { qpow := func(a float64, n int) float64 { ans := 1.0 for ; n > 0; n >>= 1 { if n&1 == 1 { ans *= a } a *= a } return ans } if n >= 0 { return qpow(x, n) } return 1 / qpow(x, -n) }
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
Java
class Solution { public double myPow(double x, int n) { return n >= 0 ? qpow(x, n) : 1 / qpow(x, -(long) n); } private double qpow(double a, long n) { double ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a; } a = a * a; } return ans; } }
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
JavaScript
/** * @param {number} x * @param {number} n * @return {number} */ var myPow = function (x, n) { const qpow = (a, n) => { let ans = 1; for (; n; n >>>= 1) { if (n & 1) { ans *= a; } a *= a; } return ans; }; return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); };
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
Python
class Solution: def myPow(self, x: float, n: int) -> float: def qpow(a: float, n: int) -> float: ans = 1 while n: if n & 1: ans *= a a *= a n >>= 1 return ans return qpow(x, n) if n >= 0 else 1 / qpow(x, -n)
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
Rust
impl Solution { #[allow(dead_code)] pub fn my_pow(x: f64, n: i32) -> f64 { let mut x = x; let n = n as i64; if n >= 0 { Self::quick_pow(&mut x, n) } else { 1.0 / Self::quick_pow(&mut x, -n) } } #[allow(dead_code)] fn quick_pow(x: &mut f64, mut n: i64) -> f64 { // `n` should greater or equal to zero let mut ret = 1.0; while n != 0 { if (n & 0x1) == 1 { ret *= *x; } *x *= *x; n >>= 1; } ret } }
50
Pow(x, n)
Medium
<p>Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = 10 <strong>Output:</strong> 1024.00000 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = 2.10000, n = 3 <strong>Output:</strong> 9.26100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 2.00000, n = -2 <strong>Output:</strong> 0.25000 <strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-100.0 &lt; x &lt; 100.0</code></li> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li> <li><code>n</code> is an integer.</li> <li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li> <li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li> </ul>
Recursion; Math
TypeScript
function myPow(x: number, n: number): number { const qpow = (a: number, n: number): number => { let ans = 1; for (; n; n >>>= 1) { if (n & 1) { ans *= a; } a *= a; } return ans; }; return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); }
51
N-Queens
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p> <p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0051.N-Queens/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]] <strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[&quot;Q&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Array; Backtracking
C++
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<int> col(n); vector<int> dg(n << 1); vector<int> udg(n << 1); vector<vector<string>> ans; vector<string> t(n, string(n, '.')); function<void(int)> dfs = [&](int i) -> void { if (i == n) { ans.push_back(t); return; } for (int j = 0; j < n; ++j) { if (col[j] + dg[i + j] + udg[n - i + j] == 0) { t[i][j] = 'Q'; col[j] = dg[i + j] = udg[n - i + j] = 1; dfs(i + 1); col[j] = dg[i + j] = udg[n - i + j] = 0; t[i][j] = '.'; } } }; dfs(0); return ans; } };
51
N-Queens
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p> <p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0051.N-Queens/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]] <strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[&quot;Q&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Array; Backtracking
C#
public class Solution { private int n; private int[] col; private int[] dg; private int[] udg; private IList<IList<string>> ans = new List<IList<string>>(); private IList<string> t = new List<string>(); public IList<IList<string>> SolveNQueens(int n) { this.n = n; col = new int[n]; dg = new int[n << 1]; udg = new int[n << 1]; dfs(0); return ans; } private void dfs(int i) { if (i == n) { ans.Add(new List<string>(t)); return; } for (int j = 0; j < n; ++j) { if (col[j] + dg[i + j] + udg[n - i + j] == 0) { char[] row = new char[n]; Array.Fill(row, '.'); row[j] = 'Q'; t.Add(new string(row)); col[j] = dg[i + j] = udg[n - i + j] = 1; dfs(i + 1); col[j] = dg[i + j] = udg[n - i + j] = 0; t.RemoveAt(t.Count - 1); } } } }
51
N-Queens
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p> <p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0051.N-Queens/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]] <strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[&quot;Q&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Array; Backtracking
Go
func solveNQueens(n int) (ans [][]string) { col := make([]int, n) dg := make([]int, n<<1) udg := make([]int, n<<1) t := make([][]byte, n) for i := range t { t[i] = make([]byte, n) for j := range t[i] { t[i][j] = '.' } } var dfs func(int) dfs = func(i int) { if i == n { tmp := make([]string, n) for i := range tmp { tmp[i] = string(t[i]) } ans = append(ans, tmp) return } for j := 0; j < n; j++ { if col[j]+dg[i+j]+udg[n-i+j] == 0 { col[j], dg[i+j], udg[n-i+j] = 1, 1, 1 t[i][j] = 'Q' dfs(i + 1) t[i][j] = '.' col[j], dg[i+j], udg[n-i+j] = 0, 0, 0 } } } dfs(0) return }
51
N-Queens
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p> <p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0051.N-Queens/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]] <strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[&quot;Q&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Array; Backtracking
Java
class Solution { private List<List<String>> ans = new ArrayList<>(); private int[] col; private int[] dg; private int[] udg; private String[][] g; private int n; public List<List<String>> solveNQueens(int n) { this.n = n; col = new int[n]; dg = new int[n << 1]; udg = new int[n << 1]; g = new String[n][n]; for (int i = 0; i < n; ++i) { Arrays.fill(g[i], "."); } dfs(0); return ans; } private void dfs(int i) { if (i == n) { List<String> t = new ArrayList<>(); for (int j = 0; j < n; ++j) { t.add(String.join("", g[j])); } ans.add(t); return; } for (int j = 0; j < n; ++j) { if (col[j] + dg[i + j] + udg[n - i + j] == 0) { g[i][j] = "Q"; col[j] = dg[i + j] = udg[n - i + j] = 1; dfs(i + 1); col[j] = dg[i + j] = udg[n - i + j] = 0; g[i][j] = "."; } } } }
51
N-Queens
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p> <p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0051.N-Queens/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]] <strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[&quot;Q&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Array; Backtracking
Python
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: def dfs(i: int): if i == n: ans.append(["".join(row) for row in g]) return for j in range(n): if col[j] + dg[i + j] + udg[n - i + j] == 0: g[i][j] = "Q" col[j] = dg[i + j] = udg[n - i + j] = 1 dfs(i + 1) col[j] = dg[i + j] = udg[n - i + j] = 0 g[i][j] = "." ans = [] g = [["."] * n for _ in range(n)] col = [0] * n dg = [0] * (n << 1) udg = [0] * (n << 1) dfs(0) return ans
51
N-Queens
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p> <p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0051.N-Queens/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]] <strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[&quot;Q&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Array; Backtracking
TypeScript
function solveNQueens(n: number): string[][] { const col: number[] = Array(n).fill(0); const dg: number[] = Array(n << 1).fill(0); const udg: number[] = Array(n << 1).fill(0); const ans: string[][] = []; const t: string[][] = Array.from({ length: n }, () => Array(n).fill('.')); const dfs = (i: number) => { if (i === n) { ans.push(t.map(x => x.join(''))); return; } for (let j = 0; j < n; ++j) { if (col[j] + dg[i + j] + udg[n - i + j] === 0) { t[i][j] = 'Q'; col[j] = dg[i + j] = udg[n - i + j] = 1; dfs(i + 1); col[j] = dg[i + j] = udg[n - i + j] = 0; t[i][j] = '.'; } } }; dfs(0); return ans; }
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
C++
class Solution { public: int totalNQueens(int n) { bitset<10> cols; bitset<20> dg; bitset<20> udg; int ans = 0; function<void(int)> dfs = [&](int i) { if (i == n) { ++ans; return; } for (int j = 0; j < n; ++j) { int a = i + j, b = i - j + n; if (cols[j] || dg[a] || udg[b]) continue; cols[j] = dg[a] = udg[b] = 1; dfs(i + 1); cols[j] = dg[a] = udg[b] = 0; } }; dfs(0); return ans; } };
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
C#
public class Solution { public int TotalNQueens(int n) { bool[] cols = new bool[10]; bool[] dg = new bool[20]; bool[] udg = new bool[20]; int ans = 0; void dfs(int i) { if (i == n) { ans++; return; } for (int j = 0; j < n; j++) { int a = i + j, b = i - j + n; if (cols[j] || dg[a] || udg[b]) { continue; } cols[j] = dg[a] = udg[b] = true; dfs(i + 1); cols[j] = dg[a] = udg[b] = false; } } dfs(0); return ans; } }
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
Go
func totalNQueens(n int) (ans int) { cols := [10]bool{} dg := [20]bool{} udg := [20]bool{} var dfs func(int) dfs = func(i int) { if i == n { ans++ return } for j := 0; j < n; j++ { a, b := i+j, i-j+n if cols[j] || dg[a] || udg[b] { continue } cols[j], dg[a], udg[b] = true, true, true dfs(i + 1) cols[j], dg[a], udg[b] = false, false, false } } dfs(0) return }
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
Java
class Solution { private int n; private int ans; private boolean[] cols = new boolean[10]; private boolean[] dg = new boolean[20]; private boolean[] udg = new boolean[20]; public int totalNQueens(int n) { this.n = n; dfs(0); return ans; } private void dfs(int i) { if (i == n) { ++ans; return; } for (int j = 0; j < n; ++j) { int a = i + j, b = i - j + n; if (cols[j] || dg[a] || udg[b]) { continue; } cols[j] = true; dg[a] = true; udg[b] = true; dfs(i + 1); cols[j] = false; dg[a] = false; udg[b] = false; } } }
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
JavaScript
function totalNQueens(n) { const cols = Array(10).fill(false); const dg = Array(20).fill(false); const udg = Array(20).fill(false); let ans = 0; const dfs = i => { if (i === n) { ++ans; return; } for (let j = 0; j < n; ++j) { let [a, b] = [i + j, i - j + n]; if (cols[j] || dg[a] || udg[b]) { continue; } cols[j] = dg[a] = udg[b] = true; dfs(i + 1); cols[j] = dg[a] = udg[b] = false; } }; dfs(0); return ans; }
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
Python
class Solution: def totalNQueens(self, n: int) -> int: def dfs(i: int): if i == n: nonlocal ans ans += 1 return for j in range(n): a, b = i + j, i - j + n if cols[j] or dg[a] or udg[b]: continue cols[j] = dg[a] = udg[b] = True dfs(i + 1) cols[j] = dg[a] = udg[b] = False cols = [False] * 10 dg = [False] * 20 udg = [False] * 20 ans = 0 dfs(0) return ans
52
N-Queens II
Hard
<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p> <p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0052.N-Queens%20II/images/queens.jpg" style="width: 600px; height: 268px;" /> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 9</code></li> </ul>
Backtracking
TypeScript
function totalNQueens(n: number): number { const cols: boolean[] = Array(10).fill(false); const dg: boolean[] = Array(20).fill(false); const udg: boolean[] = Array(20).fill(false); let ans = 0; const dfs = (i: number) => { if (i === n) { ++ans; return; } for (let j = 0; j < n; ++j) { let [a, b] = [i + j, i - j + n]; if (cols[j] || dg[a] || udg[b]) { continue; } cols[j] = dg[a] = udg[b] = true; dfs(i + 1); cols[j] = dg[a] = udg[b] = false; } }; dfs(0); return ans; }
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
C++
class Solution { public: int maxSubArray(vector<int>& nums) { int ans = nums[0], f = nums[0]; for (int i = 1; i < nums.size(); ++i) { f = max(f, 0) + nums[i]; ans = max(ans, f); } return ans; } };
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
C#
public class Solution { public int MaxSubArray(int[] nums) { int ans = nums[0], f = nums[0]; for (int i = 1; i < nums.Length; ++i) { f = Math.Max(f, 0) + nums[i]; ans = Math.Max(ans, f); } return ans; } }
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
Go
func maxSubArray(nums []int) int { ans, f := nums[0], nums[0] for _, x := range nums[1:] { f = max(f, 0) + x ans = max(ans, f) } return ans }
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
Java
class Solution { public int maxSubArray(int[] nums) { int ans = nums[0]; for (int i = 1, f = nums[0]; i < nums.length; ++i) { f = Math.max(f, 0) + nums[i]; ans = Math.max(ans, f); } return ans; } }
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
JavaScript
/** * @param {number[]} nums * @return {number} */ var maxSubArray = function (nums) { let [ans, f] = [nums[0], nums[0]]; for (let i = 1; i < nums.length; ++i) { f = Math.max(f, 0) + nums[i]; ans = Math.max(ans, f); } return ans; };
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
Python
class Solution: def maxSubArray(self, nums: List[int]) -> int: ans = f = nums[0] for x in nums[1:]: f = max(f, 0) + x ans = max(ans, f) return ans
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
Rust
impl Solution { pub fn max_sub_array(nums: Vec<i32>) -> i32 { let n = nums.len(); let mut ans = nums[0]; let mut f = nums[0]; for i in 1..n { f = f.max(0) + nums[i]; ans = ans.max(f); } ans } }
53
Maximum Subarray
Medium
<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The subarray [1] has the largest sum 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,-1,7,8] <strong>Output:</strong> 23 <strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
Array; Divide and Conquer; Dynamic Programming
TypeScript
function maxSubArray(nums: number[]): number { let [ans, f] = [nums[0], nums[0]]; for (let i = 1; i < nums.length; ++i) { f = Math.max(f, 0) + nums[i]; ans = Math.max(ans, f); } return ans; }
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
C++
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); int dirs[5] = {0, 1, 0, -1, 0}; int i = 0, j = 0, k = 0; vector<int> ans; bool vis[m][n]; memset(vis, false, sizeof(vis)); for (int h = m * n; h; --h) { ans.push_back(matrix[i][j]); vis[i][j] = true; int x = i + dirs[k], y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } return ans; } };
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
C#
public class Solution { public IList<int> SpiralOrder(int[][] matrix) { int m = matrix.Length, n = matrix[0].Length; int[] dirs = { 0, 1, 0, -1, 0 }; int i = 0, j = 0, k = 0; IList<int> ans = new List<int>(); bool[,] vis = new bool[m, n]; for (int h = m * n; h > 0; --h) { ans.Add(matrix[i][j]); vis[i, j] = true; int x = i + dirs[k], y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || vis[x, y]) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } return ans; } }
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
Go
func spiralOrder(matrix [][]int) (ans []int) { m, n := len(matrix), len(matrix[0]) vis := make([][]bool, m) for i := range vis { vis[i] = make([]bool, n) } dirs := [5]int{0, 1, 0, -1, 0} i, j, k := 0, 0, 0 for h := m * n; h > 0; h-- { ans = append(ans, matrix[i][j]) vis[i][j] = true x, y := i+dirs[k], j+dirs[k+1] if x < 0 || x >= m || y < 0 || y >= n || vis[x][y] { k = (k + 1) % 4 } i, j = i+dirs[k], j+dirs[k+1] } return }
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
Java
class Solution { public List<Integer> spiralOrder(int[][] matrix) { int m = matrix.length, n = matrix[0].length; int[] dirs = {0, 1, 0, -1, 0}; int i = 0, j = 0, k = 0; List<Integer> ans = new ArrayList<>(); boolean[][] vis = new boolean[m][n]; for (int h = m * n; h > 0; --h) { ans.add(matrix[i][j]); vis[i][j] = true; int x = i + dirs[k], y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } return ans; } }
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
JavaScript
/** * @param {number[][]} matrix * @return {number[]} */ var spiralOrder = function (matrix) { const m = matrix.length; const n = matrix[0].length; const ans = []; const vis = Array.from({ length: m }, () => Array(n).fill(false)); const dirs = [0, 1, 0, -1, 0]; for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { ans.push(matrix[i][j]); vis[i][j] = true; const x = i + dirs[k]; const y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } return ans; };
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
Python
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: m, n = len(matrix), len(matrix[0]) dirs = (0, 1, 0, -1, 0) vis = [[False] * n for _ in range(m)] i = j = k = 0 ans = [] for _ in range(m * n): ans.append(matrix[i][j]) vis[i][j] = True x, y = i + dirs[k], j + dirs[k + 1] if x < 0 or x >= m or y < 0 or y >= n or vis[x][y]: k = (k + 1) % 4 i += dirs[k] j += dirs[k + 1] return ans
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
Rust
impl Solution { pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> { let m = matrix.len(); let n = matrix[0].len(); let mut dirs = vec![0, 1, 0, -1, 0]; let mut vis = vec![vec![false; n]; m]; let mut i = 0; let mut j = 0; let mut k = 0; let mut ans = Vec::new(); for _ in 0..(m * n) { ans.push(matrix[i][j]); vis[i][j] = true; let x = i as i32 + dirs[k] as i32; let y = j as i32 + dirs[k + 1] as i32; if x < 0 || x >= m as i32 || y < 0 || y >= n as i32 || vis[x as usize][y as usize] { k = (k + 1) % 4; } i = (i as i32 + dirs[k] as i32) as usize; j = (j as i32 + dirs[k + 1] as i32) as usize; } ans } }
54
Spiral Matrix
Medium
<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,3,6,9,8,7,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] <strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> </ul>
Array; Matrix; Simulation
TypeScript
function spiralOrder(matrix: number[][]): number[] { const m = matrix.length; const n = matrix[0].length; const ans: number[] = []; const vis: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false)); const dirs = [0, 1, 0, -1, 0]; for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { ans.push(matrix[i][j]); vis[i][j] = true; const x = i + dirs[k]; const y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } return ans; }
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
C++
class Solution { public: bool canJump(vector<int>& nums) { int mx = 0; for (int i = 0; i < nums.size(); ++i) { if (mx < i) { return false; } mx = max(mx, i + nums[i]); } return true; } };
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
C#
public class Solution { public bool CanJump(int[] nums) { int mx = 0; for (int i = 0; i < nums.Length; ++i) { if (mx < i) { return false; } mx = Math.Max(mx, i + nums[i]); } return true; } }
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Go
func canJump(nums []int) bool { mx := 0 for i, x := range nums { if mx < i { return false } mx = max(mx, i+x) } return true }
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Java
class Solution { public boolean canJump(int[] nums) { int mx = 0; for (int i = 0; i < nums.length; ++i) { if (mx < i) { return false; } mx = Math.max(mx, i + nums[i]); } return true; } }
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
JavaScript
/** * @param {number[]} nums * @return {boolean} */ var canJump = function (nums) { let mx = 0; for (let i = 0; i < nums.length; ++i) { if (mx < i) { return false; } mx = Math.max(mx, i + nums[i]); } return true; };
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Python
class Solution: def canJump(self, nums: List[int]) -> bool: mx = 0 for i, x in enumerate(nums): if mx < i: return False mx = max(mx, i + x) return True
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Rust
impl Solution { #[allow(dead_code)] pub fn can_jump(nums: Vec<i32>) -> bool { let n = nums.len(); let mut mx = 0; for i in 0..n { if mx < i { return false; } mx = std::cmp::max(mx, i + (nums[i] as usize)); } true } }
55
Jump Game
Medium
<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p> <p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,0,4] <strong>Output:</strong> false <strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
TypeScript
function canJump(nums: number[]): boolean { let mx: number = 0; for (let i = 0; i < nums.length; ++i) { if (mx < i) { return false; } mx = Math.max(mx, i + nums[i]); } return true; }
56
Merge Intervals
Medium
<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]] <strong>Output:</strong> [[1,6],[8,10],[15,18]] <strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[4,5]] <strong>Output:</strong> [[1,5]] <strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sorting
C++
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { sort(intervals.begin(), intervals.end()); int st = intervals[0][0], ed = intervals[0][1]; vector<vector<int>> ans; for (int i = 1; i < intervals.size(); ++i) { if (ed < intervals[i][0]) { ans.push_back({st, ed}); st = intervals[i][0]; ed = intervals[i][1]; } else { ed = max(ed, intervals[i][1]); } } ans.push_back({st, ed}); return ans; } };
56
Merge Intervals
Medium
<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]] <strong>Output:</strong> [[1,6],[8,10],[15,18]] <strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[4,5]] <strong>Output:</strong> [[1,5]] <strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sorting
C#
public class Solution { public int[][] Merge(int[][] intervals) { intervals = intervals.OrderBy(a => a[0]).ToArray(); int st = intervals[0][0], ed = intervals[0][1]; var ans = new List<int[]>(); for (int i = 1; i < intervals.Length; ++i) { if (ed < intervals[i][0]) { ans.Add(new int[] { st, ed }); st = intervals[i][0]; ed = intervals[i][1]; } else { ed = Math.Max(ed, intervals[i][1]); } } ans.Add(new int[] { st, ed }); return ans.ToArray(); } }
56
Merge Intervals
Medium
<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]] <strong>Output:</strong> [[1,6],[8,10],[15,18]] <strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[4,5]] <strong>Output:</strong> [[1,5]] <strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sorting
Go
func merge(intervals [][]int) (ans [][]int) { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) st, ed := intervals[0][0], intervals[0][1] for _, e := range intervals[1:] { if ed < e[0] { ans = append(ans, []int{st, ed}) st, ed = e[0], e[1] } else if ed < e[1] { ed = e[1] } } ans = append(ans, []int{st, ed}) return ans }