id
int64
1
3.71k
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
399
Evaluate Division
Medium
<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p> <p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p> <p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p> <p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p> <p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]] <strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000] <strong>Explanation:</strong> Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em> queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em> return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined =&gt; -1.0</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]] <strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]] <strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= equations.length &lt;= 20</code></li> <li><code>equations[i].length == 2</code></li> <li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li> <li><code>values.length == equations.length</code></li> <li><code>0.0 &lt; values[i] &lt;= 20.0</code></li> <li><code>1 &lt;= queries.length &lt;= 20</code></li> <li><code>queries[i].length == 2</code></li> <li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li> <li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; String; Shortest Path
Go
func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 { p := make(map[string]string) w := make(map[string]float64) for _, e := range equations { a, b := e[0], e[1] p[a], p[b] = a, b w[a], w[b] = 1.0, 1.0 } var find func(x string) string find = func(x string) string { if p[x] != x { origin := p[x] p[x] = find(p[x]) w[x] *= w[origin] } return p[x] } for i, v := range values { a, b := equations[i][0], equations[i][1] pa, pb := find(a), find(b) if pa == pb { continue } p[pa] = pb w[pa] = w[b] * v / w[a] } var ans []float64 for _, e := range queries { c, d := e[0], e[1] if p[c] == "" || p[d] == "" || find(c) != find(d) { ans = append(ans, -1.0) } else { ans = append(ans, w[c]/w[d]) } } return ans }
399
Evaluate Division
Medium
<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p> <p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p> <p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p> <p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p> <p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]] <strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000] <strong>Explanation:</strong> Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em> queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em> return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined =&gt; -1.0</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]] <strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]] <strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= equations.length &lt;= 20</code></li> <li><code>equations[i].length == 2</code></li> <li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li> <li><code>values.length == equations.length</code></li> <li><code>0.0 &lt; values[i] &lt;= 20.0</code></li> <li><code>1 &lt;= queries.length &lt;= 20</code></li> <li><code>queries[i].length == 2</code></li> <li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li> <li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; String; Shortest Path
Java
class Solution { private Map<String, String> p; private Map<String, Double> w; public double[] calcEquation( List<List<String>> equations, double[] values, List<List<String>> queries) { int n = equations.size(); p = new HashMap<>(); w = new HashMap<>(); for (List<String> e : equations) { p.put(e.get(0), e.get(0)); p.put(e.get(1), e.get(1)); w.put(e.get(0), 1.0); w.put(e.get(1), 1.0); } for (int i = 0; i < n; ++i) { List<String> e = equations.get(i); String a = e.get(0), b = e.get(1); String pa = find(a), pb = find(b); if (Objects.equals(pa, pb)) { continue; } p.put(pa, pb); w.put(pa, w.get(b) * values[i] / w.get(a)); } int m = queries.size(); double[] ans = new double[m]; for (int i = 0; i < m; ++i) { String c = queries.get(i).get(0), d = queries.get(i).get(1); ans[i] = !p.containsKey(c) || !p.containsKey(d) || !Objects.equals(find(c), find(d)) ? -1.0 : w.get(c) / w.get(d); } return ans; } private String find(String x) { if (!Objects.equals(p.get(x), x)) { String origin = p.get(x); p.put(x, find(p.get(x))); w.put(x, w.get(x) * w.get(origin)); } return p.get(x); } }
399
Evaluate Division
Medium
<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p> <p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p> <p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p> <p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p> <p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]] <strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000] <strong>Explanation:</strong> Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em> queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em> return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined =&gt; -1.0</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]] <strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]] <strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= equations.length &lt;= 20</code></li> <li><code>equations[i].length == 2</code></li> <li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li> <li><code>values.length == equations.length</code></li> <li><code>0.0 &lt; values[i] &lt;= 20.0</code></li> <li><code>1 &lt;= queries.length &lt;= 20</code></li> <li><code>queries[i].length == 2</code></li> <li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li> <li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; String; Shortest Path
Python
class Solution: def calcEquation( self, equations: List[List[str]], values: List[float], queries: List[List[str]] ) -> List[float]: def find(x): if p[x] != x: origin = p[x] p[x] = find(p[x]) w[x] *= w[origin] return p[x] w = defaultdict(lambda: 1) p = defaultdict() for a, b in equations: p[a], p[b] = a, b for i, v in enumerate(values): a, b = equations[i] pa, pb = find(a), find(b) if pa == pb: continue p[pa] = pb w[pa] = w[b] * v / w[a] return [ -1 if c not in p or d not in p or find(c) != find(d) else w[c] / w[d] for c, d in queries ]
399
Evaluate Division
Medium
<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p> <p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p> <p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p> <p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p> <p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]] <strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000] <strong>Explanation:</strong> Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em> queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em> return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined =&gt; -1.0</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]] <strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]] <strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= equations.length &lt;= 20</code></li> <li><code>equations[i].length == 2</code></li> <li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li> <li><code>values.length == equations.length</code></li> <li><code>0.0 &lt; values[i] &lt;= 20.0</code></li> <li><code>1 &lt;= queries.length &lt;= 20</code></li> <li><code>queries[i].length == 2</code></li> <li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li> <li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; String; Shortest Path
Rust
use std::collections::HashMap; #[derive(Debug)] pub struct DSUNode { parent: String, weight: f64, } pub struct DisjointSetUnion { nodes: HashMap<String, DSUNode>, } impl DisjointSetUnion { pub fn new(equations: &Vec<Vec<String>>) -> DisjointSetUnion { let mut nodes = HashMap::new(); for equation in equations.iter() { for iter in equation.iter() { nodes.insert( iter.clone(), DSUNode { parent: iter.clone(), weight: 1.0, }, ); } } DisjointSetUnion { nodes } } pub fn find(&mut self, v: &String) -> String { let origin = self.nodes[v].parent.clone(); if origin == *v { return origin; } let root = self.find(&origin); self.nodes.get_mut(v).unwrap().parent = root.clone(); self.nodes.get_mut(v).unwrap().weight *= self.nodes[&origin].weight; root } pub fn union(&mut self, a: &String, b: &String, v: f64) { let pa = self.find(a); let pb = self.find(b); if pa == pb { return; } let (wa, wb) = (self.nodes[a].weight, self.nodes[b].weight); self.nodes.get_mut(&pa).unwrap().parent = pb; self.nodes.get_mut(&pa).unwrap().weight = (wb * v) / wa; } pub fn exist(&mut self, k: &String) -> bool { self.nodes.contains_key(k) } pub fn calc_value(&mut self, a: &String, b: &String) -> f64 { if !self.exist(a) || !self.exist(b) || self.find(a) != self.find(b) { -1.0 } else { let wa = self.nodes[a].weight; let wb = self.nodes[b].weight; wa / wb } } } impl Solution { pub fn calc_equation( equations: Vec<Vec<String>>, values: Vec<f64>, queries: Vec<Vec<String>>, ) -> Vec<f64> { let mut dsu = DisjointSetUnion::new(&equations); for (i, &v) in values.iter().enumerate() { let (a, b) = (&equations[i][0], &equations[i][1]); dsu.union(a, b, v); } let mut ans = vec![]; for querie in queries { let (c, d) = (&querie[0], &querie[1]); ans.push(dsu.calc_value(c, d)); } ans } }
399
Evaluate Division
Medium
<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p> <p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p> <p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p> <p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p> <p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]] <strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000] <strong>Explanation:</strong> Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em> queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em> return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined =&gt; -1.0</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]] <strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]] <strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= equations.length &lt;= 20</code></li> <li><code>equations[i].length == 2</code></li> <li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li> <li><code>values.length == equations.length</code></li> <li><code>0.0 &lt; values[i] &lt;= 20.0</code></li> <li><code>1 &lt;= queries.length &lt;= 20</code></li> <li><code>queries[i].length == 2</code></li> <li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li> <li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; String; Shortest Path
TypeScript
function calcEquation(equations: string[][], values: number[], queries: string[][]): number[] { const g: Record<string, [string, number][]> = {}; const ans = Array.from({ length: queries.length }, () => -1); for (let i = 0; i < equations.length; i++) { const [a, b] = equations[i]; (g[a] ??= []).push([b, values[i]]); (g[b] ??= []).push([a, 1 / values[i]]); } for (let i = 0; i < queries.length; i++) { const [c, d] = queries[i]; const vis = new Set<string>(); const q: [string, number][] = [[c, 1]]; if (!g[c] || !g[d]) continue; if (c === d) { ans[i] = 1; continue; } for (const [current, v] of q) { if (vis.has(current)) continue; vis.add(current); for (const [intermediate, multiplier] of g[current]) { if (vis.has(intermediate)) continue; if (intermediate === d) { ans[i] = v * multiplier; break; } q.push([intermediate, v * multiplier]); } if (ans[i] !== -1) break; } } return ans; }
400
Nth Digit
Medium
<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
C++
class Solution { public: int findNthDigit(int n) { int k = 1, cnt = 9; while (1ll * k * cnt < n) { n -= k * cnt; ++k; cnt *= 10; } int num = pow(10, k - 1) + (n - 1) / k; int idx = (n - 1) % k; return to_string(num)[idx] - '0'; } };
400
Nth Digit
Medium
<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
C#
public class Solution { public int FindNthDigit(int n) { int k = 1, cnt = 9; while ((long) k * cnt < n) { n -= k * cnt; ++k; cnt *= 10; } int num = (int) Math.Pow(10, k - 1) + (n - 1) / k; int idx = (n - 1) % k; return num.ToString()[idx] - '0'; } }
400
Nth Digit
Medium
<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Go
func findNthDigit(n int) int { k, cnt := 1, 9 for k*cnt < n { n -= k * cnt k++ cnt *= 10 } num := int(math.Pow10(k-1)) + (n-1)/k idx := (n - 1) % k return int(strconv.Itoa(num)[idx] - '0') }
400
Nth Digit
Medium
<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Java
class Solution { public int findNthDigit(int n) { int k = 1, cnt = 9; while ((long) k * cnt < n) { n -= k * cnt; ++k; cnt *= 10; } int num = (int) Math.pow(10, k - 1) + (n - 1) / k; int idx = (n - 1) % k; return String.valueOf(num).charAt(idx) - '0'; } }
400
Nth Digit
Medium
<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
JavaScript
/** * @param {number} n * @return {number} */ var findNthDigit = function (n) { let k = 1, cnt = 9; while (k * cnt < n) { n -= k * cnt; ++k; cnt *= 10; } const num = Math.pow(10, k - 1) + (n - 1) / k; const idx = (n - 1) % k; return num.toString()[idx]; };
400
Nth Digit
Medium
<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Python
class Solution: def findNthDigit(self, n: int) -> int: k, cnt = 1, 9 while k * cnt < n: n -= k * cnt k += 1 cnt *= 10 num = 10 ** (k - 1) + (n - 1) // k idx = (n - 1) % k return int(str(num)[idx])
401
Binary Watch
Easy
<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p> <ul> <li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0401.Binary%20Watch/images/binarywatch.jpg" style="width: 500px; height: 500px;" /></p> <p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p> <p>The hour must not contain a leading zero.</p> <ul> <li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li> </ul> <p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p> <ul> <li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> turnedOn = 1 <strong>Output:</strong> ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> turnedOn = 9 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= turnedOn &lt;= 10</code></li> </ul>
Bit Manipulation; Backtracking
C++
class Solution { public: vector<string> readBinaryWatch(int turnedOn) { vector<string> ans; for (int i = 0; i < 12; ++i) { for (int j = 0; j < 60; ++j) { if (__builtin_popcount(i) + __builtin_popcount(j) == turnedOn) { ans.push_back(to_string(i) + ":" + (j < 10 ? "0" : "") + to_string(j)); } } } return ans; } };
401
Binary Watch
Easy
<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p> <ul> <li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0401.Binary%20Watch/images/binarywatch.jpg" style="width: 500px; height: 500px;" /></p> <p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p> <p>The hour must not contain a leading zero.</p> <ul> <li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li> </ul> <p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p> <ul> <li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> turnedOn = 1 <strong>Output:</strong> ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> turnedOn = 9 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= turnedOn &lt;= 10</code></li> </ul>
Bit Manipulation; Backtracking
Go
func readBinaryWatch(turnedOn int) []string { var ans []string for i := 0; i < 12; i++ { for j := 0; j < 60; j++ { if bits.OnesCount(uint(i))+bits.OnesCount(uint(j)) == turnedOn { ans = append(ans, fmt.Sprintf("%d:%02d", i, j)) } } } return ans }
401
Binary Watch
Easy
<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p> <ul> <li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0401.Binary%20Watch/images/binarywatch.jpg" style="width: 500px; height: 500px;" /></p> <p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p> <p>The hour must not contain a leading zero.</p> <ul> <li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li> </ul> <p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p> <ul> <li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> turnedOn = 1 <strong>Output:</strong> ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> turnedOn = 9 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= turnedOn &lt;= 10</code></li> </ul>
Bit Manipulation; Backtracking
Java
class Solution { public List<String> readBinaryWatch(int turnedOn) { List<String> ans = new ArrayList<>(); for (int i = 0; i < 12; ++i) { for (int j = 0; j < 60; ++j) { if (Integer.bitCount(i) + Integer.bitCount(j) == turnedOn) { ans.add(String.format("%d:%02d", i, j)); } } } return ans; } }
401
Binary Watch
Easy
<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p> <ul> <li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0401.Binary%20Watch/images/binarywatch.jpg" style="width: 500px; height: 500px;" /></p> <p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p> <p>The hour must not contain a leading zero.</p> <ul> <li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li> </ul> <p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p> <ul> <li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> turnedOn = 1 <strong>Output:</strong> ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> turnedOn = 9 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= turnedOn &lt;= 10</code></li> </ul>
Bit Manipulation; Backtracking
Python
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: return [ '{:d}:{:02d}'.format(i, j) for i in range(12) for j in range(60) if (bin(i) + bin(j)).count('1') == turnedOn ]
401
Binary Watch
Easy
<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p> <ul> <li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0401.Binary%20Watch/images/binarywatch.jpg" style="width: 500px; height: 500px;" /></p> <p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p> <p>The hour must not contain a leading zero.</p> <ul> <li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li> </ul> <p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p> <ul> <li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> turnedOn = 1 <strong>Output:</strong> ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> turnedOn = 9 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= turnedOn &lt;= 10</code></li> </ul>
Bit Manipulation; Backtracking
Rust
impl Solution { fn create_time(bit_arr: &[bool; 10]) -> (i32, i32) { let mut h = 0; let mut m = 0; for i in 0..4 { h <<= 1; h |= if bit_arr[i] { 1 } else { 0 }; } for i in 4..10 { m <<= 1; m |= if bit_arr[i] { 1 } else { 0 }; } (h, m) } fn helper(res: &mut Vec<String>, bit_arr: &mut [bool; 10], i: usize, count: usize) { if i + count > 10 || count == 0 { return; } bit_arr[i] = true; if count == 1 { let (h, m) = Self::create_time(bit_arr); if h < 12 && m < 60 { if m < 10 { res.push(format!("{}:0{}", h, m)); } else { res.push(format!("{}:{}", h, m)); } } } Self::helper(res, bit_arr, i + 1, count - 1); bit_arr[i] = false; Self::helper(res, bit_arr, i + 1, count); } pub fn read_binary_watch(turned_on: i32) -> Vec<String> { if turned_on == 0 { return vec![String::from("0:00")]; } let mut res = vec![]; let mut bit_arr = [false; 10]; Self::helper(&mut res, &mut bit_arr, 0, turned_on as usize); res } }
401
Binary Watch
Easy
<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p> <ul> <li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0401.Binary%20Watch/images/binarywatch.jpg" style="width: 500px; height: 500px;" /></p> <p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p> <p>The hour must not contain a leading zero.</p> <ul> <li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li> </ul> <p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p> <ul> <li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> turnedOn = 1 <strong>Output:</strong> ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> turnedOn = 9 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= turnedOn &lt;= 10</code></li> </ul>
Bit Manipulation; Backtracking
TypeScript
function readBinaryWatch(turnedOn: number): string[] { if (turnedOn === 0) { return ['0:00']; } const n = 10; const res = []; const bitArr = new Array(10).fill(false); const createTime = () => { return [ bitArr.slice(0, 4).reduce((p, v) => (p << 1) | Number(v), 0), bitArr.slice(4).reduce((p, v) => (p << 1) | Number(v), 0), ]; }; const helper = (i: number, count: number) => { if (i + count > n || count === 0) { return; } bitArr[i] = true; if (count === 1) { const [h, m] = createTime(); if (h < 12 && m < 60) { res.push(`${h}:${m < 10 ? '0' + m : m}`); } } helper(i + 1, count - 1); bitArr[i] = false; helper(i + 1, count); }; helper(0, turnedOn); return res; }
402
Remove K Digits
Medium
<p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;1432219&quot;, k = 3 <strong>Output:</strong> &quot;1219&quot; <strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;10200&quot;, k = 1 <strong>Output:</strong> &quot;200&quot; <strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot;, k = 2 <strong>Output:</strong> &quot;0&quot; <strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not have any leading zeros except for the zero itself.</li> </ul>
Stack; Greedy; String; Monotonic Stack
C++
class Solution { public: string removeKdigits(string num, int k) { string stk; for (char& c : num) { while (k && stk.size() && stk.back() > c) { stk.pop_back(); --k; } stk += c; } while (k--) { stk.pop_back(); } int i = 0; for (; i < stk.size() && stk[i] == '0'; ++i) { } string ans = stk.substr(i); return ans == "" ? "0" : ans; } };
402
Remove K Digits
Medium
<p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;1432219&quot;, k = 3 <strong>Output:</strong> &quot;1219&quot; <strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;10200&quot;, k = 1 <strong>Output:</strong> &quot;200&quot; <strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot;, k = 2 <strong>Output:</strong> &quot;0&quot; <strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not have any leading zeros except for the zero itself.</li> </ul>
Stack; Greedy; String; Monotonic Stack
Go
func removeKdigits(num string, k int) string { stk, remain := make([]byte, 0), len(num)-k for i := 0; i < len(num); i++ { n := len(stk) for k > 0 && n > 0 && stk[n-1] > num[i] { stk = stk[:n-1] n, k = n-1, k-1 } stk = append(stk, num[i]) } for i := 0; i < len(stk) && i < remain; i++ { if stk[i] != '0' { return string(stk[i:remain]) } } return "0" }
402
Remove K Digits
Medium
<p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;1432219&quot;, k = 3 <strong>Output:</strong> &quot;1219&quot; <strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;10200&quot;, k = 1 <strong>Output:</strong> &quot;200&quot; <strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot;, k = 2 <strong>Output:</strong> &quot;0&quot; <strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not have any leading zeros except for the zero itself.</li> </ul>
Stack; Greedy; String; Monotonic Stack
Java
class Solution { public String removeKdigits(String num, int k) { StringBuilder stk = new StringBuilder(); for (char c : num.toCharArray()) { while (k > 0 && stk.length() > 0 && stk.charAt(stk.length() - 1) > c) { stk.deleteCharAt(stk.length() - 1); --k; } stk.append(c); } for (; k > 0; --k) { stk.deleteCharAt(stk.length() - 1); } int i = 0; for (; i < stk.length() && stk.charAt(i) == '0'; ++i) { } String ans = stk.substring(i); return "".equals(ans) ? "0" : ans; } }
402
Remove K Digits
Medium
<p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;1432219&quot;, k = 3 <strong>Output:</strong> &quot;1219&quot; <strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;10200&quot;, k = 1 <strong>Output:</strong> &quot;200&quot; <strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot;, k = 2 <strong>Output:</strong> &quot;0&quot; <strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not have any leading zeros except for the zero itself.</li> </ul>
Stack; Greedy; String; Monotonic Stack
Python
class Solution: def removeKdigits(self, num: str, k: int) -> str: stk = [] remain = len(num) - k for c in num: while k and stk and stk[-1] > c: stk.pop() k -= 1 stk.append(c) return ''.join(stk[:remain]).lstrip('0') or '0'
402
Remove K Digits
Medium
<p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;1432219&quot;, k = 3 <strong>Output:</strong> &quot;1219&quot; <strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;10200&quot;, k = 1 <strong>Output:</strong> &quot;200&quot; <strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot;, k = 2 <strong>Output:</strong> &quot;0&quot; <strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li> <li><code>num</code> consists of only digits.</li> <li><code>num</code> does not have any leading zeros except for the zero itself.</li> </ul>
Stack; Greedy; String; Monotonic Stack
TypeScript
function removeKdigits(num: string, k: number): string { const stk: string[] = []; for (const c of num) { while (k && stk.length > 0 && stk[stk.length - 1] > c) { stk.pop(); k--; } stk.push(c); } while (k--) { stk.pop(); } return stk.join('').replace(/^0*/g, '') || '0'; }
403
Frog Jump
Hard
<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p> <p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p> <p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,3,5,6,8,12,17] <strong>Output:</strong> true <strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,2,3,4,8,9,11] <strong>Output:</strong> false <strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= stones.length &lt;= 2000</code></li> <li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>stones[0] == 0</code></li> <li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li> </ul>
Array; Dynamic Programming
C++
class Solution { public: bool canCross(vector<int>& stones) { int n = stones.size(); int f[n][n]; memset(f, -1, sizeof(f)); unordered_map<int, int> pos; for (int i = 0; i < n; ++i) { pos[stones[i]] = i; } function<bool(int, int)> dfs = [&](int i, int k) -> bool { if (i == n - 1) { return true; } if (f[i][k] != -1) { return f[i][k]; } for (int j = k - 1; j <= k + 1; ++j) { if (j > 0 && pos.count(stones[i] + j) && dfs(pos[stones[i] + j], j)) { return f[i][k] = true; } } return f[i][k] = false; }; return dfs(0, 0); } };
403
Frog Jump
Hard
<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p> <p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p> <p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,3,5,6,8,12,17] <strong>Output:</strong> true <strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,2,3,4,8,9,11] <strong>Output:</strong> false <strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= stones.length &lt;= 2000</code></li> <li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>stones[0] == 0</code></li> <li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li> </ul>
Array; Dynamic Programming
Go
func canCross(stones []int) bool { n := len(stones) f := make([][]int, n) pos := map[int]int{} for i := range f { pos[stones[i]] = i f[i] = make([]int, n) for j := range f[i] { f[i][j] = -1 } } var dfs func(int, int) bool dfs = func(i, k int) bool { if i == n-1 { return true } if f[i][k] != -1 { return f[i][k] == 1 } for j := k - 1; j <= k+1; j++ { if j > 0 { if p, ok := pos[stones[i]+j]; ok { if dfs(p, j) { f[i][k] = 1 return true } } } } f[i][k] = 0 return false } return dfs(0, 0) }
403
Frog Jump
Hard
<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p> <p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p> <p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,3,5,6,8,12,17] <strong>Output:</strong> true <strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,2,3,4,8,9,11] <strong>Output:</strong> false <strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= stones.length &lt;= 2000</code></li> <li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>stones[0] == 0</code></li> <li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li> </ul>
Array; Dynamic Programming
Java
class Solution { private Boolean[][] f; private Map<Integer, Integer> pos = new HashMap<>(); private int[] stones; private int n; public boolean canCross(int[] stones) { n = stones.length; f = new Boolean[n][n]; this.stones = stones; for (int i = 0; i < n; ++i) { pos.put(stones[i], i); } return dfs(0, 0); } private boolean dfs(int i, int k) { if (i == n - 1) { return true; } if (f[i][k] != null) { return f[i][k]; } for (int j = k - 1; j <= k + 1; ++j) { if (j > 0) { int h = stones[i] + j; if (pos.containsKey(h) && dfs(pos.get(h), j)) { return f[i][k] = true; } } } return f[i][k] = false; } }
403
Frog Jump
Hard
<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p> <p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p> <p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,3,5,6,8,12,17] <strong>Output:</strong> true <strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,2,3,4,8,9,11] <strong>Output:</strong> false <strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= stones.length &lt;= 2000</code></li> <li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>stones[0] == 0</code></li> <li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li> </ul>
Array; Dynamic Programming
Python
class Solution: def canCross(self, stones: List[int]) -> bool: @cache def dfs(i, k): if i == n - 1: return True for j in range(k - 1, k + 2): if j > 0 and stones[i] + j in pos and dfs(pos[stones[i] + j], j): return True return False n = len(stones) pos = {s: i for i, s in enumerate(stones)} return dfs(0, 0)
403
Frog Jump
Hard
<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p> <p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p> <p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,3,5,6,8,12,17] <strong>Output:</strong> true <strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,2,3,4,8,9,11] <strong>Output:</strong> false <strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= stones.length &lt;= 2000</code></li> <li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>stones[0] == 0</code></li> <li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li> </ul>
Array; Dynamic Programming
Rust
use std::collections::HashMap; impl Solution { #[allow(dead_code)] pub fn can_cross(stones: Vec<i32>) -> bool { let n = stones.len(); let mut record = vec![vec![-1; n]; n]; let mut pos = HashMap::new(); for (i, &s) in stones.iter().enumerate() { pos.insert(s, i); } Self::dfs(&mut record, 0, 0, n, &pos, &stones) } #[allow(dead_code)] fn dfs( record: &mut Vec<Vec<i32>>, i: usize, k: usize, n: usize, pos: &HashMap<i32, usize>, stones: &Vec<i32>, ) -> bool { if i == n - 1 { return true; } if record[i][k] != -1 { return record[i][k] == 1; } let k = k as i32; for j in k - 1..=k + 1 { if j > 0 && pos.contains_key(&(stones[i] + j)) && Self::dfs(record, pos[&(stones[i] + j)], j as usize, n, pos, stones) { record[i][k as usize] = 1; return true; } } record[i][k as usize] = 0; false } }
403
Frog Jump
Hard
<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p> <p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p> <p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,3,5,6,8,12,17] <strong>Output:</strong> true <strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stones = [0,1,2,3,4,8,9,11] <strong>Output:</strong> false <strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= stones.length &lt;= 2000</code></li> <li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>stones[0] == 0</code></li> <li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li> </ul>
Array; Dynamic Programming
TypeScript
function canCross(stones: number[]): boolean { const n = stones.length; const pos: Map<number, number> = new Map(); for (let i = 0; i < n; ++i) { pos.set(stones[i], i); } const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); const dfs = (i: number, k: number): boolean => { if (i === n - 1) { return true; } if (f[i][k] !== -1) { return f[i][k] === 1; } for (let j = k - 1; j <= k + 1; ++j) { if (j > 0 && pos.has(stones[i] + j)) { if (dfs(pos.get(stones[i] + j)!, j)) { f[i][k] = 1; return true; } } } f[i][k] = 0; return false; }; return dfs(0, 0); }
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int sumOfLeftLeaves(struct TreeNode* root) { if (!root) { return 0; } int ans = sumOfLeftLeaves(root->right); if (root->left) { if (!root->left->left && !root->left->right) { ans += root->left->val; } else { ans += sumOfLeftLeaves(root->left); } } return ans; }
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if (!root) { return 0; } int ans = sumOfLeftLeaves(root->right); if (root->left) { if (!root->left->left && !root->left->right) { ans += root->left->val; } else { ans += sumOfLeftLeaves(root->left); } } return ans; } };
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func sumOfLeftLeaves(root *TreeNode) int { if root == nil { return 0 } ans := sumOfLeftLeaves(root.Right) if root.Left != nil { if root.Left.Left == root.Left.Right { ans += root.Left.Val } else { ans += sumOfLeftLeaves(root.Left) } } return ans }
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null) { return 0; } int ans = sumOfLeftLeaves(root.right); if (root.left != null) { if (root.left.left == root.left.right) { ans += root.left.val; } else { ans += sumOfLeftLeaves(root.left); } } return ans; } }
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: if root is None: return 0 ans = self.sumOfLeftLeaves(root.right) if root.left: if root.left.left == root.left.right: ans += root.left.val else: ans += self.sumOfLeftLeaves(root.left) return ans
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, is_left: bool) -> i32 { if root.is_none() { return 0; } let node = root.as_ref().unwrap().borrow(); let left = &node.left; let right = &node.right; if left.is_none() && right.is_none() { if is_left { return node.val; } return 0; } Self::dfs(left, true) + Self::dfs(right, false) } pub fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { Self::dfs(&root, false) } }
404
Sum of Left Leaves
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p> <p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0404.Sum%20of%20Left%20Leaves/images/leftsum-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 24 <strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-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 sumOfLeftLeaves(root: TreeNode | null): number { if (!root) { return 0; } let ans = sumOfLeftLeaves(root.right); if (root.left) { if (root.left.left === root.left.right) { ans += root.left.val; } else { ans += sumOfLeftLeaves(root.left); } } return ans; }
405
Convert a Number to Hexadecimal
Easy
<p>Given a 32-bit integer <code>num</code>, return <em>a string representing its hexadecimal representation</em>. For negative integers, <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">two&rsquo;s complement</a> method is used.</p> <p>All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.</p> <p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in library method to directly solve this problem.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 26 <strong>Output:</strong> "1a" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -1 <strong>Output:</strong> "ffffffff" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Math; String
C++
class Solution { public: string toHex(int num) { if (num == 0) return "0"; string s = ""; for (int i = 7; i >= 0; --i) { int x = (num >> (4 * i)) & 0xf; if (s.size() > 0 || x != 0) { char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); s += c; } } return s; } };
405
Convert a Number to Hexadecimal
Easy
<p>Given a 32-bit integer <code>num</code>, return <em>a string representing its hexadecimal representation</em>. For negative integers, <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">two&rsquo;s complement</a> method is used.</p> <p>All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.</p> <p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in library method to directly solve this problem.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 26 <strong>Output:</strong> "1a" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -1 <strong>Output:</strong> "ffffffff" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Math; String
Go
func toHex(num int) string { if num == 0 { return "0" } sb := &strings.Builder{} for i := 7; i >= 0; i-- { x := num >> (4 * i) & 0xf if x > 0 || sb.Len() > 0 { var c byte if x < 10 { c = '0' + byte(x) } else { c = 'a' + byte(x-10) } sb.WriteByte(c) } } return sb.String() }
405
Convert a Number to Hexadecimal
Easy
<p>Given a 32-bit integer <code>num</code>, return <em>a string representing its hexadecimal representation</em>. For negative integers, <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">two&rsquo;s complement</a> method is used.</p> <p>All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.</p> <p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in library method to directly solve this problem.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 26 <strong>Output:</strong> "1a" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -1 <strong>Output:</strong> "ffffffff" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Math; String
Java
class Solution { public String toHex(int num) { if (num == 0) { return "0"; } StringBuilder sb = new StringBuilder(); while (num != 0) { int x = num & 15; if (x < 10) { sb.append(x); } else { sb.append((char) (x - 10 + 'a')); } num >>>= 4; } return sb.reverse().toString(); } }
405
Convert a Number to Hexadecimal
Easy
<p>Given a 32-bit integer <code>num</code>, return <em>a string representing its hexadecimal representation</em>. For negative integers, <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">two&rsquo;s complement</a> method is used.</p> <p>All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.</p> <p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in library method to directly solve this problem.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 26 <strong>Output:</strong> "1a" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -1 <strong>Output:</strong> "ffffffff" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Math; String
Python
class Solution: def toHex(self, num: int) -> str: if num == 0: return '0' chars = '0123456789abcdef' s = [] for i in range(7, -1, -1): x = (num >> (4 * i)) & 0xF if s or x != 0: s.append(chars[x]) return ''.join(s)
406
Queue Reconstruction by Height
Medium
<p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p> <p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] <strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] <strong>Explanation:</strong> Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] <strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= people.length &lt;= 2000</code></li> <li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li> <li>It is guaranteed that the queue can be reconstructed.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Sorting
C++
class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(), people.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); }); vector<vector<int>> ans; for (const vector<int>& p : people) ans.insert(ans.begin() + p[1], p); return ans; } };
406
Queue Reconstruction by Height
Medium
<p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p> <p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] <strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] <strong>Explanation:</strong> Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] <strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= people.length &lt;= 2000</code></li> <li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li> <li>It is guaranteed that the queue can be reconstructed.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Sorting
Go
func reconstructQueue(people [][]int) [][]int { sort.Slice(people, func(i, j int) bool { a, b := people[i], people[j] return a[0] > b[0] || a[0] == b[0] && a[1] < b[1] }) var ans [][]int for _, p := range people { i := p[1] ans = append(ans[:i], append([][]int{p}, ans[i:]...)...) } return ans }
406
Queue Reconstruction by Height
Medium
<p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p> <p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] <strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] <strong>Explanation:</strong> Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] <strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= people.length &lt;= 2000</code></li> <li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li> <li>It is guaranteed that the queue can be reconstructed.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Sorting
Java
class Solution { public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); List<int[]> ans = new ArrayList<>(people.length); for (int[] p : people) { ans.add(p[1], p); } return ans.toArray(new int[ans.size()][]); } }
406
Queue Reconstruction by Height
Medium
<p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p> <p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] <strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] <strong>Explanation:</strong> Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] <strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= people.length &lt;= 2000</code></li> <li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li> <li>It is guaranteed that the queue can be reconstructed.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Sorting
Python
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda x: (-x[0], x[1])) ans = [] for p in people: ans.insert(p[1], p) return ans
407
Trapping Rain Water II
Hard
<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</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/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap1-3d.jpg" style="width: 361px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap2-3d.jpg" style="width: 401px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heightMap.length</code></li> <li><code>n == heightMap[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
C++
class Solution { public: int trapRainWater(vector<vector<int>>& heightMap) { using tii = tuple<int, int, int>; priority_queue<tii, vector<tii>, greater<tii>> pq; int m = heightMap.size(), n = heightMap[0].size(); bool vis[m][n]; memset(vis, 0, sizeof vis); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { pq.emplace(heightMap[i][j], i, j); vis[i][j] = true; } } } int ans = 0; int dirs[5] = {-1, 0, 1, 0, -1}; while (!pq.empty()) { auto [h, i, j] = pq.top(); pq.pop(); for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) { ans += max(0, h - heightMap[x][y]); vis[x][y] = true; pq.emplace(max(heightMap[x][y], h), x, y); } } } return ans; } };
407
Trapping Rain Water II
Hard
<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</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/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap1-3d.jpg" style="width: 361px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap2-3d.jpg" style="width: 401px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heightMap.length</code></li> <li><code>n == heightMap[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
Go
func trapRainWater(heightMap [][]int) (ans int) { m, n := len(heightMap), len(heightMap[0]) pq := hp{} vis := make([][]bool, m) for i, row := range heightMap { vis[i] = make([]bool, n) for j, v := range row { if i == 0 || i == m-1 || j == 0 || j == n-1 { heap.Push(&pq, tuple{v, i, j}) vis[i][j] = true } } } dirs := []int{-1, 0, 1, 0, -1} for len(pq) > 0 { p := heap.Pop(&pq).(tuple) for k := 0; k < 4; k++ { x, y := p.i+dirs[k], p.j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] { ans += max(0, p.v-heightMap[x][y]) vis[x][y] = true heap.Push(&pq, tuple{max(p.v, heightMap[x][y]), x, y}) } } } return } type tuple struct{ v, i, j int } type hp []tuple func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].v < h[j].v } 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.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
407
Trapping Rain Water II
Hard
<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</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/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap1-3d.jpg" style="width: 361px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap2-3d.jpg" style="width: 401px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heightMap.length</code></li> <li><code>n == heightMap[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
Java
class Solution { public int trapRainWater(int[][] heightMap) { int m = heightMap.length, n = heightMap[0].length; boolean[][] vis = new boolean[m][n]; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { pq.offer(new int[] {heightMap[i][j], i, j}); vis[i][j] = true; } } } int ans = 0; int[] dirs = {-1, 0, 1, 0, -1}; while (!pq.isEmpty()) { var p = pq.poll(); for (int k = 0; k < 4; ++k) { int x = p[1] + dirs[k], y = p[2] + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) { ans += Math.max(0, p[0] - heightMap[x][y]); vis[x][y] = true; pq.offer(new int[] {Math.max(p[0], heightMap[x][y]), x, y}); } } } return ans; } }
407
Trapping Rain Water II
Hard
<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</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/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap1-3d.jpg" style="width: 361px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap2-3d.jpg" style="width: 401px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heightMap.length</code></li> <li><code>n == heightMap[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
Python
class Solution: def trapRainWater(self, heightMap: List[List[int]]) -> int: m, n = len(heightMap), len(heightMap[0]) vis = [[False] * n for _ in range(m)] pq = [] for i in range(m): for j in range(n): if i == 0 or i == m - 1 or j == 0 or j == n - 1: heappush(pq, (heightMap[i][j], i, j)) vis[i][j] = True ans = 0 dirs = (-1, 0, 1, 0, -1) while pq: h, i, j = heappop(pq) for a, b in pairwise(dirs): x, y = i + a, j + b if x >= 0 and x < m and y >= 0 and y < n and not vis[x][y]: ans += max(0, h - heightMap[x][y]) vis[x][y] = True heappush(pq, (max(h, heightMap[x][y]), x, y)) return ans
407
Trapping Rain Water II
Hard
<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</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/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap1-3d.jpg" style="width: 361px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0407.Trapping%20Rain%20Water%20II/images/trap2-3d.jpg" style="width: 401px; height: 321px;" /> <pre> <strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heightMap.length</code></li> <li><code>n == heightMap[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
TypeScript
function trapRainWater(heightMap: number[][]): number { const m = heightMap.length; const n = heightMap[0].length; const vis: boolean[][] = Array.from({ length: m }, () => new Array(n).fill(false)); const pq = new MinPriorityQueue<[number, number, number]>({ compare: (a, b) => a[0] - b[0], }); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (i === 0 || i === m - 1 || j === 0 || j === n - 1) { pq.enqueue([heightMap[i][j], i, j]); vis[i][j] = true; } } } let ans = 0; const dirs = [-1, 0, 1, 0, -1]; while (!pq.isEmpty()) { const [h, i, j] = pq.dequeue(); for (let k = 0; k < 4; ++k) { const x = i + dirs[k]; const y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) { ans += Math.max(0, h - heightMap[x][y]); vis[x][y] = true; pq.enqueue([Math.max(h, heightMap[x][y]), x, y]); } } } return ans; }
408
Valid Word Abbreviation
Easy
<p>A string can be <strong>abbreviated</strong> by replacing any number of <strong>non-adjacent</strong>, <strong>non-empty</strong> substrings with their lengths. The lengths <strong>should not</strong> have leading zeros.</p> <p>For example, a string such as <code>&quot;substitution&quot;</code> could be abbreviated as (but not limited to):</p> <ul> <li><code>&quot;s10n&quot;</code> (<code>&quot;s <u>ubstitutio</u> n&quot;</code>)</li> <li><code>&quot;sub4u4&quot;</code> (<code>&quot;sub <u>stit</u> u <u>tion</u>&quot;</code>)</li> <li><code>&quot;12&quot;</code> (<code>&quot;<u>substitution</u>&quot;</code>)</li> <li><code>&quot;su3i1u2on&quot;</code> (<code>&quot;su <u>bst</u> i <u>t</u> u <u>ti</u> on&quot;</code>)</li> <li><code>&quot;substitution&quot;</code> (no substrings replaced)</li> </ul> <p>The following are <strong>not valid</strong> abbreviations:</p> <ul> <li><code>&quot;s55n&quot;</code> (<code>&quot;s <u>ubsti</u> <u>tutio</u> n&quot;</code>, the replaced substrings are adjacent)</li> <li><code>&quot;s010n&quot;</code> (has leading zeros)</li> <li><code>&quot;s0ubstitution&quot;</code> (replaces an empty substring)</li> </ul> <p>Given a string <code>word</code> and an abbreviation <code>abbr</code>, return <em>whether the string <strong>matches</strong> the given abbreviation</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;internationalization&quot;, abbr = &quot;i12iz4n&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The word &quot;internationalization&quot; can be abbreviated as &quot;i12iz4n&quot; (&quot;i <u>nternational</u> iz <u>atio</u> n&quot;). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;apple&quot;, abbr = &quot;a2e&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The word &quot;apple&quot; cannot be abbreviated as &quot;a2e&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= abbr.length &lt;= 10</code></li> <li><code>abbr</code> consists of lowercase English letters and digits.</li> <li>All the integers in <code>abbr</code> will fit in a 32-bit integer.</li> </ul>
Two Pointers; String
C++
class Solution { public: bool validWordAbbreviation(string word, string abbr) { int m = word.size(), n = abbr.size(); int i = 0, j = 0, x = 0; for (; i < m && j < n; ++j) { if (isdigit(abbr[j])) { if (abbr[j] == '0' && x == 0) { return false; } x = x * 10 + (abbr[j] - '0'); } else { i += x; x = 0; if (i >= m || word[i] != abbr[j]) { return false; } ++i; } } return i + x == m && j == n; } };
408
Valid Word Abbreviation
Easy
<p>A string can be <strong>abbreviated</strong> by replacing any number of <strong>non-adjacent</strong>, <strong>non-empty</strong> substrings with their lengths. The lengths <strong>should not</strong> have leading zeros.</p> <p>For example, a string such as <code>&quot;substitution&quot;</code> could be abbreviated as (but not limited to):</p> <ul> <li><code>&quot;s10n&quot;</code> (<code>&quot;s <u>ubstitutio</u> n&quot;</code>)</li> <li><code>&quot;sub4u4&quot;</code> (<code>&quot;sub <u>stit</u> u <u>tion</u>&quot;</code>)</li> <li><code>&quot;12&quot;</code> (<code>&quot;<u>substitution</u>&quot;</code>)</li> <li><code>&quot;su3i1u2on&quot;</code> (<code>&quot;su <u>bst</u> i <u>t</u> u <u>ti</u> on&quot;</code>)</li> <li><code>&quot;substitution&quot;</code> (no substrings replaced)</li> </ul> <p>The following are <strong>not valid</strong> abbreviations:</p> <ul> <li><code>&quot;s55n&quot;</code> (<code>&quot;s <u>ubsti</u> <u>tutio</u> n&quot;</code>, the replaced substrings are adjacent)</li> <li><code>&quot;s010n&quot;</code> (has leading zeros)</li> <li><code>&quot;s0ubstitution&quot;</code> (replaces an empty substring)</li> </ul> <p>Given a string <code>word</code> and an abbreviation <code>abbr</code>, return <em>whether the string <strong>matches</strong> the given abbreviation</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;internationalization&quot;, abbr = &quot;i12iz4n&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The word &quot;internationalization&quot; can be abbreviated as &quot;i12iz4n&quot; (&quot;i <u>nternational</u> iz <u>atio</u> n&quot;). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;apple&quot;, abbr = &quot;a2e&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The word &quot;apple&quot; cannot be abbreviated as &quot;a2e&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= abbr.length &lt;= 10</code></li> <li><code>abbr</code> consists of lowercase English letters and digits.</li> <li>All the integers in <code>abbr</code> will fit in a 32-bit integer.</li> </ul>
Two Pointers; String
Go
func validWordAbbreviation(word string, abbr string) bool { m, n := len(word), len(abbr) i, j, x := 0, 0, 0 for ; i < m && j < n; j++ { if abbr[j] >= '0' && abbr[j] <= '9' { if x == 0 && abbr[j] == '0' { return false } x = x*10 + int(abbr[j]-'0') } else { i += x x = 0 if i >= m || word[i] != abbr[j] { return false } i++ } } return i+x == m && j == n }
408
Valid Word Abbreviation
Easy
<p>A string can be <strong>abbreviated</strong> by replacing any number of <strong>non-adjacent</strong>, <strong>non-empty</strong> substrings with their lengths. The lengths <strong>should not</strong> have leading zeros.</p> <p>For example, a string such as <code>&quot;substitution&quot;</code> could be abbreviated as (but not limited to):</p> <ul> <li><code>&quot;s10n&quot;</code> (<code>&quot;s <u>ubstitutio</u> n&quot;</code>)</li> <li><code>&quot;sub4u4&quot;</code> (<code>&quot;sub <u>stit</u> u <u>tion</u>&quot;</code>)</li> <li><code>&quot;12&quot;</code> (<code>&quot;<u>substitution</u>&quot;</code>)</li> <li><code>&quot;su3i1u2on&quot;</code> (<code>&quot;su <u>bst</u> i <u>t</u> u <u>ti</u> on&quot;</code>)</li> <li><code>&quot;substitution&quot;</code> (no substrings replaced)</li> </ul> <p>The following are <strong>not valid</strong> abbreviations:</p> <ul> <li><code>&quot;s55n&quot;</code> (<code>&quot;s <u>ubsti</u> <u>tutio</u> n&quot;</code>, the replaced substrings are adjacent)</li> <li><code>&quot;s010n&quot;</code> (has leading zeros)</li> <li><code>&quot;s0ubstitution&quot;</code> (replaces an empty substring)</li> </ul> <p>Given a string <code>word</code> and an abbreviation <code>abbr</code>, return <em>whether the string <strong>matches</strong> the given abbreviation</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;internationalization&quot;, abbr = &quot;i12iz4n&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The word &quot;internationalization&quot; can be abbreviated as &quot;i12iz4n&quot; (&quot;i <u>nternational</u> iz <u>atio</u> n&quot;). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;apple&quot;, abbr = &quot;a2e&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The word &quot;apple&quot; cannot be abbreviated as &quot;a2e&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= abbr.length &lt;= 10</code></li> <li><code>abbr</code> consists of lowercase English letters and digits.</li> <li>All the integers in <code>abbr</code> will fit in a 32-bit integer.</li> </ul>
Two Pointers; String
Java
class Solution { public boolean validWordAbbreviation(String word, String abbr) { int m = word.length(), n = abbr.length(); int i = 0, j = 0, x = 0; for (; i < m && j < n; ++j) { char c = abbr.charAt(j); if (Character.isDigit(c)) { if (c == '0' && x == 0) { return false; } x = x * 10 + (c - '0'); } else { i += x; x = 0; if (i >= m || word.charAt(i) != c) { return false; } ++i; } } return i + x == m && j == n; } }
408
Valid Word Abbreviation
Easy
<p>A string can be <strong>abbreviated</strong> by replacing any number of <strong>non-adjacent</strong>, <strong>non-empty</strong> substrings with their lengths. The lengths <strong>should not</strong> have leading zeros.</p> <p>For example, a string such as <code>&quot;substitution&quot;</code> could be abbreviated as (but not limited to):</p> <ul> <li><code>&quot;s10n&quot;</code> (<code>&quot;s <u>ubstitutio</u> n&quot;</code>)</li> <li><code>&quot;sub4u4&quot;</code> (<code>&quot;sub <u>stit</u> u <u>tion</u>&quot;</code>)</li> <li><code>&quot;12&quot;</code> (<code>&quot;<u>substitution</u>&quot;</code>)</li> <li><code>&quot;su3i1u2on&quot;</code> (<code>&quot;su <u>bst</u> i <u>t</u> u <u>ti</u> on&quot;</code>)</li> <li><code>&quot;substitution&quot;</code> (no substrings replaced)</li> </ul> <p>The following are <strong>not valid</strong> abbreviations:</p> <ul> <li><code>&quot;s55n&quot;</code> (<code>&quot;s <u>ubsti</u> <u>tutio</u> n&quot;</code>, the replaced substrings are adjacent)</li> <li><code>&quot;s010n&quot;</code> (has leading zeros)</li> <li><code>&quot;s0ubstitution&quot;</code> (replaces an empty substring)</li> </ul> <p>Given a string <code>word</code> and an abbreviation <code>abbr</code>, return <em>whether the string <strong>matches</strong> the given abbreviation</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;internationalization&quot;, abbr = &quot;i12iz4n&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The word &quot;internationalization&quot; can be abbreviated as &quot;i12iz4n&quot; (&quot;i <u>nternational</u> iz <u>atio</u> n&quot;). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;apple&quot;, abbr = &quot;a2e&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The word &quot;apple&quot; cannot be abbreviated as &quot;a2e&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= abbr.length &lt;= 10</code></li> <li><code>abbr</code> consists of lowercase English letters and digits.</li> <li>All the integers in <code>abbr</code> will fit in a 32-bit integer.</li> </ul>
Two Pointers; String
Python
class Solution: def validWordAbbreviation(self, word: str, abbr: str) -> bool: m, n = len(word), len(abbr) i = j = x = 0 while i < m and j < n: if abbr[j].isdigit(): if abbr[j] == "0" and x == 0: return False x = x * 10 + int(abbr[j]) else: i += x x = 0 if i >= m or word[i] != abbr[j]: return False i += 1 j += 1 return i + x == m and j == n
408
Valid Word Abbreviation
Easy
<p>A string can be <strong>abbreviated</strong> by replacing any number of <strong>non-adjacent</strong>, <strong>non-empty</strong> substrings with their lengths. The lengths <strong>should not</strong> have leading zeros.</p> <p>For example, a string such as <code>&quot;substitution&quot;</code> could be abbreviated as (but not limited to):</p> <ul> <li><code>&quot;s10n&quot;</code> (<code>&quot;s <u>ubstitutio</u> n&quot;</code>)</li> <li><code>&quot;sub4u4&quot;</code> (<code>&quot;sub <u>stit</u> u <u>tion</u>&quot;</code>)</li> <li><code>&quot;12&quot;</code> (<code>&quot;<u>substitution</u>&quot;</code>)</li> <li><code>&quot;su3i1u2on&quot;</code> (<code>&quot;su <u>bst</u> i <u>t</u> u <u>ti</u> on&quot;</code>)</li> <li><code>&quot;substitution&quot;</code> (no substrings replaced)</li> </ul> <p>The following are <strong>not valid</strong> abbreviations:</p> <ul> <li><code>&quot;s55n&quot;</code> (<code>&quot;s <u>ubsti</u> <u>tutio</u> n&quot;</code>, the replaced substrings are adjacent)</li> <li><code>&quot;s010n&quot;</code> (has leading zeros)</li> <li><code>&quot;s0ubstitution&quot;</code> (replaces an empty substring)</li> </ul> <p>Given a string <code>word</code> and an abbreviation <code>abbr</code>, return <em>whether the string <strong>matches</strong> the given abbreviation</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;internationalization&quot;, abbr = &quot;i12iz4n&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The word &quot;internationalization&quot; can be abbreviated as &quot;i12iz4n&quot; (&quot;i <u>nternational</u> iz <u>atio</u> n&quot;). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;apple&quot;, abbr = &quot;a2e&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The word &quot;apple&quot; cannot be abbreviated as &quot;a2e&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= abbr.length &lt;= 10</code></li> <li><code>abbr</code> consists of lowercase English letters and digits.</li> <li>All the integers in <code>abbr</code> will fit in a 32-bit integer.</li> </ul>
Two Pointers; String
TypeScript
function validWordAbbreviation(word: string, abbr: string): boolean { const [m, n] = [word.length, abbr.length]; let [i, j, x] = [0, 0, 0]; for (; i < m && j < n; ++j) { if (abbr[j] >= '0' && abbr[j] <= '9') { if (abbr[j] === '0' && x === 0) { return false; } x = x * 10 + Number(abbr[j]); } else { i += x; x = 0; if (i >= m || word[i++] !== abbr[j]) { return false; } } } return i + x === m && j === n; }
409
Longest Palindrome
Easy
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p> <p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abccccdd&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;a&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2000</code></li> <li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li> </ul>
Greedy; Hash Table; String
C++
class Solution { public: int longestPalindrome(string s) { int cnt[128]{}; for (char c : s) { ++cnt[c]; } int ans = 0; for (int v : cnt) { ans += v / 2 * 2; } ans += ans < s.size(); return ans; } };
409
Longest Palindrome
Easy
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p> <p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abccccdd&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;a&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2000</code></li> <li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li> </ul>
Greedy; Hash Table; String
Go
func longestPalindrome(s string) (ans int) { cnt := [128]int{} for _, c := range s { cnt[c]++ } for _, v := range cnt { ans += v / 2 * 2 } if ans < len(s) { ans++ } return }
409
Longest Palindrome
Easy
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p> <p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abccccdd&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;a&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2000</code></li> <li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li> </ul>
Greedy; Hash Table; String
Java
class Solution { public int longestPalindrome(String s) { int[] cnt = new int[128]; int n = s.length(); for (int i = 0; i < n; ++i) { ++cnt[s.charAt(i)]; } int ans = 0; for (int v : cnt) { ans += v / 2 * 2; } ans += ans < n ? 1 : 0; return ans; } }
409
Longest Palindrome
Easy
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p> <p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abccccdd&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;a&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2000</code></li> <li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li> </ul>
Greedy; Hash Table; String
Python
class Solution: def longestPalindrome(self, s: str) -> int: cnt = Counter(s) ans = sum(v // 2 * 2 for v in cnt.values()) ans += int(ans < len(s)) return ans
409
Longest Palindrome
Easy
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p> <p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abccccdd&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;a&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2000</code></li> <li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li> </ul>
Greedy; Hash Table; String
Rust
use std::collections::HashMap; impl Solution { pub fn longest_palindrome(s: String) -> i32 { let mut cnt = HashMap::new(); for ch in s.chars() { *cnt.entry(ch).or_insert(0) += 1; } let mut ans = 0; for &v in cnt.values() { ans += (v / 2) * 2; } if ans < (s.len() as i32) { ans += 1; } ans } }
409
Longest Palindrome
Easy
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p> <p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abccccdd&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;a&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2000</code></li> <li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li> </ul>
Greedy; Hash Table; String
TypeScript
function longestPalindrome(s: string): number { const cnt: Record<string, number> = {}; for (const c of s) { cnt[c] = (cnt[c] || 0) + 1; } let ans = Object.values(cnt).reduce((acc, v) => acc + Math.floor(v / 2) * 2, 0); ans += ans < s.length ? 1 : 0; return ans; }
410
Split Array Largest Sum
Hard
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p> <p>Return <em>the minimized largest sum of the split</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,2,5,10,8], k = 2 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 2 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Prefix Sum
C++
class Solution { public: int splitArray(vector<int>& nums, int k) { int left = 0, right = 0; for (int& x : nums) { left = max(left, x); right += x; } auto check = [&](int mx) { int s = 1 << 30, cnt = 0; for (int& x : nums) { s += x; if (s > mx) { s = x; ++cnt; } } return cnt <= k; }; while (left < right) { int mid = (left + right) >> 1; if (check(mid)) { right = mid; } else { left = mid + 1; } } return left; } };
410
Split Array Largest Sum
Hard
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p> <p>Return <em>the minimized largest sum of the split</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,2,5,10,8], k = 2 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 2 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Prefix Sum
Go
func splitArray(nums []int, k int) int { left, right := 0, 0 for _, x := range nums { left = max(left, x) right += x } return left + sort.Search(right-left, func(mx int) bool { mx += left s, cnt := 1<<30, 0 for _, x := range nums { s += x if s > mx { s = x cnt++ } } return cnt <= k }) }
410
Split Array Largest Sum
Hard
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p> <p>Return <em>the minimized largest sum of the split</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,2,5,10,8], k = 2 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 2 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Prefix Sum
Java
class Solution { public int splitArray(int[] nums, int k) { int left = 0, right = 0; for (int x : nums) { left = Math.max(left, x); right += x; } while (left < right) { int mid = (left + right) >> 1; if (check(nums, mid, k)) { right = mid; } else { left = mid + 1; } } return left; } private boolean check(int[] nums, int mx, int k) { int s = 1 << 30, cnt = 0; for (int x : nums) { s += x; if (s > mx) { ++cnt; s = x; } } return cnt <= k; } }
410
Split Array Largest Sum
Hard
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p> <p>Return <em>the minimized largest sum of the split</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,2,5,10,8], k = 2 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 2 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Prefix Sum
JavaScript
/** * @param {number[]} nums * @param {number} k * @return {number} */ var splitArray = function (nums, k) { let l = Math.max(...nums); let r = nums.reduce((a, b) => a + b); const check = mx => { let [s, cnt] = [0, 0]; for (const x of nums) { s += x; if (s > mx) { s = x; if (++cnt === k) return false; } } return true; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; };
410
Split Array Largest Sum
Hard
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p> <p>Return <em>the minimized largest sum of the split</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,2,5,10,8], k = 2 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 2 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Prefix Sum
Python
class Solution: def splitArray(self, nums: List[int], k: int) -> int: def check(mx): s, cnt = inf, 0 for x in nums: s += x if s > mx: s = x cnt += 1 return cnt <= k left, right = max(nums), sum(nums) return left + bisect_left(range(left, right + 1), True, key=check)
410
Split Array Largest Sum
Hard
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p> <p>Return <em>the minimized largest sum of the split</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,2,5,10,8], k = 2 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 2 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Prefix Sum
TypeScript
function splitArray(nums: number[], k: number): number { let l = Math.max(...nums); let r = nums.reduce((a, b) => a + b); const check = (mx: number) => { let [s, cnt] = [0, 0]; for (const x of nums) { s += x; if (s > mx) { s = x; if (++cnt === k) return false; } } return true; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; }
412
Fizz Buzz
Easy
<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p> <ul> <li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li> <li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li> <li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li> <li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["1","2","Fizz"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> ["1","2","Fizz","4","Buzz"] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 15 <strong>Output:</strong> ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Math; String; Simulation
C++
class Solution { public: vector<string> fizzBuzz(int n) { vector<string> ans; for (int i = 1; i <= n; ++i) { string s = ""; if (i % 3 == 0) { s += "Fizz"; } if (i % 5 == 0) { s += "Buzz"; } if (s.empty()) { s = to_string(i); } ans.push_back(s); } return ans; } };
412
Fizz Buzz
Easy
<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p> <ul> <li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li> <li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li> <li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li> <li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["1","2","Fizz"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> ["1","2","Fizz","4","Buzz"] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 15 <strong>Output:</strong> ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Math; String; Simulation
Go
func fizzBuzz(n int) []string { ans := make([]string, 0, n) for i := 1; i < n+1; i++ { switch { case i%15 == 0: ans = append(ans, "FizzBuzz") case i%3 == 0: ans = append(ans, "Fizz") case i%5 == 0: ans = append(ans, "Buzz") default: ans = append(ans, strconv.Itoa(i)) } } return ans }
412
Fizz Buzz
Easy
<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p> <ul> <li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li> <li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li> <li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li> <li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["1","2","Fizz"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> ["1","2","Fizz","4","Buzz"] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 15 <strong>Output:</strong> ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Math; String; Simulation
Java
class Solution { public List<String> fizzBuzz(int n) { List<String> ans = new ArrayList<>(); for (int i = 1; i <= n; ++i) { String s = ""; if (i % 3 == 0) { s += "Fizz"; } if (i % 5 == 0) { s += "Buzz"; } if (s.length() == 0) { s += i; } ans.add(s); } return ans; } }
412
Fizz Buzz
Easy
<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p> <ul> <li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li> <li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li> <li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li> <li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["1","2","Fizz"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> ["1","2","Fizz","4","Buzz"] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 15 <strong>Output:</strong> ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Math; String; Simulation
JavaScript
/** * @param {number} n * @return {string[]} */ var fizzBuzz = function (n) { const ans = []; for (let i = 1; i <= n; ++i) { if (i % 15 === 0) { ans.push('FizzBuzz'); } else if (i % 3 === 0) { ans.push('Fizz'); } else if (i % 5 === 0) { ans.push('Buzz'); } else { ans.push(`${i}`); } } return ans; };
412
Fizz Buzz
Easy
<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p> <ul> <li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li> <li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li> <li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li> <li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["1","2","Fizz"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> ["1","2","Fizz","4","Buzz"] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 15 <strong>Output:</strong> ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Math; String; Simulation
PHP
class Solution { /** * @param Integer $n * @return String[] */ function fizzBuzz($n) { $ans = []; for ($i = 1; $i <= $n; ++$i) { $s = ''; if ($i % 3 == 0) { $s .= 'Fizz'; } if ($i % 5 == 0) { $s .= 'Buzz'; } if (strlen($s) == 0) { $s .= $i; } $ans[] = $s; } return $ans; } }
412
Fizz Buzz
Easy
<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p> <ul> <li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li> <li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li> <li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li> <li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["1","2","Fizz"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> ["1","2","Fizz","4","Buzz"] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 15 <strong>Output:</strong> ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Math; String; Simulation
Python
class Solution: def fizzBuzz(self, n: int) -> List[str]: ans = [] for i in range(1, n + 1): if i % 15 == 0: ans.append('FizzBuzz') elif i % 3 == 0: ans.append('Fizz') elif i % 5 == 0: ans.append('Buzz') else: ans.append(str(i)) return ans
413
Arithmetic Slices
Medium
<p>An integer array is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code>, and <code>[3,-1,-5,-9]</code> are arithmetic sequences.</li> </ul> <p>Given an integer array <code>nums</code>, return <em>the number of arithmetic <strong>subarrays</strong> of</em> <code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous subsequence of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Sliding Window
C++
class Solution { public: int numberOfArithmeticSlices(vector<int>& nums) { int ans = 0, cnt = 0; int d = 3000; for (int i = 0; i < nums.size() - 1; ++i) { if (nums[i + 1] - nums[i] == d) { ++cnt; } else { d = nums[i + 1] - nums[i]; cnt = 0; } ans += cnt; } return ans; } };
413
Arithmetic Slices
Medium
<p>An integer array is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code>, and <code>[3,-1,-5,-9]</code> are arithmetic sequences.</li> </ul> <p>Given an integer array <code>nums</code>, return <em>the number of arithmetic <strong>subarrays</strong> of</em> <code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous subsequence of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Sliding Window
Go
func numberOfArithmeticSlices(nums []int) (ans int) { cnt, d := 0, 3000 for i, b := range nums[1:] { a := nums[i] if b-a == d { cnt++ } else { d = b - a cnt = 0 } ans += cnt } return }
413
Arithmetic Slices
Medium
<p>An integer array is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code>, and <code>[3,-1,-5,-9]</code> are arithmetic sequences.</li> </ul> <p>Given an integer array <code>nums</code>, return <em>the number of arithmetic <strong>subarrays</strong> of</em> <code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous subsequence of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Sliding Window
Java
class Solution { public int numberOfArithmeticSlices(int[] nums) { int ans = 0, cnt = 0; int d = 3000; for (int i = 0; i < nums.length - 1; ++i) { if (nums[i + 1] - nums[i] == d) { ++cnt; } else { d = nums[i + 1] - nums[i]; cnt = 0; } ans += cnt; } return ans; } }
413
Arithmetic Slices
Medium
<p>An integer array is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code>, and <code>[3,-1,-5,-9]</code> are arithmetic sequences.</li> </ul> <p>Given an integer array <code>nums</code>, return <em>the number of arithmetic <strong>subarrays</strong> of</em> <code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous subsequence of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Sliding Window
Python
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: ans = cnt = 0 d = 3000 for a, b in pairwise(nums): if b - a == d: cnt += 1 else: d = b - a cnt = 0 ans += cnt return ans
413
Arithmetic Slices
Medium
<p>An integer array is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code>, and <code>[3,-1,-5,-9]</code> are arithmetic sequences.</li> </ul> <p>Given an integer array <code>nums</code>, return <em>the number of arithmetic <strong>subarrays</strong> of</em> <code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous subsequence of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Sliding Window
TypeScript
function numberOfArithmeticSlices(nums: number[]): number { let ans = 0; let cnt = 0; let d = 3000; for (let i = 0; i < nums.length - 1; ++i) { const a = nums[i]; const b = nums[i + 1]; if (b - a == d) { ++cnt; } else { d = b - a; cnt = 0; } ans += cnt; } return ans; }
414
Third Maximum Number
Easy
<p>Given an integer array <code>nums</code>, return <em>the <strong>third distinct maximum</strong> number in this array. If the third maximum does not exist, return the <strong>maximum</strong> number</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2 (both 2&#39;s are counted together since they have the same value). The third distinct maximum is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you find an <code>O(n)</code> solution?
Array; Sorting
C++
class Solution { public: int thirdMax(vector<int>& nums) { long m1 = LONG_MIN, m2 = LONG_MIN, m3 = LONG_MIN; for (int num : nums) { if (num == m1 || num == m2 || num == m3) continue; if (num > m1) { m3 = m2; m2 = m1; m1 = num; } else if (num > m2) { m3 = m2; m2 = num; } else if (num > m3) { m3 = num; } } return (int) (m3 != LONG_MIN ? m3 : m1); } };
414
Third Maximum Number
Easy
<p>Given an integer array <code>nums</code>, return <em>the <strong>third distinct maximum</strong> number in this array. If the third maximum does not exist, return the <strong>maximum</strong> number</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2 (both 2&#39;s are counted together since they have the same value). The third distinct maximum is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you find an <code>O(n)</code> solution?
Array; Sorting
Go
func thirdMax(nums []int) int { m1, m2, m3 := math.MinInt64, math.MinInt64, math.MinInt64 for _, num := range nums { if num == m1 || num == m2 || num == m3 { continue } if num > m1 { m3, m2, m1 = m2, m1, num } else if num > m2 { m3, m2 = m2, num } else if num > m3 { m3 = num } } if m3 != math.MinInt64 { return m3 } return m1 }
414
Third Maximum Number
Easy
<p>Given an integer array <code>nums</code>, return <em>the <strong>third distinct maximum</strong> number in this array. If the third maximum does not exist, return the <strong>maximum</strong> number</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2 (both 2&#39;s are counted together since they have the same value). The third distinct maximum is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you find an <code>O(n)</code> solution?
Array; Sorting
Java
class Solution { public int thirdMax(int[] nums) { long m1 = Long.MIN_VALUE; long m2 = Long.MIN_VALUE; long m3 = Long.MIN_VALUE; for (int num : nums) { if (num == m1 || num == m2 || num == m3) { continue; } if (num > m1) { m3 = m2; m2 = m1; m1 = num; } else if (num > m2) { m3 = m2; m2 = num; } else if (num > m3) { m3 = num; } } return (int) (m3 != Long.MIN_VALUE ? m3 : m1); } }
414
Third Maximum Number
Easy
<p>Given an integer array <code>nums</code>, return <em>the <strong>third distinct maximum</strong> number in this array. If the third maximum does not exist, return the <strong>maximum</strong> number</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The first distinct maximum is 3. The second distinct maximum is 2 (both 2&#39;s are counted together since they have the same value). The third distinct maximum is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you find an <code>O(n)</code> solution?
Array; Sorting
Python
class Solution: def thirdMax(self, nums: List[int]) -> int: m1 = m2 = m3 = -inf for num in nums: if num in [m1, m2, m3]: continue if num > m1: m3, m2, m1 = m2, m1, num elif num > m2: m3, m2 = m2, num elif num > m3: m3 = num return m3 if m3 != -inf else m1
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
C++
class Solution { public: string addStrings(string num1, string num2) { int i = num1.size() - 1, j = num2.size() - 1; string ans; for (int c = 0; i >= 0 || j >= 0 || c; --i, --j) { int a = i < 0 ? 0 : num1[i] - '0'; int b = j < 0 ? 0 : num2[j] - '0'; c += a + b; ans += to_string(c % 10); c /= 10; } reverse(ans.begin(), ans.end()); return ans; } string subStrings(string num1, string num2) { int m = num1.size(), n = num2.size(); bool neg = m < n || (m == n && num1 < num2); if (neg) { swap(num1, num2); } int i = num1.size() - 1, j = num2.size() - 1; string ans; for (int c = 0; i >= 0; --i, --j) { c = (num1[i] - '0') - c - (j < 0 ? 0 : num2[j] - '0'); ans += to_string((c + 10) % 10); c = c < 0 ? 1 : 0; } while (ans.size() > 1 && ans.back() == '0') { ans.pop_back(); } if (neg) { ans.push_back('-'); } reverse(ans.begin(), ans.end()); return ans; } };
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
Go
func addStrings(num1 string, num2 string) string { i, j := len(num1)-1, len(num2)-1 ans := []byte{} for c := 0; i >= 0 || j >= 0 || c > 0; i, j = i-1, j-1 { if i >= 0 { c += int(num1[i] - '0') } if j >= 0 { c += int(num2[j] - '0') } ans = append(ans, byte(c%10+'0')) c /= 10 } for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { ans[i], ans[j] = ans[j], ans[i] } return string(ans) } func subStrings(num1 string, num2 string) string { m, n := len(num1), len(num2) neg := m < n || (m == n && num1 < num2) if neg { num1, num2 = num2, num1 } i, j := len(num1)-1, len(num2)-1 ans := []byte{} for c := 0; i >= 0; i, j = i-1, j-1 { c = int(num1[i]-'0') - c if j >= 0 { c -= int(num2[j] - '0') } ans = append(ans, byte((c+10)%10+'0')) if c < 0 { c = 1 } else { c = 0 } } for len(ans) > 1 && ans[len(ans)-1] == '0' { ans = ans[:len(ans)-1] } if neg { ans = append(ans, '-') } for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { ans[i], ans[j] = ans[j], ans[i] } return string(ans) }
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
Java
class Solution { public String addStrings(String num1, String num2) { int i = num1.length() - 1, j = num2.length() - 1; StringBuilder ans = new StringBuilder(); for (int c = 0; i >= 0 || j >= 0 || c > 0; --i, --j) { int a = i < 0 ? 0 : num1.charAt(i) - '0'; int b = j < 0 ? 0 : num2.charAt(j) - '0'; c += a + b; ans.append(c % 10); c /= 10; } return ans.reverse().toString(); } public String subStrings(String num1, String num2) { int m = num1.length(), n = num2.length(); boolean neg = m < n || (m == n && num1.compareTo(num2) < 0); if (neg) { String t = num1; num1 = num2; num2 = t; } int i = num1.length() - 1, j = num2.length() - 1; StringBuilder ans = new StringBuilder(); for (int c = 0; i >= 0; --i, --j) { c = (num1.charAt(i) - '0') - c - (j < 0 ? 0 : num2.charAt(j) - '0'); ans.append((c + 10) % 10); c = c < 0 ? 1 : 0; } while (ans.length() > 1 && ans.charAt(ans.length() - 1) == '0') { ans.deleteCharAt(ans.length() - 1); } if (neg) { ans.append('-'); } return ans.reverse().toString(); } }
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
JavaScript
/** * @param {string} num1 * @param {string} num2 * @return {string} */ var addStrings = function (num1, num2) { let i = num1.length - 1; let j = num2.length - 1; const ans = []; for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) { c += i < 0 ? 0 : +num1[i]; c += j < 0 ? 0 : +num2[j]; ans.push(c % 10); c = Math.floor(c / 10); } return ans.reverse().join(''); }; /** * @param {string} num1 * @param {string} num2 * @return {string} */ var subStrings = function (num1, num2) { const m = num1.length; const n = num2.length; const neg = m < n || (m == n && num1 < num2); if (neg) { const t = num1; num1 = num2; num2 = t; } let i = num1.length - 1; let j = num2.length - 1; const ans = []; for (let c = 0; i >= 0; --i, --j) { c = +num1[i] - c; if (j >= 0) { c -= +num2[j]; } ans.push((c + 10) % 10); c = c < 0 ? 1 : 0; } while (ans.length > 1 && ans.at(-1) === 0) { ans.pop(); } return (neg ? '-' : '') + ans.reverse().join(''); };
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
Kotlin
class Solution { fun addStrings(num1: String, num2: String): String { val result = mutableListOf<Int>() val chars_1 = num1.toCharArray() val chars_2 = num2.toCharArray() var over = 0 var i = num1.length var j = num2.length while (i > 0 || j > 0 || over > 0) { val a = if (i > 0) chars_1[--i] - '0' else 0 val b = if (j > 0) chars_2[--j] - '0' else 0 val sum = a + b + over over = sum / 10 result.add(sum % 10) } return result.reversed().joinToString("") } }
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
Python
class Solution: def addStrings(self, num1: str, num2: str) -> str: i, j = len(num1) - 1, len(num2) - 1 ans = [] c = 0 while i >= 0 or j >= 0 or c: a = 0 if i < 0 else int(num1[i]) b = 0 if j < 0 else int(num2[j]) c, v = divmod(a + b + c, 10) ans.append(str(v)) i, j = i - 1, j - 1 return "".join(ans[::-1]) def subStrings(self, num1: str, num2: str) -> str: m, n = len(num1), len(num2) neg = m < n or (m == n and num1 < num2) if neg: num1, num2 = num2, num1 i, j = len(num1) - 1, len(num2) - 1 ans = [] c = 0 while i >= 0: c = int(num1[i]) - c - (0 if j < 0 else int(num2[j])) ans.append(str((c + 10) % 10)) c = 1 if c < 0 else 0 i, j = i - 1, j - 1 while len(ans) > 1 and ans[-1] == '0': ans.pop() if neg: ans.append('-') return ''.join(ans[::-1])
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
Rust
impl Solution { pub fn add_strings(num1: String, num2: String) -> String { let mut res = vec![]; let s1 = num1.as_bytes(); let s2 = num2.as_bytes(); let (mut i, mut j) = (s1.len(), s2.len()); let mut is_over = false; while i != 0 || j != 0 || is_over { let mut sum = if is_over { 1 } else { 0 }; if i != 0 { sum += (s1[i - 1] - b'0') as i32; i -= 1; } if j != 0 { sum += (s2[j - 1] - b'0') as i32; j -= 1; } is_over = sum >= 10; res.push((sum % 10).to_string()); } res.into_iter().rev().collect() } }
415
Add Strings
Easy
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p> <p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot; <strong>Output:</strong> &quot;134&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot; <strong>Output:</strong> &quot;533&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot; <strong>Output:</strong> &quot;0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li> <li><code>num1</code> and <code>num2</code> consist of only digits.</li> <li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li> </ul>
Math; String; Simulation
TypeScript
function addStrings(num1: string, num2: string): string { let i = num1.length - 1; let j = num2.length - 1; const ans: number[] = []; for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) { c += i < 0 ? 0 : +num1[i]; c += j < 0 ? 0 : +num2[j]; ans.push(c % 10); c = Math.floor(c / 10); } return ans.reverse().join(''); } function subStrings(num1: string, num2: string): string { const m = num1.length; const n = num2.length; const neg = m < n || (m == n && num1 < num2); if (neg) { const t = num1; num1 = num2; num2 = t; } let i = num1.length - 1; let j = num2.length - 1; const ans: number[] = []; for (let c = 0; i >= 0; --i, --j) { c = +num1[i] - c; if (j >= 0) { c -= +num2[j]; } ans.push((c + 10) % 10); c = c < 0 ? 1 : 0; } while (ans.length > 1 && ans.at(-1) === 0) { ans.pop(); } return (neg ? '-' : '') + ans.reverse().join(''); }
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: bool canPartition(vector<int>& nums) { int s = accumulate(nums.begin(), nums.end(), 0); if (s % 2 == 1) { return false; } int n = nums.size(); int m = s >> 1; bool f[n + 1][m + 1]; memset(f, false, sizeof(f)); f[0][0] = true; for (int i = 1; i <= n; ++i) { int x = nums[i - 1]; for (int j = 0; j <= m; ++j) { f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } return f[n][m]; } };
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Go
func canPartition(nums []int) bool { s := 0 for _, x := range nums { s += x } if s%2 == 1 { return false } n, m := len(nums), s>>1 f := make([][]bool, n+1) for i := range f { f[i] = make([]bool, m+1) } f[0][0] = true for i := 1; i <= n; i++ { x := nums[i-1] for j := 0; j <= m; j++ { f[i][j] = f[i-1][j] || (j >= x && f[i-1][j-x]) } } return f[n][m] }
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public boolean canPartition(int[] nums) { // int s = Arrays.stream(nums).sum(); int s = 0; for (int x : nums) { s += x; } if (s % 2 == 1) { return false; } int n = nums.length; int m = s >> 1; boolean[][] f = new boolean[n + 1][m + 1]; f[0][0] = true; for (int i = 1; i <= n; ++i) { int x = nums[i - 1]; for (int j = 0; j <= m; ++j) { f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } return f[n][m]; } }
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
JavaScript
/** * @param {number[]} nums * @return {boolean} */ var canPartition = function (nums) { const s = nums.reduce((a, b) => a + b, 0); if (s % 2 === 1) { return false; } const n = nums.length; const m = s >> 1; const f = Array.from({ length: n + 1 }, () => Array(m + 1).fill(false)); f[0][0] = true; for (let i = 1; i <= n; ++i) { const x = nums[i - 1]; for (let j = 0; j <= m; ++j) { f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } return f[n][m]; };
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def canPartition(self, nums: List[int]) -> bool: m, mod = divmod(sum(nums), 2) if mod: return False n = len(nums) f = [[False] * (m + 1) for _ in range(n + 1)] f[0][0] = True for i, x in enumerate(nums, 1): for j in range(m + 1): f[i][j] = f[i - 1][j] or (j >= x and f[i - 1][j - x]) return f[n][m]
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn can_partition(nums: Vec<i32>) -> bool { let s: i32 = nums.iter().sum(); if s % 2 != 0 { return false; } let m = (s / 2) as usize; let n = nums.len(); let mut f = vec![vec![false; m + 1]; n + 1]; f[0][0] = true; for i in 1..=n { let x = nums[i - 1] as usize; for j in 0..=m { f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } f[n][m] } }
416
Partition Equal Subset Sum
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,11,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,5] <strong>Output:</strong> false <strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Dynamic Programming
TypeScript
function canPartition(nums: number[]): boolean { const s = nums.reduce((a, b) => a + b, 0); if (s % 2 === 1) { return false; } const n = nums.length; const m = s >> 1; const f: boolean[][] = Array.from({ length: n + 1 }, () => Array(m + 1).fill(false)); f[0][0] = true; for (let i = 1; i <= n; ++i) { const x = nums[i - 1]; for (let j = 0; j <= m; ++j) { f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } } return f[n][m]; }
417
Pacific Atlantic Water Flow
Medium
<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p> <p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p> <p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p> <p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</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/0400-0499/0417.Pacific%20Atlantic%20Water%20Flow/images/waterflow-grid.jpg" style="width: 400px; height: 400px;" /> <pre> <strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] <strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] <strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -&gt; Pacific Ocean &nbsp; [0,4] -&gt; Atlantic Ocean [1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,3] -&gt; [1,4] -&gt; Atlantic Ocean [1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,4] -&gt; Atlantic Ocean [2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean &nbsp; [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean [3,0]: [3,0] -&gt; Pacific Ocean &nbsp; [3,0] -&gt; [4,0] -&gt; Atlantic Ocean [3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean &nbsp; [3,1] -&gt; [4,1] -&gt; Atlantic Ocean [4,0]: [4,0] -&gt; Pacific Ocean [4,0] -&gt; Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heights = [[1]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heights.length</code></li> <li><code>n == heights[r].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
C++
class Solution { public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) { int m = heights.size(), n = heights[0].size(); vector<vector<bool>> vis1(m, vector<bool>(n, false)), vis2(m, vector<bool>(n, false)); queue<pair<int, int>> q1, q2; vector<int> dirs = {-1, 0, 1, 0, -1}; for (int i = 0; i < m; ++i) { q1.emplace(i, 0); vis1[i][0] = true; q2.emplace(i, n - 1); vis2[i][n - 1] = true; } for (int j = 0; j < n; ++j) { q1.emplace(0, j); vis1[0][j] = true; q2.emplace(m - 1, j); vis2[m - 1][j] = true; } auto bfs = [&](queue<pair<int, int>>& q, vector<vector<bool>>& vis) { while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int k = 0; k < 4; ++k) { int nx = x + dirs[k], ny = y + dirs[k + 1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny] && heights[nx][ny] >= heights[x][y]) { vis[nx][ny] = true; q.emplace(nx, ny); } } } }; bfs(q1, vis1); bfs(q2, vis2); vector<vector<int>> ans; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (vis1[i][j] && vis2[i][j]) ans.push_back({i, j}); return ans; } };
417
Pacific Atlantic Water Flow
Medium
<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p> <p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p> <p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p> <p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</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/0400-0499/0417.Pacific%20Atlantic%20Water%20Flow/images/waterflow-grid.jpg" style="width: 400px; height: 400px;" /> <pre> <strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] <strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] <strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -&gt; Pacific Ocean &nbsp; [0,4] -&gt; Atlantic Ocean [1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,3] -&gt; [1,4] -&gt; Atlantic Ocean [1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,4] -&gt; Atlantic Ocean [2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean &nbsp; [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean [3,0]: [3,0] -&gt; Pacific Ocean &nbsp; [3,0] -&gt; [4,0] -&gt; Atlantic Ocean [3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean &nbsp; [3,1] -&gt; [4,1] -&gt; Atlantic Ocean [4,0]: [4,0] -&gt; Pacific Ocean [4,0] -&gt; Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heights = [[1]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heights.length</code></li> <li><code>n == heights[r].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Go
func pacificAtlantic(heights [][]int) [][]int { m, n := len(heights), len(heights[0]) vis1 := make([][]bool, m) vis2 := make([][]bool, m) for i := range vis1 { vis1[i] = make([]bool, n) vis2[i] = make([]bool, n) } q1, q2 := [][2]int{}, [][2]int{} dirs := [5]int{-1, 0, 1, 0, -1} for i := 0; i < m; i++ { q1 = append(q1, [2]int{i, 0}) vis1[i][0] = true q2 = append(q2, [2]int{i, n - 1}) vis2[i][n-1] = true } for j := 0; j < n; j++ { q1 = append(q1, [2]int{0, j}) vis1[0][j] = true q2 = append(q2, [2]int{m - 1, j}) vis2[m-1][j] = true } bfs := func(q [][2]int, vis [][]bool) { for len(q) > 0 { x, y := q[0][0], q[0][1] q = q[1:] for k := 0; k < 4; k++ { nx, ny := x+dirs[k], y+dirs[k+1] if nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny] && heights[nx][ny] >= heights[x][y] { vis[nx][ny] = true q = append(q, [2]int{nx, ny}) } } } } bfs(q1, vis1) bfs(q2, vis2) var ans [][]int for i := 0; i < m; i++ { for j := 0; j < n; j++ { if vis1[i][j] && vis2[i][j] { ans = append(ans, []int{i, j}) } } } return ans }
417
Pacific Atlantic Water Flow
Medium
<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p> <p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p> <p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p> <p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</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/0400-0499/0417.Pacific%20Atlantic%20Water%20Flow/images/waterflow-grid.jpg" style="width: 400px; height: 400px;" /> <pre> <strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] <strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] <strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -&gt; Pacific Ocean &nbsp; [0,4] -&gt; Atlantic Ocean [1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,3] -&gt; [1,4] -&gt; Atlantic Ocean [1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,4] -&gt; Atlantic Ocean [2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean &nbsp; [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean [3,0]: [3,0] -&gt; Pacific Ocean &nbsp; [3,0] -&gt; [4,0] -&gt; Atlantic Ocean [3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean &nbsp; [3,1] -&gt; [4,1] -&gt; Atlantic Ocean [4,0]: [4,0] -&gt; Pacific Ocean [4,0] -&gt; Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heights = [[1]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heights.length</code></li> <li><code>n == heights[r].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Java
class Solution { public List<List<Integer>> pacificAtlantic(int[][] heights) { int m = heights.length, n = heights[0].length; boolean[][] vis1 = new boolean[m][n]; boolean[][] vis2 = new boolean[m][n]; Deque<int[]> q1 = new ArrayDeque<>(); Deque<int[]> q2 = new ArrayDeque<>(); int[] dirs = {-1, 0, 1, 0, -1}; for (int i = 0; i < m; ++i) { q1.offer(new int[] {i, 0}); vis1[i][0] = true; q2.offer(new int[] {i, n - 1}); vis2[i][n - 1] = true; } for (int j = 0; j < n; ++j) { q1.offer(new int[] {0, j}); vis1[0][j] = true; q2.offer(new int[] {m - 1, j}); vis2[m - 1][j] = true; } BiConsumer<Deque<int[]>, boolean[][]> bfs = (q, vis) -> { while (!q.isEmpty()) { var cell = q.poll(); int x = cell[0], y = cell[1]; for (int k = 0; k < 4; ++k) { int nx = x + dirs[k], ny = y + dirs[k + 1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny] && heights[nx][ny] >= heights[x][y]) { vis[nx][ny] = true; q.offer(new int[] {nx, ny}); } } } }; bfs.accept(q1, vis1); bfs.accept(q2, vis2); List<List<Integer>> ans = new ArrayList<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (vis1[i][j] && vis2[i][j]) { ans.add(List.of(i, j)); } } } return ans; } }
417
Pacific Atlantic Water Flow
Medium
<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p> <p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p> <p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p> <p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</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/0400-0499/0417.Pacific%20Atlantic%20Water%20Flow/images/waterflow-grid.jpg" style="width: 400px; height: 400px;" /> <pre> <strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] <strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] <strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -&gt; Pacific Ocean &nbsp; [0,4] -&gt; Atlantic Ocean [1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,3] -&gt; [1,4] -&gt; Atlantic Ocean [1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,4] -&gt; Atlantic Ocean [2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean &nbsp; [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean [3,0]: [3,0] -&gt; Pacific Ocean &nbsp; [3,0] -&gt; [4,0] -&gt; Atlantic Ocean [3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean &nbsp; [3,1] -&gt; [4,1] -&gt; Atlantic Ocean [4,0]: [4,0] -&gt; Pacific Ocean [4,0] -&gt; Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heights = [[1]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heights.length</code></li> <li><code>n == heights[r].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Python
class Solution: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: def bfs(q: Deque[Tuple[int, int]], vis: List[List[bool]]) -> None: while q: x, y = q.popleft() for dx, dy in pairwise(dirs): nx, ny = x + dx, y + dy if ( 0 <= nx < m and 0 <= ny < n and not vis[nx][ny] and heights[nx][ny] >= heights[x][y] ): vis[nx][ny] = True q.append((nx, ny)) m, n = len(heights), len(heights[0]) vis1 = [[False] * n for _ in range(m)] vis2 = [[False] * n for _ in range(m)] q1: Deque[Tuple[int, int]] = deque() q2: Deque[Tuple[int, int]] = deque() dirs = (-1, 0, 1, 0, -1) for i in range(m): q1.append((i, 0)) vis1[i][0] = True q2.append((i, n - 1)) vis2[i][n - 1] = True for j in range(n): q1.append((0, j)) vis1[0][j] = True q2.append((m - 1, j)) vis2[m - 1][j] = True bfs(q1, vis1) bfs(q2, vis2) return [(i, j) for i in range(m) for j in range(n) if vis1[i][j] and vis2[i][j]]
417
Pacific Atlantic Water Flow
Medium
<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p> <p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p> <p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p> <p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</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/0400-0499/0417.Pacific%20Atlantic%20Water%20Flow/images/waterflow-grid.jpg" style="width: 400px; height: 400px;" /> <pre> <strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] <strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] <strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -&gt; Pacific Ocean &nbsp; [0,4] -&gt; Atlantic Ocean [1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,3] -&gt; [1,4] -&gt; Atlantic Ocean [1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,4] -&gt; Atlantic Ocean [2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean &nbsp; [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean [3,0]: [3,0] -&gt; Pacific Ocean &nbsp; [3,0] -&gt; [4,0] -&gt; Atlantic Ocean [3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean &nbsp; [3,1] -&gt; [4,1] -&gt; Atlantic Ocean [4,0]: [4,0] -&gt; Pacific Ocean [4,0] -&gt; Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heights = [[1]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heights.length</code></li> <li><code>n == heights[r].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Rust
use std::collections::VecDeque; impl Solution { pub fn pacific_atlantic(heights: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let (m, n) = (heights.len(), heights[0].len()); let mut vis1 = vec![vec![false; n]; m]; let mut vis2 = vec![vec![false; n]; m]; let mut q1 = VecDeque::new(); let mut q2 = VecDeque::new(); let dirs = [-1, 0, 1, 0, -1]; for i in 0..m { q1.push_back((i, 0)); vis1[i][0] = true; q2.push_back((i, n - 1)); vis2[i][n - 1] = true; } for j in 0..n { q1.push_back((0, j)); vis1[0][j] = true; q2.push_back((m - 1, j)); vis2[m - 1][j] = true; } let bfs = |q: &mut VecDeque<(usize, usize)>, vis: &mut Vec<Vec<bool>>| { while let Some((x, y)) = q.pop_front() { for k in 0..4 { let nx = x as i32 + dirs[k]; let ny = y as i32 + dirs[k + 1]; if nx >= 0 && nx < m as i32 && ny >= 0 && ny < n as i32 && !vis[nx as usize][ny as usize] && heights[nx as usize][ny as usize] >= heights[x][y] { vis[nx as usize][ny as usize] = true; q.push_back((nx as usize, ny as usize)); } } } }; bfs(&mut q1, &mut vis1); bfs(&mut q2, &mut vis2); let mut ans = vec![]; for i in 0..m { for j in 0..n { if vis1[i][j] && vis2[i][j] { ans.push(vec![i as i32, j as i32]); } } } ans } }