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
637
Average of Levels in Binary Tree
Easy
Given the <code>root</code> of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/images/avg1-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/images/avg2-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,15,7] <strong>Output:</strong> [3.00000,14.50000,11.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[]} */ var averageOfLevels = function (root) { const q = [root]; const ans = []; while (q.length) { const n = q.length; const nq = []; let s = 0; for (const { val, left, right } of q) { s += val; left && nq.push(left); right && nq.push(right); } ans.push(s / n); q.splice(0, q.length, ...nq); } return ans; };
637
Average of Levels in Binary Tree
Easy
Given the <code>root</code> of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/images/avg1-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/images/avg2-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,15,7] <strong>Output:</strong> [3.00000,14.50000,11.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</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 averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: q = deque([root]) ans = [] while q: s, n = 0, len(q) for _ in range(n): root = q.popleft() s += root.val if root.left: q.append(root.left) if root.right: q.append(root.right) ans.append(s / n) return ans
637
Average of Levels in Binary Tree
Easy
Given the <code>root</code> of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/images/avg1-tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/images/avg2-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,15,7] <strong>Output:</strong> [3.00000,14.50000,11.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</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::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> { let mut ans = vec![]; let mut q = VecDeque::new(); if let Some(root_node) = root { q.push_back(root_node); } while !q.is_empty() { let n = q.len(); let mut s: i64 = 0; for _ in 0..n { if let Some(node) = q.pop_front() { let node_borrow = node.borrow(); s += node_borrow.val as i64; if let Some(left) = node_borrow.left.clone() { q.push_back(left); } if let Some(right) = node_borrow.right.clone() { q.push_back(right); } } } ans.push((s as f64) / (n as f64)); } ans } }
638
Shopping Offers
Medium
<p>In LeetCode Store, there are <code>n</code> items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.</p> <p>You are given an integer array <code>price</code> where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> item, and an integer array <code>needs</code> where <code>needs[i]</code> is the number of pieces of the <code>i<sup>th</sup></code> item you want to buy.</p> <p>You are also given an array <code>special</code> where <code>special[i]</code> is of size <code>n + 1</code> where <code>special[i][j]</code> is the number of pieces of the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> offer and <code>special[i][n]</code> (i.e., the last integer in the array) is the price of the <code>i<sup>th</sup></code> offer.</p> <p>Return <em>the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers</em>. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] <strong>Output:</strong> 14 <strong>Explanation:</strong> There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] <strong>Output:</strong> 11 <strong>Explanation:</strong> The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == price.length == needs.length</code></li> <li><code>1 &lt;= n &lt;= 6</code></li> <li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li> <li><code>1 &lt;= special.length &lt;= 100</code></li> <li><code>special[i].length == n + 1</code></li> <li><code>0 &lt;= special[i][j] &lt;= 50</code></li> <li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li> </ul>
Bit Manipulation; Memoization; Array; Dynamic Programming; Backtracking; Bitmask
C++
class Solution { public: int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) { const int bits = 4; int n = needs.size(); unordered_map<int, int> f; int mask = 0; for (int i = 0; i < n; ++i) { mask |= needs[i] << (i * bits); } function<int(int)> dfs = [&](int cur) { if (f.contains(cur)) { return f[cur]; } int ans = 0; for (int i = 0; i < n; ++i) { ans += price[i] * ((cur >> (i * bits)) & 0xf); } for (const auto& offer : special) { int nxt = cur; bool ok = true; for (int j = 0; j < n; ++j) { if (((cur >> (j * bits)) & 0xf) < offer[j]) { ok = false; break; } nxt -= offer[j] << (j * bits); } if (ok) { ans = min(ans, offer[n] + dfs(nxt)); } } f[cur] = ans; return ans; }; return dfs(mask); } };
638
Shopping Offers
Medium
<p>In LeetCode Store, there are <code>n</code> items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.</p> <p>You are given an integer array <code>price</code> where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> item, and an integer array <code>needs</code> where <code>needs[i]</code> is the number of pieces of the <code>i<sup>th</sup></code> item you want to buy.</p> <p>You are also given an array <code>special</code> where <code>special[i]</code> is of size <code>n + 1</code> where <code>special[i][j]</code> is the number of pieces of the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> offer and <code>special[i][n]</code> (i.e., the last integer in the array) is the price of the <code>i<sup>th</sup></code> offer.</p> <p>Return <em>the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers</em>. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] <strong>Output:</strong> 14 <strong>Explanation:</strong> There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] <strong>Output:</strong> 11 <strong>Explanation:</strong> The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == price.length == needs.length</code></li> <li><code>1 &lt;= n &lt;= 6</code></li> <li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li> <li><code>1 &lt;= special.length &lt;= 100</code></li> <li><code>special[i].length == n + 1</code></li> <li><code>0 &lt;= special[i][j] &lt;= 50</code></li> <li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li> </ul>
Bit Manipulation; Memoization; Array; Dynamic Programming; Backtracking; Bitmask
Go
func shoppingOffers(price []int, special [][]int, needs []int) int { const bits = 4 n := len(needs) f := make(map[int]int) mask := 0 for i, need := range needs { mask |= need << (i * bits) } var dfs func(int) int dfs = func(cur int) int { if v, ok := f[cur]; ok { return v } ans := 0 for i := 0; i < n; i++ { ans += price[i] * ((cur >> (i * bits)) & 0xf) } for _, offer := range special { nxt := cur ok := true for j := 0; j < n; j++ { if ((cur >> (j * bits)) & 0xf) < offer[j] { ok = false break } nxt -= offer[j] << (j * bits) } if ok { ans = min(ans, offer[n]+dfs(nxt)) } } f[cur] = ans return ans } return dfs(mask) }
638
Shopping Offers
Medium
<p>In LeetCode Store, there are <code>n</code> items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.</p> <p>You are given an integer array <code>price</code> where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> item, and an integer array <code>needs</code> where <code>needs[i]</code> is the number of pieces of the <code>i<sup>th</sup></code> item you want to buy.</p> <p>You are also given an array <code>special</code> where <code>special[i]</code> is of size <code>n + 1</code> where <code>special[i][j]</code> is the number of pieces of the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> offer and <code>special[i][n]</code> (i.e., the last integer in the array) is the price of the <code>i<sup>th</sup></code> offer.</p> <p>Return <em>the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers</em>. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] <strong>Output:</strong> 14 <strong>Explanation:</strong> There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] <strong>Output:</strong> 11 <strong>Explanation:</strong> The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == price.length == needs.length</code></li> <li><code>1 &lt;= n &lt;= 6</code></li> <li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li> <li><code>1 &lt;= special.length &lt;= 100</code></li> <li><code>special[i].length == n + 1</code></li> <li><code>0 &lt;= special[i][j] &lt;= 50</code></li> <li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li> </ul>
Bit Manipulation; Memoization; Array; Dynamic Programming; Backtracking; Bitmask
Java
class Solution { private final int bits = 4; private int n; private List<Integer> price; private List<List<Integer>> special; private Map<Integer, Integer> f = new HashMap<>(); public int shoppingOffers( List<Integer> price, List<List<Integer>> special, List<Integer> needs) { n = needs.size(); this.price = price; this.special = special; int mask = 0; for (int i = 0; i < n; ++i) { mask |= needs.get(i) << (i * bits); } return dfs(mask); } private int dfs(int cur) { if (f.containsKey(cur)) { return f.get(cur); } int ans = 0; for (int i = 0; i < n; ++i) { ans += price.get(i) * (cur >> (i * bits) & 0xf); } for (List<Integer> offer : special) { int nxt = cur; boolean ok = true; for (int j = 0; j < n; ++j) { if ((cur >> (j * bits) & 0xf) < offer.get(j)) { ok = false; break; } nxt -= offer.get(j) << (j * bits); } if (ok) { ans = Math.min(ans, offer.get(n) + dfs(nxt)); } } f.put(cur, ans); return ans; } }
638
Shopping Offers
Medium
<p>In LeetCode Store, there are <code>n</code> items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.</p> <p>You are given an integer array <code>price</code> where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> item, and an integer array <code>needs</code> where <code>needs[i]</code> is the number of pieces of the <code>i<sup>th</sup></code> item you want to buy.</p> <p>You are also given an array <code>special</code> where <code>special[i]</code> is of size <code>n + 1</code> where <code>special[i][j]</code> is the number of pieces of the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> offer and <code>special[i][n]</code> (i.e., the last integer in the array) is the price of the <code>i<sup>th</sup></code> offer.</p> <p>Return <em>the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers</em>. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] <strong>Output:</strong> 14 <strong>Explanation:</strong> There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] <strong>Output:</strong> 11 <strong>Explanation:</strong> The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == price.length == needs.length</code></li> <li><code>1 &lt;= n &lt;= 6</code></li> <li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li> <li><code>1 &lt;= special.length &lt;= 100</code></li> <li><code>special[i].length == n + 1</code></li> <li><code>0 &lt;= special[i][j] &lt;= 50</code></li> <li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li> </ul>
Bit Manipulation; Memoization; Array; Dynamic Programming; Backtracking; Bitmask
Python
class Solution: def shoppingOffers( self, price: List[int], special: List[List[int]], needs: List[int] ) -> int: @cache def dfs(cur: int) -> int: ans = sum(p * (cur >> (i * bits) & 0xF) for i, p in enumerate(price)) for offer in special: nxt = cur for j in range(len(needs)): if (cur >> (j * bits) & 0xF) < offer[j]: break nxt -= offer[j] << (j * bits) else: ans = min(ans, offer[-1] + dfs(nxt)) return ans bits, mask = 4, 0 for i, need in enumerate(needs): mask |= need << i * bits return dfs(mask)
638
Shopping Offers
Medium
<p>In LeetCode Store, there are <code>n</code> items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.</p> <p>You are given an integer array <code>price</code> where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> item, and an integer array <code>needs</code> where <code>needs[i]</code> is the number of pieces of the <code>i<sup>th</sup></code> item you want to buy.</p> <p>You are also given an array <code>special</code> where <code>special[i]</code> is of size <code>n + 1</code> where <code>special[i][j]</code> is the number of pieces of the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> offer and <code>special[i][n]</code> (i.e., the last integer in the array) is the price of the <code>i<sup>th</sup></code> offer.</p> <p>Return <em>the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers</em>. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] <strong>Output:</strong> 14 <strong>Explanation:</strong> There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] <strong>Output:</strong> 11 <strong>Explanation:</strong> The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == price.length == needs.length</code></li> <li><code>1 &lt;= n &lt;= 6</code></li> <li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li> <li><code>1 &lt;= special.length &lt;= 100</code></li> <li><code>special[i].length == n + 1</code></li> <li><code>0 &lt;= special[i][j] &lt;= 50</code></li> <li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li> </ul>
Bit Manipulation; Memoization; Array; Dynamic Programming; Backtracking; Bitmask
TypeScript
function shoppingOffers(price: number[], special: number[][], needs: number[]): number { const bits = 4; const n = needs.length; const f: Map<number, number> = new Map(); let mask = 0; for (let i = 0; i < n; i++) { mask |= needs[i] << (i * bits); } const dfs = (cur: number): number => { if (f.has(cur)) { return f.get(cur)!; } let ans = 0; for (let i = 0; i < n; i++) { ans += price[i] * ((cur >> (i * bits)) & 0xf); } for (const offer of special) { let nxt = cur; let ok = true; for (let j = 0; j < n; j++) { if (((cur >> (j * bits)) & 0xf) < offer[j]) { ok = false; break; } nxt -= offer[j] << (j * bits); } if (ok) { ans = Math.min(ans, offer[n] + dfs(nxt)); } } f.set(cur, ans); return ans; }; return dfs(mask); }
639
Decode Ways II
Hard
<p>A message containing letters from <code>A-Z</code> can be <strong>encoded</strong> into numbers using the following mapping:</p> <pre> &#39;A&#39; -&gt; &quot;1&quot; &#39;B&#39; -&gt; &quot;2&quot; ... &#39;Z&#39; -&gt; &quot;26&quot; </pre> <p>To <strong>decode</strong> an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, <code>&quot;11106&quot;</code> can be mapped into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1 1 10 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11 10 6)</code></li> </ul> <p>Note that the grouping <code>(1 11 06)</code> is invalid because <code>&quot;06&quot;</code> cannot be mapped into <code>&#39;F&#39;</code> since <code>&quot;6&quot;</code> is different from <code>&quot;06&quot;</code>.</p> <p><strong>In addition</strong> to the mapping above, an encoded message may contain the <code>&#39;*&#39;</code> character, which can represent any digit from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code> (<code>&#39;0&#39;</code> is excluded). For example, the encoded message <code>&quot;1*&quot;</code> may represent any of the encoded messages <code>&quot;11&quot;</code>, <code>&quot;12&quot;</code>, <code>&quot;13&quot;</code>, <code>&quot;14&quot;</code>, <code>&quot;15&quot;</code>, <code>&quot;16&quot;</code>, <code>&quot;17&quot;</code>, <code>&quot;18&quot;</code>, or <code>&quot;19&quot;</code>. Decoding <code>&quot;1*&quot;</code> is equivalent to decoding <strong>any</strong> of the encoded messages it can represent.</p> <p>Given a string <code>s</code> consisting of digits and <code>&#39;*&#39;</code> characters, return <em>the <strong>number</strong> of ways to <strong>decode</strong> it</em>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;*&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, or &quot;9&quot;. Each of these can be decoded to the strings &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, and &quot;I&quot; respectively. Hence, there are a total of 9 ways to decode &quot;*&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;1*&quot; <strong>Output:</strong> 18 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, or &quot;19&quot;. Each of these encoded messages have 2 ways to be decoded (e.g. &quot;11&quot; can be decoded to &quot;AA&quot; or &quot;K&quot;). Hence, there are a total of 9 * 2 = 18 ways to decode &quot;1*&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;2*&quot; <strong>Output:</strong> 15 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, &quot;26&quot;, &quot;27&quot;, &quot;28&quot;, or &quot;29&quot;. &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, and &quot;26&quot; have 2 ways of being decoded, but &quot;27&quot;, &quot;28&quot;, and &quot;29&quot; only have 1 way. Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode &quot;2*&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is a digit or <code>&#39;*&#39;</code>.</li> </ul>
String; Dynamic Programming
Go
const mod int = 1e9 + 7 func numDecodings(s string) int { n := len(s) // dp[i - 2], dp[i - 1], dp[i] a, b, c := 0, 1, 0 for i := 1; i <= n; i++ { // 1 digit if s[i-1] == '*' { c = 9 * b % mod } else if s[i-1] != '0' { c = b } else { c = 0 } // 2 digits if i > 1 { if s[i-2] == '*' && s[i-1] == '*' { c = (c + 15*a) % mod } else if s[i-2] == '*' { if s[i-1] > '6' { c = (c + a) % mod } else { c = (c + 2*a) % mod } } else if s[i-1] == '*' { if s[i-2] == '1' { c = (c + 9*a) % mod } else if s[i-2] == '2' { c = (c + 6*a) % mod } } else if s[i-2] != '0' && (s[i-2]-'0')*10+s[i-1]-'0' <= 26 { c = (c + a) % mod } } a, b = b, c } return c }
639
Decode Ways II
Hard
<p>A message containing letters from <code>A-Z</code> can be <strong>encoded</strong> into numbers using the following mapping:</p> <pre> &#39;A&#39; -&gt; &quot;1&quot; &#39;B&#39; -&gt; &quot;2&quot; ... &#39;Z&#39; -&gt; &quot;26&quot; </pre> <p>To <strong>decode</strong> an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, <code>&quot;11106&quot;</code> can be mapped into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1 1 10 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11 10 6)</code></li> </ul> <p>Note that the grouping <code>(1 11 06)</code> is invalid because <code>&quot;06&quot;</code> cannot be mapped into <code>&#39;F&#39;</code> since <code>&quot;6&quot;</code> is different from <code>&quot;06&quot;</code>.</p> <p><strong>In addition</strong> to the mapping above, an encoded message may contain the <code>&#39;*&#39;</code> character, which can represent any digit from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code> (<code>&#39;0&#39;</code> is excluded). For example, the encoded message <code>&quot;1*&quot;</code> may represent any of the encoded messages <code>&quot;11&quot;</code>, <code>&quot;12&quot;</code>, <code>&quot;13&quot;</code>, <code>&quot;14&quot;</code>, <code>&quot;15&quot;</code>, <code>&quot;16&quot;</code>, <code>&quot;17&quot;</code>, <code>&quot;18&quot;</code>, or <code>&quot;19&quot;</code>. Decoding <code>&quot;1*&quot;</code> is equivalent to decoding <strong>any</strong> of the encoded messages it can represent.</p> <p>Given a string <code>s</code> consisting of digits and <code>&#39;*&#39;</code> characters, return <em>the <strong>number</strong> of ways to <strong>decode</strong> it</em>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;*&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, or &quot;9&quot;. Each of these can be decoded to the strings &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, and &quot;I&quot; respectively. Hence, there are a total of 9 ways to decode &quot;*&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;1*&quot; <strong>Output:</strong> 18 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, or &quot;19&quot;. Each of these encoded messages have 2 ways to be decoded (e.g. &quot;11&quot; can be decoded to &quot;AA&quot; or &quot;K&quot;). Hence, there are a total of 9 * 2 = 18 ways to decode &quot;1*&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;2*&quot; <strong>Output:</strong> 15 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, &quot;26&quot;, &quot;27&quot;, &quot;28&quot;, or &quot;29&quot;. &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, and &quot;26&quot; have 2 ways of being decoded, but &quot;27&quot;, &quot;28&quot;, and &quot;29&quot; only have 1 way. Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode &quot;2*&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is a digit or <code>&#39;*&#39;</code>.</li> </ul>
String; Dynamic Programming
Java
class Solution { private static final int MOD = 1000000007; public int numDecodings(String s) { int n = s.length(); char[] cs = s.toCharArray(); // dp[i - 2], dp[i - 1], dp[i] long a = 0, b = 1, c = 0; for (int i = 1; i <= n; i++) { // 1 digit if (cs[i - 1] == '*') { c = 9 * b % MOD; } else if (cs[i - 1] != '0') { c = b; } else { c = 0; } // 2 digits if (i > 1) { if (cs[i - 2] == '*' && cs[i - 1] == '*') { c = (c + 15 * a) % MOD; } else if (cs[i - 2] == '*') { if (cs[i - 1] > '6') { c = (c + a) % MOD; } else { c = (c + 2 * a) % MOD; } } else if (cs[i - 1] == '*') { if (cs[i - 2] == '1') { c = (c + 9 * a) % MOD; } else if (cs[i - 2] == '2') { c = (c + 6 * a) % MOD; } } else if (cs[i - 2] != '0' && (cs[i - 2] - '0') * 10 + cs[i - 1] - '0' <= 26) { c = (c + a) % MOD; } } a = b; b = c; } return (int) c; } }
639
Decode Ways II
Hard
<p>A message containing letters from <code>A-Z</code> can be <strong>encoded</strong> into numbers using the following mapping:</p> <pre> &#39;A&#39; -&gt; &quot;1&quot; &#39;B&#39; -&gt; &quot;2&quot; ... &#39;Z&#39; -&gt; &quot;26&quot; </pre> <p>To <strong>decode</strong> an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, <code>&quot;11106&quot;</code> can be mapped into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1 1 10 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11 10 6)</code></li> </ul> <p>Note that the grouping <code>(1 11 06)</code> is invalid because <code>&quot;06&quot;</code> cannot be mapped into <code>&#39;F&#39;</code> since <code>&quot;6&quot;</code> is different from <code>&quot;06&quot;</code>.</p> <p><strong>In addition</strong> to the mapping above, an encoded message may contain the <code>&#39;*&#39;</code> character, which can represent any digit from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code> (<code>&#39;0&#39;</code> is excluded). For example, the encoded message <code>&quot;1*&quot;</code> may represent any of the encoded messages <code>&quot;11&quot;</code>, <code>&quot;12&quot;</code>, <code>&quot;13&quot;</code>, <code>&quot;14&quot;</code>, <code>&quot;15&quot;</code>, <code>&quot;16&quot;</code>, <code>&quot;17&quot;</code>, <code>&quot;18&quot;</code>, or <code>&quot;19&quot;</code>. Decoding <code>&quot;1*&quot;</code> is equivalent to decoding <strong>any</strong> of the encoded messages it can represent.</p> <p>Given a string <code>s</code> consisting of digits and <code>&#39;*&#39;</code> characters, return <em>the <strong>number</strong> of ways to <strong>decode</strong> it</em>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;*&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, or &quot;9&quot;. Each of these can be decoded to the strings &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, and &quot;I&quot; respectively. Hence, there are a total of 9 ways to decode &quot;*&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;1*&quot; <strong>Output:</strong> 18 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, or &quot;19&quot;. Each of these encoded messages have 2 ways to be decoded (e.g. &quot;11&quot; can be decoded to &quot;AA&quot; or &quot;K&quot;). Hence, there are a total of 9 * 2 = 18 ways to decode &quot;1*&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;2*&quot; <strong>Output:</strong> 15 <strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, &quot;26&quot;, &quot;27&quot;, &quot;28&quot;, or &quot;29&quot;. &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, and &quot;26&quot; have 2 ways of being decoded, but &quot;27&quot;, &quot;28&quot;, and &quot;29&quot; only have 1 way. Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode &quot;2*&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is a digit or <code>&#39;*&#39;</code>.</li> </ul>
String; Dynamic Programming
Python
class Solution: def numDecodings(self, s: str) -> int: mod = int(1e9 + 7) n = len(s) # dp[i - 2], dp[i - 1], dp[i] a, b, c = 0, 1, 0 for i in range(1, n + 1): # 1 digit if s[i - 1] == "*": c = 9 * b % mod elif s[i - 1] != "0": c = b else: c = 0 # 2 digits if i > 1: if s[i - 2] == "*" and s[i - 1] == "*": c = (c + 15 * a) % mod elif s[i - 2] == "*": if s[i - 1] > "6": c = (c + a) % mod else: c = (c + 2 * a) % mod elif s[i - 1] == "*": if s[i - 2] == "1": c = (c + 9 * a) % mod elif s[i - 2] == "2": c = (c + 6 * a) % mod elif ( s[i - 2] != "0" and (ord(s[i - 2]) - ord("0")) * 10 + ord(s[i - 1]) - ord("0") <= 26 ): c = (c + a) % mod a, b = b, c return c
640
Solve the Equation
Medium
<p>Solve a given equation and return the value of <code>&#39;x&#39;</code> in the form of a string <code>&quot;x=#value&quot;</code>. The equation contains only <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code> operation, the variable <code>&#39;x&#39;</code> and its coefficient. You should return <code>&quot;No solution&quot;</code> if there is no solution for the equation, or <code>&quot;Infinite solutions&quot;</code> if there are infinite solutions for the equation.</p> <p>If there is exactly one solution for the equation, we ensure that the value of <code>&#39;x&#39;</code> is an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x+5-3+x=6+x-2&quot; <strong>Output:</strong> &quot;x=2&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x=x&quot; <strong>Output:</strong> &quot;Infinite solutions&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equation = &quot;2x=x&quot; <strong>Output:</strong> &quot;x=0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= equation.length &lt;= 1000</code></li> <li><code>equation</code> has exactly one <code>&#39;=&#39;</code>.</li> <li><code>equation</code> consists of integers with an absolute value in the range <code>[0, 100]</code> without any leading zeros, and the variable <code>&#39;x&#39;</code>.</li> <li>The input is generated that if there is a single solution, it will be an integer.</li> </ul>
Math; String; Simulation
Go
func solveEquation(equation string) string { f := func(s string) []int { x, y := 0, 0 if s[0] != '-' { s = "+" + s } i, n := 0, len(s) for i < n { sign := 1 if s[i] == '-' { sign = -1 } i++ j := i for j < n && s[j] != '+' && s[j] != '-' { j++ } v := s[i:j] if s[j-1] == 'x' { a := 1 if len(v) > 1 { a, _ = strconv.Atoi(v[:len(v)-1]) } x += sign * a } else { a, _ := strconv.Atoi(v) y += sign * a } i = j } return []int{x, y} } es := strings.Split(equation, "=") a, b := f(es[0]), f(es[1]) x1, y1 := a[0], a[1] x2, y2 := b[0], b[1] if x1 == x2 { if y1 == y2 { return "Infinite solutions" } else { return "No solution" } } return fmt.Sprintf("x=%d", (y2-y1)/(x1-x2)) }
640
Solve the Equation
Medium
<p>Solve a given equation and return the value of <code>&#39;x&#39;</code> in the form of a string <code>&quot;x=#value&quot;</code>. The equation contains only <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code> operation, the variable <code>&#39;x&#39;</code> and its coefficient. You should return <code>&quot;No solution&quot;</code> if there is no solution for the equation, or <code>&quot;Infinite solutions&quot;</code> if there are infinite solutions for the equation.</p> <p>If there is exactly one solution for the equation, we ensure that the value of <code>&#39;x&#39;</code> is an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x+5-3+x=6+x-2&quot; <strong>Output:</strong> &quot;x=2&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x=x&quot; <strong>Output:</strong> &quot;Infinite solutions&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equation = &quot;2x=x&quot; <strong>Output:</strong> &quot;x=0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= equation.length &lt;= 1000</code></li> <li><code>equation</code> has exactly one <code>&#39;=&#39;</code>.</li> <li><code>equation</code> consists of integers with an absolute value in the range <code>[0, 100]</code> without any leading zeros, and the variable <code>&#39;x&#39;</code>.</li> <li>The input is generated that if there is a single solution, it will be an integer.</li> </ul>
Math; String; Simulation
Java
class Solution { public String solveEquation(String equation) { String[] es = equation.split("="); int[] a = f(es[0]), b = f(es[1]); int x1 = a[0], y1 = a[1]; int x2 = b[0], y2 = b[1]; if (x1 == x2) { return y1 == y2 ? "Infinite solutions" : "No solution"; } return "x=" + (y2 - y1) / (x1 - x2); } private int[] f(String s) { int x = 0, y = 0; if (s.charAt(0) != '-') { s = "+" + s; } int i = 0, n = s.length(); while (i < n) { int sign = s.charAt(i) == '+' ? 1 : -1; ++i; int j = i; while (j < n && s.charAt(j) != '+' && s.charAt(j) != '-') { ++j; } String v = s.substring(i, j); if (s.charAt(j - 1) == 'x') { x += sign * (v.length() > 1 ? Integer.parseInt(v.substring(0, v.length() - 1)) : 1); } else { y += sign * Integer.parseInt(v); } i = j; } return new int[] {x, y}; } }
640
Solve the Equation
Medium
<p>Solve a given equation and return the value of <code>&#39;x&#39;</code> in the form of a string <code>&quot;x=#value&quot;</code>. The equation contains only <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code> operation, the variable <code>&#39;x&#39;</code> and its coefficient. You should return <code>&quot;No solution&quot;</code> if there is no solution for the equation, or <code>&quot;Infinite solutions&quot;</code> if there are infinite solutions for the equation.</p> <p>If there is exactly one solution for the equation, we ensure that the value of <code>&#39;x&#39;</code> is an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x+5-3+x=6+x-2&quot; <strong>Output:</strong> &quot;x=2&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x=x&quot; <strong>Output:</strong> &quot;Infinite solutions&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equation = &quot;2x=x&quot; <strong>Output:</strong> &quot;x=0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= equation.length &lt;= 1000</code></li> <li><code>equation</code> has exactly one <code>&#39;=&#39;</code>.</li> <li><code>equation</code> consists of integers with an absolute value in the range <code>[0, 100]</code> without any leading zeros, and the variable <code>&#39;x&#39;</code>.</li> <li>The input is generated that if there is a single solution, it will be an integer.</li> </ul>
Math; String; Simulation
Python
class Solution: def solveEquation(self, equation: str) -> str: def f(s): x = y = 0 if s[0] != '-': s = '+' + s i, n = 0, len(s) while i < n: sign = 1 if s[i] == '+' else -1 i += 1 j = i while j < n and s[j] not in '+-': j += 1 v = s[i:j] if v[-1] == 'x': x += sign * (int(v[:-1]) if len(v) > 1 else 1) else: y += sign * int(v) i = j return x, y a, b = equation.split('=') x1, y1 = f(a) x2, y2 = f(b) if x1 == x2: return 'Infinite solutions' if y1 == y2 else 'No solution' return f'x={(y2 - y1) // (x1 - x2)}'
640
Solve the Equation
Medium
<p>Solve a given equation and return the value of <code>&#39;x&#39;</code> in the form of a string <code>&quot;x=#value&quot;</code>. The equation contains only <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code> operation, the variable <code>&#39;x&#39;</code> and its coefficient. You should return <code>&quot;No solution&quot;</code> if there is no solution for the equation, or <code>&quot;Infinite solutions&quot;</code> if there are infinite solutions for the equation.</p> <p>If there is exactly one solution for the equation, we ensure that the value of <code>&#39;x&#39;</code> is an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x+5-3+x=6+x-2&quot; <strong>Output:</strong> &quot;x=2&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equation = &quot;x=x&quot; <strong>Output:</strong> &quot;Infinite solutions&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equation = &quot;2x=x&quot; <strong>Output:</strong> &quot;x=0&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= equation.length &lt;= 1000</code></li> <li><code>equation</code> has exactly one <code>&#39;=&#39;</code>.</li> <li><code>equation</code> consists of integers with an absolute value in the range <code>[0, 100]</code> without any leading zeros, and the variable <code>&#39;x&#39;</code>.</li> <li>The input is generated that if there is a single solution, it will be an integer.</li> </ul>
Math; String; Simulation
TypeScript
function solveEquation(equation: string): string { const [left, right] = equation.split('='); const createExpr = (s: string) => { let x = 0; let n = 0; let i = 0; let sym = 1; let cur = 0; let isX = false; for (const c of s) { if (c === '+' || c === '-') { if (isX) { if (i === 0 && cur === 0) { cur = 1; } x += cur * sym; } else { n += cur * sym; } isX = false; cur = 0; i = 0; if (c === '+') { sym = 1; } else { sym = -1; } } else if (c === 'x') { isX = true; } else { i++; cur *= 10; cur += Number(c); } } if (isX) { if (i === 0 && cur === 0) { cur = 1; } x += cur * sym; } else { n += cur * sym; } return [x, n]; }; const lExpr = createExpr(left); const rExpr = createExpr(right); if (lExpr[0] === rExpr[0]) { if (lExpr[1] !== rExpr[1]) { return 'No solution'; } return 'Infinite solutions'; } return `x=${(lExpr[1] - rExpr[1]) / (rExpr[0] - lExpr[0])}`; }
641
Design Circular Deque
Medium
<p>Design your implementation of the circular double-ended queue (deque).</p> <p>Implement the <code>MyCircularDeque</code> class:</p> <ul> <li><code>MyCircularDeque(int k)</code> Initializes the deque with a maximum size of <code>k</code>.</li> <li><code>boolean insertFront()</code> Adds an item at the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean insertLast()</code> Adds an item at the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteFront()</code> Deletes an item from the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteLast()</code> Deletes an item from the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>int getFront()</code> Returns the front item from the Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>int getRear()</code> Returns the last item from Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>boolean isEmpty()</code> Returns <code>true</code> if the deque is empty, or <code>false</code> otherwise.</li> <li><code>boolean isFull()</code> Returns <code>true</code> if the deque is full, or <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 2, true, true, true, 4] <strong>Explanation</strong> MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>0 &lt;= value &lt;= 1000</code></li> <li>At most <code>2000</code> calls will be made to <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
C++
class MyCircularDeque { public: vector<int> q; int front = 0; int size = 0; int capacity = 0; MyCircularDeque(int k) { q.assign(k, 0); capacity = k; } bool insertFront(int value) { if (isFull()) { return false; } if (!isEmpty()) { front = (front - 1 + capacity) % capacity; } q[front] = value; ++size; return true; } bool insertLast(int value) { if (isFull()) { return false; } int idx = (front + size) % capacity; q[idx] = value; ++size; return true; } bool deleteFront() { if (isEmpty()) { return false; } front = (front + 1) % capacity; --size; return true; } bool deleteLast() { if (isEmpty()) { return false; } --size; return true; } int getFront() { return isEmpty() ? -1 : q[front]; } int getRear() { return isEmpty() ? -1 : q[(front + size - 1) % capacity]; } bool isEmpty() { return size == 0; } bool isFull() { return size == capacity; } }; /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque* obj = new MyCircularDeque(k); * bool param_1 = obj->insertFront(value); * bool param_2 = obj->insertLast(value); * bool param_3 = obj->deleteFront(); * bool param_4 = obj->deleteLast(); * int param_5 = obj->getFront(); * int param_6 = obj->getRear(); * bool param_7 = obj->isEmpty(); * bool param_8 = obj->isFull(); */
641
Design Circular Deque
Medium
<p>Design your implementation of the circular double-ended queue (deque).</p> <p>Implement the <code>MyCircularDeque</code> class:</p> <ul> <li><code>MyCircularDeque(int k)</code> Initializes the deque with a maximum size of <code>k</code>.</li> <li><code>boolean insertFront()</code> Adds an item at the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean insertLast()</code> Adds an item at the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteFront()</code> Deletes an item from the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteLast()</code> Deletes an item from the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>int getFront()</code> Returns the front item from the Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>int getRear()</code> Returns the last item from Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>boolean isEmpty()</code> Returns <code>true</code> if the deque is empty, or <code>false</code> otherwise.</li> <li><code>boolean isFull()</code> Returns <code>true</code> if the deque is full, or <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 2, true, true, true, 4] <strong>Explanation</strong> MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>0 &lt;= value &lt;= 1000</code></li> <li>At most <code>2000</code> calls will be made to <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Go
type MyCircularDeque struct { q []int size int front int capacity int } func Constructor(k int) MyCircularDeque { q := make([]int, k) return MyCircularDeque{q, 0, 0, k} } func (this *MyCircularDeque) InsertFront(value int) bool { if this.IsFull() { return false } if !this.IsEmpty() { this.front = (this.front - 1 + this.capacity) % this.capacity } this.q[this.front] = value this.size++ return true } func (this *MyCircularDeque) InsertLast(value int) bool { if this.IsFull() { return false } idx := (this.front + this.size) % this.capacity this.q[idx] = value this.size++ return true } func (this *MyCircularDeque) DeleteFront() bool { if this.IsEmpty() { return false } this.front = (this.front + 1) % this.capacity this.size -= 1 return true } func (this *MyCircularDeque) DeleteLast() bool { if this.IsEmpty() { return false } this.size -= 1 return true } func (this *MyCircularDeque) GetFront() int { if this.IsEmpty() { return -1 } return this.q[this.front] } func (this *MyCircularDeque) GetRear() int { if this.IsEmpty() { return -1 } return this.q[(this.front+this.size-1)%this.capacity] } func (this *MyCircularDeque) IsEmpty() bool { return this.size == 0 } func (this *MyCircularDeque) IsFull() bool { return this.size == this.capacity } /** * Your MyCircularDeque object will be instantiated and called as such: * obj := Constructor(k); * param_1 := obj.InsertFront(value); * param_2 := obj.InsertLast(value); * param_3 := obj.DeleteFront(); * param_4 := obj.DeleteLast(); * param_5 := obj.GetFront(); * param_6 := obj.GetRear(); * param_7 := obj.IsEmpty(); * param_8 := obj.IsFull(); */
641
Design Circular Deque
Medium
<p>Design your implementation of the circular double-ended queue (deque).</p> <p>Implement the <code>MyCircularDeque</code> class:</p> <ul> <li><code>MyCircularDeque(int k)</code> Initializes the deque with a maximum size of <code>k</code>.</li> <li><code>boolean insertFront()</code> Adds an item at the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean insertLast()</code> Adds an item at the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteFront()</code> Deletes an item from the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteLast()</code> Deletes an item from the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>int getFront()</code> Returns the front item from the Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>int getRear()</code> Returns the last item from Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>boolean isEmpty()</code> Returns <code>true</code> if the deque is empty, or <code>false</code> otherwise.</li> <li><code>boolean isFull()</code> Returns <code>true</code> if the deque is full, or <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 2, true, true, true, 4] <strong>Explanation</strong> MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>0 &lt;= value &lt;= 1000</code></li> <li>At most <code>2000</code> calls will be made to <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Java
class MyCircularDeque { private int[] q; private int front; private int size; private int capacity; /** Initialize your data structure here. Set the size of the deque to be k. */ public MyCircularDeque(int k) { q = new int[k]; capacity = k; } /** Adds an item at the front of Deque. Return true if the operation is successful. */ public boolean insertFront(int value) { if (isFull()) { return false; } if (!isEmpty()) { front = (front - 1 + capacity) % capacity; } q[front] = value; ++size; return true; } /** Adds an item at the rear of Deque. Return true if the operation is successful. */ public boolean insertLast(int value) { if (isFull()) { return false; } int idx = (front + size) % capacity; q[idx] = value; ++size; return true; } /** Deletes an item from the front of Deque. Return true if the operation is successful. */ public boolean deleteFront() { if (isEmpty()) { return false; } front = (front + 1) % capacity; --size; return true; } /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ public boolean deleteLast() { if (isEmpty()) { return false; } --size; return true; } /** Get the front item from the deque. */ public int getFront() { if (isEmpty()) { return -1; } return q[front]; } /** Get the last item from the deque. */ public int getRear() { if (isEmpty()) { return -1; } int idx = (front + size - 1) % capacity; return q[idx]; } /** Checks whether the circular deque is empty or not. */ public boolean isEmpty() { return size == 0; } /** Checks whether the circular deque is full or not. */ public boolean isFull() { return size == capacity; } } /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque obj = new MyCircularDeque(k); * boolean param_1 = obj.insertFront(value); * boolean param_2 = obj.insertLast(value); * boolean param_3 = obj.deleteFront(); * boolean param_4 = obj.deleteLast(); * int param_5 = obj.getFront(); * int param_6 = obj.getRear(); * boolean param_7 = obj.isEmpty(); * boolean param_8 = obj.isFull(); */
641
Design Circular Deque
Medium
<p>Design your implementation of the circular double-ended queue (deque).</p> <p>Implement the <code>MyCircularDeque</code> class:</p> <ul> <li><code>MyCircularDeque(int k)</code> Initializes the deque with a maximum size of <code>k</code>.</li> <li><code>boolean insertFront()</code> Adds an item at the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean insertLast()</code> Adds an item at the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteFront()</code> Deletes an item from the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteLast()</code> Deletes an item from the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>int getFront()</code> Returns the front item from the Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>int getRear()</code> Returns the last item from Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>boolean isEmpty()</code> Returns <code>true</code> if the deque is empty, or <code>false</code> otherwise.</li> <li><code>boolean isFull()</code> Returns <code>true</code> if the deque is full, or <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 2, true, true, true, 4] <strong>Explanation</strong> MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>0 &lt;= value &lt;= 1000</code></li> <li>At most <code>2000</code> calls will be made to <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Python
class MyCircularDeque: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self.q = [0] * k self.front = 0 self.size = 0 self.capacity = k def insertFront(self, value: int) -> bool: """ Adds an item at the front of Deque. Return true if the operation is successful. """ if self.isFull(): return False if not self.isEmpty(): self.front = (self.front - 1 + self.capacity) % self.capacity self.q[self.front] = value self.size += 1 return True def insertLast(self, value: int) -> bool: """ Adds an item at the rear of Deque. Return true if the operation is successful. """ if self.isFull(): return False idx = (self.front + self.size) % self.capacity self.q[idx] = value self.size += 1 return True def deleteFront(self) -> bool: """ Deletes an item from the front of Deque. Return true if the operation is successful. """ if self.isEmpty(): return False self.front = (self.front + 1) % self.capacity self.size -= 1 return True def deleteLast(self) -> bool: """ Deletes an item from the rear of Deque. Return true if the operation is successful. """ if self.isEmpty(): return False self.size -= 1 return True def getFront(self) -> int: """ Get the front item from the deque. """ if self.isEmpty(): return -1 return self.q[self.front] def getRear(self) -> int: """ Get the last item from the deque. """ if self.isEmpty(): return -1 idx = (self.front + self.size - 1) % self.capacity return self.q[idx] def isEmpty(self) -> bool: """ Checks whether the circular deque is empty or not. """ return self.size == 0 def isFull(self) -> bool: """ Checks whether the circular deque is full or not. """ return self.size == self.capacity # Your MyCircularDeque object will be instantiated and called as such: # obj = MyCircularDeque(k) # param_1 = obj.insertFront(value) # param_2 = obj.insertLast(value) # param_3 = obj.deleteFront() # param_4 = obj.deleteLast() # param_5 = obj.getFront() # param_6 = obj.getRear() # param_7 = obj.isEmpty() # param_8 = obj.isFull()
641
Design Circular Deque
Medium
<p>Design your implementation of the circular double-ended queue (deque).</p> <p>Implement the <code>MyCircularDeque</code> class:</p> <ul> <li><code>MyCircularDeque(int k)</code> Initializes the deque with a maximum size of <code>k</code>.</li> <li><code>boolean insertFront()</code> Adds an item at the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean insertLast()</code> Adds an item at the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteFront()</code> Deletes an item from the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>boolean deleteLast()</code> Deletes an item from the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li> <li><code>int getFront()</code> Returns the front item from the Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>int getRear()</code> Returns the last item from Deque. Returns <code>-1</code> if the deque is empty.</li> <li><code>boolean isEmpty()</code> Returns <code>true</code> if the deque is empty, or <code>false</code> otherwise.</li> <li><code>boolean isFull()</code> Returns <code>true</code> if the deque is full, or <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 2, true, true, true, 4] <strong>Explanation</strong> MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>0 &lt;= value &lt;= 1000</code></li> <li>At most <code>2000</code> calls will be made to <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
TypeScript
class MyCircularDeque { private vals: number[]; private length: number; private size: number; private start: number; private end: number; constructor(k: number) { this.vals = new Array(k).fill(0); this.start = 0; this.end = 0; this.length = 0; this.size = k; } insertFront(value: number): boolean { if (this.isFull()) { return false; } if (this.start === 0) { this.start = this.size - 1; } else { this.start--; } this.vals[this.start] = value; this.length++; return true; } insertLast(value: number): boolean { if (this.isFull()) { return false; } this.vals[this.end] = value; this.length++; if (this.end + 1 === this.size) { this.end = 0; } else { this.end++; } return true; } deleteFront(): boolean { if (this.isEmpty()) { return false; } if (this.start + 1 === this.size) { this.start = 0; } else { this.start++; } this.length--; return true; } deleteLast(): boolean { if (this.isEmpty()) { return false; } if (this.end === 0) { this.end = this.size - 1; } else { this.end--; } this.length--; return true; } getFront(): number { if (this.isEmpty()) { return -1; } return this.vals[this.start]; } getRear(): number { if (this.isEmpty()) { return -1; } if (this.end === 0) { return this.vals[this.size - 1]; } return this.vals[this.end - 1]; } isEmpty(): boolean { return this.length === 0; } isFull(): boolean { return this.length === this.size; } } /** * Your MyCircularDeque object will be instantiated and called as such: * var obj = new MyCircularDeque(k) * var param_1 = obj.insertFront(value) * var param_2 = obj.insertLast(value) * var param_3 = obj.deleteFront() * var param_4 = obj.deleteLast() * var param_5 = obj.getFront() * var param_6 = obj.getRear() * var param_7 = obj.isEmpty() * var param_8 = obj.isFull() */
642
Design Search Autocomplete System
Hard
<p>Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character <code>&#39;#&#39;</code>).</p> <p>You are given a string array <code>sentences</code> and an integer array <code>times</code> both of length <code>n</code> where <code>sentences[i]</code> is a previously typed sentence and <code>times[i]</code> is the corresponding number of times the sentence was typed. For each input character except <code>&#39;#&#39;</code>, return the top <code>3</code> historical hot sentences that have the same prefix as the part of the sentence already typed.</p> <p>Here are the specific rules:</p> <ul> <li>The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.</li> <li>The returned top <code>3</code> hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same hot degree, use ASCII-code order (smaller one appears first).</li> <li>If less than <code>3</code> hot sentences exist, return as many as you can.</li> <li>When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.</li> </ul> <p>Implement the <code>AutocompleteSystem</code> class:</p> <ul> <li><code>AutocompleteSystem(String[] sentences, int[] times)</code> Initializes the object with the <code>sentences</code> and <code>times</code> arrays.</li> <li><code>List&lt;String&gt; input(char c)</code> This indicates that the user typed the character <code>c</code>. <ul> <li>Returns an empty array <code>[]</code> if <code>c == &#39;#&#39;</code> and stores the inputted sentence in the system.</li> <li>Returns the top <code>3</code> historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than <code>3</code> matches, return them all.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;AutocompleteSystem&quot;, &quot;input&quot;, &quot;input&quot;, &quot;input&quot;, &quot;input&quot;] [[[&quot;i love you&quot;, &quot;island&quot;, &quot;iroman&quot;, &quot;i love leetcode&quot;], [5, 3, 2, 2]], [&quot;i&quot;], [&quot; &quot;], [&quot;a&quot;], [&quot;#&quot;]] <strong>Output</strong> [null, [&quot;i love you&quot;, &quot;island&quot;, &quot;i love leetcode&quot;], [&quot;i love you&quot;, &quot;i love leetcode&quot;], [], []] <strong>Explanation</strong> AutocompleteSystem obj = new AutocompleteSystem([&quot;i love you&quot;, &quot;island&quot;, &quot;iroman&quot;, &quot;i love leetcode&quot;], [5, 3, 2, 2]); obj.input(&quot;i&quot;); // return [&quot;i love you&quot;, &quot;island&quot;, &quot;i love leetcode&quot;]. There are four sentences that have prefix &quot;i&quot;. Among them, &quot;ironman&quot; and &quot;i love leetcode&quot; have same hot degree. Since &#39; &#39; has ASCII code 32 and &#39;r&#39; has ASCII code 114, &quot;i love leetcode&quot; should be in front of &quot;ironman&quot;. Also we only need to output top 3 hot sentences, so &quot;ironman&quot; will be ignored. obj.input(&quot; &quot;); // return [&quot;i love you&quot;, &quot;i love leetcode&quot;]. There are only two sentences that have prefix &quot;i &quot;. obj.input(&quot;a&quot;); // return []. There are no sentences that have prefix &quot;i a&quot;. obj.input(&quot;#&quot;); // return []. The user finished the input, the sentence &quot;i a&quot; should be saved as a historical sentence in system. And the following input will be counted as a new search. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == sentences.length</code></li> <li><code>n == times.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= sentences[i].length &lt;= 100</code></li> <li><code>1 &lt;= times[i] &lt;= 50</code></li> <li><code>c</code> is a lowercase English letter, a hash <code>&#39;#&#39;</code>, or space <code>&#39; &#39;</code>.</li> <li>Each tested sentence will be a sequence of characters <code>c</code> that end with the character <code>&#39;#&#39;</code>.</li> <li>Each tested sentence will have a length in the range <code>[1, 200]</code>.</li> <li>The words in each input sentence are separated by single spaces.</li> <li>At most <code>5000</code> calls will be made to <code>input</code>.</li> </ul>
Depth-First Search; Design; Trie; String; Data Stream; Sorting; Heap (Priority Queue)
Java
class Trie { Trie[] children = new Trie[27]; int v; String w = ""; void insert(String w, int t) { Trie node = this; for (char c : w.toCharArray()) { int idx = c == ' ' ? 26 : c - 'a'; if (node.children[idx] == null) { node.children[idx] = new Trie(); } node = node.children[idx]; } node.v += t; node.w = w; } Trie search(String pref) { Trie node = this; for (char c : pref.toCharArray()) { int idx = c == ' ' ? 26 : c - 'a'; if (node.children[idx] == null) { return null; } node = node.children[idx]; } return node; } } class AutocompleteSystem { private Trie trie = new Trie(); private StringBuilder t = new StringBuilder(); public AutocompleteSystem(String[] sentences, int[] times) { int i = 0; for (String s : sentences) { trie.insert(s, times[i++]); } } public List<String> input(char c) { List<String> res = new ArrayList<>(); if (c == '#') { trie.insert(t.toString(), 1); t = new StringBuilder(); return res; } t.append(c); Trie node = trie.search(t.toString()); if (node == null) { return res; } PriorityQueue<Trie> q = new PriorityQueue<>((a, b) -> a.v == b.v ? b.w.compareTo(a.w) : a.v - b.v); dfs(node, q); while (!q.isEmpty()) { res.add(0, q.poll().w); } return res; } private void dfs(Trie node, PriorityQueue q) { if (node == null) { return; } if (node.v > 0) { q.offer(node); if (q.size() > 3) { q.poll(); } } for (Trie nxt : node.children) { dfs(nxt, q); } } } /** * Your AutocompleteSystem object will be instantiated and called as such: * AutocompleteSystem obj = new AutocompleteSystem(sentences, times); * List<String> param_1 = obj.input(c); */
642
Design Search Autocomplete System
Hard
<p>Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character <code>&#39;#&#39;</code>).</p> <p>You are given a string array <code>sentences</code> and an integer array <code>times</code> both of length <code>n</code> where <code>sentences[i]</code> is a previously typed sentence and <code>times[i]</code> is the corresponding number of times the sentence was typed. For each input character except <code>&#39;#&#39;</code>, return the top <code>3</code> historical hot sentences that have the same prefix as the part of the sentence already typed.</p> <p>Here are the specific rules:</p> <ul> <li>The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.</li> <li>The returned top <code>3</code> hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same hot degree, use ASCII-code order (smaller one appears first).</li> <li>If less than <code>3</code> hot sentences exist, return as many as you can.</li> <li>When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.</li> </ul> <p>Implement the <code>AutocompleteSystem</code> class:</p> <ul> <li><code>AutocompleteSystem(String[] sentences, int[] times)</code> Initializes the object with the <code>sentences</code> and <code>times</code> arrays.</li> <li><code>List&lt;String&gt; input(char c)</code> This indicates that the user typed the character <code>c</code>. <ul> <li>Returns an empty array <code>[]</code> if <code>c == &#39;#&#39;</code> and stores the inputted sentence in the system.</li> <li>Returns the top <code>3</code> historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than <code>3</code> matches, return them all.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;AutocompleteSystem&quot;, &quot;input&quot;, &quot;input&quot;, &quot;input&quot;, &quot;input&quot;] [[[&quot;i love you&quot;, &quot;island&quot;, &quot;iroman&quot;, &quot;i love leetcode&quot;], [5, 3, 2, 2]], [&quot;i&quot;], [&quot; &quot;], [&quot;a&quot;], [&quot;#&quot;]] <strong>Output</strong> [null, [&quot;i love you&quot;, &quot;island&quot;, &quot;i love leetcode&quot;], [&quot;i love you&quot;, &quot;i love leetcode&quot;], [], []] <strong>Explanation</strong> AutocompleteSystem obj = new AutocompleteSystem([&quot;i love you&quot;, &quot;island&quot;, &quot;iroman&quot;, &quot;i love leetcode&quot;], [5, 3, 2, 2]); obj.input(&quot;i&quot;); // return [&quot;i love you&quot;, &quot;island&quot;, &quot;i love leetcode&quot;]. There are four sentences that have prefix &quot;i&quot;. Among them, &quot;ironman&quot; and &quot;i love leetcode&quot; have same hot degree. Since &#39; &#39; has ASCII code 32 and &#39;r&#39; has ASCII code 114, &quot;i love leetcode&quot; should be in front of &quot;ironman&quot;. Also we only need to output top 3 hot sentences, so &quot;ironman&quot; will be ignored. obj.input(&quot; &quot;); // return [&quot;i love you&quot;, &quot;i love leetcode&quot;]. There are only two sentences that have prefix &quot;i &quot;. obj.input(&quot;a&quot;); // return []. There are no sentences that have prefix &quot;i a&quot;. obj.input(&quot;#&quot;); // return []. The user finished the input, the sentence &quot;i a&quot; should be saved as a historical sentence in system. And the following input will be counted as a new search. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == sentences.length</code></li> <li><code>n == times.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= sentences[i].length &lt;= 100</code></li> <li><code>1 &lt;= times[i] &lt;= 50</code></li> <li><code>c</code> is a lowercase English letter, a hash <code>&#39;#&#39;</code>, or space <code>&#39; &#39;</code>.</li> <li>Each tested sentence will be a sequence of characters <code>c</code> that end with the character <code>&#39;#&#39;</code>.</li> <li>Each tested sentence will have a length in the range <code>[1, 200]</code>.</li> <li>The words in each input sentence are separated by single spaces.</li> <li>At most <code>5000</code> calls will be made to <code>input</code>.</li> </ul>
Depth-First Search; Design; Trie; String; Data Stream; Sorting; Heap (Priority Queue)
Python
class Trie: def __init__(self): self.children = [None] * 27 self.v = 0 self.w = '' def insert(self, w, t): node = self for c in w: idx = 26 if c == ' ' else ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.v += t node.w = w def search(self, pref): node = self for c in pref: idx = 26 if c == ' ' else ord(c) - ord('a') if node.children[idx] is None: return None node = node.children[idx] return node class AutocompleteSystem: def __init__(self, sentences: List[str], times: List[int]): self.trie = Trie() for a, b in zip(sentences, times): self.trie.insert(a, b) self.t = [] def input(self, c: str) -> List[str]: def dfs(node): if node is None: return if node.v: res.append((node.v, node.w)) for nxt in node.children: dfs(nxt) if c == '#': s = ''.join(self.t) self.trie.insert(s, 1) self.t = [] return [] res = [] self.t.append(c) node = self.trie.search(''.join(self.t)) if node is None: return res dfs(node) res.sort(key=lambda x: (-x[0], x[1])) return [v[1] for v in res[:3]] # Your AutocompleteSystem object will be instantiated and called as such: # obj = AutocompleteSystem(sentences, times) # param_1 = obj.input(c)
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
C++
class Solution { public: double findMaxAverage(vector<int>& nums, int k) { int s = accumulate(nums.begin(), nums.begin() + k, 0); int ans = s; for (int i = k; i < nums.size(); ++i) { s += nums[i] - nums[i - k]; ans = max(ans, s); } return static_cast<double>(ans) / k; } };
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
Go
func findMaxAverage(nums []int, k int) float64 { s := 0 for _, x := range nums[:k] { s += x } ans := s for i := k; i < len(nums); i++ { s += nums[i] - nums[i-k] ans = max(ans, s) } return float64(ans) / float64(k) }
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
Java
class Solution { public double findMaxAverage(int[] nums, int k) { int s = 0; for (int i = 0; i < k; ++i) { s += nums[i]; } int ans = s; for (int i = k; i < nums.length; ++i) { s += (nums[i] - nums[i - k]); ans = Math.max(ans, s); } return ans * 1.0 / k; } }
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
PHP
class Solution { /** * @param Integer[] $nums * @param Integer $k * @return Float */ function findMaxAverage($nums, $k) { $s = 0; for ($i = 0; $i < $k; $i++) { $s += $nums[$i]; } $ans = $s; for ($j = $k; $j < count($nums); $j++) { $s = $s - $nums[$j - $k] + $nums[$j]; $ans = max($ans, $s); } return $ans / $k; } }
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
Python
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: ans = s = sum(nums[:k]) for i in range(k, len(nums)): s += nums[i] - nums[i - k] ans = max(ans, s) return ans / k
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
Rust
impl Solution { pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 { let k = k as usize; let n = nums.len(); let mut s = nums.iter().take(k).sum::<i32>(); let mut ans = s; for i in k..n { s += nums[i] - nums[i - k]; ans = ans.max(s); } f64::from(ans) / f64::from(k as i32) } }
643
Maximum Average Subarray I
Easy
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Sliding Window
TypeScript
function findMaxAverage(nums: number[], k: number): number { let s = 0; for (let i = 0; i < k; ++i) { s += nums[i]; } let ans = s; for (let i = k; i < nums.length; ++i) { s += nums[i] - nums[i - k]; ans = Math.max(ans, s); } return ans / k; }
644
Maximum Average Subarray II
Hard
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is greater than or equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <b>Explanation: </b>- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75 - When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8 - When the length is 6, averages are [9.16667] and the maximum average is 9.16667 The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75 Note that we do not consider the subarrays of length &lt; 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search; Prefix Sum
C++
class Solution { public: double findMaxAverage(vector<int>& nums, int k) { double eps = 1e-5; double l = *min_element(nums.begin(), nums.end()); double r = *max_element(nums.begin(), nums.end()); auto check = [&](double v) { double s = 0; for (int i = 0; i < k; ++i) { s += nums[i] - v; } if (s >= 0) { return true; } double t = 0; double mi = 0; for (int i = k; i < nums.size(); ++i) { s += nums[i] - v; t += nums[i - k] - v; mi = min(mi, t); if (s >= mi) { return true; } } return false; }; while (r - l >= eps) { double mid = (l + r) / 2; if (check(mid)) { l = mid; } else { r = mid; } } return l; } };
644
Maximum Average Subarray II
Hard
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is greater than or equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <b>Explanation: </b>- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75 - When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8 - When the length is 6, averages are [9.16667] and the maximum average is 9.16667 The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75 Note that we do not consider the subarrays of length &lt; 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search; Prefix Sum
Go
func findMaxAverage(nums []int, k int) float64 { eps := 1e-5 l := float64(slices.Min(nums)) r := float64(slices.Max(nums)) check := func(v float64) bool { s := 0.0 for _, x := range nums[:k] { s += float64(x) - v } if s >= 0 { return true } t := 0.0 mi := 0.0 for i := k; i < len(nums); i++ { s += float64(nums[i]) - v t += float64(nums[i-k]) - v mi = math.Min(mi, t) if s >= mi { return true } } return false } for r-l >= eps { mid := (l + r) / 2 if check(mid) { l = mid } else { r = mid } } return l }
644
Maximum Average Subarray II
Hard
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is greater than or equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <b>Explanation: </b>- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75 - When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8 - When the length is 6, averages are [9.16667] and the maximum average is 9.16667 The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75 Note that we do not consider the subarrays of length &lt; 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search; Prefix Sum
Java
class Solution { public double findMaxAverage(int[] nums, int k) { double eps = 1e-5; double l = 1e10, r = -1e10; for (int x : nums) { l = Math.min(l, x); r = Math.max(r, x); } while (r - l >= eps) { double mid = (l + r) / 2; if (check(nums, k, mid)) { l = mid; } else { r = mid; } } return l; } private boolean check(int[] nums, int k, double v) { double s = 0; for (int i = 0; i < k; ++i) { s += nums[i] - v; } if (s >= 0) { return true; } double t = 0; double mi = 0; for (int i = k; i < nums.length; ++i) { s += nums[i] - v; t += nums[i - k] - v; mi = Math.min(mi, t); if (s >= mi) { return true; } } return false; } }
644
Maximum Average Subarray II
Hard
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is greater than or equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <b>Explanation: </b>- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75 - When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8 - When the length is 6, averages are [9.16667] and the maximum average is 9.16667 The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75 Note that we do not consider the subarrays of length &lt; 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search; Prefix Sum
Python
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: def check(v: float) -> bool: s = sum(nums[:k]) - k * v if s >= 0: return True t = mi = 0 for i in range(k, len(nums)): s += nums[i] - v t += nums[i - k] - v mi = min(mi, t) if s >= mi: return True return False eps = 1e-5 l, r = min(nums), max(nums) while r - l >= eps: mid = (l + r) / 2 if check(mid): l = mid else: r = mid return l
644
Maximum Average Subarray II
Hard
<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p> <p>Find a contiguous subarray whose <strong>length is greater than or equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4 <strong>Output:</strong> 12.75000 <b>Explanation: </b>- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75 - When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8 - When the length is 6, averages are [9.16667] and the maximum average is 9.16667 The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75 Note that we do not consider the subarrays of length &lt; 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5], k = 1 <strong>Output:</strong> 5.00000 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search; Prefix Sum
TypeScript
function findMaxAverage(nums: number[], k: number): number { const eps = 1e-5; let l = Math.min(...nums); let r = Math.max(...nums); const check = (v: number): boolean => { let s = nums.slice(0, k).reduce((a, b) => a + b) - v * k; if (s >= 0) { return true; } let t = 0; let mi = 0; for (let i = k; i < nums.length; ++i) { s += nums[i] - v; t += nums[i - k] - v; mi = Math.min(mi, t); if (s >= mi) { return true; } } return false; }; while (r - l >= eps) { const mid = (l + r) / 2; if (check(mid)) { l = mid; } else { r = mid; } } return l; }
645
Set Mismatch
Easy
<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p> <p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p> <p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2,4] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; Sorting
C++
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { int n = nums.size(); int s1 = (1 + n) * n / 2; int s2 = 0; unordered_set<int> set(nums.begin(), nums.end()); for (int x : set) { s2 += x; } int s = accumulate(nums.begin(), nums.end(), 0); return {s - s2, s1 - s2}; } };
645
Set Mismatch
Easy
<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p> <p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p> <p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2,4] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; Sorting
Go
func findErrorNums(nums []int) []int { n := len(nums) s1 := (1 + n) * n / 2 s2, s := 0, 0 set := map[int]bool{} for _, x := range nums { if !set[x] { set[x] = true s2 += x } s += x } return []int{s - s2, s1 - s2} }
645
Set Mismatch
Easy
<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p> <p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p> <p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2,4] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; Sorting
Java
class Solution { public int[] findErrorNums(int[] nums) { int n = nums.length; int s1 = (1 + n) * n / 2; int s2 = 0; Set<Integer> set = new HashSet<>(); int s = 0; for (int x : nums) { if (set.add(x)) { s2 += x; } s += x; } return new int[] {s - s2, s1 - s2}; } }
645
Set Mismatch
Easy
<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p> <p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p> <p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2,4] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; Sorting
Python
class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: n = len(nums) s1 = (1 + n) * n // 2 s2 = sum(set(nums)) s = sum(nums) return [s - s2, s1 - s2]
645
Set Mismatch
Easy
<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p> <p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p> <p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2,4] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; Sorting
Rust
use std::collections::HashSet; impl Solution { pub fn find_error_nums(nums: Vec<i32>) -> Vec<i32> { let n = nums.len() as i32; let s1 = ((1 + n) * n) / 2; let s2 = nums .iter() .cloned() .collect::<HashSet<i32>>() .iter() .sum::<i32>(); let s: i32 = nums.iter().sum(); vec![s - s2, s1 - s2] } }
645
Set Mismatch
Easy
<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p> <p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p> <p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2,4] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; Sorting
TypeScript
function findErrorNums(nums: number[]): number[] { const n = nums.length; const s1 = (n * (n + 1)) >> 1; const s2 = [...new Set(nums)].reduce((a, b) => a + b); const s = nums.reduce((a, b) => a + b); return [s - s2, s1 - s2]; }
646
Maximum Length of Pair Chain
Medium
<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p> <p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p> <p>Return <em>the length longest chain which can be formed</em>.</p> <p>You do not need to use up all the given intervals. You can select pairs in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pairs.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
C++
class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { ranges::sort(pairs, {}, [](const auto& p) { return p[1]; }); int ans = 0, pre = INT_MIN; for (const auto& p : pairs) { if (pre < p[0]) { pre = p[1]; ++ans; } } return ans; } };
646
Maximum Length of Pair Chain
Medium
<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p> <p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p> <p>Return <em>the length longest chain which can be formed</em>.</p> <p>You do not need to use up all the given intervals. You can select pairs in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pairs.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Go
func findLongestChain(pairs [][]int) (ans int) { sort.Slice(pairs, func(i, j int) bool { return pairs[i][1] < pairs[j][1] }) pre := math.MinInt for _, p := range pairs { if pre < p[0] { ans++ pre = p[1] } } return }
646
Maximum Length of Pair Chain
Medium
<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p> <p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p> <p>Return <em>the length longest chain which can be formed</em>.</p> <p>You do not need to use up all the given intervals. You can select pairs in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pairs.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Java
class Solution { public int findLongestChain(int[][] pairs) { Arrays.sort(pairs, (a, b) -> Integer.compare(a[1], b[1])); int ans = 0, pre = Integer.MIN_VALUE; for (var p : pairs) { if (pre < p[0]) { ++ans; pre = p[1]; } } return ans; } }
646
Maximum Length of Pair Chain
Medium
<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p> <p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p> <p>Return <em>the length longest chain which can be formed</em>.</p> <p>You do not need to use up all the given intervals. You can select pairs in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pairs.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Python
class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int: pairs.sort(key=lambda x: x[1]) ans, pre = 0, -inf for a, b in pairs: if pre < a: ans += 1 pre = b return ans
646
Maximum Length of Pair Chain
Medium
<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p> <p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p> <p>Return <em>the length longest chain which can be formed</em>.</p> <p>You do not need to use up all the given intervals. You can select pairs in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pairs.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Rust
impl Solution { pub fn find_longest_chain(mut pairs: Vec<Vec<i32>>) -> i32 { pairs.sort_by_key(|pair| pair[1]); let mut ans = 0; let mut pre = i32::MIN; for pair in pairs { let (a, b) = (pair[0], pair[1]); if pre < a { ans += 1; pre = b; } } ans } }
646
Maximum Length of Pair Chain
Medium
<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p> <p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p> <p>Return <em>the length longest chain which can be formed</em>.</p> <p>You do not need to use up all the given intervals. You can select pairs in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pairs.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
TypeScript
function findLongestChain(pairs: number[][]): number { pairs.sort((a, b) => a[1] - b[1]); let [ans, pre] = [0, -Infinity]; for (const [a, b] of pairs) { if (pre < a) { ++ans; pre = b; } } return ans; }
647
Palindromic Substrings
Medium
<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p> <p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
C++
class Solution { public: int countSubstrings(string s) { int ans = 0; int n = s.size(); for (int k = 0; k < n * 2 - 1; ++k) { int i = k / 2, j = (k + 1) / 2; while (~i && j < n && s[i] == s[j]) { ++ans; --i; ++j; } } return ans; } };
647
Palindromic Substrings
Medium
<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p> <p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
Go
func countSubstrings(s string) int { ans, n := 0, len(s) for k := 0; k < n*2-1; k++ { i, j := k/2, (k+1)/2 for i >= 0 && j < n && s[i] == s[j] { ans++ i, j = i-1, j+1 } } return ans }
647
Palindromic Substrings
Medium
<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p> <p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
Java
class Solution { public int countSubstrings(String s) { int ans = 0; int n = s.length(); for (int k = 0; k < n * 2 - 1; ++k) { int i = k / 2, j = (k + 1) / 2; while (i >= 0 && j < n && s.charAt(i) == s.charAt(j)) { ++ans; --i; ++j; } } return ans; } }
647
Palindromic Substrings
Medium
<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p> <p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
JavaScript
/** * @param {string} s * @return {number} */ var countSubstrings = function (s) { let ans = 0; const n = s.length; for (let k = 0; k < n * 2 - 1; ++k) { let i = k >> 1; let j = (k + 1) >> 1; while (~i && j < n && s[i] == s[j]) { ++ans; --i; ++j; } } return ans; };
647
Palindromic Substrings
Medium
<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p> <p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
Python
class Solution: def countSubstrings(self, s: str) -> int: ans, n = 0, len(s) for k in range(n * 2 - 1): i, j = k // 2, (k + 1) // 2 while ~i and j < n and s[i] == s[j]: ans += 1 i, j = i - 1, j + 1 return ans
648
Replace Words
Medium
<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p> <p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p> <p>Return <em>the <code>sentence</code></em> after the replacement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot; <strong>Output:</strong> &quot;the cat was rat by the bat&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot; <strong>Output:</strong> &quot;a a b c&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li> <li><code>dictionary[i]</code> consists of only lower-case letters.</li> <li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li> <li><code>sentence</code> consists of only lower-case letters and spaces.</li> <li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li> <li><code>sentence</code> does not have leading or trailing spaces.</li> </ul>
Trie; Array; Hash Table; String
C++
class Trie { private: Trie* children[26]; int ref; public: Trie() : ref(-1) { memset(children, 0, sizeof(children)); } void insert(const string& w, int i) { Trie* node = this; for (auto& c : w) { int idx = c - 'a'; if (!node->children[idx]) { node->children[idx] = new Trie(); } node = node->children[idx]; } node->ref = i; } int search(const string& w) { Trie* node = this; for (auto& c : w) { int idx = c - 'a'; if (!node->children[idx]) { return -1; } node = node->children[idx]; if (node->ref != -1) { return node->ref; } } return -1; } }; class Solution { public: string replaceWords(vector<string>& dictionary, string sentence) { Trie* trie = new Trie(); for (int i = 0; i < dictionary.size(); ++i) { trie->insert(dictionary[i], i); } stringstream ss(sentence); string w; string ans; while (ss >> w) { int idx = trie->search(w); ans += (idx == -1 ? w : dictionary[idx]) + " "; } ans.pop_back(); return ans; } };
648
Replace Words
Medium
<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p> <p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p> <p>Return <em>the <code>sentence</code></em> after the replacement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot; <strong>Output:</strong> &quot;the cat was rat by the bat&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot; <strong>Output:</strong> &quot;a a b c&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li> <li><code>dictionary[i]</code> consists of only lower-case letters.</li> <li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li> <li><code>sentence</code> consists of only lower-case letters and spaces.</li> <li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li> <li><code>sentence</code> does not have leading or trailing spaces.</li> </ul>
Trie; Array; Hash Table; String
Go
type Trie struct { children [26]*Trie ref int } func newTrie() *Trie { return &Trie{ref: -1} } func (this *Trie) insert(w string, i int) { node := this for _, c := range w { idx := c - 'a' if node.children[idx] == nil { node.children[idx] = newTrie() } node = node.children[idx] } node.ref = i } func (this *Trie) search(w string) int { node := this for _, c := range w { idx := c - 'a' if node.children[idx] == nil { return -1 } node = node.children[idx] if node.ref != -1 { return node.ref } } return -1 } func replaceWords(dictionary []string, sentence string) string { trie := newTrie() for i, w := range dictionary { trie.insert(w, i) } ans := strings.Builder{} for _, w := range strings.Split(sentence, " ") { if idx := trie.search(w); idx != -1 { ans.WriteString(dictionary[idx]) } else { ans.WriteString(w) } ans.WriteByte(' ') } return ans.String()[:ans.Len()-1] }
648
Replace Words
Medium
<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p> <p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p> <p>Return <em>the <code>sentence</code></em> after the replacement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot; <strong>Output:</strong> &quot;the cat was rat by the bat&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot; <strong>Output:</strong> &quot;a a b c&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li> <li><code>dictionary[i]</code> consists of only lower-case letters.</li> <li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li> <li><code>sentence</code> consists of only lower-case letters and spaces.</li> <li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li> <li><code>sentence</code> does not have leading or trailing spaces.</li> </ul>
Trie; Array; Hash Table; String
Java
class Solution { public String replaceWords(List<String> dictionary, String sentence) { Set<String> s = new HashSet<>(dictionary); String[] words = sentence.split(" "); for (int i = 0; i < words.length; ++i) { String word = words[i]; for (int j = 1; j <= word.length(); ++j) { String t = word.substring(0, j); if (s.contains(t)) { words[i] = t; break; } } } return String.join(" ", words); } }
648
Replace Words
Medium
<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p> <p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p> <p>Return <em>the <code>sentence</code></em> after the replacement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot; <strong>Output:</strong> &quot;the cat was rat by the bat&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot; <strong>Output:</strong> &quot;a a b c&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li> <li><code>dictionary[i]</code> consists of only lower-case letters.</li> <li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li> <li><code>sentence</code> consists of only lower-case letters and spaces.</li> <li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li> <li><code>sentence</code> does not have leading or trailing spaces.</li> </ul>
Trie; Array; Hash Table; String
Python
class Trie: def __init__(self): self.children: List[Trie | None] = [None] * 26 self.ref: int = -1 def insert(self, w: str, i: int): node = self for c in w: idx = ord(c) - ord("a") if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.ref = i def search(self, w: str) -> int: node = self for c in w: idx = ord(c) - ord("a") if node.children[idx] is None: return -1 node = node.children[idx] if node.ref != -1: return node.ref return -1 class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: trie = Trie() for i, w in enumerate(dictionary): trie.insert(w, i) ans = [] for w in sentence.split(): idx = trie.search(w) ans.append(dictionary[idx] if idx != -1 else w) return " ".join(ans)
648
Replace Words
Medium
<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p> <p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p> <p>Return <em>the <code>sentence</code></em> after the replacement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot; <strong>Output:</strong> &quot;the cat was rat by the bat&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot; <strong>Output:</strong> &quot;a a b c&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li> <li><code>dictionary[i]</code> consists of only lower-case letters.</li> <li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li> <li><code>sentence</code> consists of only lower-case letters and spaces.</li> <li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li> <li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li> <li><code>sentence</code> does not have leading or trailing spaces.</li> </ul>
Trie; Array; Hash Table; String
TypeScript
class Trie { #children: Record<string, Trie> = {}; #ref = -1; insert(w: string, i: number) { let node: Trie = this; for (const c of w) { node.#children[c] ??= new Trie(); node = node.#children[c]; } node.#ref = i; } search(w: string): number { let node: Trie = this; for (const c of w) { if (!node.#children[c]) { return -1; } node = node.#children[c]; if (node.#ref !== -1) { return node.#ref; } } return -1; } } function replaceWords(dictionary: string[], sentence: string): string { const trie = new Trie(); for (let i = 0; i < dictionary.length; i++) { trie.insert(dictionary[i], i); } return sentence .split(' ') .map(w => { const idx = trie.search(w); return idx !== -1 ? dictionary[idx] : w; }) .join(' '); }
649
Dota2 Senate
Medium
<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p> <p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p> <ul> <li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li> <li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li> </ul> <p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p> <p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p> <p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RD&quot; <strong>Output:</strong> &quot;Radiant&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RDD&quot; <strong>Output:</strong> &quot;Dire&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == senate.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Greedy; Queue; String
C++
class Solution { public: string predictPartyVictory(string senate) { int n = senate.size(); queue<int> qr; queue<int> qd; for (int i = 0; i < n; ++i) { if (senate[i] == 'R') { qr.push(i); } else { qd.push(i); } } while (!qr.empty() && !qd.empty()) { int r = qr.front(); int d = qd.front(); qr.pop(); qd.pop(); if (r < d) { qr.push(r + n); } else { qd.push(d + n); } } return qr.empty() ? "Dire" : "Radiant"; } };
649
Dota2 Senate
Medium
<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p> <p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p> <ul> <li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li> <li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li> </ul> <p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p> <p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p> <p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RD&quot; <strong>Output:</strong> &quot;Radiant&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RDD&quot; <strong>Output:</strong> &quot;Dire&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == senate.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Greedy; Queue; String
Go
func predictPartyVictory(senate string) string { n := len(senate) qr := []int{} qd := []int{} for i, c := range senate { if c == 'R' { qr = append(qr, i) } else { qd = append(qd, i) } } for len(qr) > 0 && len(qd) > 0 { r, d := qr[0], qd[0] qr, qd = qr[1:], qd[1:] if r < d { qr = append(qr, r+n) } else { qd = append(qd, d+n) } } if len(qr) > 0 { return "Radiant" } return "Dire" }
649
Dota2 Senate
Medium
<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p> <p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p> <ul> <li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li> <li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li> </ul> <p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p> <p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p> <p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RD&quot; <strong>Output:</strong> &quot;Radiant&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RDD&quot; <strong>Output:</strong> &quot;Dire&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == senate.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Greedy; Queue; String
Java
class Solution { public String predictPartyVictory(String senate) { int n = senate.length(); Deque<Integer> qr = new ArrayDeque<>(); Deque<Integer> qd = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { if (senate.charAt(i) == 'R') { qr.offer(i); } else { qd.offer(i); } } while (!qr.isEmpty() && !qd.isEmpty()) { if (qr.peek() < qd.peek()) { qr.offer(qr.peek() + n); } else { qd.offer(qd.peek() + n); } qr.poll(); qd.poll(); } return qr.isEmpty() ? "Dire" : "Radiant"; } }
649
Dota2 Senate
Medium
<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p> <p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p> <ul> <li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li> <li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li> </ul> <p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p> <p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p> <p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RD&quot; <strong>Output:</strong> &quot;Radiant&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RDD&quot; <strong>Output:</strong> &quot;Dire&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == senate.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Greedy; Queue; String
Python
class Solution: def predictPartyVictory(self, senate: str) -> str: qr = deque() qd = deque() for i, c in enumerate(senate): if c == "R": qr.append(i) else: qd.append(i) n = len(senate) while qr and qd: if qr[0] < qd[0]: qr.append(qr[0] + n) else: qd.append(qd[0] + n) qr.popleft() qd.popleft() return "Radiant" if qr else "Dire"
649
Dota2 Senate
Medium
<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p> <p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p> <ul> <li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li> <li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li> </ul> <p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p> <p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p> <p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RD&quot; <strong>Output:</strong> &quot;Radiant&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RDD&quot; <strong>Output:</strong> &quot;Dire&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == senate.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Greedy; Queue; String
Rust
impl Solution { pub fn predict_party_victory(senate: String) -> String { let mut qr = std::collections::VecDeque::new(); let mut qd = std::collections::VecDeque::new(); let n = senate.len(); for i in 0..n { if let Some(char) = senate.chars().nth(i) { if char == 'R' { qr.push_back(i); } else { qd.push_back(i); } } } while !qr.is_empty() && !qd.is_empty() { let front_qr = qr.pop_front().unwrap(); let front_qd = qd.pop_front().unwrap(); if front_qr < front_qd { qr.push_back(front_qr + n); } else { qd.push_back(front_qd + n); } } if qr.is_empty() { return "Dire".to_string(); } "Radiant".to_string() } }
649
Dota2 Senate
Medium
<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p> <p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p> <ul> <li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li> <li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li> </ul> <p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p> <p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p> <p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RD&quot; <strong>Output:</strong> &quot;Radiant&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> senate = &quot;RDD&quot; <strong>Output:</strong> &quot;Dire&quot; <strong>Explanation:</strong> The first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. And the second senator can&#39;t exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == senate.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Greedy; Queue; String
TypeScript
function predictPartyVictory(senate: string): string { const n = senate.length; const qr: number[] = []; const qd: number[] = []; for (let i = 0; i < n; ++i) { if (senate[i] === 'R') { qr.push(i); } else { qd.push(i); } } while (qr.length > 0 && qd.length > 0) { const r = qr.shift()!; const d = qd.shift()!; if (r < d) { qr.push(r + n); } else { qd.push(d + n); } } return qr.length > 0 ? 'Radiant' : 'Dire'; }
650
2 Keys Keyboard
Medium
<p>There is only one character <code>&#39;A&#39;</code> on the screen of a notepad. You can perform one of two operations on this notepad for each step:</p> <ul> <li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li> <li>Paste: You can paste the characters which are copied last time.</li> </ul> <p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>&#39;A&#39;</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> Initially, we have one character &#39;A&#39;. In step 1, we use Copy All operation. In step 2, we use Paste operation to get &#39;AA&#39;. In step 3, we use Paste operation to get &#39;AAA&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Dynamic Programming
C++
class Solution { public: vector<int> f; int minSteps(int n) { f.assign(n + 1, -1); return dfs(n); } int dfs(int n) { if (n == 1) return 0; if (f[n] != -1) return f[n]; int ans = n; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { ans = min(ans, dfs(n / i) + i); } } f[n] = ans; return ans; } };
650
2 Keys Keyboard
Medium
<p>There is only one character <code>&#39;A&#39;</code> on the screen of a notepad. You can perform one of two operations on this notepad for each step:</p> <ul> <li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li> <li>Paste: You can paste the characters which are copied last time.</li> </ul> <p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>&#39;A&#39;</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> Initially, we have one character &#39;A&#39;. In step 1, we use Copy All operation. In step 2, we use Paste operation to get &#39;AA&#39;. In step 3, we use Paste operation to get &#39;AAA&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Dynamic Programming
Go
func minSteps(n int) int { f := make([]int, n+1) for i := range f { f[i] = -1 } var dfs func(int) int dfs = func(n int) int { if n == 1 { return 0 } if f[n] != -1 { return f[n] } ans := n for i := 2; i*i <= n; i++ { if n%i == 0 { ans = min(ans, dfs(n/i)+i) } } return ans } return dfs(n) }
650
2 Keys Keyboard
Medium
<p>There is only one character <code>&#39;A&#39;</code> on the screen of a notepad. You can perform one of two operations on this notepad for each step:</p> <ul> <li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li> <li>Paste: You can paste the characters which are copied last time.</li> </ul> <p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>&#39;A&#39;</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> Initially, we have one character &#39;A&#39;. In step 1, we use Copy All operation. In step 2, we use Paste operation to get &#39;AA&#39;. In step 3, we use Paste operation to get &#39;AAA&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Dynamic Programming
Java
class Solution { private int[] f; public int minSteps(int n) { f = new int[n + 1]; Arrays.fill(f, -1); return dfs(n); } private int dfs(int n) { if (n == 1) { return 0; } if (f[n] != -1) { return f[n]; } int ans = n; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { ans = Math.min(ans, dfs(n / i) + i); } } f[n] = ans; return ans; } }
650
2 Keys Keyboard
Medium
<p>There is only one character <code>&#39;A&#39;</code> on the screen of a notepad. You can perform one of two operations on this notepad for each step:</p> <ul> <li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li> <li>Paste: You can paste the characters which are copied last time.</li> </ul> <p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>&#39;A&#39;</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> Initially, we have one character &#39;A&#39;. In step 1, we use Copy All operation. In step 2, we use Paste operation to get &#39;AA&#39;. In step 3, we use Paste operation to get &#39;AAA&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Dynamic Programming
Python
class Solution: def minSteps(self, n: int) -> int: @cache def dfs(n): if n == 1: return 0 i, ans = 2, n while i * i <= n: if n % i == 0: ans = min(ans, dfs(n // i) + i) i += 1 return ans return dfs(n)
651
4 Keys Keyboard
Medium
<p>Imagine you have a special keyboard with the following keys:</p> <ul> <li>A: Print one <code>&#39;A&#39;</code> on the screen.</li> <li>Ctrl-A: Select the whole screen.</li> <li>Ctrl-C: Copy selection to buffer.</li> <li>Ctrl-V: Print buffer on screen appending it after what has already been printed.</li> </ul> <p>Given an integer n, return <em>the maximum number of </em><code>&#39;A&#39;</code><em> you can print on the screen with <strong>at most</strong> </em><code>n</code><em> presses on the keys</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can at most get 3 A&#39;s on screen by pressing the following key sequence: A, A, A </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 9 <strong>Explanation:</strong> We can at most get 9 A&#39;s on screen by pressing following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Dynamic Programming
C++
class Solution { public: int maxA(int n) { vector<int> dp(n + 1); iota(dp.begin(), dp.end(), 0); for (int i = 3; i < n + 1; ++i) { for (int j = 2; j < i - 1; ++j) { dp[i] = max(dp[i], dp[j - 1] * (i - j)); } } return dp[n]; } };
651
4 Keys Keyboard
Medium
<p>Imagine you have a special keyboard with the following keys:</p> <ul> <li>A: Print one <code>&#39;A&#39;</code> on the screen.</li> <li>Ctrl-A: Select the whole screen.</li> <li>Ctrl-C: Copy selection to buffer.</li> <li>Ctrl-V: Print buffer on screen appending it after what has already been printed.</li> </ul> <p>Given an integer n, return <em>the maximum number of </em><code>&#39;A&#39;</code><em> you can print on the screen with <strong>at most</strong> </em><code>n</code><em> presses on the keys</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can at most get 3 A&#39;s on screen by pressing the following key sequence: A, A, A </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 9 <strong>Explanation:</strong> We can at most get 9 A&#39;s on screen by pressing following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Dynamic Programming
Go
func maxA(n int) int { dp := make([]int, n+1) for i := range dp { dp[i] = i } for i := 3; i < n+1; i++ { for j := 2; j < i-1; j++ { dp[i] = max(dp[i], dp[j-1]*(i-j)) } } return dp[n] }
651
4 Keys Keyboard
Medium
<p>Imagine you have a special keyboard with the following keys:</p> <ul> <li>A: Print one <code>&#39;A&#39;</code> on the screen.</li> <li>Ctrl-A: Select the whole screen.</li> <li>Ctrl-C: Copy selection to buffer.</li> <li>Ctrl-V: Print buffer on screen appending it after what has already been printed.</li> </ul> <p>Given an integer n, return <em>the maximum number of </em><code>&#39;A&#39;</code><em> you can print on the screen with <strong>at most</strong> </em><code>n</code><em> presses on the keys</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can at most get 3 A&#39;s on screen by pressing the following key sequence: A, A, A </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 9 <strong>Explanation:</strong> We can at most get 9 A&#39;s on screen by pressing following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Dynamic Programming
Java
class Solution { public int maxA(int n) { int[] dp = new int[n + 1]; for (int i = 0; i < n + 1; ++i) { dp[i] = i; } for (int i = 3; i < n + 1; ++i) { for (int j = 2; j < i - 1; ++j) { dp[i] = Math.max(dp[i], dp[j - 1] * (i - j)); } } return dp[n]; } }
651
4 Keys Keyboard
Medium
<p>Imagine you have a special keyboard with the following keys:</p> <ul> <li>A: Print one <code>&#39;A&#39;</code> on the screen.</li> <li>Ctrl-A: Select the whole screen.</li> <li>Ctrl-C: Copy selection to buffer.</li> <li>Ctrl-V: Print buffer on screen appending it after what has already been printed.</li> </ul> <p>Given an integer n, return <em>the maximum number of </em><code>&#39;A&#39;</code><em> you can print on the screen with <strong>at most</strong> </em><code>n</code><em> presses on the keys</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can at most get 3 A&#39;s on screen by pressing the following key sequence: A, A, A </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 9 <strong>Explanation:</strong> We can at most get 9 A&#39;s on screen by pressing following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Dynamic Programming
Python
class Solution: def maxA(self, n: int) -> int: dp = list(range(n + 1)) for i in range(3, n + 1): for j in range(2, i - 1): dp[i] = max(dp[i], dp[j - 1] * (i - j)) return dp[-1]
652
Find Duplicate Subtrees
Medium
<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p> <p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p> <p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e1.jpg" style="width: 450px; height: 354px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4] <strong>Output:</strong> [[2,4],[4]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e2.jpg" style="width: 321px; height: 201px;" /> <pre> <strong>Input:</strong> root = [2,1,1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e33.jpg" style="width: 450px; height: 303px;" /> <pre> <strong>Input:</strong> root = [2,2,2,3,null,3,null] <strong>Output:</strong> [[2,3],[3]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li> <li><code>-200 &lt;= Node.val &lt;= 200</code></li> </ul>
Tree; Depth-First Search; Hash Table; 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: unordered_map<string, int> counter; vector<TreeNode*> ans; vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { dfs(root); return ans; } string dfs(TreeNode* root) { if (!root) return "#"; string v = to_string(root->val) + "," + dfs(root->left) + "," + dfs(root->right); ++counter[v]; if (counter[v] == 2) ans.push_back(root); return v; } };
652
Find Duplicate Subtrees
Medium
<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p> <p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p> <p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e1.jpg" style="width: 450px; height: 354px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4] <strong>Output:</strong> [[2,4],[4]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e2.jpg" style="width: 321px; height: 201px;" /> <pre> <strong>Input:</strong> root = [2,1,1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e33.jpg" style="width: 450px; height: 303px;" /> <pre> <strong>Input:</strong> root = [2,2,2,3,null,3,null] <strong>Output:</strong> [[2,3],[3]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li> <li><code>-200 &lt;= Node.val &lt;= 200</code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findDuplicateSubtrees(root *TreeNode) []*TreeNode { var ans []*TreeNode counter := make(map[string]int) var dfs func(root *TreeNode) string dfs = func(root *TreeNode) string { if root == nil { return "#" } v := strconv.Itoa(root.Val) + "," + dfs(root.Left) + "," + dfs(root.Right) counter[v]++ if counter[v] == 2 { ans = append(ans, root) } return v } dfs(root) return ans }
652
Find Duplicate Subtrees
Medium
<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p> <p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p> <p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e1.jpg" style="width: 450px; height: 354px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4] <strong>Output:</strong> [[2,4],[4]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e2.jpg" style="width: 321px; height: 201px;" /> <pre> <strong>Input:</strong> root = [2,1,1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e33.jpg" style="width: 450px; height: 303px;" /> <pre> <strong>Input:</strong> root = [2,2,2,3,null,3,null] <strong>Output:</strong> [[2,3],[3]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li> <li><code>-200 &lt;= Node.val &lt;= 200</code></li> </ul>
Tree; Depth-First Search; Hash Table; 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 { private Map<String, Integer> counter; private List<TreeNode> ans; public List<TreeNode> findDuplicateSubtrees(TreeNode root) { counter = new HashMap<>(); ans = new ArrayList<>(); dfs(root); return ans; } private String dfs(TreeNode root) { if (root == null) { return "#"; } String v = root.val + "," + dfs(root.left) + "," + dfs(root.right); counter.put(v, counter.getOrDefault(v, 0) + 1); if (counter.get(v) == 2) { ans.add(root); } return v; } }
652
Find Duplicate Subtrees
Medium
<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p> <p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p> <p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e1.jpg" style="width: 450px; height: 354px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4] <strong>Output:</strong> [[2,4],[4]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e2.jpg" style="width: 321px; height: 201px;" /> <pre> <strong>Input:</strong> root = [2,1,1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e33.jpg" style="width: 450px; height: 303px;" /> <pre> <strong>Input:</strong> root = [2,2,2,3,null,3,null] <strong>Output:</strong> [[2,3],[3]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li> <li><code>-200 &lt;= Node.val &lt;= 200</code></li> </ul>
Tree; Depth-First Search; Hash Table; 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 findDuplicateSubtrees( self, root: Optional[TreeNode] ) -> List[Optional[TreeNode]]: def dfs(root): if root is None: return '#' v = f'{root.val},{dfs(root.left)},{dfs(root.right)}' counter[v] += 1 if counter[v] == 2: ans.append(root) return v ans = [] counter = Counter() dfs(root) return ans
652
Find Duplicate Subtrees
Medium
<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p> <p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p> <p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e1.jpg" style="width: 450px; height: 354px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4] <strong>Output:</strong> [[2,4],[4]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e2.jpg" style="width: 321px; height: 201px;" /> <pre> <strong>Input:</strong> root = [2,1,1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e33.jpg" style="width: 450px; height: 303px;" /> <pre> <strong>Input:</strong> root = [2,2,2,3,null,3,null] <strong>Output:</strong> [[2,3],[3]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li> <li><code>-200 &lt;= Node.val &lt;= 200</code></li> </ul>
Tree; Depth-First Search; Hash Table; 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::collections::HashMap; use std::rc::Rc; impl Solution { fn dfs( root: &Option<Rc<RefCell<TreeNode>>>, map: &mut HashMap<String, i32>, res: &mut Vec<Option<Rc<RefCell<TreeNode>>>>, ) -> String { if root.is_none() { return String::from('#'); } let s = { let root = root.as_ref().unwrap().as_ref().borrow(); format!( "{},{},{}", root.val.to_string(), Self::dfs(&root.left, map, res), Self::dfs(&root.right, map, res) ) }; *map.entry(s.clone()).or_insert(0) += 1; if *map.get(&s).unwrap() == 2 { res.push(root.clone()); } return s; } pub fn find_duplicate_subtrees( root: Option<Rc<RefCell<TreeNode>>>, ) -> Vec<Option<Rc<RefCell<TreeNode>>>> { let mut map = HashMap::new(); let mut res = Vec::new(); Self::dfs(&root, &mut map, &mut res); res } }
652
Find Duplicate Subtrees
Medium
<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p> <p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p> <p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e1.jpg" style="width: 450px; height: 354px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4] <strong>Output:</strong> [[2,4],[4]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e2.jpg" style="width: 321px; height: 201px;" /> <pre> <strong>Input:</strong> root = [2,1,1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0652.Find%20Duplicate%20Subtrees/images/e33.jpg" style="width: 450px; height: 303px;" /> <pre> <strong>Input:</strong> root = [2,2,2,3,null,3,null] <strong>Output:</strong> [[2,3],[3]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li> <li><code>-200 &lt;= Node.val &lt;= 200</code></li> </ul>
Tree; Depth-First Search; Hash Table; 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 findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> { const map = new Map<string, number>(); const res = []; const dfs = (root: TreeNode | null) => { if (root == null) { return '#'; } const { val, left, right } = root; const s = `${val},${dfs(left)},${dfs(right)}`; map.set(s, (map.get(s) ?? 0) + 1); if (map.get(s) === 2) { res.push(root); } return s; }; dfs(root); return res; }
653
Two Sum IV - Input is a BST
Easy
<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_1.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_2.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Hash Table; Two Pointers; 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: bool findTarget(TreeNode* root, int k) { unordered_set<int> vis; function<bool(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return false; } if (vis.count(k - root->val)) { return true; } vis.insert(root->val); return dfs(root->left) || dfs(root->right); }; return dfs(root); } };
653
Two Sum IV - Input is a BST
Easy
<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_1.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_2.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Hash Table; Two Pointers; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findTarget(root *TreeNode, k int) bool { vis := map[int]bool{} var dfs func(*TreeNode) bool dfs = func(root *TreeNode) bool { if root == nil { return false } if vis[k-root.Val] { return true } vis[root.Val] = true return dfs(root.Left) || dfs(root.Right) } return dfs(root) }
653
Two Sum IV - Input is a BST
Easy
<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_1.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_2.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Hash Table; Two Pointers; 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 { private Set<Integer> vis = new HashSet<>(); private int k; public boolean findTarget(TreeNode root, int k) { this.k = k; return dfs(root); } private boolean dfs(TreeNode root) { if (root == null) { return false; } if (vis.contains(k - root.val)) { return true; } vis.add(root.val); return dfs(root.left) || dfs(root.right); } }
653
Two Sum IV - Input is a BST
Easy
<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_1.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_2.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Hash Table; Two Pointers; 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 findTarget(self, root: Optional[TreeNode], k: int) -> bool: def dfs(root): if root is None: return False if k - root.val in vis: return True vis.add(root.val) return dfs(root.left) or dfs(root.right) vis = set() return dfs(root)
653
Two Sum IV - Input is a BST
Easy
<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_1.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_2.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Hash Table; Two Pointers; 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::collections::{HashSet, VecDeque}; use std::rc::Rc; impl Solution { pub fn find_target(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> bool { let mut set = HashSet::new(); let mut q = VecDeque::new(); q.push_back(root); while let Some(node) = q.pop_front() { if let Some(node) = node { let mut node = node.as_ref().borrow_mut(); if set.contains(&node.val) { return true; } set.insert(k - node.val); q.push_back(node.left.take()); q.push_back(node.right.take()); } } false } }
653
Two Sum IV - Input is a BST
Easy
<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_1.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/images/sum_tree_2.jpg" style="width: 400px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Hash Table; Two Pointers; 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 findTarget(root: TreeNode | null, k: number): boolean { const dfs = (root: TreeNode | null) => { if (!root) { return false; } if (vis.has(k - root.val)) { return true; } vis.add(root.val); return dfs(root.left) || dfs(root.right); }; const vis = new Set<number>(); return dfs(root); }
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* construct(int* nums, int start, int end) { if (start >= end) { return NULL; } int idx = 0; int maxVal = -1; for (int i = start; i < end; i++) { if (nums[i] > maxVal) { idx = i; maxVal = nums[i]; } } struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); res->val = maxVal; res->left = construct(nums, start, idx); res->right = construct(nums, idx + 1, end); return res; } struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) { return construct(nums, 0, numsSize); }
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
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: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { return dfs(nums, 0, nums.size() - 1); } TreeNode* dfs(vector<int>& nums, int l, int r) { if (l > r) return nullptr; int i = l; for (int j = l; j <= r; ++j) { if (nums[i] < nums[j]) { i = j; } } TreeNode* root = new TreeNode(nums[i]); root->left = dfs(nums, l, i - 1); root->right = dfs(nums, i + 1, r); return root; } };
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func constructMaximumBinaryTree(nums []int) *TreeNode { var dfs func(l, r int) *TreeNode dfs = func(l, r int) *TreeNode { if l > r { return nil } i := l for j := l; j <= r; j++ { if nums[i] < nums[j] { i = j } } root := &TreeNode{Val: nums[i]} root.Left = dfs(l, i-1) root.Right = dfs(i+1, r) return root } return dfs(0, len(nums)-1) }
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
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 { private int[] nums; public TreeNode constructMaximumBinaryTree(int[] nums) { this.nums = nums; return dfs(0, nums.length - 1); } private TreeNode dfs(int l, int r) { if (l > r) { return null; } int i = l; for (int j = l; j <= r; ++j) { if (nums[i] < nums[j]) { i = j; } } TreeNode root = new TreeNode(nums[i]); root.left = dfs(l, i - 1); root.right = dfs(i + 1, r); return root; } }
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
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 constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: def dfs(nums): if not nums: return None val = max(nums) i = nums.index(val) root = TreeNode(val) root.left = dfs(nums[:i]) root.right = dfs(nums[i + 1 :]) return root return dfs(nums)
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
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 construct(nums: &Vec<i32>, start: usize, end: usize) -> Option<Rc<RefCell<TreeNode>>> { if start >= end { return None; } let mut idx = 0; let mut max_val = -1; for i in start..end { if nums[i] > max_val { idx = i; max_val = nums[i]; } } Some(Rc::new(RefCell::new(TreeNode { val: max_val, left: Self::construct(nums, start, idx), right: Self::construct(nums, idx + 1, end), }))) } pub fn construct_maximum_binary_tree(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { Self::construct(&nums, 0, nums.len()) } }
654
Maximum Binary Tree
Medium
<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree1.jpg" style="width: 302px; height: 421px;" /> <pre> <strong>Input:</strong> nums = [3,2,1,6,0,5] <strong>Output:</strong> [6,3,5,null,2,0,null,null,1] <strong>Explanation:</strong> The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0654.Maximum%20Binary%20Tree/images/tree2.jpg" style="width: 182px; height: 301px;" /> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [3,null,2,null,1] </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;= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Stack; Tree; Array; Divide and Conquer; Binary Tree; Monotonic Stack
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 constructMaximumBinaryTree(nums: number[]): TreeNode | null { const n = nums.length; if (n === 0) { return null; } const [val, i] = nums.reduce((r, v, i) => (r[0] < v ? [v, i] : r), [-1, 0]); return new TreeNode( val, constructMaximumBinaryTree(nums.slice(0, i)), constructMaximumBinaryTree(nums.slice(i + 1)), ); }
655
Print Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix </em><code>res</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print1-tree.jpg" style="width: 141px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> [[&quot;&quot;,&quot;1&quot;,&quot;&quot;], &nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print2-tree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> [[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 &lt;= Node.val &lt;= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</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: vector<vector<string>> printTree(TreeNode* root) { int h = height(root); int m = h + 1, n = (1 << (h + 1)) - 1; vector<vector<string>> ans(m, vector<string>(n, "")); dfs(root, ans, h, 0, (n - 1) / 2); return ans; } void dfs(TreeNode* root, vector<vector<string>>& ans, int h, int r, int c) { if (!root) return; ans[r][c] = to_string(root->val); dfs(root->left, ans, h, r + 1, c - pow(2, h - r - 1)); dfs(root->right, ans, h, r + 1, c + pow(2, h - r - 1)); } int height(TreeNode* root) { if (!root) return -1; return 1 + max(height(root->left), height(root->right)); } };
655
Print Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix </em><code>res</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print1-tree.jpg" style="width: 141px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> [[&quot;&quot;,&quot;1&quot;,&quot;&quot;], &nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print2-tree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> [[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 &lt;= Node.val &lt;= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</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 printTree(root *TreeNode) [][]string { var height func(root *TreeNode) int height = func(root *TreeNode) int { if root == nil { return -1 } return 1 + max(height(root.Left), height(root.Right)) } h := height(root) m, n := h+1, (1<<(h+1))-1 ans := make([][]string, m) for i := range ans { ans[i] = make([]string, n) for j := range ans[i] { ans[i][j] = "" } } var dfs func(root *TreeNode, r, c int) dfs = func(root *TreeNode, r, c int) { if root == nil { return } ans[r][c] = strconv.Itoa(root.Val) dfs(root.Left, r+1, c-int(math.Pow(float64(2), float64(h-r-1)))) dfs(root.Right, r+1, c+int(math.Pow(float64(2), float64(h-r-1)))) } dfs(root, 0, (n-1)/2) return ans }
655
Print Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix </em><code>res</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print1-tree.jpg" style="width: 141px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> [[&quot;&quot;,&quot;1&quot;,&quot;&quot;], &nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print2-tree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> [[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 &lt;= Node.val &lt;= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</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 List<List<String>> printTree(TreeNode root) { int h = height(root); int m = h + 1, n = (1 << (h + 1)) - 1; String[][] res = new String[m][n]; for (int i = 0; i < m; ++i) { Arrays.fill(res[i], ""); } dfs(root, res, h, 0, (n - 1) / 2); List<List<String>> ans = new ArrayList<>(); for (String[] t : res) { ans.add(Arrays.asList(t)); } return ans; } private void dfs(TreeNode root, String[][] res, int h, int r, int c) { if (root == null) { return; } res[r][c] = String.valueOf(root.val); dfs(root.left, res, h, r + 1, c - (1 << (h - r - 1))); dfs(root.right, res, h, r + 1, c + (1 << (h - r - 1))); } private int height(TreeNode root) { if (root == null) { return -1; } return 1 + Math.max(height(root.left), height(root.right)); } }
655
Print Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix </em><code>res</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print1-tree.jpg" style="width: 141px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> [[&quot;&quot;,&quot;1&quot;,&quot;&quot;], &nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print2-tree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> [[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 &lt;= Node.val &lt;= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</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 printTree(self, root: Optional[TreeNode]) -> List[List[str]]: def height(root): if root is None: return -1 return 1 + max(height(root.left), height(root.right)) def dfs(root, r, c): if root is None: return ans[r][c] = str(root.val) dfs(root.left, r + 1, c - 2 ** (h - r - 1)) dfs(root.right, r + 1, c + 2 ** (h - r - 1)) h = height(root) m, n = h + 1, 2 ** (h + 1) - 1 ans = [[""] * n for _ in range(m)] dfs(root, 0, (n - 1) // 2) return ans
655
Print Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix </em><code>res</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print1-tree.jpg" style="width: 141px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> [[&quot;&quot;,&quot;1&quot;,&quot;&quot;], &nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print2-tree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> [[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 &lt;= Node.val &lt;= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</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 get_height(root: &Option<Rc<RefCell<TreeNode>>>, h: u32) -> u32 { if let Some(node) = root { let node = node.borrow(); return Self::get_height(&node.left, h + 1).max(Self::get_height(&node.right, h + 1)); } h - 1 } fn dfs( root: &Option<Rc<RefCell<TreeNode>>>, i: usize, j: usize, res: &mut Vec<Vec<String>>, height: u32, ) { if root.is_none() { return; } let node = root.as_ref().unwrap().borrow(); res[i][j] = node.val.to_string(); Self::dfs( &node.left, i + 1, j - (2usize).pow(height - (i as u32) - 1), res, height, ); Self::dfs( &node.right, i + 1, j + (2usize).pow(height - (i as u32) - 1), res, height, ); } pub fn print_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<String>> { let height = Self::get_height(&root, 0); let m = (height + 1) as usize; let n = (2usize).pow(height + 1) - 1; let mut res = vec![vec![String::new(); n]; m]; Self::dfs(&root, 0, (n - 1) >> 1, &mut res, height); res } }
655
Print Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix </em><code>res</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print1-tree.jpg" style="width: 141px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> [[&quot;&quot;,&quot;1&quot;,&quot;&quot;], &nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0655.Print%20Binary%20Tree/images/print2-tree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> [[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;], &nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 &lt;= Node.val &lt;= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</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 printTree(root: TreeNode | null): string[][] { const getHeight = (root: TreeNode | null, h: number) => { if (root == null) { return h - 1; } return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1)); }; const height = getHeight(root, 0); const m = height + 1; const n = 2 ** (height + 1) - 1; const res: string[][] = Array.from({ length: m }, () => new Array(n).fill('')); const dfs = (root: TreeNode | null, i: number, j: number) => { if (root === null) { return; } const { val, left, right } = root; res[i][j] = val + ''; dfs(left, i + 1, j - 2 ** (height - i - 1)); dfs(right, i + 1, j + 2 ** (height - i - 1)); }; dfs(root, 0, (n - 1) >>> 1); return res; }
656
Coin Path
Hard
<p>You are given an integer array <code>coins</code> (<strong>1-indexed</strong>) of length <code>n</code> and an integer <code>maxJump</code>. You can jump to any index <code>i</code> of the array <code>coins</code> if <code>coins[i] != -1</code> and you have to pay <code>coins[i]</code> when you visit index <code>i</code>. In addition to that, if you are currently at index <code>i</code>, you can only jump to any index <code>i + k</code> where <code>i + k &lt;= n</code> and <code>k</code> is a value in the range <code>[1, maxJump]</code>.</p> <p>You are initially positioned at index <code>1</code> (<code>coins[1]</code> is not <code>-1</code>). You want to find the path that reaches index n with the minimum cost.</p> <p>Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the <strong>lexicographically smallest</strong> such path. If it is not possible to reach index n, return an empty array.</p> <p>A path <code>p1 = [Pa<sub>1</sub>, Pa<sub>2</sub>, ..., Pa<sub>x</sub>]</code> of length <code>x</code> is <strong>lexicographically smaller</strong> than <code>p2 = [Pb<sub>1</sub>, Pb<sub>2</sub>, ..., Pb<sub>x</sub>]</code> of length <code>y</code>, if and only if at the first <code>j</code> where <code>Pa<sub>j</sub></code> and <code>Pb<sub>j</sub></code> differ, <code>Pa<sub>j</sub> &lt; Pb<sub>j</sub></code>; when no such <code>j</code> exists, then <code>x &lt; y</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 2 <strong>Output:</strong> [1,3,5] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 1000</code></li> <li><code>-1 &lt;= coins[i] &lt;= 100</code></li> <li><code>coins[1] != -1</code></li> <li><code>1 &lt;= maxJump &lt;= 100</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: vector<int> cheapestJump(vector<int>& coins, int maxJump) { int n = coins.size(); vector<int> ans; if (coins[n - 1] == -1) { return ans; } int f[n]; const int inf = 1 << 30; f[n - 1] = coins[n - 1]; for (int i = n - 2; ~i; --i) { f[i] = inf; if (coins[i] != -1) { for (int j = i + 1; j < min(n, i + maxJump + 1); ++j) { f[i] = min(f[i], f[j] + coins[i]); } } } if (f[0] == inf) { return ans; } for (int i = 0, s = f[0]; i < n; ++i) { if (f[i] == s) { s -= coins[i]; ans.push_back(i + 1); } } return ans; } };
656
Coin Path
Hard
<p>You are given an integer array <code>coins</code> (<strong>1-indexed</strong>) of length <code>n</code> and an integer <code>maxJump</code>. You can jump to any index <code>i</code> of the array <code>coins</code> if <code>coins[i] != -1</code> and you have to pay <code>coins[i]</code> when you visit index <code>i</code>. In addition to that, if you are currently at index <code>i</code>, you can only jump to any index <code>i + k</code> where <code>i + k &lt;= n</code> and <code>k</code> is a value in the range <code>[1, maxJump]</code>.</p> <p>You are initially positioned at index <code>1</code> (<code>coins[1]</code> is not <code>-1</code>). You want to find the path that reaches index n with the minimum cost.</p> <p>Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the <strong>lexicographically smallest</strong> such path. If it is not possible to reach index n, return an empty array.</p> <p>A path <code>p1 = [Pa<sub>1</sub>, Pa<sub>2</sub>, ..., Pa<sub>x</sub>]</code> of length <code>x</code> is <strong>lexicographically smaller</strong> than <code>p2 = [Pb<sub>1</sub>, Pb<sub>2</sub>, ..., Pb<sub>x</sub>]</code> of length <code>y</code>, if and only if at the first <code>j</code> where <code>Pa<sub>j</sub></code> and <code>Pb<sub>j</sub></code> differ, <code>Pa<sub>j</sub> &lt; Pb<sub>j</sub></code>; when no such <code>j</code> exists, then <code>x &lt; y</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 2 <strong>Output:</strong> [1,3,5] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 1000</code></li> <li><code>-1 &lt;= coins[i] &lt;= 100</code></li> <li><code>coins[1] != -1</code></li> <li><code>1 &lt;= maxJump &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Go
func cheapestJump(coins []int, maxJump int) (ans []int) { n := len(coins) if coins[n-1] == -1 { return } f := make([]int, n) f[n-1] = coins[n-1] const inf = 1 << 30 for i := n - 2; i >= 0; i-- { f[i] = inf if coins[i] != -1 { for j := i + 1; j < n && j < i+maxJump+1; j++ { if f[i] > f[j]+coins[i] { f[i] = f[j] + coins[i] } } } } if f[0] == inf { return } for i, s := 0, f[0]; i < n; i++ { if f[i] == s { s -= coins[i] ans = append(ans, i+1) } } return }
656
Coin Path
Hard
<p>You are given an integer array <code>coins</code> (<strong>1-indexed</strong>) of length <code>n</code> and an integer <code>maxJump</code>. You can jump to any index <code>i</code> of the array <code>coins</code> if <code>coins[i] != -1</code> and you have to pay <code>coins[i]</code> when you visit index <code>i</code>. In addition to that, if you are currently at index <code>i</code>, you can only jump to any index <code>i + k</code> where <code>i + k &lt;= n</code> and <code>k</code> is a value in the range <code>[1, maxJump]</code>.</p> <p>You are initially positioned at index <code>1</code> (<code>coins[1]</code> is not <code>-1</code>). You want to find the path that reaches index n with the minimum cost.</p> <p>Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the <strong>lexicographically smallest</strong> such path. If it is not possible to reach index n, return an empty array.</p> <p>A path <code>p1 = [Pa<sub>1</sub>, Pa<sub>2</sub>, ..., Pa<sub>x</sub>]</code> of length <code>x</code> is <strong>lexicographically smaller</strong> than <code>p2 = [Pb<sub>1</sub>, Pb<sub>2</sub>, ..., Pb<sub>x</sub>]</code> of length <code>y</code>, if and only if at the first <code>j</code> where <code>Pa<sub>j</sub></code> and <code>Pb<sub>j</sub></code> differ, <code>Pa<sub>j</sub> &lt; Pb<sub>j</sub></code>; when no such <code>j</code> exists, then <code>x &lt; y</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 2 <strong>Output:</strong> [1,3,5] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 1000</code></li> <li><code>-1 &lt;= coins[i] &lt;= 100</code></li> <li><code>coins[1] != -1</code></li> <li><code>1 &lt;= maxJump &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public List<Integer> cheapestJump(int[] coins, int maxJump) { int n = coins.length; List<Integer> ans = new ArrayList<>(); if (coins[n - 1] == -1) { return ans; } int[] f = new int[n]; final int inf = 1 << 30; Arrays.fill(f, inf); f[n - 1] = coins[n - 1]; for (int i = n - 2; i >= 0; --i) { if (coins[i] != -1) { for (int j = i + 1; j < Math.min(n, i + maxJump + 1); ++j) { if (f[i] > f[j] + coins[i]) { f[i] = f[j] + coins[i]; } } } } if (f[0] == inf) { return ans; } for (int i = 0, s = f[0]; i < n; ++i) { if (f[i] == s) { s -= coins[i]; ans.add(i + 1); } } return ans; } }
656
Coin Path
Hard
<p>You are given an integer array <code>coins</code> (<strong>1-indexed</strong>) of length <code>n</code> and an integer <code>maxJump</code>. You can jump to any index <code>i</code> of the array <code>coins</code> if <code>coins[i] != -1</code> and you have to pay <code>coins[i]</code> when you visit index <code>i</code>. In addition to that, if you are currently at index <code>i</code>, you can only jump to any index <code>i + k</code> where <code>i + k &lt;= n</code> and <code>k</code> is a value in the range <code>[1, maxJump]</code>.</p> <p>You are initially positioned at index <code>1</code> (<code>coins[1]</code> is not <code>-1</code>). You want to find the path that reaches index n with the minimum cost.</p> <p>Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the <strong>lexicographically smallest</strong> such path. If it is not possible to reach index n, return an empty array.</p> <p>A path <code>p1 = [Pa<sub>1</sub>, Pa<sub>2</sub>, ..., Pa<sub>x</sub>]</code> of length <code>x</code> is <strong>lexicographically smaller</strong> than <code>p2 = [Pb<sub>1</sub>, Pb<sub>2</sub>, ..., Pb<sub>x</sub>]</code> of length <code>y</code>, if and only if at the first <code>j</code> where <code>Pa<sub>j</sub></code> and <code>Pb<sub>j</sub></code> differ, <code>Pa<sub>j</sub> &lt; Pb<sub>j</sub></code>; when no such <code>j</code> exists, then <code>x &lt; y</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 2 <strong>Output:</strong> [1,3,5] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 1000</code></li> <li><code>-1 &lt;= coins[i] &lt;= 100</code></li> <li><code>coins[1] != -1</code></li> <li><code>1 &lt;= maxJump &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]: if coins[-1] == -1: return [] n = len(coins) f = [inf] * n f[-1] = coins[-1] for i in range(n - 2, -1, -1): if coins[i] != -1: for j in range(i + 1, min(n, i + maxJump + 1)): if f[i] > f[j] + coins[i]: f[i] = f[j] + coins[i] if f[0] == inf: return [] ans = [] s = f[0] for i in range(n): if f[i] == s: s -= coins[i] ans.append(i + 1) return ans
656
Coin Path
Hard
<p>You are given an integer array <code>coins</code> (<strong>1-indexed</strong>) of length <code>n</code> and an integer <code>maxJump</code>. You can jump to any index <code>i</code> of the array <code>coins</code> if <code>coins[i] != -1</code> and you have to pay <code>coins[i]</code> when you visit index <code>i</code>. In addition to that, if you are currently at index <code>i</code>, you can only jump to any index <code>i + k</code> where <code>i + k &lt;= n</code> and <code>k</code> is a value in the range <code>[1, maxJump]</code>.</p> <p>You are initially positioned at index <code>1</code> (<code>coins[1]</code> is not <code>-1</code>). You want to find the path that reaches index n with the minimum cost.</p> <p>Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the <strong>lexicographically smallest</strong> such path. If it is not possible to reach index n, return an empty array.</p> <p>A path <code>p1 = [Pa<sub>1</sub>, Pa<sub>2</sub>, ..., Pa<sub>x</sub>]</code> of length <code>x</code> is <strong>lexicographically smaller</strong> than <code>p2 = [Pb<sub>1</sub>, Pb<sub>2</sub>, ..., Pb<sub>x</sub>]</code> of length <code>y</code>, if and only if at the first <code>j</code> where <code>Pa<sub>j</sub></code> and <code>Pb<sub>j</sub></code> differ, <code>Pa<sub>j</sub> &lt; Pb<sub>j</sub></code>; when no such <code>j</code> exists, then <code>x &lt; y</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 2 <strong>Output:</strong> [1,3,5] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> coins = [1,2,4,-1,2], maxJump = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 1000</code></li> <li><code>-1 &lt;= coins[i] &lt;= 100</code></li> <li><code>coins[1] != -1</code></li> <li><code>1 &lt;= maxJump &lt;= 100</code></li> </ul>
Array; Dynamic Programming
TypeScript
function cheapestJump(coins: number[], maxJump: number): number[] { const n = coins.length; const ans: number[] = []; if (coins[n - 1] == -1) { return ans; } const inf = 1 << 30; const f: number[] = new Array(n).fill(inf); f[n - 1] = coins[n - 1]; for (let i = n - 2; i >= 0; --i) { if (coins[i] !== -1) { for (let j = i + 1; j < Math.min(n, i + maxJump + 1); ++j) { f[i] = Math.min(f[i], f[j] + coins[i]); } } } if (f[0] === inf) { return ans; } for (let i = 0, s = f[0]; i < n; ++i) { if (f[i] == s) { s -= coins[i]; ans.push(i + 1); } } return ans; }