id
int64
1
3.64k
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
201
Bitwise AND of Numbers Range
Medium
<p>Given two integers <code>left</code> and <code>right</code> that represent the range <code>[left, right]</code>, return <em>the bitwise AND of all numbers in this range, inclusive</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> left = 5, right = 7 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> left = 0, right = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> left = 1, right = 2147483647 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= left &lt;= right &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation
JavaScript
/** * @param {number} left * @param {number} right * @return {number} */ var rangeBitwiseAnd = function (left, right) { while (left < right) { right &= right - 1; } return right; };
201
Bitwise AND of Numbers Range
Medium
<p>Given two integers <code>left</code> and <code>right</code> that represent the range <code>[left, right]</code>, return <em>the bitwise AND of all numbers in this range, inclusive</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> left = 5, right = 7 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> left = 0, right = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> left = 1, right = 2147483647 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= left &lt;= right &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation
Python
class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: while left < right: right &= right - 1 return right
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
C
int getNext(int n) { int res = 0; while (n) { res += (n % 10) * (n % 10); n /= 10; } return res; } bool isHappy(int n) { int slow = n; int fast = getNext(n); while (slow != fast) { slow = getNext(slow); fast = getNext(getNext(fast)); } return fast == 1; }
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
C++
class Solution { public: bool isHappy(int n) { unordered_set<int> vis; while (n != 1 && !vis.count(n)) { vis.insert(n); int x = 0; for (; n; n /= 10) { x += (n % 10) * (n % 10); } n = x; } return n == 1; } };
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
Go
func isHappy(n int) bool { vis := map[int]bool{} for n != 1 && !vis[n] { vis[n] = true x := 0 for ; n > 0; n /= 10 { x += (n % 10) * (n % 10) } n = x } return n == 1 }
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
Java
class Solution { public boolean isHappy(int n) { Set<Integer> vis = new HashSet<>(); while (n != 1 && !vis.contains(n)) { vis.add(n); int x = 0; while (n != 0) { x += (n % 10) * (n % 10); n /= 10; } n = x; } return n == 1; } }
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
Python
class Solution: def isHappy(self, n: int) -> bool: vis = set() while n != 1 and n not in vis: vis.add(n) x = 0 while n: n, v = divmod(n, 10) x += v * v n = x return n == 1
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
Rust
use std::collections::HashSet; impl Solution { fn get_next(mut n: i32) -> i32 { let mut res = 0; while n != 0 { res += (n % 10).pow(2); n /= 10; } res } pub fn is_happy(mut n: i32) -> bool { let mut set = HashSet::new(); while n != 1 { let next = Self::get_next(n); if set.contains(&next) { return false; } set.insert(next); n = next; } true } }
202
Happy Number
Easy
<p>Write an algorithm to determine if a number <code>n</code> is happy.</p> <p>A <strong>happy number</strong> is a number defined by the following process:</p> <ul> <li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li> <li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li> <li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li> </ul> <p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 19 <strong>Output:</strong> true <strong>Explanation:</strong> 1<sup>2</sup> + 9<sup>2</sup> = 82 8<sup>2</sup> + 2<sup>2</sup> = 68 6<sup>2</sup> + 8<sup>2</sup> = 100 1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Hash Table; Math; Two Pointers
TypeScript
function isHappy(n: number): boolean { const getNext = (n: number) => { let res = 0; while (n !== 0) { res += (n % 10) ** 2; n = Math.floor(n / 10); } return res; }; const set = new Set(); while (n !== 1) { const next = getNext(n); if (set.has(next)) { return false; } set.add(next); n = next; } return true; }
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
C++
class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* dummy = new ListNode(); dummy->next = head; ListNode* p = dummy; while (p->next) { if (p->next->val == val) { p->next = p->next->next; } else { p = p->next; } } return dummy->next; } };
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
C#
public class Solution { public ListNode RemoveElements(ListNode head, int val) { ListNode newHead = null; ListNode newTail = null; var current = head; while (current != null) { if (current.val != val) { if (newHead == null) { newHead = newTail = current; } else { newTail.next = current; newTail = current; } } current = current.next; } if (newTail != null) newTail.next = null; return newHead; } }
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
Go
func removeElements(head *ListNode, val int) *ListNode { dummy := new(ListNode) dummy.Next = head p := dummy for p.Next != nil { if p.Next.Val == val { p.Next = p.Next.Next } else { p = p.Next } } return dummy.Next }
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(-1, head); ListNode pre = dummy; while (pre.next != null) { if (pre.next.val != val) pre = pre.next; else pre.next = pre.next.next; } return dummy.next; } }
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: dummy = ListNode(-1, head) pre = dummy while pre.next: if pre.next.val != val: pre = pre.next else: pre.next = pre.next.next return dummy.next
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> { let mut dummy = Box::new(ListNode { val: 0, next: head }); let mut cur = &mut dummy; while let Some(mut node) = cur.next.take() { if node.val == val { cur.next = node.next.take(); } else { cur.next = Some(node); cur = cur.next.as_mut().unwrap(); } } dummy.next.take() } }
203
Remove Linked List Elements
Easy
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/0200-0299/0203.Remove%20Linked%20List%20Elements/images/removelinked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6 <strong>Output:</strong> [1,2,3,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [], val = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [7,7,7,7], val = 7 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 50</code></li> </ul>
Recursion; Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function removeElements(head: ListNode | null, val: number): ListNode | null { const dummy: ListNode = new ListNode(0, head); let cur: ListNode = dummy; while (cur.next != null) { if (cur.next.val === val) { cur.next = cur.next.next; } else { cur = cur.next; } } return dummy.next; }
204
Count Primes
Medium
<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
C++
class Solution { public: int countPrimes(int n) { vector<bool> primes(n, true); int ans = 0; for (int i = 2; i < n; ++i) { if (primes[i]) { ++ans; for (int j = i; j < n; j += i) primes[j] = false; } } return ans; } };
204
Count Primes
Medium
<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
C#
public class Solution { public int CountPrimes(int n) { var notPrimes = new bool[n]; int ans = 0; for (int i = 2; i < n; ++i) { if (!notPrimes[i]) { ++ans; for (int j = i + i; j < n; j += i) { notPrimes[j] = true; } } } return ans; } }
204
Count Primes
Medium
<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
Go
func countPrimes(n int) int { primes := make([]bool, n) for i := range primes { primes[i] = true } ans := 0 for i := 2; i < n; i++ { if primes[i] { ans++ for j := i + i; j < n; j += i { primes[j] = false } } } return ans }
204
Count Primes
Medium
<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
Java
class Solution { public int countPrimes(int n) { boolean[] primes = new boolean[n]; Arrays.fill(primes, true); int ans = 0; for (int i = 2; i < n; ++i) { if (primes[i]) { ++ans; for (int j = i + i; j < n; j += i) { primes[j] = false; } } } return ans; } }
204
Count Primes
Medium
<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
JavaScript
/** * @param {number} n * @return {number} */ var countPrimes = function (n) { let primes = new Array(n).fill(true); let ans = 0; for (let i = 2; i < n; ++i) { if (primes[i]) { ++ans; for (let j = i + i; j < n; j += i) { primes[j] = false; } } } return ans; };
204
Count Primes
Medium
<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
Python
class Solution: def countPrimes(self, n: int) -> int: primes = [True] * n ans = 0 for i in range(2, n): if primes[i]: ans += 1 for j in range(i + i, n, i): primes[j] = False return ans
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
C++
class Solution { public: bool isIsomorphic(string s, string t) { int d1[256]{}; int d2[256]{}; int n = s.size(); for (int i = 0; i < n; ++i) { char a = s[i], b = t[i]; if (d1[a] != d2[b]) { return false; } d1[a] = d2[b] = i + 1; } return true; } };
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
C#
public class Solution { public bool IsIsomorphic(string s, string t) { int[] d1 = new int[256]; int[] d2 = new int[256]; for (int i = 0; i < s.Length; ++i) { var a = s[i]; var b = t[i]; if (d1[a] != d2[b]) { return false; } d1[a] = i + 1; d2[b] = i + 1; } return true; } }
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
Go
func isIsomorphic(s string, t string) bool { d1 := [256]int{} d2 := [256]int{} for i := range s { if d1[s[i]] != d2[t[i]] { return false } d1[s[i]] = i + 1 d2[t[i]] = i + 1 } return true }
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
Java
class Solution { public boolean isIsomorphic(String s, String t) { Map<Character, Character> d1 = new HashMap<>(); Map<Character, Character> d2 = new HashMap<>(); int n = s.length(); for (int i = 0; i < n; ++i) { char a = s.charAt(i), b = t.charAt(i); if (d1.containsKey(a) && d1.get(a) != b) { return false; } if (d2.containsKey(b) && d2.get(b) != a) { return false; } d1.put(a, b); d2.put(b, a); } return true; } }
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
Python
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: d1 = {} d2 = {} for a, b in zip(s, t): if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a): return False d1[a] = b d2[b] = a return True
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
Rust
use std::collections::HashMap; impl Solution { fn help(s: &[u8], t: &[u8]) -> bool { let mut map = HashMap::new(); for i in 0..s.len() { if map.contains_key(&s[i]) { if map.get(&s[i]).unwrap() != &t[i] { return false; } } else { map.insert(s[i], t[i]); } } true } pub fn is_isomorphic(s: String, t: String) -> bool { let (s, t) = (s.as_bytes(), t.as_bytes()); Self::help(s, t) && Self::help(t, s) } }
205
Isomorphic Strings
Easy
<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p> <p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p> <p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;egg&quot;, t = &quot;add&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can be made identical by:</p> <ul> <li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li> <li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;paper&quot;, t = &quot;title&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>t.length == s.length</code></li> <li><code>s</code> and <code>t</code> consist of any valid ascii character.</li> </ul>
Hash Table; String
TypeScript
function isIsomorphic(s: string, t: string): boolean { const d1: number[] = new Array(256).fill(0); const d2: number[] = new Array(256).fill(0); for (let i = 0; i < s.length; ++i) { const a = s.charCodeAt(i); const b = t.charCodeAt(i); if (d1[a] !== d2[b]) { return false; } d1[a] = i + 1; d2[b] = i + 1; } return true; }
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* dummy = new ListNode(); ListNode* curr = head; while (curr) { ListNode* next = curr->next; curr->next = dummy->next; dummy->next = curr; curr = next; } return dummy->next; } };
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode ReverseList(ListNode head) { ListNode dummy = new ListNode(); ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = dummy.next; dummy.next = curr; curr = next; } return dummy.next; } }
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList(head *ListNode) *ListNode { dummy := &ListNode{} curr := head for curr != nil { next := curr.Next curr.Next = dummy.Next dummy.Next = curr curr = next } return dummy.Next }
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode dummy = new ListNode(); ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = dummy.next; dummy.next = curr; curr = next; } return dummy.next; } }
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseList = function (head) { let dummy = new ListNode(); let curr = head; while (curr) { let next = curr.next; curr.next = dummy.next; dummy.next = curr; curr = next; } return dummy.next; };
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: dummy = ListNode() curr = head while curr: next = curr.next curr.next = dummy.next dummy.next = curr curr = next return dummy.next
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut head = head; let mut pre = None; while let Some(mut node) = head { head = node.next.take(); node.next = pre.take(); pre = Some(node); } pre } }
206
Reverse Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</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/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [5,4,3,2,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0206.Reverse%20Linked%20List/images/rev1ex2.jpg" style="width: 182px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> [2,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li> <li><code>-5000 &lt;= Node.val &lt;= 5000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Recursion; Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function reverseList(head: ListNode | null): ListNode | null { if (head == null) { return head; } let pre = null; let cur = head; while (cur != null) { const next = cur.next; cur.next = pre; [pre, cur] = [cur, next]; } return pre; }
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
C++
class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> g(numCourses); vector<int> indeg(numCourses); for (auto& p : prerequisites) { int a = p[0], b = p[1]; g[b].push_back(a); ++indeg[a]; } queue<int> q; for (int i = 0; i < numCourses; ++i) { if (indeg[i] == 0) { q.push(i); } } while (!q.empty()) { int i = q.front(); q.pop(); --numCourses; for (int j : g[i]) { if (--indeg[j] == 0) { q.push(j); } } } return numCourses == 0; } };
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
C#
public class Solution { public bool CanFinish(int numCourses, int[][] prerequisites) { var g = new List<int>[numCourses]; for (int i = 0; i < numCourses; ++i) { g[i] = new List<int>(); } var indeg = new int[numCourses]; foreach (var p in prerequisites) { int a = p[0], b = p[1]; g[b].Add(a); ++indeg[a]; } var q = new Queue<int>(); for (int i = 0; i < numCourses; ++i) { if (indeg[i] == 0) { q.Enqueue(i); } } while (q.Count > 0) { int i = q.Dequeue(); --numCourses; foreach (int j in g[i]) { if (--indeg[j] == 0) { q.Enqueue(j); } } } return numCourses == 0; } }
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Go
func canFinish(numCourses int, prerequisites [][]int) bool { g := make([][]int, numCourses) indeg := make([]int, numCourses) for _, p := range prerequisites { a, b := p[0], p[1] g[b] = append(g[b], a) indeg[a]++ } q := []int{} for i, x := range indeg { if x == 0 { q = append(q, i) } } for len(q) > 0 { i := q[0] q = q[1:] numCourses-- for _, j := range g[i] { indeg[j]-- if indeg[j] == 0 { q = append(q, j) } } } return numCourses == 0 }
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Java
class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { List<Integer>[] g = new List[numCourses]; Arrays.setAll(g, k -> new ArrayList<>()); int[] indeg = new int[numCourses]; for (var p : prerequisites) { int a = p[0], b = p[1]; g[b].add(a); ++indeg[a]; } Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < numCourses; ++i) { if (indeg[i] == 0) { q.offer(i); } } while (!q.isEmpty()) { int i = q.poll(); --numCourses; for (int j : g[i]) { if (--indeg[j] == 0) { q.offer(j); } } } return numCourses == 0; } }
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Python
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: g = [[] for _ in range(numCourses)] indeg = [0] * numCourses for a, b in prerequisites: g[b].append(a) indeg[a] += 1 q = [i for i, x in enumerate(indeg) if x == 0] for i in q: numCourses -= 1 for j in g[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return numCourses == 0
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Rust
use std::collections::VecDeque; impl Solution { pub fn can_finish(mut num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool { let mut g: Vec<Vec<i32>> = vec![vec![]; num_courses as usize]; let mut indeg: Vec<i32> = vec![0; num_courses as usize]; for p in prerequisites { let a = p[0] as usize; let b = p[1] as usize; g[b].push(a as i32); indeg[a] += 1; } let mut q: VecDeque<usize> = VecDeque::new(); for i in 0..num_courses { if indeg[i as usize] == 0 { q.push_back(i as usize); } } while let Some(i) = q.pop_front() { num_courses -= 1; for &j in &g[i] { let j = j as usize; indeg[j] -= 1; if indeg[j] == 0 { q.push_back(j); } } } num_courses == 0 } }
207
Course Schedule
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> true <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]] <strong>Output:</strong> false <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li>All the pairs prerequisites[i] are <strong>unique</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
TypeScript
function canFinish(numCourses: number, prerequisites: number[][]): boolean { const g: number[][] = Array.from({ length: numCourses }, () => []); const indeg: number[] = Array(numCourses).fill(0); for (const [a, b] of prerequisites) { g[b].push(a); indeg[a]++; } const q: number[] = []; for (let i = 0; i < numCourses; ++i) { if (indeg[i] === 0) { q.push(i); } } for (const i of q) { --numCourses; for (const j of g[i]) { if (--indeg[j] === 0) { q.push(j); } } } return numCourses === 0; }
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
C++
class Trie { private: vector<Trie*> children; bool isEnd; Trie* searchPrefix(string s) { Trie* node = this; for (char c : s) { int idx = c - 'a'; if (!node->children[idx]) return nullptr; node = node->children[idx]; } return node; } public: Trie() : children(26) , isEnd(false) {} void insert(string word) { Trie* node = this; for (char c : word) { int idx = c - 'a'; if (!node->children[idx]) node->children[idx] = new Trie(); node = node->children[idx]; } node->isEnd = true; } bool search(string word) { Trie* node = searchPrefix(word); return node != nullptr && node->isEnd; } bool startsWith(string prefix) { Trie* node = searchPrefix(prefix); return node != nullptr; } }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
C#
public class Trie { bool isEnd; Trie[] children = new Trie[26]; public Trie() { } public void Insert(string word) { Trie node = this; foreach (var c in word) { var idx = c - 'a'; node.children[idx] ??= new Trie(); node = node.children[idx]; } node.isEnd = true; } public bool Search(string word) { Trie node = SearchPrefix(word); return node != null && node.isEnd; } public bool StartsWith(string prefix) { Trie node = SearchPrefix(prefix); return node != null; } private Trie SearchPrefix(string s) { Trie node = this; foreach (var c in s) { var idx = c - 'a'; if (node.children[idx] == null) { return null; } node = node.children[idx]; } return node; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.Insert(word); * bool param_2 = obj.Search(word); * bool param_3 = obj.StartsWith(prefix); */
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
Go
type Trie struct { children [26]*Trie isEnd bool } func Constructor() Trie { return Trie{} } func (this *Trie) Insert(word string) { node := this for _, c := range word { idx := c - 'a' if node.children[idx] == nil { node.children[idx] = &Trie{} } node = node.children[idx] } node.isEnd = true } func (this *Trie) Search(word string) bool { node := this.SearchPrefix(word) return node != nil && node.isEnd } func (this *Trie) StartsWith(prefix string) bool { node := this.SearchPrefix(prefix) return node != nil } func (this *Trie) SearchPrefix(s string) *Trie { node := this for _, c := range s { idx := c - 'a' if node.children[idx] == nil { return nil } node = node.children[idx] } return node } /** * Your Trie object will be instantiated and called as such: * obj := Constructor(); * obj.Insert(word); * param_2 := obj.Search(word); * param_3 := obj.StartsWith(prefix); */
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
Java
class Trie { private Trie[] children; private boolean isEnd; public Trie() { children = new Trie[26]; } public void insert(String word) { Trie node = this; for (char c : word.toCharArray()) { int idx = c - 'a'; if (node.children[idx] == null) { node.children[idx] = new Trie(); } node = node.children[idx]; } node.isEnd = true; } public boolean search(String word) { Trie node = searchPrefix(word); return node != null && node.isEnd; } public boolean startsWith(String prefix) { Trie node = searchPrefix(prefix); return node != null; } private Trie searchPrefix(String s) { Trie node = this; for (char c : s.toCharArray()) { int idx = c - 'a'; if (node.children[idx] == null) { return null; } node = node.children[idx]; } return node; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
JavaScript
/** * Initialize your data structure here. */ var Trie = function () { this.children = {}; }; /** * Inserts a word into the trie. * @param {string} word * @return {void} */ Trie.prototype.insert = function (word) { let node = this.children; for (let char of word) { if (!node[char]) { node[char] = {}; } node = node[char]; } node.isEnd = true; }; /** * Returns if the word is in the trie. * @param {string} word * @return {boolean} */ Trie.prototype.search = function (word) { let node = this.searchPrefix(word); return node != undefined && node.isEnd != undefined; }; Trie.prototype.searchPrefix = function (prefix) { let node = this.children; for (let char of prefix) { if (!node[char]) return false; node = node[char]; } return node; }; /** * Returns if there is any word in the trie that starts with the given prefix. * @param {string} prefix * @return {boolean} */ Trie.prototype.startsWith = function (prefix) { return this.searchPrefix(prefix); }; /** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
Python
class Trie: def __init__(self): self.children = [None] * 26 self.is_end = False def insert(self, word: str) -> None: node = self for c in word: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.is_end = True def search(self, word: str) -> bool: node = self._search_prefix(word) return node is not None and node.is_end def startsWith(self, prefix: str) -> bool: node = self._search_prefix(prefix) return node is not None def _search_prefix(self, prefix: str): node = self for c in prefix: idx = ord(c) - ord('a') if node.children[idx] is None: return None node = node.children[idx] return node # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
Rust
use std::{cell::RefCell, collections::HashMap, rc::Rc}; struct TrieNode { pub val: Option<char>, pub flag: bool, pub child: HashMap<char, Rc<RefCell<TrieNode>>>, } impl TrieNode { fn new() -> Self { Self { val: None, flag: false, child: HashMap::new(), } } fn new_with_val(val: char) -> Self { Self { val: Some(val), flag: false, child: HashMap::new(), } } } struct Trie { root: Rc<RefCell<TrieNode>>, } /// Your Trie object will be instantiated and called as such: /// let obj = Trie::new(); /// obj.insert(word); /// let ret_2: bool = obj.search(word); /// let ret_3: bool = obj.starts_with(prefix); impl Trie { fn new() -> Self { Self { root: Rc::new(RefCell::new(TrieNode::new())), } } fn insert(&self, word: String) { let char_vec: Vec<char> = word.chars().collect(); // Get the clone of current root node let mut root = Rc::clone(&self.root); for c in &char_vec { if !root.borrow().child.contains_key(c) { // We need to manually create the entry root.borrow_mut() .child .insert(*c, Rc::new(RefCell::new(TrieNode::new()))); } // Get the child node let root_clone = Rc::clone(root.borrow().child.get(c).unwrap()); root = root_clone; } { root.borrow_mut().flag = true; } } fn search(&self, word: String) -> bool { let char_vec: Vec<char> = word.chars().collect(); // Get the clone of current root node let mut root = Rc::clone(&self.root); for c in &char_vec { if !root.borrow().child.contains_key(c) { return false; } // Get the child node let root_clone = Rc::clone(root.borrow().child.get(c).unwrap()); root = root_clone; } let flag = root.borrow().flag; flag } fn starts_with(&self, prefix: String) -> bool { let char_vec: Vec<char> = prefix.chars().collect(); // Get the clone of current root node let mut root = Rc::clone(&self.root); for c in &char_vec { if !root.borrow().child.contains_key(c) { return false; } // Get the child node let root_clone = Rc::clone(root.borrow().child.get(c).unwrap()); root = root_clone; } true } }
208
Implement Trie (Prefix Tree)
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p> <p>Implement the Trie class:</p> <ul> <li><code>Trie()</code> Initializes the trie object.</li> <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;] [[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]] <strong>Output</strong> [null, null, true, false, true, null, true] <strong>Explanation</strong> Trie trie = new Trie(); trie.insert(&quot;apple&quot;); trie.search(&quot;apple&quot;); // return True trie.search(&quot;app&quot;); // return False trie.startsWith(&quot;app&quot;); // return True trie.insert(&quot;app&quot;); trie.search(&quot;app&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li> <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> </ul>
Design; Trie; Hash Table; String
TypeScript
class TrieNode { children; isEnd; constructor() { this.children = new Array(26); this.isEnd = false; } } class Trie { root; constructor() { this.root = new TrieNode(); } insert(word: string): void { let head = this.root; for (let char of word) { let index = char.charCodeAt(0) - 97; if (!head.children[index]) { head.children[index] = new TrieNode(); } head = head.children[index]; } head.isEnd = true; } search(word: string): boolean { let head = this.searchPrefix(word); return head != null && head.isEnd; } startsWith(prefix: string): boolean { return this.searchPrefix(prefix) != null; } private searchPrefix(prefix: string) { let head = this.root; for (let char of prefix) { let index = char.charCodeAt(0) - 97; if (!head.children[index]) return null; head = head.children[index]; } return head; } }
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
C++
class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { int n = nums.size(); vector<long long> s(n + 1); for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } int ans = n + 1; for (int i = 0; i <= n; ++i) { int j = lower_bound(s.begin(), s.end(), s[i] + target) - s.begin(); if (j <= n) { ans = min(ans, j - i); } } return ans <= n ? ans : 0; } };
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
C#
public class Solution { public int MinSubArrayLen(int target, int[] nums) { int n = nums.Length; long s = 0; int ans = n + 1; for (int i = 0, j = 0; i < n; ++i) { s += nums[i]; while (s >= target) { ans = Math.Min(ans, i - j + 1); s -= nums[j++]; } } return ans == n + 1 ? 0 : ans; } }
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
Go
func minSubArrayLen(target int, nums []int) int { n := len(nums) s := make([]int, n+1) for i, x := range nums { s[i+1] = s[i] + x } ans := n + 1 for i, x := range s { j := sort.SearchInts(s, x+target) if j <= n { ans = min(ans, j-i) } } if ans == n+1 { return 0 } return ans }
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
Java
class Solution { public int minSubArrayLen(int target, int[] nums) { int n = nums.length; long[] s = new long[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } int ans = n + 1; for (int i = 0; i <= n; ++i) { int j = search(s, s[i] + target); if (j <= n) { ans = Math.min(ans, j - i); } } return ans <= n ? ans : 0; } private int search(long[] nums, long x) { int l = 0, r = nums.length; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; } }
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
Python
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: n = len(nums) s = list(accumulate(nums, initial=0)) ans = n + 1 for i, x in enumerate(s): j = bisect_left(s, x + target) if j <= n: ans = min(ans, j - i) return ans if ans <= n else 0
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
Rust
impl Solution { pub fn min_sub_array_len(target: i32, nums: Vec<i32>) -> i32 { let n = nums.len(); let mut res = n + 1; let mut sum = 0; let mut i = 0; for j in 0..n { sum += nums[j]; while sum >= target { res = res.min(j - i + 1); sum -= nums[i]; i += 1; } } if res == n + 1 { return 0; } res as i32 } }
209
Minimum Size Subarray Sum
Medium
<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword="subarray-nonempty"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> target = 4, nums = [1,4,4] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.
Array; Binary Search; Prefix Sum; Sliding Window
TypeScript
function minSubArrayLen(target: number, nums: number[]): number { const n = nums.length; const s: number[] = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } let ans = n + 1; const search = (x: number) => { let l = 0; let r = n + 1; while (l < r) { const mid = (l + r) >>> 1; if (s[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; for (let i = 0; i <= n; ++i) { const j = search(s[i] + target); if (j <= n) { ans = Math.min(ans, j - i); } } return ans === n + 1 ? 0 : ans; }
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
C++
class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> g(numCourses); vector<int> indeg(numCourses); for (auto& p : prerequisites) { int a = p[0], b = p[1]; g[b].push_back(a); ++indeg[a]; } queue<int> q; for (int i = 0; i < numCourses; ++i) { if (indeg[i] == 0) { q.push(i); } } vector<int> ans; while (!q.empty()) { int i = q.front(); q.pop(); ans.push_back(i); for (int j : g[i]) { if (--indeg[j] == 0) { q.push(j); } } } return ans.size() == numCourses ? ans : vector<int>(); } };
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
C#
public class Solution { public int[] FindOrder(int numCourses, int[][] prerequisites) { var g = new List<int>[numCourses]; for (int i = 0; i < numCourses; ++i) { g[i] = new List<int>(); } var indeg = new int[numCourses]; foreach (var p in prerequisites) { int a = p[0], b = p[1]; g[b].Add(a); ++indeg[a]; } var q = new Queue<int>(); for (int i = 0; i < numCourses; ++i) { if (indeg[i] == 0) { q.Enqueue(i); } } var ans = new int[numCourses]; var cnt = 0; while (q.Count > 0) { int i = q.Dequeue(); ans[cnt++] = i; foreach (int j in g[i]) { if (--indeg[j] == 0) { q.Enqueue(j); } } } return cnt == numCourses ? ans : new int[0]; } }
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Go
func findOrder(numCourses int, prerequisites [][]int) []int { g := make([][]int, numCourses) indeg := make([]int, numCourses) for _, p := range prerequisites { a, b := p[0], p[1] g[b] = append(g[b], a) indeg[a]++ } q := []int{} for i, x := range indeg { if x == 0 { q = append(q, i) } } ans := []int{} for len(q) > 0 { i := q[0] q = q[1:] ans = append(ans, i) for _, j := range g[i] { indeg[j]-- if indeg[j] == 0 { q = append(q, j) } } } if len(ans) == numCourses { return ans } return []int{} }
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Java
class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { List<Integer>[] g = new List[numCourses]; Arrays.setAll(g, k -> new ArrayList<>()); int[] indeg = new int[numCourses]; for (var p : prerequisites) { int a = p[0], b = p[1]; g[b].add(a); ++indeg[a]; } Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < numCourses; ++i) { if (indeg[i] == 0) { q.offer(i); } } int[] ans = new int[numCourses]; int cnt = 0; while (!q.isEmpty()) { int i = q.poll(); ans[cnt++] = i; for (int j : g[i]) { if (--indeg[j] == 0) { q.offer(j); } } } return cnt == numCourses ? ans : new int[0]; } }
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Python
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: g = defaultdict(list) indeg = [0] * numCourses for a, b in prerequisites: g[b].append(a) indeg[a] += 1 ans = [] q = deque(i for i, x in enumerate(indeg) if x == 0) while q: i = q.popleft() ans.append(i) for j in g[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return ans if len(ans) == numCourses else []
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
Rust
impl Solution { pub fn find_order(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> Vec<i32> { let n = num_courses as usize; let mut adjacency = vec![vec![]; n]; let mut entry = vec![0; n]; // init for iter in prerequisites.iter() { let (a, b) = (iter[0], iter[1]); adjacency[b as usize].push(a); entry[a as usize] += 1; } // construct deque & reslut let mut deque = std::collections::VecDeque::new(); for index in 0..n { if entry[index] == 0 { deque.push_back(index); } } let mut result = vec![]; // bfs while !deque.is_empty() { let head = deque.pop_front().unwrap(); result.push(head as i32); // update degree of entry for &out_entry in adjacency[head].iter() { entry[out_entry as usize] -= 1; if entry[out_entry as usize] == 0 { deque.push_back(out_entry as usize); } } } if result.len() == n { result } else { vec![] } } }
210
Course Schedule II
Medium
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p> <ul> <li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li> </ul> <p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] <strong>Output:</strong> [0,2,1,3] <strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numCourses = 1, prerequisites = [] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numCourses &lt;= 2000</code></li> <li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li> <li><code>prerequisites[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort
TypeScript
function findOrder(numCourses: number, prerequisites: number[][]): number[] { const g: number[][] = Array.from({ length: numCourses }, () => []); const indeg: number[] = new Array(numCourses).fill(0); for (const [a, b] of prerequisites) { g[b].push(a); indeg[a]++; } const q: number[] = []; for (let i = 0; i < numCourses; ++i) { if (indeg[i] === 0) { q.push(i); } } const ans: number[] = []; while (q.length) { const i = q.shift()!; ans.push(i); for (const j of g[i]) { if (--indeg[j] === 0) { q.push(j); } } } return ans.length === numCourses ? ans : []; }
211
Design Add and Search Words Data Structure
Medium
<p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p> <p>Implement the <code>WordDictionary</code> class:</p> <ul> <li><code>WordDictionary()</code>&nbsp;Initializes the object.</li> <li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li> <li><code>bool search(word)</code>&nbsp;Returns <code>true</code> if there is any string in the data structure that matches <code>word</code>&nbsp;or <code>false</code> otherwise. <code>word</code> may contain dots <code>&#39;.&#39;</code> where dots can be matched with any letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <pre> <strong>Input</strong> [&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;] [[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]] <strong>Output</strong> [null,null,null,null,false,true,true,true] <strong>Explanation</strong> WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(&quot;bad&quot;); wordDictionary.addWord(&quot;dad&quot;); wordDictionary.addWord(&quot;mad&quot;); wordDictionary.search(&quot;pad&quot;); // return False wordDictionary.search(&quot;bad&quot;); // return True wordDictionary.search(&quot;.ad&quot;); // return True wordDictionary.search(&quot;b..&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 25</code></li> <li><code>word</code> in <code>addWord</code> consists of lowercase English letters.</li> <li><code>word</code> in <code>search</code> consist of <code>&#39;.&#39;</code> or lowercase English letters.</li> <li>There will be at most <code>2</code> dots in <code>word</code> for <code>search</code> queries.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>addWord</code> and <code>search</code>.</li> </ul>
Depth-First Search; Design; Trie; String
C++
class trie { public: vector<trie*> children; bool is_end; trie() { children = vector<trie*>(26, nullptr); is_end = false; } void insert(const string& word) { trie* cur = this; for (char c : word) { c -= 'a'; if (cur->children[c] == nullptr) { cur->children[c] = new trie; } cur = cur->children[c]; } cur->is_end = true; } }; class WordDictionary { private: trie* root; public: WordDictionary() : root(new trie) {} void addWord(string word) { root->insert(word); } bool search(string word) { return dfs(word, 0, root); } private: bool dfs(const string& word, int i, trie* cur) { if (i == word.size()) { return cur->is_end; } char c = word[i]; if (c != '.') { trie* child = cur->children[c - 'a']; if (child != nullptr && dfs(word, i + 1, child)) { return true; } } else { for (trie* child : cur->children) { if (child != nullptr && dfs(word, i + 1, child)) { return true; } } } return false; } }; /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); */
211
Design Add and Search Words Data Structure
Medium
<p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p> <p>Implement the <code>WordDictionary</code> class:</p> <ul> <li><code>WordDictionary()</code>&nbsp;Initializes the object.</li> <li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li> <li><code>bool search(word)</code>&nbsp;Returns <code>true</code> if there is any string in the data structure that matches <code>word</code>&nbsp;or <code>false</code> otherwise. <code>word</code> may contain dots <code>&#39;.&#39;</code> where dots can be matched with any letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <pre> <strong>Input</strong> [&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;] [[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]] <strong>Output</strong> [null,null,null,null,false,true,true,true] <strong>Explanation</strong> WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(&quot;bad&quot;); wordDictionary.addWord(&quot;dad&quot;); wordDictionary.addWord(&quot;mad&quot;); wordDictionary.search(&quot;pad&quot;); // return False wordDictionary.search(&quot;bad&quot;); // return True wordDictionary.search(&quot;.ad&quot;); // return True wordDictionary.search(&quot;b..&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 25</code></li> <li><code>word</code> in <code>addWord</code> consists of lowercase English letters.</li> <li><code>word</code> in <code>search</code> consist of <code>&#39;.&#39;</code> or lowercase English letters.</li> <li>There will be at most <code>2</code> dots in <code>word</code> for <code>search</code> queries.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>addWord</code> and <code>search</code>.</li> </ul>
Depth-First Search; Design; Trie; String
C#
using System.Collections.Generic; using System.Linq; class TrieNode { public bool IsEnd { get; set; } public TrieNode[] Children { get; set; } public TrieNode() { Children = new TrieNode[26]; } } public class WordDictionary { private TrieNode root; public WordDictionary() { root = new TrieNode(); } public void AddWord(string word) { var node = root; for (var i = 0; i < word.Length; ++i) { TrieNode nextNode; var index = word[i] - 'a'; nextNode = node.Children[index]; if (nextNode == null) { nextNode = new TrieNode(); node.Children[index] = nextNode; } node = nextNode; } node.IsEnd = true; } public bool Search(string word) { var queue = new Queue<TrieNode>(); queue.Enqueue(root); for (var i = 0; i < word.Length; ++i) { var count = queue.Count; while (count-- > 0) { var node = queue.Dequeue(); if (word[i] == '.') { foreach (var nextNode in node.Children) { if (nextNode != null) { queue.Enqueue(nextNode); } } } else { var nextNode = node.Children[word[i] - 'a']; if (nextNode != null) { queue.Enqueue(nextNode); } } } } return queue.Any(n => n.IsEnd); } }
211
Design Add and Search Words Data Structure
Medium
<p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p> <p>Implement the <code>WordDictionary</code> class:</p> <ul> <li><code>WordDictionary()</code>&nbsp;Initializes the object.</li> <li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li> <li><code>bool search(word)</code>&nbsp;Returns <code>true</code> if there is any string in the data structure that matches <code>word</code>&nbsp;or <code>false</code> otherwise. <code>word</code> may contain dots <code>&#39;.&#39;</code> where dots can be matched with any letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <pre> <strong>Input</strong> [&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;] [[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]] <strong>Output</strong> [null,null,null,null,false,true,true,true] <strong>Explanation</strong> WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(&quot;bad&quot;); wordDictionary.addWord(&quot;dad&quot;); wordDictionary.addWord(&quot;mad&quot;); wordDictionary.search(&quot;pad&quot;); // return False wordDictionary.search(&quot;bad&quot;); // return True wordDictionary.search(&quot;.ad&quot;); // return True wordDictionary.search(&quot;b..&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 25</code></li> <li><code>word</code> in <code>addWord</code> consists of lowercase English letters.</li> <li><code>word</code> in <code>search</code> consist of <code>&#39;.&#39;</code> or lowercase English letters.</li> <li>There will be at most <code>2</code> dots in <code>word</code> for <code>search</code> queries.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>addWord</code> and <code>search</code>.</li> </ul>
Depth-First Search; Design; Trie; String
Go
type WordDictionary struct { root *trie } func Constructor() WordDictionary { return WordDictionary{new(trie)} } func (this *WordDictionary) AddWord(word string) { this.root.insert(word) } func (this *WordDictionary) Search(word string) bool { n := len(word) var dfs func(int, *trie) bool dfs = func(i int, cur *trie) bool { if i == n { return cur.isEnd } c := word[i] if c != '.' { child := cur.children[c-'a'] if child != nil && dfs(i+1, child) { return true } } else { for _, child := range cur.children { if child != nil && dfs(i+1, child) { return true } } } return false } return dfs(0, this.root) } type trie struct { children [26]*trie isEnd bool } func (t *trie) insert(word string) { cur := t for _, c := range word { c -= 'a' if cur.children[c] == nil { cur.children[c] = new(trie) } cur = cur.children[c] } cur.isEnd = true } /** * Your WordDictionary object will be instantiated and called as such: * obj := Constructor(); * obj.AddWord(word); * param_2 := obj.Search(word); */
211
Design Add and Search Words Data Structure
Medium
<p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p> <p>Implement the <code>WordDictionary</code> class:</p> <ul> <li><code>WordDictionary()</code>&nbsp;Initializes the object.</li> <li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li> <li><code>bool search(word)</code>&nbsp;Returns <code>true</code> if there is any string in the data structure that matches <code>word</code>&nbsp;or <code>false</code> otherwise. <code>word</code> may contain dots <code>&#39;.&#39;</code> where dots can be matched with any letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <pre> <strong>Input</strong> [&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;] [[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]] <strong>Output</strong> [null,null,null,null,false,true,true,true] <strong>Explanation</strong> WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(&quot;bad&quot;); wordDictionary.addWord(&quot;dad&quot;); wordDictionary.addWord(&quot;mad&quot;); wordDictionary.search(&quot;pad&quot;); // return False wordDictionary.search(&quot;bad&quot;); // return True wordDictionary.search(&quot;.ad&quot;); // return True wordDictionary.search(&quot;b..&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 25</code></li> <li><code>word</code> in <code>addWord</code> consists of lowercase English letters.</li> <li><code>word</code> in <code>search</code> consist of <code>&#39;.&#39;</code> or lowercase English letters.</li> <li>There will be at most <code>2</code> dots in <code>word</code> for <code>search</code> queries.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>addWord</code> and <code>search</code>.</li> </ul>
Depth-First Search; Design; Trie; String
Java
class Trie { Trie[] children = new Trie[26]; boolean isEnd; } class WordDictionary { private Trie trie; /** Initialize your data structure here. */ public WordDictionary() { trie = new Trie(); } public void addWord(String word) { Trie node = trie; for (char c : word.toCharArray()) { int idx = c - 'a'; if (node.children[idx] == null) { node.children[idx] = new Trie(); } node = node.children[idx]; } node.isEnd = true; } public boolean search(String word) { return search(word, trie); } private boolean search(String word, Trie node) { for (int i = 0; i < word.length(); ++i) { char c = word.charAt(i); int idx = c - 'a'; if (c != '.' && node.children[idx] == null) { return false; } if (c == '.') { for (Trie child : node.children) { if (child != null && search(word.substring(i + 1), child)) { return true; } } return false; } node = node.children[idx]; } return node.isEnd; } } /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */
211
Design Add and Search Words Data Structure
Medium
<p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p> <p>Implement the <code>WordDictionary</code> class:</p> <ul> <li><code>WordDictionary()</code>&nbsp;Initializes the object.</li> <li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li> <li><code>bool search(word)</code>&nbsp;Returns <code>true</code> if there is any string in the data structure that matches <code>word</code>&nbsp;or <code>false</code> otherwise. <code>word</code> may contain dots <code>&#39;.&#39;</code> where dots can be matched with any letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <pre> <strong>Input</strong> [&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;] [[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]] <strong>Output</strong> [null,null,null,null,false,true,true,true] <strong>Explanation</strong> WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(&quot;bad&quot;); wordDictionary.addWord(&quot;dad&quot;); wordDictionary.addWord(&quot;mad&quot;); wordDictionary.search(&quot;pad&quot;); // return False wordDictionary.search(&quot;bad&quot;); // return True wordDictionary.search(&quot;.ad&quot;); // return True wordDictionary.search(&quot;b..&quot;); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 25</code></li> <li><code>word</code> in <code>addWord</code> consists of lowercase English letters.</li> <li><code>word</code> in <code>search</code> consist of <code>&#39;.&#39;</code> or lowercase English letters.</li> <li>There will be at most <code>2</code> dots in <code>word</code> for <code>search</code> queries.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>addWord</code> and <code>search</code>.</li> </ul>
Depth-First Search; Design; Trie; String
Python
class Trie: def __init__(self): self.children = [None] * 26 self.is_end = False class WordDictionary: def __init__(self): self.trie = Trie() def addWord(self, word: str) -> None: node = self.trie for c in word: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.is_end = True def search(self, word: str) -> bool: def search(word, node): for i in range(len(word)): c = word[i] idx = ord(c) - ord('a') if c != '.' and node.children[idx] is None: return False if c == '.': for child in node.children: if child is not None and search(word[i + 1 :], child): return True return False node = node.children[idx] return node.is_end return search(word, self.trie) # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
212
Word Search II
Hard
<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p> <p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search1.jpg" style="width: 322px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;] <strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search2.jpg" style="width: 162px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 12</code></li> <li><code>board[i][j]</code> is a lowercase English letter.</li> <li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are unique.</li> </ul>
Trie; Array; String; Backtracking; Matrix
C++
class Trie { public: vector<Trie*> children; int ref; Trie() : children(26, nullptr) , ref(-1) {} void insert(const string& w, int ref) { Trie* node = this; for (char c : w) { c -= 'a'; if (!node->children[c]) { node->children[c] = new Trie(); } node = node->children[c]; } node->ref = ref; } }; class Solution { public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { Trie* tree = new Trie(); for (int i = 0; i < words.size(); ++i) { tree->insert(words[i], i); } vector<string> ans; int m = board.size(), n = board[0].size(); function<void(Trie*, int, int)> dfs = [&](Trie* node, int i, int j) { int idx = board[i][j] - 'a'; if (!node->children[idx]) { return; } node = node->children[idx]; if (node->ref != -1) { ans.emplace_back(words[node->ref]); node->ref = -1; } int dirs[5] = {-1, 0, 1, 0, -1}; char c = board[i][j]; board[i][j] = '#'; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#') { dfs(node, x, y); } } board[i][j] = c; }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { dfs(tree, i, j); } } return ans; } };
212
Word Search II
Hard
<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p> <p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search1.jpg" style="width: 322px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;] <strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search2.jpg" style="width: 162px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 12</code></li> <li><code>board[i][j]</code> is a lowercase English letter.</li> <li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are unique.</li> </ul>
Trie; Array; String; Backtracking; Matrix
Go
type Trie struct { children [26]*Trie ref int } func newTrie() *Trie { return &Trie{ref: -1} } func (this *Trie) insert(w string, ref int) { node := this for _, c := range w { c -= 'a' if node.children[c] == nil { node.children[c] = newTrie() } node = node.children[c] } node.ref = ref } func findWords(board [][]byte, words []string) (ans []string) { trie := newTrie() for i, w := range words { trie.insert(w, i) } m, n := len(board), len(board[0]) var dfs func(*Trie, int, int) dfs = func(node *Trie, i, j int) { idx := board[i][j] - 'a' if node.children[idx] == nil { return } node = node.children[idx] if node.ref != -1 { ans = append(ans, words[node.ref]) node.ref = -1 } c := board[i][j] board[i][j] = '#' dirs := [5]int{-1, 0, 1, 0, -1} for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#' { dfs(node, x, y) } } board[i][j] = c } for i := 0; i < m; i++ { for j := 0; j < n; j++ { dfs(trie, i, j) } } return }
212
Word Search II
Hard
<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p> <p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search1.jpg" style="width: 322px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;] <strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search2.jpg" style="width: 162px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 12</code></li> <li><code>board[i][j]</code> is a lowercase English letter.</li> <li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are unique.</li> </ul>
Trie; Array; String; Backtracking; Matrix
Java
class Trie { Trie[] children = new Trie[26]; int ref = -1; public void insert(String w, int ref) { Trie node = this; for (int i = 0; i < w.length(); ++i) { int j = w.charAt(i) - 'a'; if (node.children[j] == null) { node.children[j] = new Trie(); } node = node.children[j]; } node.ref = ref; } } class Solution { private char[][] board; private String[] words; private List<String> ans = new ArrayList<>(); public List<String> findWords(char[][] board, String[] words) { this.board = board; this.words = words; Trie tree = new Trie(); for (int i = 0; i < words.length; ++i) { tree.insert(words[i], i); } int m = board.length, n = board[0].length; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { dfs(tree, i, j); } } return ans; } private void dfs(Trie node, int i, int j) { int idx = board[i][j] - 'a'; if (node.children[idx] == null) { return; } node = node.children[idx]; if (node.ref != -1) { ans.add(words[node.ref]); node.ref = -1; } char c = board[i][j]; board[i][j] = '#'; int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] != '#') { dfs(node, x, y); } } board[i][j] = c; } }
212
Word Search II
Hard
<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p> <p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search1.jpg" style="width: 322px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;] <strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search2.jpg" style="width: 162px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 12</code></li> <li><code>board[i][j]</code> is a lowercase English letter.</li> <li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are unique.</li> </ul>
Trie; Array; String; Backtracking; Matrix
Python
class Trie: def __init__(self): self.children: List[Trie | None] = [None] * 26 self.ref: int = -1 def insert(self, w: str, ref: int): node = self for c in w: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.ref = ref class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: def dfs(node: Trie, i: int, j: int): idx = ord(board[i][j]) - ord('a') if node.children[idx] is None: return node = node.children[idx] if node.ref >= 0: ans.append(words[node.ref]) node.ref = -1 c = board[i][j] board[i][j] = '#' for a, b in pairwise((-1, 0, 1, 0, -1)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and board[x][y] != '#': dfs(node, x, y) board[i][j] = c tree = Trie() for i, w in enumerate(words): tree.insert(w, i) m, n = len(board), len(board[0]) ans = [] for i in range(m): for j in range(n): dfs(tree, i, j) return ans
212
Word Search II
Hard
<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p> <p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search1.jpg" style="width: 322px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;] <strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0212.Word%20Search%20II/images/search2.jpg" style="width: 162px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 12</code></li> <li><code>board[i][j]</code> is a lowercase English letter.</li> <li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are unique.</li> </ul>
Trie; Array; String; Backtracking; Matrix
TypeScript
class Trie { children: Trie[]; ref: number; constructor() { this.children = new Array(26); this.ref = -1; } insert(w: string, ref: number): void { let node: Trie = this; for (let i = 0; i < w.length; i++) { const c = w.charCodeAt(i) - 97; if (node.children[c] == null) { node.children[c] = new Trie(); } node = node.children[c]; } node.ref = ref; } } function findWords(board: string[][], words: string[]): string[] { const tree = new Trie(); for (let i = 0; i < words.length; ++i) { tree.insert(words[i], i); } const m = board.length; const n = board[0].length; const ans: string[] = []; const dirs: number[] = [-1, 0, 1, 0, -1]; const dfs = (node: Trie, i: number, j: number) => { const idx = board[i][j].charCodeAt(0) - 97; if (node.children[idx] == null) { return; } node = node.children[idx]; if (node.ref != -1) { ans.push(words[node.ref]); node.ref = -1; } const c = board[i][j]; board[i][j] = '#'; for (let k = 0; k < 4; ++k) { const x = i + dirs[k]; const y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#') { dfs(node, x, y); } } board[i][j] = c; }; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { dfs(tree, i, j); } } return ans; }
213
House Robber II
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (n == 1) { return nums[0]; } return max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1)); } int robRange(vector<int>& nums, int l, int r) { int f = 0, g = 0; for (; l <= r; ++l) { int ff = max(f, g); g = f + nums[l]; f = ff; } return max(f, g); } };
213
House Robber II
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Go
func rob(nums []int) int { n := len(nums) if n == 1 { return nums[0] } return max(robRange(nums, 0, n-2), robRange(nums, 1, n-1)) } func robRange(nums []int, l, r int) int { f, g := 0, 0 for _, x := range nums[l : r+1] { f, g = max(f, g), f+x } return max(f, g) }
213
House Robber II
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int rob(int[] nums) { int n = nums.length; if (n == 1) { return nums[0]; } return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); } private int rob(int[] nums, int l, int r) { int f = 0, g = 0; for (; l <= r; ++l) { int ff = Math.max(f, g); g = f + nums[l]; f = ff; } return Math.max(f, g); } }
213
House Robber II
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def rob(self, nums: List[int]) -> int: def _rob(nums): f = g = 0 for x in nums: f, g = max(f, g), f + x return max(f, g) if len(nums) == 1: return nums[0] return max(_rob(nums[1:]), _rob(nums[:-1]))
213
House Robber II
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn rob(nums: Vec<i32>) -> i32 { let n = nums.len(); if n == 1 { return nums[0]; } let rob_range = |l, r| { let mut f = [0, 0]; for i in l..r { f = [f[0].max(f[1]), f[0] + nums[i]]; } f[0].max(f[1]) }; rob_range(0, n - 1).max(rob_range(1, n)) } }
213
House Robber II
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
TypeScript
function rob(nums: number[]): number { const n = nums.length; if (n === 1) { return nums[0]; } const robRange = (l: number, r: number): number => { let [f, g] = [0, 0]; for (; l <= r; ++l) { [f, g] = [Math.max(f, g), f + nums[l]]; } return Math.max(f, g); }; return Math.max(robRange(0, n - 2), robRange(1, n - 1)); }
214
Shortest Palindrome
Hard
<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p> <p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aacecaaa" <strong>Output:</strong> "aaacecaaa" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd" <strong>Output:</strong> "dcbabcd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
C++
typedef unsigned long long ull; class Solution { public: string shortestPalindrome(string s) { int base = 131; ull mul = 1; ull prefix = 0; ull suffix = 0; int idx = 0, n = s.size(); for (int i = 0; i < n; ++i) { int t = s[i] - 'a' + 1; prefix = prefix * base + t; suffix = suffix + mul * t; mul *= base; if (prefix == suffix) idx = i + 1; } if (idx == n) return s; string x = s.substr(idx, n - idx); reverse(x.begin(), x.end()); return x + s; } };
214
Shortest Palindrome
Hard
<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p> <p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aacecaaa" <strong>Output:</strong> "aaacecaaa" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd" <strong>Output:</strong> "dcbabcd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
C#
public class Solution { public string ShortestPalindrome(string s) { int baseValue = 131; int mul = 1; int mod = (int)1e9 + 7; int prefix = 0, suffix = 0; int idx = 0; int n = s.Length; for (int i = 0; i < n; ++i) { int t = s[i] - 'a' + 1; prefix = (int)(((long)prefix * baseValue + t) % mod); suffix = (int)((suffix + (long)t * mul) % mod); mul = (int)(((long)mul * baseValue) % mod); if (prefix == suffix) { idx = i + 1; } } if (idx == n) { return s; } return new string(s.Substring(idx).Reverse().ToArray()) + s; } }
214
Shortest Palindrome
Hard
<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p> <p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aacecaaa" <strong>Output:</strong> "aaacecaaa" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd" <strong>Output:</strong> "dcbabcd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Go
func shortestPalindrome(s string) string { n := len(s) base, mod := 131, int(1e9)+7 prefix, suffix, mul := 0, 0, 1 idx := 0 for i, c := range s { t := int(c-'a') + 1 prefix = (prefix*base + t) % mod suffix = (suffix + t*mul) % mod mul = (mul * base) % mod if prefix == suffix { idx = i + 1 } } if idx == n { return s } x := []byte(s[idx:]) for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 { x[i], x[j] = x[j], x[i] } return string(x) + s }
214
Shortest Palindrome
Hard
<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p> <p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aacecaaa" <strong>Output:</strong> "aaacecaaa" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd" <strong>Output:</strong> "dcbabcd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Java
class Solution { public String shortestPalindrome(String s) { int base = 131; int mul = 1; int mod = (int) 1e9 + 7; int prefix = 0, suffix = 0; int idx = 0; int n = s.length(); for (int i = 0; i < n; ++i) { int t = s.charAt(i) - 'a' + 1; prefix = (int) (((long) prefix * base + t) % mod); suffix = (int) ((suffix + (long) t * mul) % mod); mul = (int) (((long) mul * base) % mod); if (prefix == suffix) { idx = i + 1; } } if (idx == n) { return s; } return new StringBuilder(s.substring(idx)).reverse().toString() + s; } }
214
Shortest Palindrome
Hard
<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p> <p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aacecaaa" <strong>Output:</strong> "aaacecaaa" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd" <strong>Output:</strong> "dcbabcd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Python
class Solution: def shortestPalindrome(self, s: str) -> str: base = 131 mod = 10**9 + 7 n = len(s) prefix = suffix = 0 mul = 1 idx = 0 for i, c in enumerate(s): prefix = (prefix * base + (ord(c) - ord('a') + 1)) % mod suffix = (suffix + (ord(c) - ord('a') + 1) * mul) % mod mul = (mul * base) % mod if prefix == suffix: idx = i + 1 return s if idx == n else s[idx:][::-1] + s
214
Shortest Palindrome
Hard
<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p> <p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aacecaaa" <strong>Output:</strong> "aaacecaaa" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd" <strong>Output:</strong> "dcbabcd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Rust
impl Solution { pub fn shortest_palindrome(s: String) -> String { let base = 131; let (mut idx, mut prefix, mut suffix, mut mul) = (0, 0, 0, 1); for (i, c) in s.chars().enumerate() { let t = (c as u64) - ('0' as u64) + 1; prefix = prefix * base + t; suffix = suffix + t * mul; mul *= base; if prefix == suffix { idx = i + 1; } } if idx == s.len() { s } else { let x: String = (&s[idx..]).chars().rev().collect(); String::from(x + &s) } } }
215
Kth Largest Element in an Array
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p> <p>Can you solve it without sorting?</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2 <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4 <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &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>
Array; Divide and Conquer; Quickselect; Sorting; Heap (Priority Queue)
C++
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int n = nums.size(); k = n - k; auto quickSort = [&](auto&& quickSort, int l, int r) -> int { if (l == r) { return nums[l]; } int i = l - 1, j = r + 1; int x = nums[(l + r) >> 1]; while (i < j) { while (nums[++i] < x) { } while (nums[--j] > x) { } if (i < j) { swap(nums[i], nums[j]); } } if (j < k) { return quickSort(quickSort, j + 1, r); } return quickSort(quickSort, l, j); }; return quickSort(quickSort, 0, n - 1); } };
215
Kth Largest Element in an Array
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p> <p>Can you solve it without sorting?</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2 <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4 <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &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>
Array; Divide and Conquer; Quickselect; Sorting; Heap (Priority Queue)
Go
func findKthLargest(nums []int, k int) int { k = len(nums) - k var quickSort func(l, r int) int quickSort = func(l, r int) int { if l == r { return nums[l] } i, j := l-1, r+1 x := nums[(l+r)>>1] for i < j { for { i++ if nums[i] >= x { break } } for { j-- if nums[j] <= x { break } } if i < j { nums[i], nums[j] = nums[j], nums[i] } } if j < k { return quickSort(j+1, r) } return quickSort(l, j) } return quickSort(0, len(nums)-1) }
215
Kth Largest Element in an Array
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p> <p>Can you solve it without sorting?</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2 <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4 <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &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>
Array; Divide and Conquer; Quickselect; Sorting; Heap (Priority Queue)
Java
class Solution { private int[] nums; private int k; public int findKthLargest(int[] nums, int k) { this.nums = nums; this.k = nums.length - k; return quickSort(0, nums.length - 1); } private int quickSort(int l, int r) { if (l == r) { return nums[l]; } int i = l - 1, j = r + 1; int x = nums[(l + r) >>> 1]; while (i < j) { while (nums[++i] < x) { } while (nums[--j] > x) { } if (i < j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } if (j < k) { return quickSort(j + 1, r); } return quickSort(l, j); } }
215
Kth Largest Element in an Array
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p> <p>Can you solve it without sorting?</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2 <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4 <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &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>
Array; Divide and Conquer; Quickselect; Sorting; Heap (Priority Queue)
Python
class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: def quick_sort(l: int, r: int) -> int: if l == r: return nums[l] i, j = l - 1, r + 1 x = nums[(l + r) >> 1] while i < j: while 1: i += 1 if nums[i] >= x: break while 1: j -= 1 if nums[j] <= x: break if i < j: nums[i], nums[j] = nums[j], nums[i] if j < k: return quick_sort(j + 1, r) return quick_sort(l, j) n = len(nums) k = n - k return quick_sort(0, n - 1)
215
Kth Largest Element in an Array
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p> <p>Can you solve it without sorting?</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2 <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4 <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &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>
Array; Divide and Conquer; Quickselect; Sorting; Heap (Priority Queue)
Rust
impl Solution { pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { let len = nums.len(); let k = len - k as usize; Self::quick_sort(&mut nums, 0, len - 1, k) } fn quick_sort(nums: &mut Vec<i32>, l: usize, r: usize, k: usize) -> i32 { if l == r { return nums[l]; } let (mut i, mut j) = (l as isize - 1, r as isize + 1); let x = nums[(l + r) / 2]; while i < j { i += 1; while nums[i as usize] < x { i += 1; } j -= 1; while nums[j as usize] > x { j -= 1; } if i < j { nums.swap(i as usize, j as usize); } } let j = j as usize; if j < k { Self::quick_sort(nums, j + 1, r, k) } else { Self::quick_sort(nums, l, j, k) } } }
215
Kth Largest Element in an Array
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p> <p>Can you solve it without sorting?</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2 <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4 <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &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>
Array; Divide and Conquer; Quickselect; Sorting; Heap (Priority Queue)
TypeScript
function findKthLargest(nums: number[], k: number): number { const n = nums.length; k = n - k; const quickSort = (l: number, r: number): number => { if (l === r) { return nums[l]; } let [i, j] = [l - 1, r + 1]; const x = nums[(l + r) >> 1]; while (i < j) { while (nums[++i] < x); while (nums[--j] > x); if (i < j) { [nums[i], nums[j]] = [nums[j], nums[i]]; } } if (j < k) { return quickSort(j + 1, r); } return quickSort(l, j); }; return quickSort(0, n - 1); }
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
C++
class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> ans; vector<int> t; function<void(int, int)> dfs = [&](int i, int s) { if (s == 0) { if (t.size() == k) { ans.emplace_back(t); } return; } if (i > 9 || i > s || t.size() >= k) { return; } t.emplace_back(i); dfs(i + 1, s - i); t.pop_back(); dfs(i + 1, s); }; dfs(1, n); return ans; } };
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
C#
public class Solution { private List<IList<int>> ans = new List<IList<int>>(); private List<int> t = new List<int>(); private int k; public IList<IList<int>> CombinationSum3(int k, int n) { this.k = k; dfs(1, n); return ans; } private void dfs(int i, int s) { if (s == 0) { if (t.Count == k) { ans.Add(new List<int>(t)); } return; } if (i > 9 || i > s || t.Count >= k) { return; } t.Add(i); dfs(i + 1, s - i); t.RemoveAt(t.Count - 1); dfs(i + 1, s); } }
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
Go
func combinationSum3(k int, n int) (ans [][]int) { t := []int{} var dfs func(i, s int) dfs = func(i, s int) { if s == 0 { if len(t) == k { ans = append(ans, slices.Clone(t)) } return } if i > 9 || i > s || len(t) >= k { return } t = append(t, i) dfs(i+1, s-i) t = t[:len(t)-1] dfs(i+1, s) } dfs(1, n) return }
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
Java
class Solution { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); private int k; public List<List<Integer>> combinationSum3(int k, int n) { this.k = k; dfs(1, n); return ans; } private void dfs(int i, int s) { if (s == 0) { if (t.size() == k) { ans.add(new ArrayList<>(t)); } return; } if (i > 9 || i > s || t.size() >= k) { return; } t.add(i); dfs(i + 1, s - i); t.remove(t.size() - 1); dfs(i + 1, s); } }
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
JavaScript
function combinationSum3(k, n) { const ans = []; const t = []; const dfs = (i, s) => { if (s === 0) { if (t.length === k) { ans.push(t.slice()); } return; } if (i > 9 || i > s || t.length >= k) { return; } t.push(i); dfs(i + 1, s - i); t.pop(); dfs(i + 1, s); }; dfs(1, n); return ans; }
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
Python
class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: def dfs(i: int, s: int): if s == 0: if len(t) == k: ans.append(t[:]) return if i > 9 or i > s or len(t) >= k: return t.append(i) dfs(i + 1, s - i) t.pop() dfs(i + 1, s) ans = [] t = [] dfs(1, n) return ans