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
232
Implement Queue using Stacks
Easy
<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyQueue</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the back of the queue.</li> <li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li> <li><code>int peek()</code> Returns the element at the front of the queue.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li> </ul> <p><strong>Notes:</strong></p> <ul> <li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 1, 1, false] <strong>Explanation</strong> MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>
Stack; Design; Queue
Go
type MyQueue struct { stk1 []int stk2 []int } func Constructor() MyQueue { return MyQueue{[]int{}, []int{}} } func (this *MyQueue) Push(x int) { this.stk1 = append(this.stk1, x) } func (this *MyQueue) Pop() int { this.move() ans := this.stk2[len(this.stk2)-1] this.stk2 = this.stk2[:len(this.stk2)-1] return ans } func (this *MyQueue) Peek() int { this.move() return this.stk2[len(this.stk2)-1] } func (this *MyQueue) Empty() bool { return len(this.stk1) == 0 && len(this.stk2) == 0 } func (this *MyQueue) move() { if len(this.stk2) == 0 { for len(this.stk1) > 0 { this.stk2 = append(this.stk2, this.stk1[len(this.stk1)-1]) this.stk1 = this.stk1[:len(this.stk1)-1] } } } /** * Your MyQueue object will be instantiated and called as such: * obj := Constructor(); * obj.Push(x); * param_2 := obj.Pop(); * param_3 := obj.Peek(); * param_4 := obj.Empty(); */
232
Implement Queue using Stacks
Easy
<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyQueue</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the back of the queue.</li> <li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li> <li><code>int peek()</code> Returns the element at the front of the queue.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li> </ul> <p><strong>Notes:</strong></p> <ul> <li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 1, 1, false] <strong>Explanation</strong> MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>
Stack; Design; Queue
Java
class MyQueue { private Deque<Integer> stk1 = new ArrayDeque<>(); private Deque<Integer> stk2 = new ArrayDeque<>(); public MyQueue() { } public void push(int x) { stk1.push(x); } public int pop() { move(); return stk2.pop(); } public int peek() { move(); return stk2.peek(); } public boolean empty() { return stk1.isEmpty() && stk2.isEmpty(); } private void move() { while (stk2.isEmpty()) { while (!stk1.isEmpty()) { stk2.push(stk1.pop()); } } } } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
232
Implement Queue using Stacks
Easy
<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyQueue</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the back of the queue.</li> <li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li> <li><code>int peek()</code> Returns the element at the front of the queue.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li> </ul> <p><strong>Notes:</strong></p> <ul> <li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 1, 1, false] <strong>Explanation</strong> MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>
Stack; Design; Queue
Python
class MyQueue: def __init__(self): self.stk1 = [] self.stk2 = [] def push(self, x: int) -> None: self.stk1.append(x) def pop(self) -> int: self.move() return self.stk2.pop() def peek(self) -> int: self.move() return self.stk2[-1] def empty(self) -> bool: return not self.stk1 and not self.stk2 def move(self): if not self.stk2: while self.stk1: self.stk2.append(self.stk1.pop()) # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
232
Implement Queue using Stacks
Easy
<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyQueue</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the back of the queue.</li> <li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li> <li><code>int peek()</code> Returns the element at the front of the queue.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li> </ul> <p><strong>Notes:</strong></p> <ul> <li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 1, 1, false] <strong>Explanation</strong> MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>
Stack; Design; Queue
Rust
use std::collections::VecDeque; struct MyQueue { stk1: Vec<i32>, stk2: Vec<i32>, } impl MyQueue { fn new() -> Self { MyQueue { stk1: Vec::new(), stk2: Vec::new(), } } fn push(&mut self, x: i32) { self.stk1.push(x); } fn pop(&mut self) -> i32 { self.move_elements(); self.stk2.pop().unwrap() } fn peek(&mut self) -> i32 { self.move_elements(); *self.stk2.last().unwrap() } fn empty(&self) -> bool { self.stk1.is_empty() && self.stk2.is_empty() } fn move_elements(&mut self) { if self.stk2.is_empty() { while let Some(element) = self.stk1.pop() { self.stk2.push(element); } } } }
232
Implement Queue using Stacks
Easy
<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyQueue</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the back of the queue.</li> <li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li> <li><code>int peek()</code> Returns the element at the front of the queue.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li> </ul> <p><strong>Notes:</strong></p> <ul> <li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 1, 1, false] <strong>Explanation</strong> MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>
Stack; Design; Queue
TypeScript
class MyQueue { stk1: number[]; stk2: number[]; constructor() { this.stk1 = []; this.stk2 = []; } push(x: number): void { this.stk1.push(x); } pop(): number { this.move(); return this.stk2.pop(); } peek(): number { this.move(); return this.stk2.at(-1); } empty(): boolean { return !this.stk1.length && !this.stk2.length; } move(): void { if (!this.stk2.length) { while (this.stk1.length) { this.stk2.push(this.stk1.pop()!); } } } } /** * Your MyQueue object will be instantiated and called as such: * var obj = new MyQueue() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.peek() * var param_4 = obj.empty() */
233
Number of Digit One
Hard
<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math; Dynamic Programming
C++
class Solution { public: int countDigitOne(int n) { string s = to_string(n); int m = s.size(); int f[m][m]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i, int cnt, bool limit) -> int { if (i >= m) { return cnt; } if (!limit && f[i][cnt] != -1) { return f[i][cnt]; } int up = limit ? s[i] - '0' : 9; int ans = 0; for (int j = 0; j <= up; ++j) { ans += dfs(i + 1, cnt + (j == 1), limit && j == up); } if (!limit) { f[i][cnt] = ans; } return ans; }; return dfs(0, 0, true); } };
233
Number of Digit One
Hard
<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math; Dynamic Programming
C#
public class Solution { private int m; private char[] s; private int?[,] f; public int CountDigitOne(int n) { s = n.ToString().ToCharArray(); m = s.Length; f = new int?[m, m]; return Dfs(0, 0, true); } private int Dfs(int i, int cnt, bool limit) { if (i >= m) { return cnt; } if (!limit && f[i, cnt] != null) { return f[i, cnt].Value; } int up = limit ? s[i] - '0' : 9; int ans = 0; for (int j = 0; j <= up; ++j) { ans += Dfs(i + 1, cnt + (j == 1 ? 1 : 0), limit && j == up); } if (!limit) { f[i, cnt] = ans; } return ans; } }
233
Number of Digit One
Hard
<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math; Dynamic Programming
Go
func countDigitOne(n int) int { s := strconv.Itoa(n) m := len(s) f := make([][]int, m) for i := range f { f[i] = make([]int, m) for j := range f[i] { f[i][j] = -1 } } var dfs func(i, cnt int, limit bool) int dfs = func(i, cnt int, limit bool) int { if i >= m { return cnt } if !limit && f[i][cnt] != -1 { return f[i][cnt] } up := 9 if limit { up = int(s[i] - '0') } ans := 0 for j := 0; j <= up; j++ { t := 0 if j == 1 { t = 1 } ans += dfs(i+1, cnt+t, limit && j == up) } if !limit { f[i][cnt] = ans } return ans } return dfs(0, 0, true) }
233
Number of Digit One
Hard
<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math; Dynamic Programming
Java
class Solution { private int m; private char[] s; private Integer[][] f; public int countDigitOne(int n) { s = String.valueOf(n).toCharArray(); m = s.length; f = new Integer[m][m]; return dfs(0, 0, true); } private int dfs(int i, int cnt, boolean limit) { if (i >= m) { return cnt; } if (!limit && f[i][cnt] != null) { return f[i][cnt]; } int up = limit ? s[i] - '0' : 9; int ans = 0; for (int j = 0; j <= up; ++j) { ans += dfs(i + 1, cnt + (j == 1 ? 1 : 0), limit && j == up); } if (!limit) { f[i][cnt] = ans; } return ans; } }
233
Number of Digit One
Hard
<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math; Dynamic Programming
Python
class Solution: def countDigitOne(self, n: int) -> int: @cache def dfs(i: int, cnt: int, limit: bool) -> int: if i >= len(s): return cnt up = int(s[i]) if limit else 9 ans = 0 for j in range(up + 1): ans += dfs(i + 1, cnt + (j == 1), limit and j == up) return ans s = str(n) return dfs(0, 0, True)
233
Number of Digit One
Hard
<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math; Dynamic Programming
TypeScript
function countDigitOne(n: number): number { const s = n.toString(); const m = s.length; const f: number[][] = Array.from({ length: m }, () => Array(m).fill(-1)); const dfs = (i: number, cnt: number, limit: boolean): number => { if (i >= m) { return cnt; } if (!limit && f[i][cnt] !== -1) { return f[i][cnt]; } const up = limit ? +s[i] : 9; let ans = 0; for (let j = 0; j <= up; ++j) { ans += dfs(i + 1, cnt + (j === 1 ? 1 : 0), limit && j === up); } if (!limit) { f[i][cnt] = ans; } return ans; }; return dfs(0, 0, true); }
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; Linked List; Two Pointers
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { ListNode* slow = head; ListNode* fast = head->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } ListNode* pre = nullptr; ListNode* cur = slow->next; while (cur) { ListNode* t = cur->next; cur->next = pre; pre = cur; cur = t; } while (pre) { if (pre->val != head->val) return false; pre = pre->next; head = head->next; } return true; } };
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; Linked List; Two Pointers
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public bool IsPalindrome(ListNode head) { ListNode slow = head; ListNode fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode cur = slow.next; slow.next = null; ListNode pre = null; while (cur != null) { ListNode t = cur.next; cur.next = pre; pre = cur; cur = t; } while (pre != null) { if (pre.val != head.val) { return false; } pre = pre.next; head = head.next; } return true; } }
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; Linked List; Two Pointers
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func isPalindrome(head *ListNode) bool { slow, fast := head, head.Next for fast != nil && fast.Next != nil { slow, fast = slow.Next, fast.Next.Next } var pre *ListNode cur := slow.Next for cur != nil { t := cur.Next cur.Next = pre pre = cur cur = t } for pre != nil { if pre.Val != head.Val { return false } pre, head = pre.Next, head.Next } return true }
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; Linked List; Two Pointers
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public boolean isPalindrome(ListNode head) { ListNode slow = head; ListNode fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode cur = slow.next; slow.next = null; ListNode pre = null; while (cur != null) { ListNode t = cur.next; cur.next = pre; pre = cur; cur = t; } while (pre != null) { if (pre.val != head.val) { return false; } pre = pre.next; head = head.next; } return true; } }
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; Linked List; Two Pointers
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {boolean} */ var isPalindrome = function (head) { let slow = head; let fast = head.next; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } let cur = slow.next; slow.next = null; let pre = null; while (cur) { let t = cur.next; cur.next = pre; pre = cur; cur = t; } while (pre) { if (pre.val !== head.val) { return false; } pre = pre.next; head = head.next; } return true; };
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; Linked List; Two Pointers
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: slow, fast = head, head.next while fast and fast.next: slow, fast = slow.next, fast.next.next pre, cur = None, slow.next while cur: t = cur.next cur.next = pre pre, cur = cur, t while pre: if pre.val != head.val: return False pre, head = pre.next, head.next return True
234
Palindrome Linked List
Easy
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal1linked-list.jpg" style="width: 422px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2,2,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0234.Palindrome%20Linked%20List/images/pal2linked-list.jpg" style="width: 182px; height: 62px;" /> <pre> <strong>Input:</strong> head = [1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Stack; Recursion; 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 isPalindrome(head: ListNode | null): boolean { let slow: ListNode = head, fast: ListNode = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } let cur: ListNode = slow.next; slow.next = null; let prev: ListNode = null; while (cur != null) { let t: ListNode = cur.next; cur.next = prev; prev = cur; cur = t; } while (prev != null) { if (prev.val != head.val) return false; prev = prev.next; head = head.next; } return true; }
235
Lowest Common Ancestor of a Binary Search Tree
Medium
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 <strong>Output:</strong> 6 <strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [2,1], p = 2, q = 1 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the BST.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { while (1) { if (root->val < min(p->val, q->val)) { root = root->right; } else if (root->val > max(p->val, q->val)) { root = root->left; } else { return root; } } } };
235
Lowest Common Ancestor of a Binary Search Tree
Medium
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 <strong>Output:</strong> 6 <strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [2,1], p = 2, q = 1 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the BST.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while (true) { if (root.val < Math.Min(p.val, q.val)) { root = root.right; } else if (root.val > Math.Max(p.val, q.val)) { root = root.left; } else { return root; } } } }
235
Lowest Common Ancestor of a Binary Search Tree
Medium
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 <strong>Output:</strong> 6 <strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [2,1], p = 2, q = 1 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the BST.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { for { if root.Val < min(p.Val, q.Val) { root = root.Right } else if root.Val > max(p.Val, q.Val) { root = root.Left } else { return root } } }
235
Lowest Common Ancestor of a Binary Search Tree
Medium
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 <strong>Output:</strong> 6 <strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [2,1], p = 2, q = 1 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the BST.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while (true) { if (root.val < Math.min(p.val, q.val)) { root = root.right; } else if (root.val > Math.max(p.val, q.val)) { root = root.left; } else { return root; } } } }
235
Lowest Common Ancestor of a Binary Search Tree
Medium
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 <strong>Output:</strong> 6 <strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [2,1], p = 2, q = 1 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the BST.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor( self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' ) -> 'TreeNode': while 1: if root.val < min(p.val, q.val): root = root.right elif root.val > max(p.val, q.val): root = root.left else: return root
235
Lowest Common Ancestor of a Binary Search Tree
Medium
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 <strong>Output:</strong> 6 <strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/images/binarysearchtree_improved.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [2,1], p = 2, q = 1 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the BST.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; 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 lowestCommonAncestor( root: TreeNode | null, p: TreeNode | null, q: TreeNode | null, ): TreeNode | null { while (root) { if (root.val > p.val && root.val > q.val) { root = root.left; } else if (root.val < p.val && root.val < q.val) { root = root.right; } else { return root; } } }
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr || root == p || root == q) { return root; } auto left = lowestCommonAncestor(root->left, p, q); auto right = lowestCommonAncestor(root->right, p, q); if (left && right) { return root; } return left ? left : right; } };
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</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 lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if root == nil || root == p || root == q { return root } left := lowestCommonAncestor(root.Left, p, q) right := lowestCommonAncestor(root.Right, p, q) if left != nil && right != nil { return root } if left != nil { return left } return right }
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</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(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) { return root; } var left = lowestCommonAncestor(root.left, p, q); var right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; } return left == null ? right : left; } }
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</li> </ul>
Tree; Depth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */ var lowestCommonAncestor = function (root, p, q) { if (!root || root === p || root === q) { return root; } const left = lowestCommonAncestor(root.left, p, q); const right = lowestCommonAncestor(root.right, p, q); return left && right ? root : left || right; };
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor( self, root: "TreeNode", p: "TreeNode", q: "TreeNode" ) -> "TreeNode": if root in (None, p, q): return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) return root if left and right else (left or right)
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</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 { pub fn lowest_common_ancestor( root: Option<Rc<RefCell<TreeNode>>>, p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>, ) -> Option<Rc<RefCell<TreeNode>>> { if root.is_none() || root == p || root == q { return root; } let left = Self::lowest_common_ancestor( root.as_ref().unwrap().borrow().left.clone(), p.clone(), q.clone(), ); let right = Self::lowest_common_ancestor( root.as_ref().unwrap().borrow().right.clone(), p.clone(), q.clone(), ); if left.is_some() && right.is_some() { return root; } if left.is_none() { return right; } return left; } }
236
Lowest Common Ancestor of a Binary Tree
Medium
<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>Output:</strong> 5 <strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], p = 1, q = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li>All <code>Node.val</code> are <strong>unique</strong>.</li> <li><code>p != q</code></li> <li><code>p</code> and <code>q</code> will exist in the tree.</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 lowestCommonAncestor( root: TreeNode | null, p: TreeNode | null, q: TreeNode | null, ): TreeNode | null { if (!root || root === p || root === q) { return root; } const left = lowestCommonAncestor(root.left, p, q); const right = lowestCommonAncestor(root.right, p, q); return left && right ? root : left || right; }
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ void deleteNode(struct ListNode* node) { node->val = node->next->val; node->next = node->next->next; }
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node->next->next; } };
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public void DeleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } }
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func deleteNode(node *ListNode) { node.Val = node.Next.Val node.Next = node.Next.Next }
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } }
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
JavaScript
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} node * @return {void} Do not return anything, modify node in-place instead. */ var deleteNode = function (node) { node.val = node.next.val; node.next = node.next.next; };
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next
237
Delete Node in a Linked List
Medium
<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p> <p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p> <p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p> <p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p> <ul> <li>The value of the given node should not exist in the linked list.</li> <li>The number of nodes in the linked list should decrease by one.</li> <li>All the values before <code>node</code> should be in the same order.</li> <li>All the values after <code>node</code> should be in the same order.</li> </ul> <p><strong>Custom testing:</strong></p> <ul> <li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li> <li>We will build the linked list and pass the node to your function.</li> <li>The output will be the entire list after calling your function.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node1.jpg" style="width: 400px; height: 286px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 5 <strong>Output:</strong> [4,1,9] <strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/images/node2.jpg" style="width: 400px; height: 315px;" /> <pre> <strong>Input:</strong> head = [4,5,1,9], node = 1 <strong>Output:</strong> [4,5,9] <strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>The value of each node in the list is <strong>unique</strong>.</li> <li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li> </ul>
Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ /** Do not return anything, modify it in-place instead. */ function deleteNode(node: ListNode | null): void { node.val = node.next.val; node.next = node.next.next; }
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
C++
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); vector<int> ans(n); for (int i = 0, left = 1; i < n; ++i) { ans[i] = left; left *= nums[i]; } for (int i = n - 1, right = 1; ~i; --i) { ans[i] *= right; right *= nums[i]; } return ans; } };
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
C#
public class Solution { public int[] ProductExceptSelf(int[] nums) { int n = nums.Length; int[] ans = new int[n]; for (int i = 0, left = 1; i < n; ++i) { ans[i] = left; left *= nums[i]; } for (int i = n - 1, right = 1; i >= 0; --i) { ans[i] *= right; right *= nums[i]; } return ans; } }
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
Go
func productExceptSelf(nums []int) []int { n := len(nums) ans := make([]int, n) left, right := 1, 1 for i, x := range nums { ans[i] = left left *= x } for i := n - 1; i >= 0; i-- { ans[i] *= right right *= nums[i] } return ans }
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
Java
class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] ans = new int[n]; for (int i = 0, left = 1; i < n; ++i) { ans[i] = left; left *= nums[i]; } for (int i = n - 1, right = 1; i >= 0; --i) { ans[i] *= right; right *= nums[i]; } return ans; } }
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
JavaScript
/** * @param {number[]} nums * @return {number[]} */ var productExceptSelf = function (nums) { const n = nums.length; const ans = new Array(n); for (let i = 0, left = 1; i < n; ++i) { ans[i] = left; left *= nums[i]; } for (let i = n - 1, right = 1; i >= 0; --i) { ans[i] *= right; right *= nums[i]; } return ans; };
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
PHP
class Solution { /** * @param Integer[] $nums * @return Integer[] */ function productExceptSelf($nums) { $n = count($nums); $ans = []; for ($i = 0, $left = 1; $i < $n; ++$i) { $ans[$i] = $left; $left *= $nums[$i]; } for ($i = $n - 1, $right = 1; $i >= 0; --$i) { $ans[$i] *= $right; $right *= $nums[$i]; } return $ans; } }
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
Python
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) ans = [0] * n left = right = 1 for i, x in enumerate(nums): ans[i] = left left *= x for i in range(n - 1, -1, -1): ans[i] *= right right *= nums[i] return ans
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
Rust
impl Solution { pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> { let n = nums.len(); let mut ans = vec![1; n]; for i in 1..n { ans[i] = ans[i - 1] * nums[i - 1]; } let mut r = 1; for i in (0..n).rev() { ans[i] *= r; r *= nums[i]; } ans } }
238
Product of Array Except Self
Medium
<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p> <p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [24,12,8,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-1,1,0,-3,3] <strong>Output:</strong> [0,0,9,0,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-30 &lt;= nums[i] &lt;= 30</code></li> <li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
Array; Prefix Sum
TypeScript
function productExceptSelf(nums: number[]): number[] { const n = nums.length; const ans: number[] = new Array(n); for (let i = 0, left = 1; i < n; ++i) { ans[i] = left; left *= nums[i]; } for (let i = n - 1, right = 1; i >= 0; --i) { ans[i] *= right; right *= nums[i]; } return ans; }
239
Sliding Window Maximum
Hard
<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p> <p>Return <em>the max sliding window</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3 <strong>Output:</strong> [3,3,5,5,6,7] <strong>Explanation:</strong> Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 <strong>3</strong> 1 [3 -1 -3] 5 3 6 7 <strong>3</strong> 1 3 [-1 -3 5] 3 6 7 <strong> 5</strong> 1 3 -1 [-3 5 3] 6 7 <strong>5</strong> 1 3 -1 -3 [5 3 6] 7 <strong>6</strong> 1 3 -1 -3 5 [3 6 7] <strong>7</strong> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1], k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Queue; Array; Sliding Window; Monotonic Queue; Heap (Priority Queue)
C++
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { priority_queue<pair<int, int>> q; int n = nums.size(); for (int i = 0; i < k - 1; ++i) { q.push({nums[i], -i}); } vector<int> ans; for (int i = k - 1; i < n; ++i) { q.push({nums[i], -i}); while (-q.top().second <= i - k) { q.pop(); } ans.emplace_back(q.top().first); } return ans; } };
239
Sliding Window Maximum
Hard
<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p> <p>Return <em>the max sliding window</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3 <strong>Output:</strong> [3,3,5,5,6,7] <strong>Explanation:</strong> Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 <strong>3</strong> 1 [3 -1 -3] 5 3 6 7 <strong>3</strong> 1 3 [-1 -3 5] 3 6 7 <strong> 5</strong> 1 3 -1 [-3 5 3] 6 7 <strong>5</strong> 1 3 -1 -3 [5 3 6] 7 <strong>6</strong> 1 3 -1 -3 5 [3 6 7] <strong>7</strong> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1], k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Queue; Array; Sliding Window; Monotonic Queue; Heap (Priority Queue)
Go
func maxSlidingWindow(nums []int, k int) (ans []int) { q := hp{} for i, v := range nums[:k-1] { heap.Push(&q, pair{v, i}) } for i := k - 1; i < len(nums); i++ { heap.Push(&q, pair{nums[i], i}) for q[0].i <= i-k { heap.Pop(&q) } ans = append(ans, q[0].v) } return } type pair struct{ v, i int } type hp []pair func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { a, b := h[i], h[j] return a.v > b.v || (a.v == b.v && i < j) } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
239
Sliding Window Maximum
Hard
<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p> <p>Return <em>the max sliding window</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3 <strong>Output:</strong> [3,3,5,5,6,7] <strong>Explanation:</strong> Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 <strong>3</strong> 1 [3 -1 -3] 5 3 6 7 <strong>3</strong> 1 3 [-1 -3 5] 3 6 7 <strong> 5</strong> 1 3 -1 [-3 5 3] 6 7 <strong>5</strong> 1 3 -1 -3 [5 3 6] 7 <strong>6</strong> 1 3 -1 -3 5 [3 6 7] <strong>7</strong> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1], k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Queue; Array; Sliding Window; Monotonic Queue; Heap (Priority Queue)
Java
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); int n = nums.length; for (int i = 0; i < k - 1; ++i) { q.offer(new int[] {nums[i], i}); } int[] ans = new int[n - k + 1]; for (int i = k - 1, j = 0; i < n; ++i) { q.offer(new int[] {nums[i], i}); while (q.peek()[1] <= i - k) { q.poll(); } ans[j++] = q.peek()[0]; } return ans; } }
239
Sliding Window Maximum
Hard
<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p> <p>Return <em>the max sliding window</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3 <strong>Output:</strong> [3,3,5,5,6,7] <strong>Explanation:</strong> Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 <strong>3</strong> 1 [3 -1 -3] 5 3 6 7 <strong>3</strong> 1 3 [-1 -3 5] 3 6 7 <strong> 5</strong> 1 3 -1 [-3 5 3] 6 7 <strong>5</strong> 1 3 -1 -3 [5 3 6] 7 <strong>6</strong> 1 3 -1 -3 5 [3 6 7] <strong>7</strong> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1], k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Queue; Array; Sliding Window; Monotonic Queue; Heap (Priority Queue)
Python
class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: q = [(-v, i) for i, v in enumerate(nums[: k - 1])] heapify(q) ans = [] for i in range(k - 1, len(nums)): heappush(q, (-nums[i], i)) while q[0][1] <= i - k: heappop(q) ans.append(-q[0][0]) return ans
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
C++
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { for (auto& row : matrix) { int j = lower_bound(row.begin(), row.end(), target) - row.begin(); if (j < matrix[0].size() && row[j] == target) { return true; } } return false; } };
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
C#
public class Solution { public bool SearchMatrix(int[][] matrix, int target) { foreach (int[] row in matrix) { int j = Array.BinarySearch(row, target); if (j >= 0) { return true; } } return false; } }
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
Go
func searchMatrix(matrix [][]int, target int) bool { for _, row := range matrix { j := sort.SearchInts(row, target) if j < len(matrix[0]) && row[j] == target { return true } } return false }
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
Java
class Solution { public boolean searchMatrix(int[][] matrix, int target) { for (var row : matrix) { int j = Arrays.binarySearch(row, target); if (j >= 0) { return true; } } return false; } }
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
JavaScript
/** * @param {number[][]} matrix * @param {number} target * @return {boolean} */ var searchMatrix = function (matrix, target) { const n = matrix[0].length; for (const row of matrix) { const j = _.sortedIndex(row, target); if (j < n && row[j] == target) { return true; } } return false; };
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
Python
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: for row in matrix: j = bisect_left(row, target) if j < len(matrix[0]) and row[j] == target: return True return False
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
Rust
use std::cmp::Ordering; impl Solution { pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool { let m = matrix.len(); let n = matrix[0].len(); let mut i = 0; let mut j = n; while i < m && j > 0 { match target.cmp(&matrix[i][j - 1]) { Ordering::Less => { j -= 1; } Ordering::Greater => { i += 1; } Ordering::Equal => { return true; } } } false } }
240
Search a 2D Matrix II
Medium
<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p> <ul> <li>Integers in each row are sorted in ascending from left to right.</li> <li>Integers in each column are sorted in ascending from top to bottom.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid2.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0240.Search%20a%202D%20Matrix%20II/images/searchgrid.jpg" style="width: 300px; height: 300px;" /> <pre> <strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the integers in each row are <strong>sorted</strong> in ascending order.</li> <li>All the integers in each column are <strong>sorted</strong> in ascending order.</li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Divide and Conquer; Matrix
TypeScript
function searchMatrix(matrix: number[][], target: number): boolean { const n = matrix[0].length; for (const row of matrix) { const j = _.sortedIndex(row, target); if (j < n && row[j] === target) { return true; } } return false; }
241
Different Ways to Add Parentheses
Medium
<p>Given a string <code>expression</code> of numbers and operators, return <em>all possible results from computing all the different possible ways to group numbers and operators</em>. You may return the answer in <strong>any order</strong>.</p> <p>The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed <code>10<sup>4</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2-1-1&quot; <strong>Output:</strong> [0,2] <strong>Explanation:</strong> ((2-1)-1) = 0 (2-(1-1)) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2*3-4*5&quot; <strong>Output:</strong> [-34,-14,-10,-10,10] <strong>Explanation:</strong> (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= expression.length &lt;= 20</code></li> <li><code>expression</code> consists of digits and the operator <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;*&#39;</code>.</li> <li>All the integer values in the input expression are in the range <code>[0, 99]</code>.</li> <li>The integer values in the input expression do not have a leading <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> denoting the sign.</li> </ul>
Recursion; Memoization; Math; String; Dynamic Programming
C++
class Solution { public: vector<int> diffWaysToCompute(string expression) { return dfs(expression); } vector<int> dfs(string exp) { if (memo.count(exp)) return memo[exp]; if (exp.size() < 3) return {stoi(exp)}; vector<int> ans; int n = exp.size(); for (int i = 0; i < n; ++i) { char c = exp[i]; if (c == '-' || c == '+' || c == '*') { vector<int> left = dfs(exp.substr(0, i)); vector<int> right = dfs(exp.substr(i + 1, n - i - 1)); for (int& a : left) { for (int& b : right) { if (c == '-') ans.push_back(a - b); else if (c == '+') ans.push_back(a + b); else ans.push_back(a * b); } } } } memo[exp] = ans; return ans; } private: unordered_map<string, vector<int>> memo; };
241
Different Ways to Add Parentheses
Medium
<p>Given a string <code>expression</code> of numbers and operators, return <em>all possible results from computing all the different possible ways to group numbers and operators</em>. You may return the answer in <strong>any order</strong>.</p> <p>The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed <code>10<sup>4</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2-1-1&quot; <strong>Output:</strong> [0,2] <strong>Explanation:</strong> ((2-1)-1) = 0 (2-(1-1)) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2*3-4*5&quot; <strong>Output:</strong> [-34,-14,-10,-10,10] <strong>Explanation:</strong> (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= expression.length &lt;= 20</code></li> <li><code>expression</code> consists of digits and the operator <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;*&#39;</code>.</li> <li>All the integer values in the input expression are in the range <code>[0, 99]</code>.</li> <li>The integer values in the input expression do not have a leading <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> denoting the sign.</li> </ul>
Recursion; Memoization; Math; String; Dynamic Programming
C#
using System.Collections.Generic; public class Solution { public IList<int> DiffWaysToCompute(string input) { var values = new List<int>(); var operators = new List<char>(); var sum = 0; foreach (var ch in input) { if (ch == '+' || ch == '-' || ch == '*') { values.Add(sum); operators.Add(ch); sum = 0; } else { sum = sum * 10 + ch - '0'; } } values.Add(sum); var f = new List<int>[values.Count, values.Count]; for (var i = 0; i < values.Count; ++i) { f[i, i] = new List<int> { values[i] }; } for (var diff = 1; diff < values.Count; ++diff) { for (var left = 0; left + diff < values.Count; ++left) { var right = left + diff; f[left, right] = new List<int>(); for (var i = left; i < right; ++i) { foreach (var leftValue in f[left, i]) { foreach (var rightValue in f[i + 1, right]) { switch (operators[i]) { case '+': f[left, right].Add(leftValue + rightValue); break; case '-': f[left, right].Add(leftValue - rightValue); break; case '*': f[left, right].Add(leftValue * rightValue); break; } } } } } } return f[0, values.Count - 1]; } }
241
Different Ways to Add Parentheses
Medium
<p>Given a string <code>expression</code> of numbers and operators, return <em>all possible results from computing all the different possible ways to group numbers and operators</em>. You may return the answer in <strong>any order</strong>.</p> <p>The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed <code>10<sup>4</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2-1-1&quot; <strong>Output:</strong> [0,2] <strong>Explanation:</strong> ((2-1)-1) = 0 (2-(1-1)) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2*3-4*5&quot; <strong>Output:</strong> [-34,-14,-10,-10,10] <strong>Explanation:</strong> (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= expression.length &lt;= 20</code></li> <li><code>expression</code> consists of digits and the operator <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;*&#39;</code>.</li> <li>All the integer values in the input expression are in the range <code>[0, 99]</code>.</li> <li>The integer values in the input expression do not have a leading <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> denoting the sign.</li> </ul>
Recursion; Memoization; Math; String; Dynamic Programming
Go
var memo = map[string][]int{} func diffWaysToCompute(expression string) []int { return dfs(expression) } func dfs(exp string) []int { if v, ok := memo[exp]; ok { return v } if len(exp) < 3 { v, _ := strconv.Atoi(exp) return []int{v} } ans := []int{} for i, c := range exp { if c == '-' || c == '+' || c == '*' { left, right := dfs(exp[:i]), dfs(exp[i+1:]) for _, a := range left { for _, b := range right { if c == '-' { ans = append(ans, a-b) } else if c == '+' { ans = append(ans, a+b) } else { ans = append(ans, a*b) } } } } } memo[exp] = ans return ans }
241
Different Ways to Add Parentheses
Medium
<p>Given a string <code>expression</code> of numbers and operators, return <em>all possible results from computing all the different possible ways to group numbers and operators</em>. You may return the answer in <strong>any order</strong>.</p> <p>The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed <code>10<sup>4</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2-1-1&quot; <strong>Output:</strong> [0,2] <strong>Explanation:</strong> ((2-1)-1) = 0 (2-(1-1)) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2*3-4*5&quot; <strong>Output:</strong> [-34,-14,-10,-10,10] <strong>Explanation:</strong> (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= expression.length &lt;= 20</code></li> <li><code>expression</code> consists of digits and the operator <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;*&#39;</code>.</li> <li>All the integer values in the input expression are in the range <code>[0, 99]</code>.</li> <li>The integer values in the input expression do not have a leading <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> denoting the sign.</li> </ul>
Recursion; Memoization; Math; String; Dynamic Programming
Java
class Solution { private static Map<String, List<Integer>> memo = new HashMap<>(); public List<Integer> diffWaysToCompute(String expression) { return dfs(expression); } private List<Integer> dfs(String exp) { if (memo.containsKey(exp)) { return memo.get(exp); } List<Integer> ans = new ArrayList<>(); if (exp.length() < 3) { ans.add(Integer.parseInt(exp)); return ans; } for (int i = 0; i < exp.length(); ++i) { char c = exp.charAt(i); if (c == '-' || c == '+' || c == '*') { List<Integer> left = dfs(exp.substring(0, i)); List<Integer> right = dfs(exp.substring(i + 1)); for (int a : left) { for (int b : right) { if (c == '-') { ans.add(a - b); } else if (c == '+') { ans.add(a + b); } else { ans.add(a * b); } } } } } memo.put(exp, ans); return ans; } }
241
Different Ways to Add Parentheses
Medium
<p>Given a string <code>expression</code> of numbers and operators, return <em>all possible results from computing all the different possible ways to group numbers and operators</em>. You may return the answer in <strong>any order</strong>.</p> <p>The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed <code>10<sup>4</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2-1-1&quot; <strong>Output:</strong> [0,2] <strong>Explanation:</strong> ((2-1)-1) = 0 (2-(1-1)) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;2*3-4*5&quot; <strong>Output:</strong> [-34,-14,-10,-10,10] <strong>Explanation:</strong> (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= expression.length &lt;= 20</code></li> <li><code>expression</code> consists of digits and the operator <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;*&#39;</code>.</li> <li>All the integer values in the input expression are in the range <code>[0, 99]</code>.</li> <li>The integer values in the input expression do not have a leading <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> denoting the sign.</li> </ul>
Recursion; Memoization; Math; String; Dynamic Programming
Python
class Solution: def diffWaysToCompute(self, expression: str) -> List[int]: @cache def dfs(exp): if exp.isdigit(): return [int(exp)] ans = [] for i, c in enumerate(exp): if c in '-+*': left, right = dfs(exp[:i]), dfs(exp[i + 1 :]) for a in left: for b in right: if c == '-': ans.append(a - b) elif c == '+': ans.append(a + b) else: ans.append(a * b) return ans return dfs(expression)
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
C
int cmp(const void* a, const void* b) { return *(char*) a - *(char*) b; } bool isAnagram(char* s, char* t) { int n = strlen(s); int m = strlen(t); if (n != m) { return 0; } qsort(s, n, sizeof(char), cmp); qsort(t, n, sizeof(char), cmp); return !strcmp(s, t); }
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
C++
class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) { return false; } vector<int> cnt(26); for (int i = 0; i < s.size(); ++i) { ++cnt[s[i] - 'a']; --cnt[t[i] - 'a']; } return all_of(cnt.begin(), cnt.end(), [](int x) { return x == 0; }); } };
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
C#
public class Solution { public bool IsAnagram(string s, string t) { if (s.Length != t.Length) { return false; } int[] cnt = new int[26]; for (int i = 0; i < s.Length; ++i) { ++cnt[s[i] - 'a']; --cnt[t[i] - 'a']; } return cnt.All(x => x == 0); } }
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
Go
func isAnagram(s string, t string) bool { if len(s) != len(t) { return false } cnt := [26]int{} for i := 0; i < len(s); i++ { cnt[s[i]-'a']++ cnt[t[i]-'a']-- } for _, v := range cnt { if v != 0 { return false } } return true }
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
Java
class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; --cnt[t.charAt(i) - 'a']; } for (int i = 0; i < 26; ++i) { if (cnt[i] != 0) { return false; } } return true; } }
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
JavaScript
/** * @param {string} s * @param {string} t * @return {boolean} */ var isAnagram = function (s, t) { if (s.length !== t.length) { return false; } const cnt = new Array(26).fill(0); for (let i = 0; i < s.length; ++i) { ++cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)]; --cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)]; } return cnt.every(x => x === 0); };
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
Python
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False cnt = Counter(s) for c in t: cnt[c] -= 1 if cnt[c] < 0: return False return True
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
Rust
impl Solution { pub fn is_anagram(s: String, t: String) -> bool { let n = s.len(); let m = t.len(); if n != m { return false; } let mut s = s.chars().collect::<Vec<char>>(); let mut t = t.chars().collect::<Vec<char>>(); s.sort(); t.sort(); for i in 0..n { if s[i] != t[i] { return false; } } true } }
242
Valid Anagram
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
Hash Table; String; Sorting
TypeScript
function isAnagram(s: string, t: string): boolean { if (s.length !== t.length) { return false; } const cnt = new Array(26).fill(0); for (let i = 0; i < s.length; ++i) { ++cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)]; --cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)]; } return cnt.every(x => x === 0); }
243
Shortest Word Distance
Easy
<p>Given an array of strings <code>wordsDict</code> and two different strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between these two words in the list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;coding&quot;, word2 = &quot;practice&quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;makes&quot;, word2 = &quot;coding&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> </ul>
Array; String
C++
class Solution { public: int shortestDistance(vector<string>& wordsDict, string word1, string word2) { int ans = INT_MAX; for (int k = 0, i = -1, j = -1; k < wordsDict.size(); ++k) { if (wordsDict[k] == word1) { i = k; } if (wordsDict[k] == word2) { j = k; } if (i != -1 && j != -1) { ans = min(ans, abs(i - j)); } } return ans; } };
243
Shortest Word Distance
Easy
<p>Given an array of strings <code>wordsDict</code> and two different strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between these two words in the list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;coding&quot;, word2 = &quot;practice&quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;makes&quot;, word2 = &quot;coding&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> </ul>
Array; String
Go
func shortestDistance(wordsDict []string, word1 string, word2 string) int { ans := 0x3f3f3f3f i, j := -1, -1 for k, w := range wordsDict { if w == word1 { i = k } if w == word2 { j = k } if i != -1 && j != -1 { ans = min(ans, abs(i-j)) } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
243
Shortest Word Distance
Easy
<p>Given an array of strings <code>wordsDict</code> and two different strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between these two words in the list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;coding&quot;, word2 = &quot;practice&quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;makes&quot;, word2 = &quot;coding&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> </ul>
Array; String
Java
class Solution { public int shortestDistance(String[] wordsDict, String word1, String word2) { int ans = 0x3f3f3f3f; for (int k = 0, i = -1, j = -1; k < wordsDict.length; ++k) { if (wordsDict[k].equals(word1)) { i = k; } if (wordsDict[k].equals(word2)) { j = k; } if (i != -1 && j != -1) { ans = Math.min(ans, Math.abs(i - j)); } } return ans; } }
243
Shortest Word Distance
Easy
<p>Given an array of strings <code>wordsDict</code> and two different strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between these two words in the list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;coding&quot;, word2 = &quot;practice&quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wordsDict = [&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;], word1 = &quot;makes&quot;, word2 = &quot;coding&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> </ul>
Array; String
Python
class Solution: def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: i = j = -1 ans = inf for k, w in enumerate(wordsDict): if w == word1: i = k if w == word2: j = k if i != -1 and j != -1: ans = min(ans, abs(i - j)) return ans
244
Shortest Word Distance II
Medium
<p>Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.</p> <p>Implement the <code>WordDistance</code> class:</p> <ul> <li><code>WordDistance(String[] wordsDict)</code> initializes the object with the strings array <code>wordsDict</code>.</li> <li><code>int shortest(String word1, String word2)</code> returns the shortest distance between <code>word1</code> and <code>word2</code> in the array <code>wordsDict</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;WordDistance&quot;, &quot;shortest&quot;, &quot;shortest&quot;] [[[&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]], [&quot;coding&quot;, &quot;practice&quot;], [&quot;makes&quot;, &quot;coding&quot;]] <strong>Output</strong> [null, 3, 1] <strong>Explanation</strong> WordDistance wordDistance = new WordDistance([&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]); wordDistance.shortest(&quot;coding&quot;, &quot;practice&quot;); // return 3 wordDistance.shortest(&quot;makes&quot;, &quot;coding&quot;); // return 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> <li>At most <code>5000</code> calls will be made to <code>shortest</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; String
C++
class WordDistance { public: WordDistance(vector<string>& wordsDict) { for (int i = 0; i < wordsDict.size(); ++i) { d[wordsDict[i]].push_back(i); } } int shortest(string word1, string word2) { auto a = d[word1], b = d[word2]; int i = 0, j = 0; int ans = INT_MAX; while (i < a.size() && j < b.size()) { ans = min(ans, abs(a[i] - b[j])); if (a[i] <= b[j]) { ++i; } else { ++j; } } return ans; } private: unordered_map<string, vector<int>> d; }; /** * Your WordDistance object will be instantiated and called as such: * WordDistance* obj = new WordDistance(wordsDict); * int param_1 = obj->shortest(word1,word2); */
244
Shortest Word Distance II
Medium
<p>Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.</p> <p>Implement the <code>WordDistance</code> class:</p> <ul> <li><code>WordDistance(String[] wordsDict)</code> initializes the object with the strings array <code>wordsDict</code>.</li> <li><code>int shortest(String word1, String word2)</code> returns the shortest distance between <code>word1</code> and <code>word2</code> in the array <code>wordsDict</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;WordDistance&quot;, &quot;shortest&quot;, &quot;shortest&quot;] [[[&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]], [&quot;coding&quot;, &quot;practice&quot;], [&quot;makes&quot;, &quot;coding&quot;]] <strong>Output</strong> [null, 3, 1] <strong>Explanation</strong> WordDistance wordDistance = new WordDistance([&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]); wordDistance.shortest(&quot;coding&quot;, &quot;practice&quot;); // return 3 wordDistance.shortest(&quot;makes&quot;, &quot;coding&quot;); // return 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> <li>At most <code>5000</code> calls will be made to <code>shortest</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; String
Go
type WordDistance struct { d map[string][]int } func Constructor(wordsDict []string) WordDistance { d := map[string][]int{} for i, w := range wordsDict { d[w] = append(d[w], i) } return WordDistance{d} } func (this *WordDistance) Shortest(word1 string, word2 string) int { a, b := this.d[word1], this.d[word2] ans := 0x3f3f3f3f i, j := 0, 0 for i < len(a) && j < len(b) { ans = min(ans, abs(a[i]-b[j])) if a[i] <= b[j] { i++ } else { j++ } } return ans } func abs(x int) int { if x < 0 { return -x } return x } /** * Your WordDistance object will be instantiated and called as such: * obj := Constructor(wordsDict); * param_1 := obj.Shortest(word1,word2); */
244
Shortest Word Distance II
Medium
<p>Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.</p> <p>Implement the <code>WordDistance</code> class:</p> <ul> <li><code>WordDistance(String[] wordsDict)</code> initializes the object with the strings array <code>wordsDict</code>.</li> <li><code>int shortest(String word1, String word2)</code> returns the shortest distance between <code>word1</code> and <code>word2</code> in the array <code>wordsDict</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;WordDistance&quot;, &quot;shortest&quot;, &quot;shortest&quot;] [[[&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]], [&quot;coding&quot;, &quot;practice&quot;], [&quot;makes&quot;, &quot;coding&quot;]] <strong>Output</strong> [null, 3, 1] <strong>Explanation</strong> WordDistance wordDistance = new WordDistance([&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]); wordDistance.shortest(&quot;coding&quot;, &quot;practice&quot;); // return 3 wordDistance.shortest(&quot;makes&quot;, &quot;coding&quot;); // return 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> <li>At most <code>5000</code> calls will be made to <code>shortest</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; String
Java
class WordDistance { private Map<String, List<Integer>> d = new HashMap<>(); public WordDistance(String[] wordsDict) { for (int i = 0; i < wordsDict.length; ++i) { d.computeIfAbsent(wordsDict[i], k -> new ArrayList<>()).add(i); } } public int shortest(String word1, String word2) { List<Integer> a = d.get(word1), b = d.get(word2); int ans = 0x3f3f3f3f; int i = 0, j = 0; while (i < a.size() && j < b.size()) { ans = Math.min(ans, Math.abs(a.get(i) - b.get(j))); if (a.get(i) <= b.get(j)) { ++i; } else { ++j; } } return ans; } } /** * Your WordDistance object will be instantiated and called as such: * WordDistance obj = new WordDistance(wordsDict); * int param_1 = obj.shortest(word1,word2); */
244
Shortest Word Distance II
Medium
<p>Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.</p> <p>Implement the <code>WordDistance</code> class:</p> <ul> <li><code>WordDistance(String[] wordsDict)</code> initializes the object with the strings array <code>wordsDict</code>.</li> <li><code>int shortest(String word1, String word2)</code> returns the shortest distance between <code>word1</code> and <code>word2</code> in the array <code>wordsDict</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;WordDistance&quot;, &quot;shortest&quot;, &quot;shortest&quot;] [[[&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]], [&quot;coding&quot;, &quot;practice&quot;], [&quot;makes&quot;, &quot;coding&quot;]] <strong>Output</strong> [null, 3, 1] <strong>Explanation</strong> WordDistance wordDistance = new WordDistance([&quot;practice&quot;, &quot;makes&quot;, &quot;perfect&quot;, &quot;coding&quot;, &quot;makes&quot;]); wordDistance.shortest(&quot;coding&quot;, &quot;practice&quot;); // return 3 wordDistance.shortest(&quot;makes&quot;, &quot;coding&quot;); // return 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> <li><code>word1 != word2</code></li> <li>At most <code>5000</code> calls will be made to <code>shortest</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; String
Python
class WordDistance: def __init__(self, wordsDict: List[str]): self.d = defaultdict(list) for i, w in enumerate(wordsDict): self.d[w].append(i) def shortest(self, word1: str, word2: str) -> int: a, b = self.d[word1], self.d[word2] ans = inf i = j = 0 while i < len(a) and j < len(b): ans = min(ans, abs(a[i] - b[j])) if a[i] <= b[j]: i += 1 else: j += 1 return ans # Your WordDistance object will be instantiated and called as such: # obj = WordDistance(wordsDict) # param_1 = obj.shortest(word1,word2)
245
Shortest Word Distance III
Medium
<p>Given an array of strings <code>wordsDict</code> and two strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between the occurrence of these two words in the list</em>.</p> <p><strong>Note</strong> that <code>word1</code> and <code>word2</code> may be the same. It is guaranteed that they represent <strong>two individual words</strong> in the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes" <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> </ul>
Array; String
C++
class Solution { public: int shortestWordDistance(vector<string>& wordsDict, string word1, string word2) { int n = wordsDict.size(); int ans = n; if (word1 == word2) { for (int i = 0, j = -1; i < n; ++i) { if (wordsDict[i] == word1) { if (j != -1) { ans = min(ans, i - j); } j = i; } } } else { for (int k = 0, i = -1, j = -1; k < n; ++k) { if (wordsDict[k] == word1) { i = k; } if (wordsDict[k] == word2) { j = k; } if (i != -1 && j != -1) { ans = min(ans, abs(i - j)); } } } return ans; } };
245
Shortest Word Distance III
Medium
<p>Given an array of strings <code>wordsDict</code> and two strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between the occurrence of these two words in the list</em>.</p> <p><strong>Note</strong> that <code>word1</code> and <code>word2</code> may be the same. It is guaranteed that they represent <strong>two individual words</strong> in the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes" <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> </ul>
Array; String
Go
func shortestWordDistance(wordsDict []string, word1 string, word2 string) int { ans := len(wordsDict) if word1 == word2 { j := -1 for i, w := range wordsDict { if w == word1 { if j != -1 { ans = min(ans, i-j) } j = i } } } else { i, j := -1, -1 for k, w := range wordsDict { if w == word1 { i = k } if w == word2 { j = k } if i != -1 && j != -1 { ans = min(ans, abs(i-j)) } } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
245
Shortest Word Distance III
Medium
<p>Given an array of strings <code>wordsDict</code> and two strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between the occurrence of these two words in the list</em>.</p> <p><strong>Note</strong> that <code>word1</code> and <code>word2</code> may be the same. It is guaranteed that they represent <strong>two individual words</strong> in the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes" <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> </ul>
Array; String
Java
class Solution { public int shortestWordDistance(String[] wordsDict, String word1, String word2) { int ans = wordsDict.length; if (word1.equals(word2)) { for (int i = 0, j = -1; i < wordsDict.length; ++i) { if (wordsDict[i].equals(word1)) { if (j != -1) { ans = Math.min(ans, i - j); } j = i; } } } else { for (int k = 0, i = -1, j = -1; k < wordsDict.length; ++k) { if (wordsDict[k].equals(word1)) { i = k; } if (wordsDict[k].equals(word2)) { j = k; } if (i != -1 && j != -1) { ans = Math.min(ans, Math.abs(i - j)); } } } return ans; } }
245
Shortest Word Distance III
Medium
<p>Given an array of strings <code>wordsDict</code> and two strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between the occurrence of these two words in the list</em>.</p> <p><strong>Note</strong> that <code>word1</code> and <code>word2</code> may be the same. It is guaranteed that they represent <strong>two individual words</strong> in the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes" <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> </ul>
Array; String
Python
class Solution: def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: ans = len(wordsDict) if word1 == word2: j = -1 for i, w in enumerate(wordsDict): if w == word1: if j != -1: ans = min(ans, i - j) j = i else: i = j = -1 for k, w in enumerate(wordsDict): if w == word1: i = k if w == word2: j = k if i != -1 and j != -1: ans = min(ans, abs(i - j)) return ans
245
Shortest Word Distance III
Medium
<p>Given an array of strings <code>wordsDict</code> and two strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between the occurrence of these two words in the list</em>.</p> <p><strong>Note</strong> that <code>word1</code> and <code>word2</code> may be the same. It is guaranteed that they represent <strong>two individual words</strong> in the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes" <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsDict.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li> <li><code>wordsDict[i]</code> consists of lowercase English letters.</li> <li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li> </ul>
Array; String
TypeScript
function shortestWordDistance(wordsDict: string[], word1: string, word2: string): number { let ans = wordsDict.length; if (word1 === word2) { let j = -1; for (let i = 0; i < wordsDict.length; i++) { if (wordsDict[i] === word1) { if (j !== -1) { ans = Math.min(ans, i - j); } j = i; } } } else { let i = -1, j = -1; for (let k = 0; k < wordsDict.length; k++) { if (wordsDict[k] === word1) { i = k; } if (wordsDict[k] === word2) { j = k; } if (i !== -1 && j !== -1) { ans = Math.min(ans, Math.abs(i - j)); } } } return ans; }
246
Strobogrammatic Number
Easy
<p>Given a string <code>num</code> which represents an integer, return <code>true</code> <em>if</em> <code>num</code> <em>is a <strong>strobogrammatic number</strong></em>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;69&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;88&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;962&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 50</code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not contain any leading zeros except for zero itself.</li> </ul>
Hash Table; Two Pointers; String
C++
class Solution { public: bool isStrobogrammatic(string num) { vector<int> d = {0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; for (int i = 0, j = num.size() - 1; i <= j; ++i, --j) { int a = num[i] - '0', b = num[j] - '0'; if (d[a] != b) { return false; } } return true; } };
246
Strobogrammatic Number
Easy
<p>Given a string <code>num</code> which represents an integer, return <code>true</code> <em>if</em> <code>num</code> <em>is a <strong>strobogrammatic number</strong></em>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;69&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;88&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;962&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 50</code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not contain any leading zeros except for zero itself.</li> </ul>
Hash Table; Two Pointers; String
Go
func isStrobogrammatic(num string) bool { d := []int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} for i, j := 0, len(num)-1; i <= j; i, j = i+1, j-1 { a, b := int(num[i]-'0'), int(num[j]-'0') if d[a] != b { return false } } return true }
246
Strobogrammatic Number
Easy
<p>Given a string <code>num</code> which represents an integer, return <code>true</code> <em>if</em> <code>num</code> <em>is a <strong>strobogrammatic number</strong></em>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;69&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;88&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;962&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 50</code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not contain any leading zeros except for zero itself.</li> </ul>
Hash Table; Two Pointers; String
Java
class Solution { public boolean isStrobogrammatic(String num) { int[] d = new int[] {0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; for (int i = 0, j = num.length() - 1; i <= j; ++i, --j) { int a = num.charAt(i) - '0', b = num.charAt(j) - '0'; if (d[a] != b) { return false; } } return true; } }
246
Strobogrammatic Number
Easy
<p>Given a string <code>num</code> which represents an integer, return <code>true</code> <em>if</em> <code>num</code> <em>is a <strong>strobogrammatic number</strong></em>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;69&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;88&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;962&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 50</code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not contain any leading zeros except for zero itself.</li> </ul>
Hash Table; Two Pointers; String
Python
class Solution: def isStrobogrammatic(self, num: str) -> bool: d = [0, 1, -1, -1, -1, -1, 9, -1, 8, 6] i, j = 0, len(num) - 1 while i <= j: a, b = int(num[i]), int(num[j]) if d[a] != b: return False i, j = i + 1, j - 1 return True
247
Strobogrammatic Number II
Medium
<p>Given an integer <code>n</code>, return all the <strong>strobogrammatic numbers</strong> that are of length <code>n</code>. You may return the answer in <strong>any order</strong>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> ["11","69","88","96"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["0","1","8"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 14</code></li> </ul>
Recursion; Array; String
C++
class Solution { public: const vector<pair<char, char>> pairs = {{'1', '1'}, {'8', '8'}, {'6', '9'}, {'9', '6'}}; vector<string> findStrobogrammatic(int n) { function<vector<string>(int)> dfs = [&](int u) { if (u == 0) return vector<string>{""}; if (u == 1) return vector<string>{"0", "1", "8"}; vector<string> ans; for (auto& v : dfs(u - 2)) { for (auto& [l, r] : pairs) ans.push_back(l + v + r); if (u != n) ans.push_back('0' + v + '0'); } return ans; }; return dfs(n); } };
247
Strobogrammatic Number II
Medium
<p>Given an integer <code>n</code>, return all the <strong>strobogrammatic numbers</strong> that are of length <code>n</code>. You may return the answer in <strong>any order</strong>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> ["11","69","88","96"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["0","1","8"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 14</code></li> </ul>
Recursion; Array; String
Go
func findStrobogrammatic(n int) []string { var dfs func(int) []string dfs = func(u int) []string { if u == 0 { return []string{""} } if u == 1 { return []string{"0", "1", "8"} } var ans []string pairs := [][]string{{"1", "1"}, {"8", "8"}, {"6", "9"}, {"9", "6"}} for _, v := range dfs(u - 2) { for _, p := range pairs { ans = append(ans, p[0]+v+p[1]) } if u != n { ans = append(ans, "0"+v+"0") } } return ans } return dfs(n) }
247
Strobogrammatic Number II
Medium
<p>Given an integer <code>n</code>, return all the <strong>strobogrammatic numbers</strong> that are of length <code>n</code>. You may return the answer in <strong>any order</strong>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> ["11","69","88","96"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["0","1","8"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 14</code></li> </ul>
Recursion; Array; String
Java
class Solution { private static final int[][] PAIRS = {{1, 1}, {8, 8}, {6, 9}, {9, 6}}; private int n; public List<String> findStrobogrammatic(int n) { this.n = n; return dfs(n); } private List<String> dfs(int u) { if (u == 0) { return Collections.singletonList(""); } if (u == 1) { return Arrays.asList("0", "1", "8"); } List<String> ans = new ArrayList<>(); for (String v : dfs(u - 2)) { for (var p : PAIRS) { ans.add(p[0] + v + p[1]); } if (u != n) { ans.add(0 + v + 0); } } return ans; } }
247
Strobogrammatic Number II
Medium
<p>Given an integer <code>n</code>, return all the <strong>strobogrammatic numbers</strong> that are of length <code>n</code>. You may return the answer in <strong>any order</strong>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> ["11","69","88","96"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["0","1","8"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 14</code></li> </ul>
Recursion; Array; String
Python
class Solution: def findStrobogrammatic(self, n: int) -> List[str]: def dfs(u): if u == 0: return [''] if u == 1: return ['0', '1', '8'] ans = [] for v in dfs(u - 2): for l, r in ('11', '88', '69', '96'): ans.append(l + v + r) if u != n: ans.append('0' + v + '0') return ans return dfs(n)
248
Strobogrammatic Number III
Hard
<p>Given two strings low and high that represent two integers <code>low</code> and <code>high</code> where <code>low &lt;= high</code>, return <em>the number of <strong>strobogrammatic numbers</strong> in the range</em> <code>[low, high]</code>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> low = "50", high = "100" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> low = "0", high = "0" <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low.length, high.length &lt;= 15</code></li> <li><code>low</code> and <code>high</code> consist of only digits.</li> <li><code>low &lt;= high</code></li> <li><code>low</code> and <code>high</code> do not contain any leading zeros except for zero itself.</li> </ul>
Recursion; Array; String
C++
using ll = long long; class Solution { public: const vector<pair<char, char>> pairs = {{'1', '1'}, {'8', '8'}, {'6', '9'}, {'9', '6'}}; int strobogrammaticInRange(string low, string high) { int n; function<vector<string>(int)> dfs = [&](int u) { if (u == 0) return vector<string>{""}; if (u == 1) return vector<string>{"0", "1", "8"}; vector<string> ans; for (auto& v : dfs(u - 2)) { for (auto& [l, r] : pairs) ans.push_back(l + v + r); if (u != n) ans.push_back('0' + v + '0'); } return ans; }; int a = low.size(), b = high.size(); int ans = 0; ll l = stoll(low), r = stoll(high); for (n = a; n <= b; ++n) { for (auto& s : dfs(n)) { ll v = stoll(s); if (l <= v && v <= r) { ++ans; } } } return ans; } };
248
Strobogrammatic Number III
Hard
<p>Given two strings low and high that represent two integers <code>low</code> and <code>high</code> where <code>low &lt;= high</code>, return <em>the number of <strong>strobogrammatic numbers</strong> in the range</em> <code>[low, high]</code>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> low = "50", high = "100" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> low = "0", high = "0" <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low.length, high.length &lt;= 15</code></li> <li><code>low</code> and <code>high</code> consist of only digits.</li> <li><code>low &lt;= high</code></li> <li><code>low</code> and <code>high</code> do not contain any leading zeros except for zero itself.</li> </ul>
Recursion; Array; String
Go
func strobogrammaticInRange(low string, high string) int { n := 0 var dfs func(int) []string dfs = func(u int) []string { if u == 0 { return []string{""} } if u == 1 { return []string{"0", "1", "8"} } var ans []string pairs := [][]string{{"1", "1"}, {"8", "8"}, {"6", "9"}, {"9", "6"}} for _, v := range dfs(u - 2) { for _, p := range pairs { ans = append(ans, p[0]+v+p[1]) } if u != n { ans = append(ans, "0"+v+"0") } } return ans } a, b := len(low), len(high) l, _ := strconv.Atoi(low) r, _ := strconv.Atoi(high) ans := 0 for n = a; n <= b; n++ { for _, s := range dfs(n) { v, _ := strconv.Atoi(s) if l <= v && v <= r { ans++ } } } return ans }
248
Strobogrammatic Number III
Hard
<p>Given two strings low and high that represent two integers <code>low</code> and <code>high</code> where <code>low &lt;= high</code>, return <em>the number of <strong>strobogrammatic numbers</strong> in the range</em> <code>[low, high]</code>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> low = "50", high = "100" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> low = "0", high = "0" <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low.length, high.length &lt;= 15</code></li> <li><code>low</code> and <code>high</code> consist of only digits.</li> <li><code>low &lt;= high</code></li> <li><code>low</code> and <code>high</code> do not contain any leading zeros except for zero itself.</li> </ul>
Recursion; Array; String
Java
class Solution { private static final int[][] PAIRS = {{1, 1}, {8, 8}, {6, 9}, {9, 6}}; private int n; public int strobogrammaticInRange(String low, String high) { int a = low.length(), b = high.length(); long l = Long.parseLong(low), r = Long.parseLong(high); int ans = 0; for (n = a; n <= b; ++n) { for (String s : dfs(n)) { long v = Long.parseLong(s); if (l <= v && v <= r) { ++ans; } } } return ans; } private List<String> dfs(int u) { if (u == 0) { return Collections.singletonList(""); } if (u == 1) { return Arrays.asList("0", "1", "8"); } List<String> ans = new ArrayList<>(); for (String v : dfs(u - 2)) { for (var p : PAIRS) { ans.add(p[0] + v + p[1]); } if (u != n) { ans.add(0 + v + 0); } } return ans; } }
248
Strobogrammatic Number III
Hard
<p>Given two strings low and high that represent two integers <code>low</code> and <code>high</code> where <code>low &lt;= high</code>, return <em>the number of <strong>strobogrammatic numbers</strong> in the range</em> <code>[low, high]</code>.</p> <p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> low = "50", high = "100" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> low = "0", high = "0" <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low.length, high.length &lt;= 15</code></li> <li><code>low</code> and <code>high</code> consist of only digits.</li> <li><code>low &lt;= high</code></li> <li><code>low</code> and <code>high</code> do not contain any leading zeros except for zero itself.</li> </ul>
Recursion; Array; String
Python
class Solution: def strobogrammaticInRange(self, low: str, high: str) -> int: def dfs(u): if u == 0: return [''] if u == 1: return ['0', '1', '8'] ans = [] for v in dfs(u - 2): for l, r in ('11', '88', '69', '96'): ans.append(l + v + r) if u != n: ans.append('0' + v + '0') return ans a, b = len(low), len(high) low, high = int(low), int(high) ans = 0 for n in range(a, b + 1): for s in dfs(n): if low <= int(s) <= high: ans += 1 return ans
249
Group Shifted Strings
Medium
<p>Perform the following shift operations on a string:</p> <ul> <li><strong>Right shift</strong>: Replace every letter with the <strong>successive</strong> letter of the English alphabet, where &#39;z&#39; is replaced by &#39;a&#39;. For example, <code>&quot;abc&quot;</code> can be right-shifted to <code>&quot;bcd&quot; </code>or <code>&quot;xyz&quot;</code> can be right-shifted to <code>&quot;yza&quot;</code>.</li> <li><strong>Left shift</strong>: Replace every letter with the <strong>preceding</strong> letter of the English alphabet, where &#39;a&#39; is replaced by &#39;z&#39;. For example, <code>&quot;bcd&quot;</code> can be left-shifted to <code>&quot;abc&quot;<font face="Times New Roman"> or </font></code><code>&quot;yza&quot;</code> can be left-shifted to <code>&quot;xyz&quot;</code>.</li> </ul> <p>We can keep shifting the string in both directions to form an <strong>endless</strong> <strong>shifting sequence</strong>.</p> <ul> <li>For example, shift <code>&quot;abc&quot;</code> to form the sequence: <code>... &lt;-&gt; &quot;abc&quot; &lt;-&gt; &quot;bcd&quot; &lt;-&gt; ... &lt;-&gt; &quot;xyz&quot; &lt;-&gt; &quot;yza&quot; &lt;-&gt; ...</code>.<code> &lt;-&gt; &quot;zab&quot; &lt;-&gt; &quot;abc&quot; &lt;-&gt; ...</code></li> </ul> <p>You are given an array of strings <code>strings</code>, group together all <code>strings[i]</code> that belong to the same shifting sequence. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;abc&quot;,&quot;bcd&quot;,&quot;acef&quot;,&quot;xyz&quot;,&quot;az&quot;,&quot;ba&quot;,&quot;a&quot;,&quot;z&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;acef&quot;],[&quot;a&quot;,&quot;z&quot;],[&quot;abc&quot;,&quot;bcd&quot;,&quot;xyz&quot;],[&quot;az&quot;,&quot;ba&quot;]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strings.length &lt;= 200</code></li> <li><code>1 &lt;= strings[i].length &lt;= 50</code></li> <li><code>strings[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String
C++
class Solution { public: vector<vector<string>> groupStrings(vector<string>& strings) { unordered_map<string, vector<string>> g; for (auto& s : strings) { string t; int diff = s[0] - 'a'; for (int i = 0; i < s.size(); ++i) { char c = s[i] - diff; if (c < 'a') { c += 26; } t.push_back(c); } g[t].emplace_back(s); } vector<vector<string>> ans; for (auto& p : g) { ans.emplace_back(move(p.second)); } return ans; } };