id
int64 1
3.65k
| 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
|
---|---|---|---|---|---|---|
127 |
Word Ladder
|
Hard
|
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -> s<sub>1</sub> -> s<sub>2</sub> -> ... -> s<sub>k</sub></code> such that:</p>
<ul>
<li>Every adjacent pair of words differs by a single letter.</li>
<li>Every <code>s<sub>i</sub></code> for <code>1 <= i <= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>
<li><code>s<sub>k</sub> == endWord</code></li>
</ul>
<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
<strong>Output:</strong> 5
<strong>Explanation:</strong> One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= beginWord.length <= 10</code></li>
<li><code>endWord.length == beginWord.length</code></li>
<li><code>1 <= wordList.length <= 5000</code></li>
<li><code>wordList[i].length == beginWord.length</code></li>
<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>
<li><code>beginWord != endWord</code></li>
<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>
</ul>
|
Breadth-First Search; Hash Table; String
|
Java
|
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> words = new HashSet<>(wordList);
Queue<String> q = new ArrayDeque<>();
q.offer(beginWord);
int ans = 1;
while (!q.isEmpty()) {
++ans;
for (int i = q.size(); i > 0; --i) {
String s = q.poll();
char[] chars = s.toCharArray();
for (int j = 0; j < chars.length; ++j) {
char ch = chars[j];
for (char k = 'a'; k <= 'z'; ++k) {
chars[j] = k;
String t = new String(chars);
if (!words.contains(t)) {
continue;
}
if (endWord.equals(t)) {
return ans;
}
q.offer(t);
words.remove(t);
}
chars[j] = ch;
}
}
}
return 0;
}
}
|
127 |
Word Ladder
|
Hard
|
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -> s<sub>1</sub> -> s<sub>2</sub> -> ... -> s<sub>k</sub></code> such that:</p>
<ul>
<li>Every adjacent pair of words differs by a single letter.</li>
<li>Every <code>s<sub>i</sub></code> for <code>1 <= i <= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>
<li><code>s<sub>k</sub> == endWord</code></li>
</ul>
<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
<strong>Output:</strong> 5
<strong>Explanation:</strong> One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= beginWord.length <= 10</code></li>
<li><code>endWord.length == beginWord.length</code></li>
<li><code>1 <= wordList.length <= 5000</code></li>
<li><code>wordList[i].length == beginWord.length</code></li>
<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>
<li><code>beginWord != endWord</code></li>
<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>
</ul>
|
Breadth-First Search; Hash Table; String
|
Python
|
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
words = set(wordList)
q = deque([beginWord])
ans = 1
while q:
ans += 1
for _ in range(len(q)):
s = q.popleft()
s = list(s)
for i in range(len(s)):
ch = s[i]
for j in range(26):
s[i] = chr(ord('a') + j)
t = ''.join(s)
if t not in words:
continue
if t == endWord:
return ans
q.append(t)
words.remove(t)
s[i] = ch
return 0
|
127 |
Word Ladder
|
Hard
|
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -> s<sub>1</sub> -> s<sub>2</sub> -> ... -> s<sub>k</sub></code> such that:</p>
<ul>
<li>Every adjacent pair of words differs by a single letter.</li>
<li>Every <code>s<sub>i</sub></code> for <code>1 <= i <= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>
<li><code>s<sub>k</sub> == endWord</code></li>
</ul>
<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
<strong>Output:</strong> 5
<strong>Explanation:</strong> One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= beginWord.length <= 10</code></li>
<li><code>endWord.length == beginWord.length</code></li>
<li><code>1 <= wordList.length <= 5000</code></li>
<li><code>wordList[i].length == beginWord.length</code></li>
<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>
<li><code>beginWord != endWord</code></li>
<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>
</ul>
|
Breadth-First Search; Hash Table; String
|
TypeScript
|
function ladderLength(beginWord: string, endWord: string, wordList: string[]): number {
if (!wordList.includes(endWord)) return 0;
const replace = (s: string, i: number, ch: string) => s.slice(0, i) + ch + s.slice(i + 1);
const { length } = beginWord;
const words: Record<string, string[]> = {};
const g: Record<string, string[]> = {};
for (const w of [beginWord, ...wordList]) {
const derivatives: string[] = [];
for (let i = 0; i < length; i++) {
const nextW = replace(w, i, '*');
derivatives.push(nextW);
g[nextW] ??= [];
g[nextW].push(w);
}
words[w] = derivatives;
}
let ans = 0;
let q = words[beginWord];
const vis = new Set<string>([beginWord]);
while (q.length) {
const nextQ: string[] = [];
ans++;
for (const variant of q) {
for (const w of g[variant]) {
if (w === endWord) return ans + 1;
if (vis.has(w)) continue;
vis.add(w);
nextQ.push(...words[w]);
}
}
q = nextQ;
}
return 0;
}
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
C++
|
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int ans = 0;
unordered_map<int, int> d;
for (int x : nums) {
int y = x;
while (s.contains(y)) {
s.erase(y++);
}
d[x] = (d.contains(y) ? d[y] : 0) + y - x;
ans = max(ans, d[x]);
}
return ans;
}
};
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
Go
|
func longestConsecutive(nums []int) (ans int) {
s := map[int]bool{}
for _, x := range nums {
s[x] = true
}
d := map[int]int{}
for _, x := range nums {
y := x
for s[y] {
delete(s, y)
y++
}
d[x] = d[y] + y - x
ans = max(ans, d[x])
}
return
}
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
Java
|
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int x : nums) {
s.add(x);
}
int ans = 0;
Map<Integer, Integer> d = new HashMap<>();
for (int x : nums) {
int y = x;
while (s.contains(y)) {
s.remove(y++);
}
d.put(x, d.getOrDefault(y, 0) + y - x);
ans = Math.max(ans, d.get(x));
}
return ans;
}
}
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
JavaScript
|
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function (nums) {
const s = new Set(nums);
let ans = 0;
const d = new Map();
for (const x of nums) {
let y = x;
while (s.has(y)) {
s.delete(y++);
}
d.set(x, (d.get(y) || 0) + (y - x));
ans = Math.max(ans, d.get(x));
}
return ans;
};
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
Python
|
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
ans = 0
d = defaultdict(int)
for x in nums:
y = x
while y in s:
s.remove(y)
y += 1
d[x] = d[y] + y - x
ans = max(ans, d[x])
return ans
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
Rust
|
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let mut s: HashSet<i32> = nums.iter().cloned().collect();
let mut ans = 0;
let mut d: HashMap<i32, i32> = HashMap::new();
for &x in &nums {
let mut y = x;
while s.contains(&y) {
s.remove(&y);
y += 1;
}
let length = d.get(&(y)).unwrap_or(&0) + y - x;
d.insert(x, length);
ans = ans.max(length);
}
ans
}
}
|
128 |
Longest Consecutive Sequence
|
Medium
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
<p>You must write an algorithm that runs in <code>O(n)</code> time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Union Find; Array; Hash Table
|
TypeScript
|
function longestConsecutive(nums: number[]): number {
const s = new Set(nums);
let ans = 0;
const d = new Map<number, number>();
for (const x of nums) {
let y = x;
while (s.has(y)) {
s.delete(y++);
}
d.set(x, (d.get(y) || 0) + (y - x));
ans = Math.max(ans, d.get(x)!);
}
return ans;
}
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
C
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int dfs(struct TreeNode* root, int num) {
if (!root) {
return 0;
}
num = num * 10 + root->val;
if (!root->left && !root->right) {
return num;
}
return dfs(root->left, num) + dfs(root->right, num);
}
int sumNumbers(struct TreeNode* root) {
return dfs(root, 0);
}
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
function<int(TreeNode*, int)> dfs = [&](TreeNode* root, int s) -> int {
if (!root) return 0;
s = s * 10 + root->val;
if (!root->left && !root->right) return s;
return dfs(root->left, s) + dfs(root->right, s);
};
return dfs(root, 0);
}
};
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
var dfs func(*TreeNode, int) int
dfs = func(root *TreeNode, s int) int {
if root == nil {
return 0
}
s = s*10 + root.Val
if root.Left == nil && root.Right == nil {
return s
}
return dfs(root.Left, s) + dfs(root.Right, s)
}
return dfs(root, 0)
}
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
private int dfs(TreeNode root, int s) {
if (root == null) {
return 0;
}
s = s * 10 + root.val;
if (root.left == null && root.right == null) {
return s;
}
return dfs(root.left, s) + dfs(root.right, s);
}
}
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
JavaScript
|
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function (root) {
function dfs(root, s) {
if (!root) return 0;
s = s * 10 + root.val;
if (!root.left && !root.right) return s;
return dfs(root.left, s) + dfs(root.right, s);
}
return dfs(root, 0);
};
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
def dfs(root, s):
if root is None:
return 0
s = s * 10 + root.val
if root.left is None and root.right is None:
return s
return dfs(root.left, s) + dfs(root.right, s)
return dfs(root, 0)
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Rust
|
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, mut num: i32) -> i32 {
if node.is_none() {
return 0;
}
let node = node.as_ref().unwrap().borrow();
num = num * 10 + node.val;
if node.left.is_none() && node.right.is_none() {
return num;
}
Self::dfs(&node.left, num) + Self::dfs(&node.right, num)
}
pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
Self::dfs(&root, 0)
}
}
|
129 |
Sum Root to Leaf Numbers
|
Medium
|
<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>
<p>Each root-to-leaf path in the tree represents a number.</p>
<ul>
<li>For example, the root-to-leaf path <code>1 -> 2 -> 3</code> represents the number <code>123</code>.</li>
</ul>
<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p>A <strong>leaf</strong> node is a node with no children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/images/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [4,9,0,5,1]
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
<li><code>0 <= Node.val <= 9</code></li>
<li>The depth of the tree will not exceed <code>10</code>.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
TypeScript
|
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function sumNumbers(root: TreeNode | null): number {
function dfs(root: TreeNode | null, s: number): number {
if (!root) return 0;
s = s * 10 + root.val;
if (!root.left && !root.right) return s;
return dfs(root.left, s) + dfs(root.right, s);
}
return dfs(root, 0);
}
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
C++
|
class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size(), n = board[0].size();
int dirs[5] = {-1, 0, 1, 0, -1};
function<void(int, int)> dfs = [&](int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') {
return;
}
board[i][j] = '.';
for (int k = 0; k < 4; ++k) {
dfs(i + dirs[k], j + dirs[k + 1]);
}
};
for (int i = 0; i < m; ++i) {
dfs(i, 0);
dfs(i, n - 1);
}
for (int j = 1; j < n - 1; ++j) {
dfs(0, j);
dfs(m - 1, j);
}
for (auto& row : board) {
for (auto& c : row) {
if (c == '.') {
c = 'O';
} else if (c == 'O') {
c = 'X';
}
}
}
}
};
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
C#
|
public class Solution {
private readonly int[] dirs = {-1, 0, 1, 0, -1};
private char[][] board;
private int m;
private int n;
public void Solve(char[][] board) {
m = board.Length;
n = board[0].Length;
this.board = board;
for (int i = 0; i < m; ++i) {
Dfs(i, 0);
Dfs(i, n - 1);
}
for (int j = 0; j < n; ++j) {
Dfs(0, j);
Dfs(m - 1, j);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == '.') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void Dfs(int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') {
return;
}
board[i][j] = '.';
for (int k = 0; k < 4; ++k) {
Dfs(i + dirs[k], j + dirs[k + 1]);
}
}
}
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Go
|
func solve(board [][]byte) {
m, n := len(board), len(board[0])
dirs := [5]int{-1, 0, 1, 0, -1}
var dfs func(i, j int)
dfs = func(i, j int) {
if i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O' {
return
}
board[i][j] = '.'
for k := 0; k < 4; k++ {
dfs(i+dirs[k], j+dirs[k+1])
}
}
for i := 0; i < m; i++ {
dfs(i, 0)
dfs(i, n-1)
}
for j := 0; j < n; j++ {
dfs(0, j)
dfs(m-1, j)
}
for i, row := range board {
for j, c := range row {
if c == '.' {
board[i][j] = 'O'
} else if c == 'O' {
board[i][j] = 'X'
}
}
}
}
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Java
|
class Solution {
private final int[] dirs = {-1, 0, 1, 0, -1};
private char[][] board;
private int m;
private int n;
public void solve(char[][] board) {
m = board.length;
n = board[0].length;
this.board = board;
for (int i = 0; i < m; ++i) {
dfs(i, 0);
dfs(i, n - 1);
}
for (int j = 0; j < n; ++j) {
dfs(0, j);
dfs(m - 1, j);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == '.') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void dfs(int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') {
return;
}
board[i][j] = '.';
for (int k = 0; k < 4; ++k) {
dfs(i + dirs[k], j + dirs[k + 1]);
}
}
}
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Python
|
class Solution:
def solve(self, board: List[List[str]]) -> None:
def dfs(i: int, j: int):
if not (0 <= i < m and 0 <= j < n and board[i][j] == "O"):
return
board[i][j] = "."
for a, b in pairwise((-1, 0, 1, 0, -1)):
dfs(i + a, j + b)
m, n = len(board), len(board[0])
for i in range(m):
dfs(i, 0)
dfs(i, n - 1)
for j in range(n):
dfs(0, j)
dfs(m - 1, j)
for i in range(m):
for j in range(n):
if board[i][j] == ".":
board[i][j] = "O"
elif board[i][j] == "O":
board[i][j] = "X"
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Rust
|
impl Solution {
pub fn solve(board: &mut Vec<Vec<char>>) {
let m = board.len();
let n = board[0].len();
let dirs = vec![-1, 0, 1, 0, -1];
fn dfs(
board: &mut Vec<Vec<char>>,
i: usize,
j: usize,
dirs: &Vec<i32>,
m: usize,
n: usize,
) {
if i >= 0 && i < m && j >= 0 && j < n && board[i][j] == 'O' {
board[i][j] = '.';
for k in 0..4 {
dfs(
board,
((i as i32) + dirs[k]) as usize,
((j as i32) + dirs[k + 1]) as usize,
dirs,
m,
n,
);
}
}
}
for i in 0..m {
dfs(board, i, 0, &dirs, m, n);
dfs(board, i, n - 1, &dirs, m, n);
}
for j in 0..n {
dfs(board, 0, j, &dirs, m, n);
dfs(board, m - 1, j, &dirs, m, n);
}
for i in 0..m {
for j in 0..n {
if board[i][j] == '.' {
board[i][j] = 'O';
} else if board[i][j] == 'O' {
board[i][j] = 'X';
}
}
}
}
}
|
130 |
Surrounded Regions
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>'X'</code> and <code>'O'</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>
<ul>
<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>
<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>'O'</code> cell.</li>
<li><strong>Surround</strong>: The region is surrounded with <code>'X'</code> cells if you can <strong>connect the region </strong>with <code>'X'</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>
</ul>
<p>To capture a <strong>surrounded region</strong>, replace all <code>'O'</code>s with <code>'X'</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0130.Surrounded%20Regions/images/xogrid.jpg" style="width: 367px; height: 158px;" />
<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [["X"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[["X"]]</span></p>
</div>
<p> </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 <= m, n <= 200</code></li>
<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
TypeScript
|
function solve(board: string[][]): void {
const m = board.length;
const n = board[0].length;
const dirs: number[] = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number): void => {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] !== 'O') {
return;
}
board[i][j] = '.';
for (let k = 0; k < 4; ++k) {
dfs(i + dirs[k], j + dirs[k + 1]);
}
};
for (let i = 0; i < m; ++i) {
dfs(i, 0);
dfs(i, n - 1);
}
for (let j = 0; j < n; ++j) {
dfs(0, j);
dfs(m - 1, j);
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (board[i][j] === '.') {
board[i][j] = 'O';
} else if (board[i][j] === 'O') {
board[i][j] = 'X';
}
}
}
}
|
131 |
Palindrome Partitioning
|
Medium
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming; Backtracking
|
C++
|
class Solution {
public:
vector<vector<string>> partition(string s) {
int n = s.size();
bool f[n][n];
memset(f, true, sizeof(f));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
f[i][j] = s[i] == s[j] && f[i + 1][j - 1];
}
}
vector<vector<string>> ans;
vector<string> t;
auto dfs = [&](this auto&& dfs, int i) -> void {
if (i == n) {
ans.emplace_back(t);
return;
}
for (int j = i; j < n; ++j) {
if (f[i][j]) {
t.emplace_back(s.substr(i, j - i + 1));
dfs(j + 1);
t.pop_back();
}
}
};
dfs(0);
return ans;
}
};
|
131 |
Palindrome Partitioning
|
Medium
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming; Backtracking
|
C#
|
public class Solution {
private int n;
private string s;
private bool[,] f;
private IList<IList<string>> ans = new List<IList<string>>();
private IList<string> t = new List<string>();
public IList<IList<string>> Partition(string s) {
n = s.Length;
this.s = s;
f = new bool[n, n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
f[i, j] = true;
}
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
f[i, j] = s[i] == s[j] && f[i + 1, j - 1];
}
}
dfs(0);
return ans;
}
private void dfs(int i) {
if (i == n) {
ans.Add(new List<string>(t));
return;
}
for (int j = i; j < n; ++j) {
if (f[i, j]) {
t.Add(s.Substring(i, j + 1 - i));
dfs(j + 1);
t.RemoveAt(t.Count - 1);
}
}
}
}
|
131 |
Palindrome Partitioning
|
Medium
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming; Backtracking
|
Go
|
func partition(s string) (ans [][]string) {
n := len(s)
f := make([][]bool, n)
for i := range f {
f[i] = make([]bool, n)
for j := range f[i] {
f[i][j] = true
}
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
f[i][j] = s[i] == s[j] && f[i+1][j-1]
}
}
t := []string{}
var dfs func(int)
dfs = func(i int) {
if i == n {
ans = append(ans, append([]string(nil), t...))
return
}
for j := i; j < n; j++ {
if f[i][j] {
t = append(t, s[i:j+1])
dfs(j + 1)
t = t[:len(t)-1]
}
}
}
dfs(0)
return
}
|
131 |
Palindrome Partitioning
|
Medium
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming; Backtracking
|
Java
|
class Solution {
private int n;
private String s;
private boolean[][] f;
private List<String> t = new ArrayList<>();
private List<List<String>> ans = new ArrayList<>();
public List<List<String>> partition(String s) {
n = s.length();
f = new boolean[n][n];
for (int i = 0; i < n; ++i) {
Arrays.fill(f[i], true);
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
f[i][j] = s.charAt(i) == s.charAt(j) && f[i + 1][j - 1];
}
}
this.s = s;
dfs(0);
return ans;
}
private void dfs(int i) {
if (i == s.length()) {
ans.add(new ArrayList<>(t));
return;
}
for (int j = i; j < n; ++j) {
if (f[i][j]) {
t.add(s.substring(i, j + 1));
dfs(j + 1);
t.remove(t.size() - 1);
}
}
}
}
|
131 |
Palindrome Partitioning
|
Medium
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming; Backtracking
|
Python
|
class Solution:
def partition(self, s: str) -> List[List[str]]:
def dfs(i: int):
if i == n:
ans.append(t[:])
return
for j in range(i, n):
if f[i][j]:
t.append(s[i : j + 1])
dfs(j + 1)
t.pop()
n = len(s)
f = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
f[i][j] = s[i] == s[j] and f[i + 1][j - 1]
ans = []
t = []
dfs(0)
return ans
|
131 |
Palindrome Partitioning
|
Medium
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming; Backtracking
|
TypeScript
|
function partition(s: string): string[][] {
const n = s.length;
const f: boolean[][] = Array.from({ length: n }, () => Array(n).fill(true));
for (let i = n - 1; i >= 0; --i) {
for (let j = i + 1; j < n; ++j) {
f[i][j] = s[i] === s[j] && f[i + 1][j - 1];
}
}
const ans: string[][] = [];
const t: string[] = [];
const dfs = (i: number) => {
if (i === n) {
ans.push(t.slice());
return;
}
for (let j = i; j < n; ++j) {
if (f[i][j]) {
t.push(s.slice(i, j + 1));
dfs(j + 1);
t.pop();
}
}
};
dfs(0);
return ans;
}
|
132 |
Palindrome Partitioning II
|
Hard
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>
<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aab"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning ["aa","b"] could be produced using 1 cut.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "ab"
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int minCut(string s) {
int n = s.size();
bool g[n][n];
memset(g, true, sizeof(g));
for (int i = n - 1; ~i; --i) {
for (int j = i + 1; j < n; ++j) {
g[i][j] = s[i] == s[j] && g[i + 1][j - 1];
}
}
int f[n];
iota(f, f + n, 0);
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
if (g[j][i]) {
f[i] = min(f[i], j ? 1 + f[j - 1] : 0);
}
}
}
return f[n - 1];
}
};
|
132 |
Palindrome Partitioning II
|
Hard
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>
<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aab"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning ["aa","b"] could be produced using 1 cut.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "ab"
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String; Dynamic Programming
|
C#
|
public class Solution {
public int MinCut(string s) {
int n = s.Length;
bool[,] g = new bool[n,n];
int[] f = new int[n];
for (int i = 0; i < n; ++i) {
f[i] = i;
for (int j = 0; j < n; ++j) {
g[i,j] = true;
}
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
g[i,j] = s[i] == s[j] && g[i + 1,j - 1];
}
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
if (g[j,i]) {
f[i] = Math.Min(f[i], j > 0 ? 1 + f[j - 1] : 0);
}
}
}
return f[n - 1];
}
}
|
132 |
Palindrome Partitioning II
|
Hard
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>
<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aab"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning ["aa","b"] could be produced using 1 cut.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "ab"
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func minCut(s string) int {
n := len(s)
g := make([][]bool, n)
f := make([]int, n)
for i := range g {
g[i] = make([]bool, n)
f[i] = i
for j := range g[i] {
g[i][j] = true
}
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
g[i][j] = s[i] == s[j] && g[i+1][j-1]
}
}
for i := 1; i < n; i++ {
for j := 0; j <= i; j++ {
if g[j][i] {
if j == 0 {
f[i] = 0
} else {
f[i] = min(f[i], f[j-1]+1)
}
}
}
}
return f[n-1]
}
|
132 |
Palindrome Partitioning II
|
Hard
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>
<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aab"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning ["aa","b"] could be produced using 1 cut.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "ab"
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
public int minCut(String s) {
int n = s.length();
boolean[][] g = new boolean[n][n];
for (var row : g) {
Arrays.fill(row, true);
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
g[i][j] = s.charAt(i) == s.charAt(j) && g[i + 1][j - 1];
}
}
int[] f = new int[n];
for (int i = 0; i < n; ++i) {
f[i] = i;
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
if (g[j][i]) {
f[i] = Math.min(f[i], j > 0 ? 1 + f[j - 1] : 0);
}
}
}
return f[n - 1];
}
}
|
132 |
Palindrome Partitioning II
|
Hard
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>
<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aab"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning ["aa","b"] could be produced using 1 cut.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "ab"
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def minCut(self, s: str) -> int:
n = len(s)
g = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
g[i][j] = s[i] == s[j] and g[i + 1][j - 1]
f = list(range(n))
for i in range(1, n):
for j in range(i + 1):
if g[j][i]:
f[i] = min(f[i], 1 + f[j - 1] if j else 0)
return f[-1]
|
132 |
Palindrome Partitioning II
|
Hard
|
<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>
<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aab"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning ["aa","b"] could be produced using 1 cut.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "ab"
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function minCut(s: string): number {
const n = s.length;
const g: boolean[][] = Array.from({ length: n }, () => Array(n).fill(true));
for (let i = n - 1; ~i; --i) {
for (let j = i + 1; j < n; ++j) {
g[i][j] = s[i] === s[j] && g[i + 1][j - 1];
}
}
const f: number[] = Array.from({ length: n }, (_, i) => i);
for (let i = 1; i < n; ++i) {
for (let j = 0; j <= i; ++j) {
if (g[j][i]) {
f[i] = Math.min(f[i], j ? 1 + f[j - 1] : 0);
}
}
}
return f[n - 1];
}
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
C++
|
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
unordered_map<Node*, Node*> g;
auto dfs = [&](this auto&& dfs, Node* node) -> Node* {
if (!node) {
return nullptr;
}
if (g.contains(node)) {
return g[node];
}
Node* cloned = new Node(node->val);
g[node] = cloned;
for (auto& nxt : node->neighbors) {
cloned->neighbors.push_back(dfs(nxt));
}
return cloned;
};
return dfs(node);
}
};
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
C#
|
/*
// Definition for a Node.
public class Node {
public int val;
public IList<Node> neighbors;
public Node() {
val = 0;
neighbors = new List<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new List<Node>();
}
public Node(int _val, List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/
public class Solution {
public Node CloneGraph(Node node) {
var g = new Dictionary<Node, Node>();
Node Dfs(Node n) {
if (n == null) {
return null;
}
if (g.ContainsKey(n)) {
return g[n];
}
var cloned = new Node(n.val);
g[n] = cloned;
foreach (var neighbor in n.neighbors) {
cloned.neighbors.Add(Dfs(neighbor));
}
return cloned;
}
return Dfs(node);
}
}
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
Go
|
/**
* Definition for a Node.
* type Node struct {
* Val int
* Neighbors []*Node
* }
*/
func cloneGraph(node *Node) *Node {
g := map[*Node]*Node{}
var dfs func(node *Node) *Node
dfs = func(node *Node) *Node {
if node == nil {
return nil
}
if n, ok := g[node]; ok {
return n
}
cloned := &Node{node.Val, []*Node{}}
g[node] = cloned
for _, nxt := range node.Neighbors {
cloned.Neighbors = append(cloned.Neighbors, dfs(nxt))
}
return cloned
}
return dfs(node)
}
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
Java
|
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/
class Solution {
private Map<Node, Node> g = new HashMap<>();
public Node cloneGraph(Node node) {
return dfs(node);
}
private Node dfs(Node node) {
if (node == null) {
return null;
}
Node cloned = g.get(node);
if (cloned == null) {
cloned = new Node(node.val);
g.put(node, cloned);
for (Node nxt : node.neighbors) {
cloned.neighbors.add(dfs(nxt));
}
}
return cloned;
}
}
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
JavaScript
|
/**
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function (node) {
const g = new Map();
const dfs = node => {
if (!node) {
return null;
}
if (g.has(node)) {
return g.get(node);
}
const cloned = new _Node(node.val);
g.set(node, cloned);
for (const nxt of node.neighbors) {
cloned.neighbors.push(dfs(nxt));
}
return cloned;
};
return dfs(node);
};
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
Python
|
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
def dfs(node):
if node is None:
return None
if node in g:
return g[node]
cloned = Node(node.val)
g[node] = cloned
for nxt in node.neighbors:
cloned.neighbors.append(dfs(nxt))
return cloned
g = defaultdict()
return dfs(node)
|
133 |
Clone Graph
|
Medium
|
<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>
<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>
<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>
<pre>
class Node {
public int val;
public List<Node> neighbors;
}
</pre>
<p> </p>
<p><strong>Test case format:</strong></p>
<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>
<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>
<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/133_clone_graph_question.png" style="width: 454px; height: 500px;" />
<pre>
<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0133.Clone%20Graph/images/graph.png" style="width: 163px; height: 148px;" />
<pre>
<strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> adjList = []
<strong>Output:</strong> []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li><code>Node.val</code> is unique for each node.</li>
<li>There are no repeated edges and no self-loops in the graph.</li>
<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Hash Table
|
TypeScript
|
/**
* Definition for _Node.
* class _Node {
* val: number
* neighbors: _Node[]
*
* constructor(val?: number, neighbors?: _Node[]) {
* this.val = (val===undefined ? 0 : val)
* this.neighbors = (neighbors===undefined ? [] : neighbors)
* }
* }
*
*/
function cloneGraph(node: _Node | null): _Node | null {
const g: Map<_Node, _Node> = new Map();
const dfs = (node: _Node | null): _Node | null => {
if (!node) {
return null;
}
if (g.has(node)) {
return g.get(node);
}
const cloned = new _Node(node.val);
g.set(node, cloned);
for (const nxt of node.neighbors) {
cloned.neighbors.push(dfs(nxt));
}
return cloned;
};
return dfs(node);
}
|
134 |
Gas Station
|
Medium
|
<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>
<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>
<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong>
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == gas.length == cost.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= gas[i], cost[i] <= 10<sup>4</sup></code></li>
<li>The input is generated such that the answer is unique.</li>
</ul>
|
Greedy; Array
|
C++
|
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int i = n - 1, j = n - 1;
int cnt = 0, s = 0;
while (cnt < n) {
s += gas[j] - cost[j];
++cnt;
j = (j + 1) % n;
while (s < 0 && cnt < n) {
--i;
s += gas[i] - cost[i];
++cnt;
}
}
return s < 0 ? -1 : i;
}
};
|
134 |
Gas Station
|
Medium
|
<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>
<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>
<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong>
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == gas.length == cost.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= gas[i], cost[i] <= 10<sup>4</sup></code></li>
<li>The input is generated such that the answer is unique.</li>
</ul>
|
Greedy; Array
|
C#
|
public class Solution {
public int CanCompleteCircuit(int[] gas, int[] cost) {
int n = gas.Length;
int i = n - 1, j = n - 1;
int s = 0, cnt = 0;
while (cnt < n) {
s += gas[j] - cost[j];
++cnt;
j = (j + 1) % n;
while (s < 0 && cnt < n) {
--i;
s += gas[i] - cost[i];
++cnt;
}
}
return s < 0 ? -1 : i;
}
}
|
134 |
Gas Station
|
Medium
|
<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>
<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>
<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong>
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == gas.length == cost.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= gas[i], cost[i] <= 10<sup>4</sup></code></li>
<li>The input is generated such that the answer is unique.</li>
</ul>
|
Greedy; Array
|
Go
|
func canCompleteCircuit(gas []int, cost []int) int {
n := len(gas)
i, j := n-1, n-1
cnt, s := 0, 0
for cnt < n {
s += gas[j] - cost[j]
cnt++
j = (j + 1) % n
for s < 0 && cnt < n {
i--
s += gas[i] - cost[i]
cnt++
}
}
if s < 0 {
return -1
}
return i
}
|
134 |
Gas Station
|
Medium
|
<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>
<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>
<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong>
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == gas.length == cost.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= gas[i], cost[i] <= 10<sup>4</sup></code></li>
<li>The input is generated such that the answer is unique.</li>
</ul>
|
Greedy; Array
|
Java
|
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int i = n - 1, j = n - 1;
int cnt = 0, s = 0;
while (cnt < n) {
s += gas[j] - cost[j];
++cnt;
j = (j + 1) % n;
while (s < 0 && cnt < n) {
--i;
s += gas[i] - cost[i];
++cnt;
}
}
return s < 0 ? -1 : i;
}
}
|
134 |
Gas Station
|
Medium
|
<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>
<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>
<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong>
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == gas.length == cost.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= gas[i], cost[i] <= 10<sup>4</sup></code></li>
<li>The input is generated such that the answer is unique.</li>
</ul>
|
Greedy; Array
|
Python
|
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
i = j = n - 1
cnt = s = 0
while cnt < n:
s += gas[j] - cost[j]
cnt += 1
j = (j + 1) % n
while s < 0 and cnt < n:
i -= 1
s += gas[i] - cost[i]
cnt += 1
return -1 if s < 0 else i
|
134 |
Gas Station
|
Medium
|
<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>
<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>
<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong>
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == gas.length == cost.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= gas[i], cost[i] <= 10<sup>4</sup></code></li>
<li>The input is generated such that the answer is unique.</li>
</ul>
|
Greedy; Array
|
TypeScript
|
function canCompleteCircuit(gas: number[], cost: number[]): number {
const n = gas.length;
let i = n - 1;
let j = n - 1;
let s = 0;
let cnt = 0;
while (cnt < n) {
s += gas[j] - cost[j];
++cnt;
j = (j + 1) % n;
while (s < 0 && cnt < n) {
--i;
s += gas[i] - cost[i];
++cnt;
}
}
return s < 0 ? -1 : i;
}
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
C++
|
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> left(n, 1);
vector<int> right(n, 1);
for (int i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (int i = n - 2; ~i; --i) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += max(left[i], right[i]);
}
return ans;
}
};
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
C#
|
public class Solution {
public int Candy(int[] ratings) {
int n = ratings.Length;
int[] left = new int[n];
int[] right = new int[n];
Array.Fill(left, 1);
Array.Fill(right, 1);
for (int i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.Max(left[i], right[i]);
}
return ans;
}
}
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Go
|
func candy(ratings []int) int {
n := len(ratings)
left := make([]int, n)
right := make([]int, n)
for i := range left {
left[i] = 1
right[i] = 1
}
for i := 1; i < n; i++ {
if ratings[i] > ratings[i-1] {
left[i] = left[i-1] + 1
}
}
for i := n - 2; i >= 0; i-- {
if ratings[i] > ratings[i+1] {
right[i] = right[i+1] + 1
}
}
ans := 0
for i, a := range left {
b := right[i]
ans += max(a, b)
}
return ans
}
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Java
|
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, 1);
Arrays.fill(right, 1);
for (int i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.max(left[i], right[i]);
}
return ans;
}
}
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Python
|
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
left = [1] * n
right = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
left[i] = left[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
right[i] = right[i + 1] + 1
return sum(max(a, b) for a, b in zip(left, right))
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Rust
|
impl Solution {
pub fn candy(ratings: Vec<i32>) -> i32 {
let n = ratings.len();
let mut left = vec![1; n];
let mut right = vec![1; n];
for i in 1..n {
if ratings[i] > ratings[i - 1] {
left[i] = left[i - 1] + 1;
}
}
for i in (0..n - 1).rev() {
if ratings[i] > ratings[i + 1] {
right[i] = right[i + 1] + 1;
}
}
ratings
.iter()
.enumerate()
.map(|(i, _)| left[i].max(right[i]) as i32)
.sum()
}
}
|
135 |
Candy
|
Hard
|
<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>
<p>You are giving candies to these children subjected to the following requirements:</p>
<ul>
<li>Each child must have at least one candy.</li>
<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>
<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == ratings.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= ratings[i] <= 2 * 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
TypeScript
|
function candy(ratings: number[]): number {
const n = ratings.length;
const left = new Array(n).fill(1);
const right = new Array(n).fill(1);
for (let i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (let i = n - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
let ans = 0;
for (let i = 0; i < n; ++i) {
ans += Math.max(left[i], right[i]);
}
return ans;
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
C
|
int singleNumber(int* nums, int numsSize) {
int ans = 0;
for (int i = 0; i < numsSize; i++) {
ans ^= nums[i];
}
return ans;
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int v : nums) {
ans ^= v;
}
return ans;
}
};
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
C#
|
public class Solution {
public int SingleNumber(int[] nums) {
return nums.Aggregate(0, (a, b) => a ^ b);
}
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func singleNumber(nums []int) (ans int) {
for _, v := range nums {
ans ^= v
}
return
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int singleNumber(int[] nums) {
int ans = 0;
for (int v : nums) {
ans ^= v;
}
return ans;
}
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
JavaScript
|
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
return nums.reduce((a, b) => a ^ b);
};
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(xor, nums)
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
Rust
|
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
nums.into_iter().reduce(|r, v| r ^ v).unwrap()
}
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
Swift
|
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
return nums.reduce(0, ^)
}
}
|
136 |
Single Number
|
Easy
|
<p>Given a <strong>non-empty</strong> array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code></li>
<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function singleNumber(nums: number[]): number {
return nums.reduce((r, v) => r ^ v);
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
C
|
int singleNumber(int* nums, int numsSize) {
int ans = 0;
for (int i = 0; i < 32; i++) {
int count = 0;
for (int j = 0; j < numsSize; j++) {
if (nums[j] >> i & 1) {
count++;
}
}
ans |= (uint) (count % 3) << i;
}
return ans;
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
int cnt = 0;
for (int num : nums) {
cnt += ((num >> i) & 1);
}
cnt %= 3;
ans |= cnt << i;
}
return ans;
}
};
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func singleNumber(nums []int) int {
ans := int32(0)
for i := 0; i < 32; i++ {
cnt := int32(0)
for _, num := range nums {
cnt += int32(num) >> i & 1
}
cnt %= 3
ans |= cnt << i
}
return int(ans)
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int singleNumber(int[] nums) {
int ans = 0;
for (int i = 0; i < 32; i++) {
int cnt = 0;
for (int num : nums) {
cnt += num >> i & 1;
}
cnt %= 3;
ans |= cnt << i;
}
return ans;
}
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
JavaScript
|
function singleNumber(nums) {
let ans = 0;
for (let i = 0; i < 32; i++) {
const count = nums.reduce((r, v) => r + ((v >> i) & 1), 0);
ans |= count % 3 << i;
}
return ans;
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for i in range(32):
cnt = sum(num >> i & 1 for num in nums)
if cnt % 3:
if i == 31:
ans -= 1 << i
else:
ans |= 1 << i
return ans
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
Rust
|
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
let mut ans = 0;
for i in 0..32 {
let count = nums.iter().map(|v| (v >> i) & 1).sum::<i32>();
ans |= count % 3 << i;
}
ans
}
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
Swift
|
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
var a = nums.sorted()
var n = a.count
for i in stride(from: 0, through: n - 2, by: 3) {
if a[i] != a[i + 1] {
return a[i]
}
}
return a[n - 1]
}
}
|
137 |
Single Number II
|
Medium
|
<p>Given an integer array <code>nums</code> where every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>
<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [2,2,3,2]
<strong>Output:</strong> 3
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]
<strong>Output:</strong> 99
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function singleNumber(nums: number[]): number {
let ans = 0;
for (let i = 0; i < 32; i++) {
const count = nums.reduce((r, v) => r + ((v >> i) & 1), 0);
ans |= count % 3 << i;
}
return ans;
}
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
C++
|
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* dummy = new Node(0);
Node* tail = dummy;
unordered_map<Node*, Node*> d;
for (Node* cur = head; cur; cur = cur->next) {
Node* node = new Node(cur->val);
tail->next = node;
tail = node;
d[cur] = node;
}
for (Node* cur = head; cur; cur = cur->next) {
d[cur]->random = cur->random ? d[cur->random] : nullptr;
}
return dummy->next;
}
};
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
C#
|
/*
// Definition for a Node.
public class Node {
public int val;
public Node next;
public Node random;
public Node(int _val) {
val = _val;
next = null;
random = null;
}
}
*/
public class Solution {
public Node CopyRandomList(Node head) {
Dictionary<Node, Node> d = new Dictionary<Node, Node>();
Node dummy = new Node(0);
Node tail = dummy;
for (Node cur = head; cur != null; cur = cur.next) {
Node node = new Node(cur.val);
tail.next = node;
tail = node;
d[cur] = node;
}
for (Node cur = head; cur != null; cur = cur.next) {
if (cur.random != null) {
d[cur].random = d[cur.random];
}
}
return dummy.next;
}
}
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
Go
|
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
dummy := &Node{}
tail := dummy
d := map[*Node]*Node{}
for cur := head; cur != nil; cur = cur.Next {
node := &Node{Val: cur.Val}
d[cur] = node
tail.Next = node
tail = node
}
for cur := head; cur != nil; cur = cur.Next {
if cur.Random != nil {
d[cur].Random = d[cur.Random]
}
}
return dummy.Next
}
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
Java
|
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> d = new HashMap<>();
Node dummy = new Node(0);
Node tail = dummy;
for (Node cur = head; cur != null; cur = cur.next) {
Node node = new Node(cur.val);
tail.next = node;
tail = node;
d.put(cur, node);
}
for (Node cur = head; cur != null; cur = cur.next) {
d.get(cur).random = cur.random == null ? null : d.get(cur.random);
}
return dummy.next;
}
}
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
JavaScript
|
/**
* // Definition for a _Node.
* function _Node(val, next, random) {
* this.val = val;
* this.next = next;
* this.random = random;
* };
*/
/**
* @param {_Node} head
* @return {_Node}
*/
var copyRandomList = function (head) {
const d = new Map();
const dummy = new _Node();
let tail = dummy;
for (let cur = head; cur; cur = cur.next) {
const node = new _Node(cur.val);
tail.next = node;
tail = node;
d.set(cur, node);
}
for (let cur = head; cur; cur = cur.next) {
d.get(cur).random = cur.random ? d.get(cur.random) : null;
}
return dummy.next;
};
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
Python
|
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
d = {}
dummy = tail = Node(0)
cur = head
while cur:
node = Node(cur.val)
tail.next = node
tail = tail.next
d[cur] = node
cur = cur.next
cur = head
while cur:
d[cur].random = d[cur.random] if cur.random else None
cur = cur.next
return dummy.next
|
138 |
Copy List with Random Pointer
|
Medium
|
<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>
<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --> Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --> y</code>.</p>
<p>Return <em>the head of the copied linked list</em>.</p>
<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>
<ul>
<li><code>val</code>: an integer representing <code>Node.val</code></li>
<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>
<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e1.png" style="width: 700px; height: 142px;" />
<pre>
<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e2.png" style="width: 700px; height: 114px;" />
<pre>
<strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/images/e3.png" style="width: 700px; height: 122px;" /></strong></p>
<pre>
<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
|
Hash Table; Linked List
|
TypeScript
|
/**
* Definition for _Node.
* class _Node {
* val: number
* next: _Node | null
* random: _Node | null
*
* constructor(val?: number, next?: _Node, random?: _Node) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* this.random = (random===undefined ? null : random)
* }
* }
*/
function copyRandomList(head: _Node | null): _Node | null {
const d: Map<_Node, _Node> = new Map();
const dummy = new _Node();
let tail = dummy;
for (let cur = head; cur; cur = cur.next) {
const node = new _Node(cur.val);
tail.next = node;
tail = node;
d.set(cur, node);
}
for (let cur = head; cur; cur = cur.next) {
d.get(cur)!.random = cur.random ? d.get(cur.random)! : null;
}
return dummy.next;
}
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
C++
|
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> words(wordDict.begin(), wordDict.end());
int n = s.size();
bool f[n + 1];
memset(f, false, sizeof(f));
f[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
if (f[j] && words.count(s.substr(j, i - j))) {
f[i] = true;
break;
}
}
}
return f[n];
}
};
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
C#
|
public class Solution {
public bool WordBreak(string s, IList<string> wordDict) {
var words = new HashSet<string>(wordDict);
int n = s.Length;
var f = new bool[n + 1];
f[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
if (f[j] && words.Contains(s.Substring(j, i - j))) {
f[i] = true;
break;
}
}
}
return f[n];
}
}
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
Go
|
func wordBreak(s string, wordDict []string) bool {
words := map[string]bool{}
for _, w := range wordDict {
words[w] = true
}
n := len(s)
f := make([]bool, n+1)
f[0] = true
for i := 1; i <= n; i++ {
for j := 0; j < i; j++ {
if f[j] && words[s[j:i]] {
f[i] = true
break
}
}
}
return f[n]
}
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
Java
|
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> words = new HashSet<>(wordDict);
int n = s.length();
boolean[] f = new boolean[n + 1];
f[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
if (f[j] && words.contains(s.substring(j, i))) {
f[i] = true;
break;
}
}
}
return f[n];
}
}
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
Python
|
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
n = len(s)
f = [True] + [False] * n
for i in range(1, n + 1):
f[i] = any(f[j] and s[j:i] in words for j in range(i))
return f[n]
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
Rust
|
impl Solution {
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
let words: std::collections::HashSet<String> = word_dict.into_iter().collect();
let mut f = vec![false; s.len() + 1];
f[0] = true;
for i in 1..=s.len() {
for j in 0..i {
f[i] |= f[j] && words.contains(&s[j..i]);
}
}
f[s.len()]
}
}
|
139 |
Word Break
|
Medium
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 300</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 20</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming
|
TypeScript
|
function wordBreak(s: string, wordDict: string[]): boolean {
const words = new Set(wordDict);
const n = s.length;
const f: boolean[] = new Array(n + 1).fill(false);
f[0] = true;
for (let i = 1; i <= n; ++i) {
for (let j = 0; j < i; ++j) {
if (f[j] && words.has(s.substring(j, i))) {
f[i] = true;
break;
}
}
}
return f[n];
}
|
140 |
Word Break II
|
Hard
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, add spaces in <code>s</code> to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in <strong>any order</strong>.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
<strong>Output:</strong> ["cats and dog","cat sand dog"]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
<strong>Output:</strong> ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
<strong>Explanation:</strong> Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> []
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 10</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
<li>Input is generated in a way that the length of the answer doesn't exceed 10<sup>5</sup>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming; Backtracking
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Node
{
public int Index1 { get; set; }
public int Index2 { get; set; }
}
public class Solution {
public IList<string> WordBreak(string s, IList<string> wordDict) {
var paths = new List<Tuple<int, string>>[s.Length + 1];
paths[s.Length] = new List<Tuple<int, string>> { Tuple.Create(-1, (string)null) };
var wordDictGroup = wordDict.GroupBy(word => word.Length);
for (var i = s.Length - 1; i >= 0; --i)
{
paths[i] = new List<Tuple<int, string>>();
foreach (var wordGroup in wordDictGroup)
{
var wordLength = wordGroup.Key;
if (i + wordLength <= s.Length && paths[i + wordLength].Count > 0)
{
foreach (var word in wordGroup)
{
if (s.Substring(i, wordLength) == word)
{
paths[i].Add(Tuple.Create(i + wordLength, word));
}
}
}
}
}
return GenerateResults(paths);
}
private IList<string> GenerateResults(List<Tuple<int, string>>[] paths)
{
var results = new List<string>();
var sb = new StringBuilder();
var stack = new Stack<Node>();
stack.Push(new Node());
while (stack.Count > 0)
{
var node = stack.Peek();
if (node.Index1 == paths.Length - 1 || node.Index2 == paths[node.Index1].Count)
{
if (node.Index1 == paths.Length - 1)
{
results.Add(sb.ToString());
}
stack.Pop();
if (stack.Count > 0)
{
var parent = stack.Peek();
var length = paths[parent.Index1][parent.Index2 - 1].Item2.Length;
if (length < sb.Length) ++length;
sb.Remove(sb.Length - length, length);
}
}
else
{
var newNode = new Node { Index1 = paths[node.Index1][node.Index2].Item1, Index2 = 0 };
if (sb.Length != 0)
{
sb.Append(' ');
}
sb.Append(paths[node.Index1][node.Index2].Item2);
stack.Push(newNode);
++node.Index2;
}
}
return results;
}
}
|
140 |
Word Break II
|
Hard
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, add spaces in <code>s</code> to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in <strong>any order</strong>.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
<strong>Output:</strong> ["cats and dog","cat sand dog"]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
<strong>Output:</strong> ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
<strong>Explanation:</strong> Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> []
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 10</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
<li>Input is generated in a way that the length of the answer doesn't exceed 10<sup>5</sup>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming; Backtracking
|
Go
|
type Trie struct {
children [26]*Trie
isEnd bool
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func (this *Trie) search(word string) bool {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return node.isEnd
}
func wordBreak(s string, wordDict []string) []string {
trie := newTrie()
for _, w := range wordDict {
trie.insert(w)
}
var dfs func(string) [][]string
dfs = func(s string) [][]string {
res := [][]string{}
if len(s) == 0 {
res = append(res, []string{})
return res
}
for i := 1; i <= len(s); i++ {
if trie.search(s[:i]) {
for _, v := range dfs(s[i:]) {
v = append([]string{s[:i]}, v...)
res = append(res, v)
}
}
}
return res
}
res := dfs(s)
ans := []string{}
for _, v := range res {
ans = append(ans, strings.Join(v, " "))
}
return ans
}
|
140 |
Word Break II
|
Hard
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, add spaces in <code>s</code> to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in <strong>any order</strong>.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
<strong>Output:</strong> ["cats and dog","cat sand dog"]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
<strong>Output:</strong> ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
<strong>Explanation:</strong> Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> []
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 10</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
<li>Input is generated in a way that the length of the answer doesn't exceed 10<sup>5</sup>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming; Backtracking
|
Java
|
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;
void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
boolean search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
}
class Solution {
private Trie trie = new Trie();
public List<String> wordBreak(String s, List<String> wordDict) {
for (String w : wordDict) {
trie.insert(w);
}
List<List<String>> res = dfs(s);
return res.stream().map(e -> String.join(" ", e)).collect(Collectors.toList());
}
private List<List<String>> dfs(String s) {
List<List<String>> res = new ArrayList<>();
if ("".equals(s)) {
res.add(new ArrayList<>());
return res;
}
for (int i = 1; i <= s.length(); ++i) {
if (trie.search(s.substring(0, i))) {
for (List<String> v : dfs(s.substring(i))) {
v.add(0, s.substring(0, i));
res.add(v);
}
}
}
return res;
}
}
|
140 |
Word Break II
|
Hard
|
<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, add spaces in <code>s</code> to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in <strong>any order</strong>.</p>
<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
<strong>Output:</strong> ["cats and dog","cat sand dog"]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
<strong>Output:</strong> ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
<strong>Explanation:</strong> Note that you are allowed to reuse a dictionary word.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
<strong>Output:</strong> []
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>1 <= wordDict.length <= 1000</code></li>
<li><code>1 <= wordDict[i].length <= 10</code></li>
<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
<li>Input is generated in a way that the length of the answer doesn't exceed 10<sup>5</sup>.</li>
</ul>
|
Trie; Memoization; Array; Hash Table; String; Dynamic Programming; Backtracking
|
Python
|
class Trie:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, word):
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):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return False
node = node.children[idx]
return node.is_end
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def dfs(s):
if not s:
return [[]]
res = []
for i in range(1, len(s) + 1):
if trie.search(s[:i]):
for v in dfs(s[i:]):
res.append([s[:i]] + v)
return res
trie = Trie()
for w in wordDict:
trie.insert(w)
ans = dfs(s)
return [' '.join(v) for v in ans]
|
141 |
Linked List Cycle
|
Easy
|
<p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>
<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to. <strong>Note that <code>pos</code> is not passed as a parameter</strong>.</p>
<p>Return <code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist.png" style="width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;" />
<pre>
<strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test2.png" style="width: 141px; height: 74px;" />
<pre>
<strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test3.png" style="width: 45px; height: 45px;" />
<pre>
<strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
|
Hash Table; Linked List; Two Pointers
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode* head) {
unordered_set<ListNode*> s;
for (; head; head = head->next) {
if (s.contains(head)) {
return true;
}
s.insert(head);
}
return false;
}
};
|
141 |
Linked List Cycle
|
Easy
|
<p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>
<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to. <strong>Note that <code>pos</code> is not passed as a parameter</strong>.</p>
<p>Return <code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist.png" style="width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;" />
<pre>
<strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test2.png" style="width: 141px; height: 74px;" />
<pre>
<strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test3.png" style="width: 45px; height: 45px;" />
<pre>
<strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
|
Hash Table; Linked List; Two Pointers
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
s := map[*ListNode]bool{}
for ; head != nil; head = head.Next {
if s[head] {
return true
}
s[head] = true
}
return false
}
|
141 |
Linked List Cycle
|
Easy
|
<p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>
<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to. <strong>Note that <code>pos</code> is not passed as a parameter</strong>.</p>
<p>Return <code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist.png" style="width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;" />
<pre>
<strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test2.png" style="width: 141px; height: 74px;" />
<pre>
<strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test3.png" style="width: 45px; height: 45px;" />
<pre>
<strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
|
Hash Table; Linked List; Two Pointers
|
Java
|
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> s = new HashSet<>();
for (; head != null; head = head.next) {
if (!s.add(head)) {
return true;
}
}
return false;
}
}
|
141 |
Linked List Cycle
|
Easy
|
<p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>
<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to. <strong>Note that <code>pos</code> is not passed as a parameter</strong>.</p>
<p>Return <code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist.png" style="width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;" />
<pre>
<strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test2.png" style="width: 141px; height: 74px;" />
<pre>
<strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test3.png" style="width: 45px; height: 45px;" />
<pre>
<strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
|
Hash Table; Linked List; Two Pointers
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
s = set()
while head:
if head in s:
return True
s.add(head)
head = head.next
return False
|
141 |
Linked List Cycle
|
Easy
|
<p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>
<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to. <strong>Note that <code>pos</code> is not passed as a parameter</strong>.</p>
<p>Return <code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist.png" style="width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;" />
<pre>
<strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test2.png" style="width: 141px; height: 74px;" />
<pre>
<strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> true
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0141.Linked%20List%20Cycle/images/circularlinkedlist_test3.png" style="width: 45px; height: 45px;" />
<pre>
<strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
|
Hash Table; Linked List; Two Pointers
|
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 hasCycle(head: ListNode | null): boolean {
const s: Set<ListNode> = new Set();
for (; head; head = head.next) {
if (s.has(head)) {
return true;
}
s.add(head);
}
return false;
}
|
142 |
Linked List Cycle II
|
Medium
|
<p>Given the <code>head</code> of a linked list, return <em>the node where the cycle begins. If there is no cycle, return </em><code>null</code>.</p>
<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to (<strong>0-indexed</strong>). It is <code>-1</code> if there is no cycle. <strong>Note that</strong> <code>pos</code> <strong>is not passed as a parameter</strong>.</p>
<p><strong>Do not modify</strong> the linked list.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0142.Linked%20List%20Cycle%20II/images/circularlinkedlist.png" style="height: 145px; width: 450px;" />
<pre>
<strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> tail connects to node index 1
<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the second node.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0142.Linked%20List%20Cycle%20II/images/circularlinkedlist_test2.png" style="height: 105px; width: 201px;" />
<pre>
<strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> tail connects to node index 0
<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the first node.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0142.Linked%20List%20Cycle%20II/images/circularlinkedlist_test3.png" style="height: 65px; width: 65px;" />
<pre>
<strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> no cycle
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
|
Hash Table; Linked List; Two Pointers
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* detectCycle(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
ListNode* ans = head;
while (ans != slow) {
ans = ans->next;
slow = slow->next;
}
return ans;
}
}
return nullptr;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.