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
609
Find Duplicate File in System
Medium
<p>Given a list <code>paths</code> of directory info, including the directory path, and all the files with contents in this directory, return <em>all the duplicate files in the file system in terms of their paths</em>. You may return the answer in <strong>any order</strong>.</p> <p>A group of duplicate files consists of at least two files that have the same content.</p> <p>A single directory info string in the input list has the following format:</p> <ul> <li><code>&quot;root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)&quot;</code></li> </ul> <p>It means there are <code>n</code> files <code>(f1.txt, f2.txt ... fn.txt)</code> with content <code>(f1_content, f2_content ... fn_content)</code> respectively in the directory &quot;<code>root/d1/d2/.../dm&quot;</code>. Note that <code>n &gt;= 1</code> and <code>m &gt;= 0</code>. If <code>m = 0</code>, it means the directory is just the root directory.</p> <p>The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:</p> <ul> <li><code>&quot;directory_path/file_name.txt&quot;</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= paths[i].length &lt;= 3000</code></li> <li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li> <li><code>paths[i]</code> consist of English letters, digits, <code>&#39;/&#39;</code>, <code>&#39;.&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li>You may assume no files or directories share the same name in the same directory.</li> <li>You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Imagine you are given a real file system, how will you search files? DFS or BFS?</li> <li>If the file content is very large (GB level), how will you modify your solution?</li> <li>If you can only read the file by 1kb each time, how will you modify your solution?</li> <li>What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?</li> <li>How to make sure the duplicated files you find are not false positive?</li> </ul>
Array; Hash Table; String
Go
func findDuplicate(paths []string) [][]string { d := map[string][]string{} for _, p := range paths { ps := strings.Split(p, " ") for i := 1; i < len(ps); i++ { j := strings.IndexByte(ps[i], '(') content := ps[i][j+1 : len(ps[i])-1] name := ps[0] + "/" + ps[i][:j] d[content] = append(d[content], name) } } ans := [][]string{} for _, e := range d { if len(e) > 1 { ans = append(ans, e) } } return ans }
609
Find Duplicate File in System
Medium
<p>Given a list <code>paths</code> of directory info, including the directory path, and all the files with contents in this directory, return <em>all the duplicate files in the file system in terms of their paths</em>. You may return the answer in <strong>any order</strong>.</p> <p>A group of duplicate files consists of at least two files that have the same content.</p> <p>A single directory info string in the input list has the following format:</p> <ul> <li><code>&quot;root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)&quot;</code></li> </ul> <p>It means there are <code>n</code> files <code>(f1.txt, f2.txt ... fn.txt)</code> with content <code>(f1_content, f2_content ... fn_content)</code> respectively in the directory &quot;<code>root/d1/d2/.../dm&quot;</code>. Note that <code>n &gt;= 1</code> and <code>m &gt;= 0</code>. If <code>m = 0</code>, it means the directory is just the root directory.</p> <p>The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:</p> <ul> <li><code>&quot;directory_path/file_name.txt&quot;</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= paths[i].length &lt;= 3000</code></li> <li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li> <li><code>paths[i]</code> consist of English letters, digits, <code>&#39;/&#39;</code>, <code>&#39;.&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li>You may assume no files or directories share the same name in the same directory.</li> <li>You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Imagine you are given a real file system, how will you search files? DFS or BFS?</li> <li>If the file content is very large (GB level), how will you modify your solution?</li> <li>If you can only read the file by 1kb each time, how will you modify your solution?</li> <li>What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?</li> <li>How to make sure the duplicated files you find are not false positive?</li> </ul>
Array; Hash Table; String
Java
class Solution { public List<List<String>> findDuplicate(String[] paths) { Map<String, List<String>> d = new HashMap<>(); for (String p : paths) { String[] ps = p.split(" "); for (int i = 1; i < ps.length; ++i) { int j = ps[i].indexOf('('); String content = ps[i].substring(j + 1, ps[i].length() - 1); String name = ps[0] + '/' + ps[i].substring(0, j); d.computeIfAbsent(content, k -> new ArrayList<>()).add(name); } } List<List<String>> ans = new ArrayList<>(); for (var e : d.values()) { if (e.size() > 1) { ans.add(e); } } return ans; } }
609
Find Duplicate File in System
Medium
<p>Given a list <code>paths</code> of directory info, including the directory path, and all the files with contents in this directory, return <em>all the duplicate files in the file system in terms of their paths</em>. You may return the answer in <strong>any order</strong>.</p> <p>A group of duplicate files consists of at least two files that have the same content.</p> <p>A single directory info string in the input list has the following format:</p> <ul> <li><code>&quot;root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)&quot;</code></li> </ul> <p>It means there are <code>n</code> files <code>(f1.txt, f2.txt ... fn.txt)</code> with content <code>(f1_content, f2_content ... fn_content)</code> respectively in the directory &quot;<code>root/d1/d2/.../dm&quot;</code>. Note that <code>n &gt;= 1</code> and <code>m &gt;= 0</code>. If <code>m = 0</code>, it means the directory is just the root directory.</p> <p>The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:</p> <ul> <li><code>&quot;directory_path/file_name.txt&quot;</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= paths[i].length &lt;= 3000</code></li> <li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li> <li><code>paths[i]</code> consist of English letters, digits, <code>&#39;/&#39;</code>, <code>&#39;.&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li>You may assume no files or directories share the same name in the same directory.</li> <li>You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Imagine you are given a real file system, how will you search files? DFS or BFS?</li> <li>If the file content is very large (GB level), how will you modify your solution?</li> <li>If you can only read the file by 1kb each time, how will you modify your solution?</li> <li>What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?</li> <li>How to make sure the duplicated files you find are not false positive?</li> </ul>
Array; Hash Table; String
Python
class Solution: def findDuplicate(self, paths: List[str]) -> List[List[str]]: d = defaultdict(list) for p in paths: ps = p.split() for f in ps[1:]: i = f.find('(') name, content = f[:i], f[i + 1 : -1] d[content].append(ps[0] + '/' + name) return [v for v in d.values() if len(v) > 1]
609
Find Duplicate File in System
Medium
<p>Given a list <code>paths</code> of directory info, including the directory path, and all the files with contents in this directory, return <em>all the duplicate files in the file system in terms of their paths</em>. You may return the answer in <strong>any order</strong>.</p> <p>A group of duplicate files consists of at least two files that have the same content.</p> <p>A single directory info string in the input list has the following format:</p> <ul> <li><code>&quot;root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)&quot;</code></li> </ul> <p>It means there are <code>n</code> files <code>(f1.txt, f2.txt ... fn.txt)</code> with content <code>(f1_content, f2_content ... fn_content)</code> respectively in the directory &quot;<code>root/d1/d2/.../dm&quot;</code>. Note that <code>n &gt;= 1</code> and <code>m &gt;= 0</code>. If <code>m = 0</code>, it means the directory is just the root directory.</p> <p>The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:</p> <ul> <li><code>&quot;directory_path/file_name.txt&quot;</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] <strong>Output:</strong> [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= paths[i].length &lt;= 3000</code></li> <li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li> <li><code>paths[i]</code> consist of English letters, digits, <code>&#39;/&#39;</code>, <code>&#39;.&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li>You may assume no files or directories share the same name in the same directory.</li> <li>You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Imagine you are given a real file system, how will you search files? DFS or BFS?</li> <li>If the file content is very large (GB level), how will you modify your solution?</li> <li>If you can only read the file by 1kb each time, how will you modify your solution?</li> <li>What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?</li> <li>How to make sure the duplicated files you find are not false positive?</li> </ul>
Array; Hash Table; String
TypeScript
function findDuplicate(paths: string[]): string[][] { const d = new Map<string, string[]>(); for (const p of paths) { const [root, ...fs] = p.split(' '); for (const f of fs) { const [name, content] = f.split(/\(|\)/g).filter(Boolean); const t = d.get(content) ?? []; t.push(root + '/' + name); d.set(content, t); } } return [...d.values()].filter(e => e.length > 1); }
610
Triangle Judgement
Easy
<p>Table: <code>Triangle</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | x | int | | y | int | | z | int | +-------------+------+ In SQL, (x, y, z) is the primary key column for this table. Each row of this table contains the lengths of three line segments. </pre> <p>&nbsp;</p> <p>Report for every three line segments whether they can form a triangle.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Triangle table: +----+----+----+ | x | y | z | +----+----+----+ | 13 | 15 | 30 | | 10 | 20 | 15 | +----+----+----+ <strong>Output:</strong> +----+----+----+----------+ | x | y | z | triangle | +----+----+----+----------+ | 13 | 15 | 30 | No | | 10 | 20 | 15 | Yes | +----+----+----+----------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT *, IF(x + y > z AND x + z > y AND y + z > x, 'Yes', 'No') AS triangle FROM Triangle;
611
Valid Triangle Number
Medium
<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,3,4] <strong>Output:</strong> 4 </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> </ul>
Greedy; Array; Two Pointers; Binary Search; Sorting
C++
class Solution { public: int triangleNumber(vector<int>& nums) { ranges::sort(nums); int ans = 0, n = nums.size(); for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { int sum = nums[i] + nums[j]; auto it = ranges::lower_bound(nums.begin() + j + 1, nums.end(), sum); int k = int(it - nums.begin()) - 1; ans += max(0, k - j); } } return ans; } };
611
Valid Triangle Number
Medium
<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,3,4] <strong>Output:</strong> 4 </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> </ul>
Greedy; Array; Two Pointers; Binary Search; Sorting
Go
func triangleNumber(nums []int) int { sort.Ints(nums) n := len(nums) ans := 0 for i := 0; i < n-2; i++ { for j := i + 1; j < n-1; j++ { sum := nums[i] + nums[j] k := sort.SearchInts(nums[j+1:], sum) + j + 1 - 1 if k > j { ans += k - j } } } return ans }
611
Valid Triangle Number
Medium
<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,3,4] <strong>Output:</strong> 4 </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> </ul>
Greedy; Array; Two Pointers; Binary Search; Sorting
Java
class Solution { public int triangleNumber(int[] nums) { Arrays.sort(nums); int n = nums.length; int res = 0; for (int i = n - 1; i >= 2; --i) { int l = 0, r = i - 1; while (l < r) { if (nums[l] + nums[r] > nums[i]) { res += r - l; --r; } else { ++l; } } } return res; } }
611
Valid Triangle Number
Medium
<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,3,4] <strong>Output:</strong> 4 </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> </ul>
Greedy; Array; Two Pointers; Binary Search; Sorting
Python
class Solution: def triangleNumber(self, nums: List[int]) -> int: nums.sort() ans, n = 0, len(nums) for i in range(n - 2): for j in range(i + 1, n - 1): k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1 ans += k - j return ans
611
Valid Triangle Number
Medium
<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,3,4] <strong>Output:</strong> 4 </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> </ul>
Greedy; Array; Two Pointers; Binary Search; Sorting
Rust
impl Solution { pub fn triangle_number(mut nums: Vec<i32>) -> i32 { nums.sort(); let n = nums.len(); let mut ans = 0; for i in 0..n.saturating_sub(2) { for j in i + 1..n.saturating_sub(1) { let sum = nums[i] + nums[j]; let mut left = j + 1; let mut right = n; while left < right { let mid = (left + right) / 2; if nums[mid] < sum { left = mid + 1; } else { right = mid; } } if left > j + 1 { ans += (left - 1 - j) as i32; } } } ans } }
611
Valid Triangle Number
Medium
<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,3,4] <strong>Output:</strong> 4 </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> </ul>
Greedy; Array; Two Pointers; Binary Search; Sorting
TypeScript
function triangleNumber(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; let ans = 0; for (let i = 0; i < n - 2; i++) { for (let j = i + 1; j < n - 1; j++) { const sum = nums[i] + nums[j]; let k = _.sortedIndex(nums, sum, j + 1) - 1; if (k > j) { ans += k - j; } } } return ans; }
612
Shortest Distance in a Plane
Medium
<p>Table: <code>Point2D</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | x | int | | y | int | +-------------+------+ (x, y) is the primary key column (combination of columns with unique values) for this table. Each row of this table indicates the position of a point on the X-Y plane. </pre> <p>&nbsp;</p> <p>The distance between two points <code>p<sub>1</sub>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>p<sub>2</sub>(x<sub>2</sub>, y<sub>2</sub>)</code> is <code>sqrt((x<sub>2</sub> - x<sub>1</sub>)<sup>2</sup> + (y<sub>2</sub> - y<sub>1</sub>)<sup>2</sup>)</code>.</p> <p>Write a solution to report the shortest distance between any two points from the <code>Point2D</code> table. Round the distance to <strong>two decimal points</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Point2D table: +----+----+ | x | y | +----+----+ | -1 | -1 | | 0 | 0 | | -1 | -2 | +----+----+ <strong>Output:</strong> +----------+ | shortest | +----------+ | 1.00 | +----------+ <strong>Explanation:</strong> The shortest distance is 1.00 from point (-1, -1) to (-1, 2). </pre>
Database
SQL
# Write your MySQL query statement below SELECT ROUND(SQRT(POW(p1.x - p2.x, 2) + POW(p1.y - p2.y, 2)), 2) AS shortest FROM Point2D AS p1 JOIN Point2D AS p2 ON p1.x != p2.x OR p1.y != p2.y ORDER BY 1 LIMIT 1;
613
Shortest Distance in a Line
Easy
<p>Table: <code>Point</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | x | int | +-------------+------+ In SQL, x is the primary key column for this table. Each row of this table indicates the position of a point on the X-axis. </pre> <p>&nbsp;</p> <p>Find the shortest distance between any two points from the <code>Point</code> table.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Point table: +----+ | x | +----+ | -1 | | 0 | | 2 | +----+ <strong>Output:</strong> +----------+ | shortest | +----------+ | 1 | +----------+ <strong>Explanation:</strong> The shortest distance is between points -1 and 0 which is |(-1) - 0| = 1. </pre> <p>&nbsp;</p> <p><strong>Follow up:</strong> How could you optimize your solution if the <code>Point</code> table is ordered <strong>in ascending order</strong>?</p>
Database
SQL
# Write your MySQL query statement below SELECT MIN(p2.x - p1.x) AS shortest FROM Point AS p1 JOIN Point AS p2 ON p1.x < p2.x;
614
Second Degree Follower
Medium
<p>Table: <code>Follow</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | followee | varchar | | follower | varchar | +-------------+---------+ (followee, follower) is the primary key (combination of columns with unique values) for this table. Each row of this table indicates that the user follower follows the user followee on a social network. There will not be a user following themself. </pre> <p>&nbsp;</p> <p>A <strong>second-degree follower</strong> is a user who:</p> <ul> <li>follows at least one user, and</li> <li>is followed by at least one user.</li> </ul> <p>Write a solution&nbsp;to report the <strong>second-degree users</strong> and the number of their followers.</p> <p>Return the result table <strong>ordered</strong> by <code>follower</code> <strong>in alphabetical order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Follow table: +----------+----------+ | followee | follower | +----------+----------+ | Alice | Bob | | Bob | Cena | | Bob | Donald | | Donald | Edward | +----------+----------+ <strong>Output:</strong> +----------+-----+ | follower | num | +----------+-----+ | Bob | 2 | | Donald | 1 | +----------+-----+ <strong>Explanation:</strong> User Bob has 2 followers. Bob is a second-degree follower because he follows Alice, so we include him in the result table. User Donald has 1 follower. Donald is a second-degree follower because he follows Bob, so we include him in the result table. User Alice has 1 follower. Alice is not a second-degree follower because she does not follow anyone, so we don not include her in the result table. </pre>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT f1.follower AS follower, f2.follower AS followee FROM Follow AS f1 JOIN Follow AS f2 ON f1.follower = f2.followee ) SELECT follower, COUNT(DISTINCT followee) AS num FROM T GROUP BY 1 ORDER BY 1;
615
Average Salary Departments VS Company
Hard
<p>Table: <code>Salary</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | employee_id | int | | amount | int | | pay_date | date | +-------------+------+ In SQL, id is the primary key column for this table. Each row of this table indicates the salary of an employee in one month. employee_id is a foreign key (reference column) from the Employee table. </pre> <p>&nbsp;</p> <p>Table: <code>Employee</code></p> <pre> +---------------+------+ | Column Name | Type | +---------------+------+ | employee_id | int | | department_id | int | +---------------+------+ In SQL, employee_id is the primary key column for this table. Each row of this table indicates the department of an employee. </pre> <p>&nbsp;</p> <p>Find the comparison result <strong>(higher/lower/same)</strong> of the average salary of employees in a department to the company&#39;s average salary.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Salary table: +----+-------------+--------+------------+ | id | employee_id | amount | pay_date | +----+-------------+--------+------------+ | 1 | 1 | 9000 | 2017/03/31 | | 2 | 2 | 6000 | 2017/03/31 | | 3 | 3 | 10000 | 2017/03/31 | | 4 | 1 | 7000 | 2017/02/28 | | 5 | 2 | 6000 | 2017/02/28 | | 6 | 3 | 8000 | 2017/02/28 | +----+-------------+--------+------------+ Employee table: +-------------+---------------+ | employee_id | department_id | +-------------+---------------+ | 1 | 1 | | 2 | 2 | | 3 | 2 | +-------------+---------------+ <strong>Output:</strong> +-----------+---------------+------------+ | pay_month | department_id | comparison | +-----------+---------------+------------+ | 2017-02 | 1 | same | | 2017-03 | 1 | higher | | 2017-02 | 2 | same | | 2017-03 | 2 | lower | +-----------+---------------+------------+ <strong>Explanation:</strong> In March, the company&#39;s average salary is (9000+6000+10000)/3 = 8333.33... The average salary for department &#39;1&#39; is 9000, which is the salary of employee_id &#39;1&#39; since there is only one employee in this department. So the comparison result is &#39;higher&#39; since 9000 &gt; 8333.33 obviously. The average salary of department &#39;2&#39; is (6000 + 10000)/2 = 8000, which is the average of employee_id &#39;2&#39; and &#39;3&#39;. So the comparison result is &#39;lower&#39; since 8000 &lt; 8333.33. With he same formula for the average salary comparison in February, the result is &#39;same&#39; since both the department &#39;1&#39; and &#39;2&#39; have the same average salary with the company, which is 7000. </pre>
Database
SQL
# Write your MySQL query statement below WITH t AS ( SELECT DATE_FORMAT(pay_date, '%Y-%m') AS pay_month, department_id, AVG(amount) OVER (PARTITION BY pay_date) AS company_avg_amount, AVG(amount) OVER (PARTITION BY pay_date, department_id) AS department_avg_amount FROM Salary AS s JOIN Employee AS e ON s.employee_id = e.employee_id ) SELECT DISTINCT pay_month, department_id, CASE WHEN company_avg_amount = department_avg_amount THEN 'same' WHEN company_avg_amount < department_avg_amount THEN 'higher' ELSE 'lower' END AS comparison FROM t;
616
Add Bold Tag in String
Medium
<p>You are given a string <code>s</code> and an array of strings <code>words</code>.</p> <p>You should add a closed pair of bold tag <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> to wrap the substrings in <code>s</code> that exist in <code>words</code>.</p> <ul> <li>If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag.</li> <li>If two substrings wrapped by bold tags are consecutive, you should combine them.</li> </ul> <p>Return <code>s</code> <em>after adding the bold tags</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcxyz123&quot;, words = [&quot;abc&quot;,&quot;123&quot;] <strong>Output:</strong> &quot;&lt;b&gt;abc&lt;/b&gt;xyz&lt;b&gt;123&lt;/b&gt;&quot; <strong>Explanation:</strong> The two strings of words are substrings of s as following: &quot;<u>abc</u>xyz<u>123</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabbb&quot;, words = [&quot;aa&quot;,&quot;b&quot;] <strong>Output:</strong> &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot; <strong>Explanation:</strong> &quot;aa&quot; appears as a substring two times: &quot;<u>aa</u>abbb&quot; and &quot;a<u>aa</u>bbb&quot;. &quot;b&quot; appears as a substring three times: &quot;aaa<u>b</u>bb&quot;, &quot;aaab<u>b</u>b&quot;, and &quot;aaabb<u>b</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring: &quot;&lt;b&gt;a&lt;b&gt;a&lt;/b&gt;a&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since the first two &lt;b&gt;&#39;s overlap, we merge them: &quot;&lt;b&gt;aaa&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since now the four &lt;b&gt;&#39;s are consecutive, we merge them: &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>0 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>words[i]</code> consist of English letters and digits.</li> <li>All the values of <code>words</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/bold-words-in-string/description/" target="_blank">758. Bold Words in String</a>.</p>
Trie; Array; Hash Table; String; String Matching
C++
class Trie { public: vector<Trie*> children; bool isEnd; Trie() { children.resize(128); isEnd = false; } void insert(string word) { Trie* node = this; for (char c : word) { if (!node->children[c]) node->children[c] = new Trie(); node = node->children[c]; } node->isEnd = true; } }; class Solution { public: string addBoldTag(string s, vector<string>& words) { Trie* trie = new Trie(); for (string w : words) trie->insert(w); int n = s.size(); vector<pair<int, int>> pairs; for (int i = 0; i < n; ++i) { Trie* node = trie; for (int j = i; j < n; ++j) { int idx = s[j]; if (!node->children[idx]) break; node = node->children[idx]; if (node->isEnd) pairs.push_back({i, j}); } } if (pairs.empty()) return s; vector<pair<int, int>> t; int st = pairs[0].first, ed = pairs[0].second; for (int i = 1; i < pairs.size(); ++i) { int a = pairs[i].first, b = pairs[i].second; if (ed + 1 < a) { t.push_back({st, ed}); st = a, ed = b; } else ed = max(ed, b); } t.push_back({st, ed}); string ans = ""; int i = 0, j = 0; while (i < n) { if (j == t.size()) { ans += s.substr(i); break; } st = t[j].first, ed = t[j].second; if (i < st) ans += s.substr(i, st - i); ans += "<b>"; ans += s.substr(st, ed - st + 1); ans += "</b>"; i = ed + 1; ++j; } return ans; } };
616
Add Bold Tag in String
Medium
<p>You are given a string <code>s</code> and an array of strings <code>words</code>.</p> <p>You should add a closed pair of bold tag <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> to wrap the substrings in <code>s</code> that exist in <code>words</code>.</p> <ul> <li>If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag.</li> <li>If two substrings wrapped by bold tags are consecutive, you should combine them.</li> </ul> <p>Return <code>s</code> <em>after adding the bold tags</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcxyz123&quot;, words = [&quot;abc&quot;,&quot;123&quot;] <strong>Output:</strong> &quot;&lt;b&gt;abc&lt;/b&gt;xyz&lt;b&gt;123&lt;/b&gt;&quot; <strong>Explanation:</strong> The two strings of words are substrings of s as following: &quot;<u>abc</u>xyz<u>123</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabbb&quot;, words = [&quot;aa&quot;,&quot;b&quot;] <strong>Output:</strong> &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot; <strong>Explanation:</strong> &quot;aa&quot; appears as a substring two times: &quot;<u>aa</u>abbb&quot; and &quot;a<u>aa</u>bbb&quot;. &quot;b&quot; appears as a substring three times: &quot;aaa<u>b</u>bb&quot;, &quot;aaab<u>b</u>b&quot;, and &quot;aaabb<u>b</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring: &quot;&lt;b&gt;a&lt;b&gt;a&lt;/b&gt;a&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since the first two &lt;b&gt;&#39;s overlap, we merge them: &quot;&lt;b&gt;aaa&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since now the four &lt;b&gt;&#39;s are consecutive, we merge them: &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>0 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>words[i]</code> consist of English letters and digits.</li> <li>All the values of <code>words</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/bold-words-in-string/description/" target="_blank">758. Bold Words in String</a>.</p>
Trie; Array; Hash Table; String; String Matching
Go
type Trie struct { children [128]*Trie isEnd bool } func newTrie() *Trie { return &Trie{} } func (this *Trie) insert(word string) { node := this for _, c := range word { if node.children[c] == nil { node.children[c] = newTrie() } node = node.children[c] } node.isEnd = true } func addBoldTag(s string, words []string) string { trie := newTrie() for _, w := range words { trie.insert(w) } n := len(s) var pairs [][]int for i := range s { node := trie for j := i; j < n; j++ { if node.children[s[j]] == nil { break } node = node.children[s[j]] if node.isEnd { pairs = append(pairs, []int{i, j}) } } } if len(pairs) == 0 { return s } var t [][]int st, ed := pairs[0][0], pairs[0][1] for i := 1; i < len(pairs); i++ { a, b := pairs[i][0], pairs[i][1] if ed+1 < a { t = append(t, []int{st, ed}) st, ed = a, b } else { ed = max(ed, b) } } t = append(t, []int{st, ed}) var ans strings.Builder i, j := 0, 0 for i < n { if j == len(t) { ans.WriteString(s[i:]) break } st, ed = t[j][0], t[j][1] if i < st { ans.WriteString(s[i:st]) } ans.WriteString("<b>") ans.WriteString(s[st : ed+1]) ans.WriteString("</b>") i = ed + 1 j++ } return ans.String() }
616
Add Bold Tag in String
Medium
<p>You are given a string <code>s</code> and an array of strings <code>words</code>.</p> <p>You should add a closed pair of bold tag <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> to wrap the substrings in <code>s</code> that exist in <code>words</code>.</p> <ul> <li>If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag.</li> <li>If two substrings wrapped by bold tags are consecutive, you should combine them.</li> </ul> <p>Return <code>s</code> <em>after adding the bold tags</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcxyz123&quot;, words = [&quot;abc&quot;,&quot;123&quot;] <strong>Output:</strong> &quot;&lt;b&gt;abc&lt;/b&gt;xyz&lt;b&gt;123&lt;/b&gt;&quot; <strong>Explanation:</strong> The two strings of words are substrings of s as following: &quot;<u>abc</u>xyz<u>123</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabbb&quot;, words = [&quot;aa&quot;,&quot;b&quot;] <strong>Output:</strong> &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot; <strong>Explanation:</strong> &quot;aa&quot; appears as a substring two times: &quot;<u>aa</u>abbb&quot; and &quot;a<u>aa</u>bbb&quot;. &quot;b&quot; appears as a substring three times: &quot;aaa<u>b</u>bb&quot;, &quot;aaab<u>b</u>b&quot;, and &quot;aaabb<u>b</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring: &quot;&lt;b&gt;a&lt;b&gt;a&lt;/b&gt;a&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since the first two &lt;b&gt;&#39;s overlap, we merge them: &quot;&lt;b&gt;aaa&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since now the four &lt;b&gt;&#39;s are consecutive, we merge them: &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>0 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>words[i]</code> consist of English letters and digits.</li> <li>All the values of <code>words</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/bold-words-in-string/description/" target="_blank">758. Bold Words in String</a>.</p>
Trie; Array; Hash Table; String; String Matching
Java
class Trie { Trie[] children = new Trie[128]; boolean isEnd; public void insert(String word) { Trie node = this; for (char c : word.toCharArray()) { if (node.children[c] == null) { node.children[c] = new Trie(); } node = node.children[c]; } node.isEnd = true; } } class Solution { public String addBoldTag(String s, String[] words) { Trie trie = new Trie(); for (String w : words) { trie.insert(w); } List<int[]> pairs = new ArrayList<>(); int n = s.length(); for (int i = 0; i < n; ++i) { Trie node = trie; for (int j = i; j < n; ++j) { int idx = s.charAt(j); if (node.children[idx] == null) { break; } node = node.children[idx]; if (node.isEnd) { pairs.add(new int[] {i, j}); } } } if (pairs.isEmpty()) { return s; } List<int[]> t = new ArrayList<>(); int st = pairs.get(0)[0], ed = pairs.get(0)[1]; for (int j = 1; j < pairs.size(); ++j) { int a = pairs.get(j)[0], b = pairs.get(j)[1]; if (ed + 1 < a) { t.add(new int[] {st, ed}); st = a; ed = b; } else { ed = Math.max(ed, b); } } t.add(new int[] {st, ed}); int i = 0, j = 0; StringBuilder ans = new StringBuilder(); while (i < n) { if (j == t.size()) { ans.append(s.substring(i)); break; } st = t.get(j)[0]; ed = t.get(j)[1]; if (i < st) { ans.append(s.substring(i, st)); } ++j; ans.append("<b>"); ans.append(s.substring(st, ed + 1)); ans.append("</b>"); i = ed + 1; } return ans.toString(); } }
616
Add Bold Tag in String
Medium
<p>You are given a string <code>s</code> and an array of strings <code>words</code>.</p> <p>You should add a closed pair of bold tag <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> to wrap the substrings in <code>s</code> that exist in <code>words</code>.</p> <ul> <li>If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag.</li> <li>If two substrings wrapped by bold tags are consecutive, you should combine them.</li> </ul> <p>Return <code>s</code> <em>after adding the bold tags</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcxyz123&quot;, words = [&quot;abc&quot;,&quot;123&quot;] <strong>Output:</strong> &quot;&lt;b&gt;abc&lt;/b&gt;xyz&lt;b&gt;123&lt;/b&gt;&quot; <strong>Explanation:</strong> The two strings of words are substrings of s as following: &quot;<u>abc</u>xyz<u>123</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabbb&quot;, words = [&quot;aa&quot;,&quot;b&quot;] <strong>Output:</strong> &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot; <strong>Explanation:</strong> &quot;aa&quot; appears as a substring two times: &quot;<u>aa</u>abbb&quot; and &quot;a<u>aa</u>bbb&quot;. &quot;b&quot; appears as a substring three times: &quot;aaa<u>b</u>bb&quot;, &quot;aaab<u>b</u>b&quot;, and &quot;aaabb<u>b</u>&quot;. We add &lt;b&gt; before each substring and &lt;/b&gt; after each substring: &quot;&lt;b&gt;a&lt;b&gt;a&lt;/b&gt;a&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since the first two &lt;b&gt;&#39;s overlap, we merge them: &quot;&lt;b&gt;aaa&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&lt;b&gt;b&lt;/b&gt;&quot;. Since now the four &lt;b&gt;&#39;s are consecutive, we merge them: &quot;&lt;b&gt;aaabbb&lt;/b&gt;&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>0 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>words[i]</code> consist of English letters and digits.</li> <li>All the values of <code>words</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/bold-words-in-string/description/" target="_blank">758. Bold Words in String</a>.</p>
Trie; Array; Hash Table; String; String Matching
Python
class Trie: def __init__(self): self.children = [None] * 128 self.is_end = False def insert(self, word): node = self for c in word: idx = ord(c) if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.is_end = True class Solution: def addBoldTag(self, s: str, words: List[str]) -> str: trie = Trie() for w in words: trie.insert(w) n = len(s) pairs = [] for i in range(n): node = trie for j in range(i, n): idx = ord(s[j]) if node.children[idx] is None: break node = node.children[idx] if node.is_end: pairs.append([i, j]) if not pairs: return s st, ed = pairs[0] t = [] for a, b in pairs[1:]: if ed + 1 < a: t.append([st, ed]) st, ed = a, b else: ed = max(ed, b) t.append([st, ed]) ans = [] i = j = 0 while i < n: if j == len(t): ans.append(s[i:]) break st, ed = t[j] if i < st: ans.append(s[i:st]) ans.append('<b>') ans.append(s[st : ed + 1]) ans.append('</b>') j += 1 i = ed + 1 return ''.join(ans)
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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: TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { if (!root1) return root2; if (!root2) return root1; TreeNode* node = new TreeNode(root1->val + root2->val); node->left = mergeTrees(root1->left, root2->left); node->right = mergeTrees(root1->right, root2->right); return node; } };
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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 mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode { if root1 == nil { return root2 } if root2 == nil { return root1 } node := &TreeNode{Val: root1.Val + root2.Val} node.Left = mergeTrees(root1.Left, root2.Left) node.Right = mergeTrees(root1.Right, root2.Right) return node }
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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 TreeNode mergeTrees(TreeNode root1, TreeNode root2) { if (root1 == null) { return root2; } if (root2 == null) { return root1; } TreeNode node = new TreeNode(root1.val + root2.val); node.left = mergeTrees(root1.left, root2.left); node.right = mergeTrees(root1.right, root2.right); return node; } }
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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} root1 * @param {TreeNode} root2 * @return {TreeNode} */ var mergeTrees = function (root1, root2) { if (!root1) { return root2; } if (!root2) { return root1; } const node = new TreeNode(root1.val + root2.val); node.left = mergeTrees(root1.left, root2.left); node.right = mergeTrees(root1.right, root2.right); return node; };
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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 mergeTrees( self, root1: Optional[TreeNode], root2: Optional[TreeNode] ) -> Optional[TreeNode]: if root1 is None: return root2 if root2 is None: return root1 node = TreeNode(root1.val + root2.val) node.left = self.mergeTrees(root1.left, root2.left) node.right = self.mergeTrees(root1.right, root2.right) return node
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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 { pub fn merge_trees( root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>, ) -> Option<Rc<RefCell<TreeNode>>> { match (root1.is_some(), root2.is_some()) { (false, false) => None, (true, false) => root1, (false, true) => root2, (true, true) => { { let mut r1 = root1.as_ref().unwrap().borrow_mut(); let mut r2 = root2.as_ref().unwrap().borrow_mut(); r1.val += r2.val; r1.left = Self::merge_trees(r1.left.take(), r2.left.take()); r1.right = Self::merge_trees(r1.right.take(), r2.right.take()); } root1 } } } }
617
Merge Two Binary Trees
Easy
<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p> <p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p> <p>Return <em>the merged tree</em>.</p> <p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</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/0617.Merge%20Two%20Binary%20Trees/images/merge.jpg" style="width: 600px; height: 163px;" /> <pre> <strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] <strong>Output:</strong> [3,4,5,5,4,null,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root1 = [1], root2 = [1,2] <strong>Output:</strong> [2,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></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 mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { if (root1 === null && root2 === null) return null; if (root1 === null) return root2; if (root2 === null) return root1; const left = mergeTrees(root1.left, root2.left); const right = mergeTrees(root1.right, root2.right); return new TreeNode(root1.val + root2.val, left, right); }
618
Students Report By Geography
Hard
<p>Table: <code>Student</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | name | varchar | | continent | varchar | +-------------+---------+ This table may contain duplicate rows. Each row of this table indicates the name of a student and the continent they came from. </pre> <p>&nbsp;</p> <p>A school has students from Asia, Europe, and America.</p> <p>Write a solution to <a href="https://en.wikipedia.org/wiki/Pivot_table" target="_blank">pivot</a> the continent column in the <code>Student</code> table so that each name is <strong>sorted alphabetically</strong> and displayed underneath its corresponding continent. The output headers should be <code>America</code>, <code>Asia</code>, and <code>Europe</code>, respectively.</p> <p>The test cases are generated so that the student number from America is not less than either Asia or Europe.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Student table: +--------+-----------+ | name | continent | +--------+-----------+ | Jane | America | | Pascal | Europe | | Xi | Asia | | Jack | America | +--------+-----------+ <strong>Output:</strong> +---------+------+--------+ | America | Asia | Europe | +---------+------+--------+ | Jack | Xi | Pascal | | Jane | null | null | +---------+------+--------+ </pre> <p>&nbsp;</p> <p><strong>Follow up:</strong> If it is unknown which continent has the most students, could you write a solution to generate the student report?</p>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY continent ORDER BY name ) AS rk FROM Student ) SELECT MAX(IF(continent = 'America', name, NULL)) AS 'America', MAX(IF(continent = 'Asia', name, NULL)) AS 'Asia', MAX(IF(continent = 'Europe', name, NULL)) AS 'Europe' FROM T GROUP BY rk;
619
Biggest Single Number
Easy
<p>Table: <code>MyNumbers</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | num | int | +-------------+------+ This table may contain duplicates (In other words, there is no primary key for this table in SQL). Each row of this table contains an integer. </pre> <p>&nbsp;</p> <p>A <strong>single number</strong> is a number that appeared only once in the <code>MyNumbers</code> table.</p> <p>Find the largest <strong>single number</strong>. If there is no <strong>single number</strong>, report <code>null</code>.</p> <p>The result format is in the following example.</p> <ptable> </ptable> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> MyNumbers table: +-----+ | num | +-----+ | 8 | | 8 | | 3 | | 3 | | 1 | | 4 | | 5 | | 6 | +-----+ <strong>Output:</strong> +-----+ | num | +-----+ | 6 | +-----+ <strong>Explanation:</strong> The single numbers are 1, 4, 5, and 6. Since 6 is the largest single number, we return it. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> MyNumbers table: +-----+ | num | +-----+ | 8 | | 8 | | 7 | | 7 | | 3 | | 3 | | 3 | +-----+ <strong>Output:</strong> +------+ | num | +------+ | null | +------+ <strong>Explanation:</strong> There are no single numbers in the input table so we return null. </pre>
Database
SQL
# Write your MySQL query statement below SELECT MAX(num) AS num FROM ( SELECT num FROM MyNumbers GROUP BY 1 HAVING COUNT(1) = 1 ) AS t;
620
Not Boring Movies
Easy
<p>Table: <code>Cinema</code></p> <pre> +----------------+----------+ | Column Name | Type | +----------------+----------+ | id | int | | movie | varchar | | description | varchar | | rating | float | +----------------+----------+ id is the primary key (column with unique values) for this table. Each row contains information about the name of a movie, its genre, and its rating. rating is a 2 decimal places float in the range [0, 10] </pre> <p>&nbsp;</p> <p>Write a solution to report the movies with an odd-numbered ID and a description that is not <code>&quot;boring&quot;</code>.</p> <p>Return the result table ordered by <code>rating</code> <strong>in descending order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Cinema table: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 1 | War | great 3D | 8.9 | | 2 | Science | fiction | 8.5 | | 3 | irish | boring | 6.2 | | 4 | Ice song | Fantacy | 8.6 | | 5 | House card | Interesting | 9.1 | +----+------------+-------------+--------+ <strong>Output:</strong> +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 5 | House card | Interesting | 9.1 | | 1 | War | great 3D | 8.9 | +----+------------+-------------+--------+ <strong>Explanation:</strong> We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer. </pre>
Database
SQL
# Write your MySQL query statement below SELECT * FROM Cinema WHERE description != 'boring' AND id & 1 = 1 ORDER BY 4 DESC;
621
Task Scheduler
Medium
<p>You are given an array of CPU <code>tasks</code>, each labeled with a letter from A to Z, and a number <code>n</code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#39;s a constraint: there has to be a gap of <strong>at least</strong> <code>n</code> intervals between two tasks with the same label.</p> <p>Return the <strong>minimum</strong> number of CPU intervals required to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">8</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p> <p>After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3<sup>rd</sup> interval, neither A nor B can be done, so you idle. By the 4<sup>th</sup> interval, you can do A again as 2 intervals have passed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">6</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p> <p>With a cooling interval of 1, you can repeat a task after just one other task.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">10</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p> <p>There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li> <li><code>tasks[i]</code> is an uppercase English letter.</li> <li><code>0 &lt;= n &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table; Counting; Sorting; Heap (Priority Queue)
C++
class Solution { public: int leastInterval(vector<char>& tasks, int n) { vector<int> cnt(26); int x = 0; for (char c : tasks) { c -= 'A'; ++cnt[c]; x = max(x, cnt[c]); } int s = 0; for (int v : cnt) { s += v == x; } return max((int) tasks.size(), (x - 1) * (n + 1) + s); } };
621
Task Scheduler
Medium
<p>You are given an array of CPU <code>tasks</code>, each labeled with a letter from A to Z, and a number <code>n</code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#39;s a constraint: there has to be a gap of <strong>at least</strong> <code>n</code> intervals between two tasks with the same label.</p> <p>Return the <strong>minimum</strong> number of CPU intervals required to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">8</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p> <p>After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3<sup>rd</sup> interval, neither A nor B can be done, so you idle. By the 4<sup>th</sup> interval, you can do A again as 2 intervals have passed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">6</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p> <p>With a cooling interval of 1, you can repeat a task after just one other task.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">10</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p> <p>There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li> <li><code>tasks[i]</code> is an uppercase English letter.</li> <li><code>0 &lt;= n &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table; Counting; Sorting; Heap (Priority Queue)
C#
public class Solution { public int LeastInterval(char[] tasks, int n) { int[] cnt = new int[26]; int x = 0; foreach (char c in tasks) { cnt[c - 'A']++; x = Math.Max(x, cnt[c - 'A']); } int s = 0; foreach (int v in cnt) { s = v == x ? s + 1 : s; } return Math.Max(tasks.Length, (x - 1) * (n + 1) + s); } }
621
Task Scheduler
Medium
<p>You are given an array of CPU <code>tasks</code>, each labeled with a letter from A to Z, and a number <code>n</code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#39;s a constraint: there has to be a gap of <strong>at least</strong> <code>n</code> intervals between two tasks with the same label.</p> <p>Return the <strong>minimum</strong> number of CPU intervals required to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">8</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p> <p>After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3<sup>rd</sup> interval, neither A nor B can be done, so you idle. By the 4<sup>th</sup> interval, you can do A again as 2 intervals have passed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">6</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p> <p>With a cooling interval of 1, you can repeat a task after just one other task.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">10</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p> <p>There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li> <li><code>tasks[i]</code> is an uppercase English letter.</li> <li><code>0 &lt;= n &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table; Counting; Sorting; Heap (Priority Queue)
Go
func leastInterval(tasks []byte, n int) int { cnt := make([]int, 26) x := 0 for _, c := range tasks { c -= 'A' cnt[c]++ x = max(x, cnt[c]) } s := 0 for _, v := range cnt { if v == x { s++ } } return max(len(tasks), (x-1)*(n+1)+s) }
621
Task Scheduler
Medium
<p>You are given an array of CPU <code>tasks</code>, each labeled with a letter from A to Z, and a number <code>n</code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#39;s a constraint: there has to be a gap of <strong>at least</strong> <code>n</code> intervals between two tasks with the same label.</p> <p>Return the <strong>minimum</strong> number of CPU intervals required to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">8</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p> <p>After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3<sup>rd</sup> interval, neither A nor B can be done, so you idle. By the 4<sup>th</sup> interval, you can do A again as 2 intervals have passed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">6</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p> <p>With a cooling interval of 1, you can repeat a task after just one other task.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">10</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p> <p>There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li> <li><code>tasks[i]</code> is an uppercase English letter.</li> <li><code>0 &lt;= n &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table; Counting; Sorting; Heap (Priority Queue)
Java
class Solution { public int leastInterval(char[] tasks, int n) { int[] cnt = new int[26]; int x = 0; for (char c : tasks) { c -= 'A'; ++cnt[c]; x = Math.max(x, cnt[c]); } int s = 0; for (int v : cnt) { if (v == x) { ++s; } } return Math.max(tasks.length, (x - 1) * (n + 1) + s); } }
621
Task Scheduler
Medium
<p>You are given an array of CPU <code>tasks</code>, each labeled with a letter from A to Z, and a number <code>n</code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#39;s a constraint: there has to be a gap of <strong>at least</strong> <code>n</code> intervals between two tasks with the same label.</p> <p>Return the <strong>minimum</strong> number of CPU intervals required to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">8</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p> <p>After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3<sup>rd</sup> interval, neither A nor B can be done, so you idle. By the 4<sup>th</sup> interval, you can do A again as 2 intervals have passed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">6</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p> <p>With a cooling interval of 1, you can repeat a task after just one other task.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">10</span></p> <p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p> <p>There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li> <li><code>tasks[i]</code> is an uppercase English letter.</li> <li><code>0 &lt;= n &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table; Counting; Sorting; Heap (Priority Queue)
Python
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: cnt = Counter(tasks) x = max(cnt.values()) s = sum(v == x for v in cnt.values()) return max(len(tasks), (x - 1) * (n + 1) + s)
622
Design Circular Queue
Medium
<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p> <p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p> <p>Implement the <code>MyCircularQueue</code> class:</p> <ul> <li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li> <li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li> <li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li> </ul> <p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 3, true, true, true, 4] <strong>Explanation</strong> MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // 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>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
C++
class MyCircularQueue { private: int front; int size; int capacity; vector<int> q; public: MyCircularQueue(int k) { capacity = k; q = vector<int>(k); front = size = 0; } bool enQueue(int value) { if (isFull()) return false; int idx = (front + size) % capacity; q[idx] = value; ++size; return true; } bool deQueue() { if (isEmpty()) return false; front = (front + 1) % capacity; --size; return true; } int Front() { if (isEmpty()) return -1; return q[front]; } int Rear() { if (isEmpty()) return -1; int idx = (front + size - 1) % capacity; return q[idx]; } bool isEmpty() { return size == 0; } bool isFull() { return size == capacity; } }; /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue* obj = new MyCircularQueue(k); * bool param_1 = obj->enQueue(value); * bool param_2 = obj->deQueue(); * int param_3 = obj->Front(); * int param_4 = obj->Rear(); * bool param_5 = obj->isEmpty(); * bool param_6 = obj->isFull(); */
622
Design Circular Queue
Medium
<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p> <p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p> <p>Implement the <code>MyCircularQueue</code> class:</p> <ul> <li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li> <li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li> <li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li> </ul> <p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 3, true, true, true, 4] <strong>Explanation</strong> MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // 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>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Go
type MyCircularQueue struct { front int size int capacity int q []int } func Constructor(k int) MyCircularQueue { q := make([]int, k) return MyCircularQueue{0, 0, k, q} } func (this *MyCircularQueue) EnQueue(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 *MyCircularQueue) DeQueue() bool { if this.IsEmpty() { return false } this.front = (this.front + 1) % this.capacity this.size-- return true } func (this *MyCircularQueue) Front() int { if this.IsEmpty() { return -1 } return this.q[this.front] } func (this *MyCircularQueue) Rear() int { if this.IsEmpty() { return -1 } idx := (this.front + this.size - 1) % this.capacity return this.q[idx] } func (this *MyCircularQueue) IsEmpty() bool { return this.size == 0 } func (this *MyCircularQueue) IsFull() bool { return this.size == this.capacity } /** * Your MyCircularQueue object will be instantiated and called as such: * obj := Constructor(k); * param_1 := obj.EnQueue(value); * param_2 := obj.DeQueue(); * param_3 := obj.Front(); * param_4 := obj.Rear(); * param_5 := obj.IsEmpty(); * param_6 := obj.IsFull(); */
622
Design Circular Queue
Medium
<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p> <p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p> <p>Implement the <code>MyCircularQueue</code> class:</p> <ul> <li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li> <li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li> <li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li> </ul> <p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 3, true, true, true, 4] <strong>Explanation</strong> MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // 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>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Java
class MyCircularQueue { private int[] q; private int front; private int size; private int capacity; public MyCircularQueue(int k) { q = new int[k]; capacity = k; } public boolean enQueue(int value) { if (isFull()) { return false; } int idx = (front + size) % capacity; q[idx] = value; ++size; return true; } public boolean deQueue() { if (isEmpty()) { return false; } front = (front + 1) % capacity; --size; return true; } public int Front() { if (isEmpty()) { return -1; } return q[front]; } public int Rear() { if (isEmpty()) { return -1; } int idx = (front + size - 1) % capacity; return q[idx]; } public boolean isEmpty() { return size == 0; } public boolean isFull() { return size == capacity; } } /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue obj = new MyCircularQueue(k); * boolean param_1 = obj.enQueue(value); * boolean param_2 = obj.deQueue(); * int param_3 = obj.Front(); * int param_4 = obj.Rear(); * boolean param_5 = obj.isEmpty(); * boolean param_6 = obj.isFull(); */
622
Design Circular Queue
Medium
<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p> <p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p> <p>Implement the <code>MyCircularQueue</code> class:</p> <ul> <li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li> <li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li> <li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li> </ul> <p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 3, true, true, true, 4] <strong>Explanation</strong> MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // 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>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Python
class MyCircularQueue: def __init__(self, k: int): self.q = [0] * k self.size = 0 self.capacity = k self.front = 0 def enQueue(self, value: int) -> bool: if self.isFull(): return False self.q[(self.front + self.size) % self.capacity] = value self.size += 1 return True def deQueue(self) -> bool: if self.isEmpty(): return False self.front = (self.front + 1) % self.capacity self.size -= 1 return True def Front(self) -> int: return -1 if self.isEmpty() else self.q[self.front] def Rear(self) -> int: if self.isEmpty(): return -1 return self.q[(self.front + self.size - 1) % self.capacity] def isEmpty(self) -> bool: return self.size == 0 def isFull(self) -> bool: return self.size == self.capacity # Your MyCircularQueue object will be instantiated and called as such: # obj = MyCircularQueue(k) # param_1 = obj.enQueue(value) # param_2 = obj.deQueue() # param_3 = obj.Front() # param_4 = obj.Rear() # param_5 = obj.isEmpty() # param_6 = obj.isFull()
622
Design Circular Queue
Medium
<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p> <p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p> <p>Implement the <code>MyCircularQueue</code> class:</p> <ul> <li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li> <li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li> <li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li> </ul> <p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 3, true, true, true, 4] <strong>Explanation</strong> MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // 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>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
Rust
struct MyCircularQueue { q: Vec<i32>, size: usize, capacity: usize, front: usize, } impl MyCircularQueue { fn new(k: i32) -> Self { MyCircularQueue { q: vec![0; k as usize], size: 0, capacity: k as usize, front: 0, } } fn en_queue(&mut self, value: i32) -> bool { if self.is_full() { return false; } let rear = (self.front + self.size) % self.capacity; self.q[rear] = value; self.size += 1; true } fn de_queue(&mut self) -> bool { if self.is_empty() { return false; } self.front = (self.front + 1) % self.capacity; self.size -= 1; true } fn front(&self) -> i32 { if self.is_empty() { -1 } else { self.q[self.front] } } fn rear(&self) -> i32 { if self.is_empty() { -1 } else { let rear = (self.front + self.size - 1) % self.capacity; self.q[rear] } } fn is_empty(&self) -> bool { self.size == 0 } fn is_full(&self) -> bool { self.size == self.capacity } }
622
Design Circular Queue
Medium
<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p> <p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p> <p>Implement the <code>MyCircularQueue</code> class:</p> <ul> <li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li> <li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li> <li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li> <li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li> <li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li> </ul> <p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;] [[3], [1], [2], [3], [4], [], [], [], [4], []] <strong>Output</strong> [null, true, true, true, false, 3, true, true, true, 4] <strong>Explanation</strong> MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // 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>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li> </ul>
Design; Queue; Array; Linked List
TypeScript
class MyCircularQueue { private queue: number[]; private left: number; private right: number; private capacity: number; constructor(k: number) { this.queue = new Array(k); this.left = 0; this.right = 0; this.capacity = k; } enQueue(value: number): boolean { if (this.isFull()) { return false; } this.queue[this.right % this.capacity] = value; this.right++; return true; } deQueue(): boolean { if (this.isEmpty()) { return false; } this.left++; return true; } Front(): number { if (this.isEmpty()) { return -1; } return this.queue[this.left % this.capacity]; } Rear(): number { if (this.isEmpty()) { return -1; } return this.queue[(this.right - 1) % this.capacity]; } isEmpty(): boolean { return this.right - this.left === 0; } isFull(): boolean { return this.right - this.left === this.capacity; } } /** * Your MyCircularQueue object will be instantiated and called as such: * var obj = new MyCircularQueue(k) * var param_1 = obj.enQueue(value) * var param_2 = obj.deQueue() * var param_3 = obj.Front() * var param_4 = obj.Rear() * var param_5 = obj.isEmpty() * var param_6 = obj.isFull() */
623
Add One Row to Tree
Medium
<p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p> <p>Note that the <code>root</code> node is at depth <code>1</code>.</p> <p>The adding rule is:</p> <ul> <li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>&#39;s left subtree root and right subtree root.</li> <li><code>cur</code>&#39;s original left subtree should be the left subtree of the new left subtree root.</li> <li><code>cur</code>&#39;s original right subtree should be the right subtree of the new right subtree root.</li> <li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/addrow-tree.jpg" style="width: 500px; height: 231px;" /> <pre> <strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2 <strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/add2-tree.jpg" style="width: 500px; height: 277px;" /> <pre> <strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3 <strong>Output:</strong> [4,2,null,1,1,3,null,null,1] </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>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= depth &lt;= the depth of tree + 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int val; int depth; TreeNode* addOneRow(TreeNode* root, int val, int depth) { if (depth == 1) return new TreeNode(val, root, nullptr); this->val = val; this->depth = depth; dfs(root, 1); return root; } void dfs(TreeNode* root, int d) { if (!root) return; if (d == depth - 1) { auto l = new TreeNode(val, root->left, nullptr); auto r = new TreeNode(val, nullptr, root->right); root->left = l; root->right = r; return; } dfs(root->left, d + 1); dfs(root->right, d + 1); } };
623
Add One Row to Tree
Medium
<p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p> <p>Note that the <code>root</code> node is at depth <code>1</code>.</p> <p>The adding rule is:</p> <ul> <li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>&#39;s left subtree root and right subtree root.</li> <li><code>cur</code>&#39;s original left subtree should be the left subtree of the new left subtree root.</li> <li><code>cur</code>&#39;s original right subtree should be the right subtree of the new right subtree root.</li> <li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/addrow-tree.jpg" style="width: 500px; height: 231px;" /> <pre> <strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2 <strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/add2-tree.jpg" style="width: 500px; height: 277px;" /> <pre> <strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3 <strong>Output:</strong> [4,2,null,1,1,3,null,null,1] </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>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= depth &lt;= the depth of tree + 1</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 addOneRow(root *TreeNode, val int, depth int) *TreeNode { if depth == 1 { return &TreeNode{Val: val, Left: root} } var dfs func(root *TreeNode, d int) dfs = func(root *TreeNode, d int) { if root == nil { return } if d == depth-1 { l, r := &TreeNode{Val: val, Left: root.Left}, &TreeNode{Val: val, Right: root.Right} root.Left, root.Right = l, r return } dfs(root.Left, d+1) dfs(root.Right, d+1) } dfs(root, 1) return root }
623
Add One Row to Tree
Medium
<p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p> <p>Note that the <code>root</code> node is at depth <code>1</code>.</p> <p>The adding rule is:</p> <ul> <li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>&#39;s left subtree root and right subtree root.</li> <li><code>cur</code>&#39;s original left subtree should be the left subtree of the new left subtree root.</li> <li><code>cur</code>&#39;s original right subtree should be the right subtree of the new right subtree root.</li> <li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/addrow-tree.jpg" style="width: 500px; height: 231px;" /> <pre> <strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2 <strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/add2-tree.jpg" style="width: 500px; height: 277px;" /> <pre> <strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3 <strong>Output:</strong> [4,2,null,1,1,3,null,null,1] </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>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= depth &lt;= the depth of tree + 1</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 { private int val; private int depth; public TreeNode addOneRow(TreeNode root, int val, int depth) { if (depth == 1) { return new TreeNode(val, root, null); } this.val = val; this.depth = depth; dfs(root, 1); return root; } private void dfs(TreeNode root, int d) { if (root == null) { return; } if (d == depth - 1) { TreeNode l = new TreeNode(val, root.left, null); TreeNode r = new TreeNode(val, null, root.right); root.left = l; root.right = r; return; } dfs(root.left, d + 1); dfs(root.right, d + 1); } }
623
Add One Row to Tree
Medium
<p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p> <p>Note that the <code>root</code> node is at depth <code>1</code>.</p> <p>The adding rule is:</p> <ul> <li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>&#39;s left subtree root and right subtree root.</li> <li><code>cur</code>&#39;s original left subtree should be the left subtree of the new left subtree root.</li> <li><code>cur</code>&#39;s original right subtree should be the right subtree of the new right subtree root.</li> <li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/addrow-tree.jpg" style="width: 500px; height: 231px;" /> <pre> <strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2 <strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/add2-tree.jpg" style="width: 500px; height: 277px;" /> <pre> <strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3 <strong>Output:</strong> [4,2,null,1,1,3,null,null,1] </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>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= depth &lt;= the depth of tree + 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 addOneRow( self, root: Optional[TreeNode], val: int, depth: int ) -> Optional[TreeNode]: def dfs(root, d): if root is None: return if d == depth - 1: root.left = TreeNode(val, root.left, None) root.right = TreeNode(val, None, root.right) return dfs(root.left, d + 1) dfs(root.right, d + 1) if depth == 1: return TreeNode(val, root) dfs(root, 1) return root
623
Add One Row to Tree
Medium
<p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p> <p>Note that the <code>root</code> node is at depth <code>1</code>.</p> <p>The adding rule is:</p> <ul> <li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>&#39;s left subtree root and right subtree root.</li> <li><code>cur</code>&#39;s original left subtree should be the left subtree of the new left subtree root.</li> <li><code>cur</code>&#39;s original right subtree should be the right subtree of the new right subtree root.</li> <li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/addrow-tree.jpg" style="width: 500px; height: 231px;" /> <pre> <strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2 <strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0623.Add%20One%20Row%20to%20Tree/images/add2-tree.jpg" style="width: 500px; height: 277px;" /> <pre> <strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3 <strong>Output:</strong> [4,2,null,1,1,3,null,null,1] </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>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= depth &lt;= the depth of tree + 1</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 addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { function dfs(root, d) { if (!root) { return; } if (d == depth - 1) { root.left = new TreeNode(val, root.left, null); root.right = new TreeNode(val, null, root.right); return; } dfs(root.left, d + 1); dfs(root.right, d + 1); } if (depth == 1) { return new TreeNode(val, root); } dfs(root, 1); return root; }
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
C++
class Solution { public: int maxDistance(vector<vector<int>>& arrays) { int ans = 0; int mi = arrays[0][0], mx = arrays[0][arrays[0].size() - 1]; for (int i = 1; i < arrays.size(); ++i) { auto& arr = arrays[i]; int a = abs(arr[0] - mx), b = abs(arr[arr.size() - 1] - mi); ans = max({ans, a, b}); mi = min(mi, arr[0]); mx = max(mx, arr[arr.size() - 1]); } return ans; } };
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
Go
func maxDistance(arrays [][]int) (ans int) { mi, mx := arrays[0][0], arrays[0][len(arrays[0])-1] for _, arr := range arrays[1:] { a, b := abs(arr[0]-mx), abs(arr[len(arr)-1]-mi) ans = max(ans, max(a, b)) mi = min(mi, arr[0]) mx = max(mx, arr[len(arr)-1]) } return ans } func abs(x int) int { if x < 0 { return -x } return x }
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
Java
class Solution { public int maxDistance(List<List<Integer>> arrays) { int ans = 0; int mi = arrays.get(0).get(0); int mx = arrays.get(0).get(arrays.get(0).size() - 1); for (int i = 1; i < arrays.size(); ++i) { var arr = arrays.get(i); int a = Math.abs(arr.get(0) - mx); int b = Math.abs(arr.get(arr.size() - 1) - mi); ans = Math.max(ans, Math.max(a, b)); mi = Math.min(mi, arr.get(0)); mx = Math.max(mx, arr.get(arr.size() - 1)); } return ans; } }
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
JavaScript
/** * @param {number[][]} arrays * @return {number} */ var maxDistance = function (arrays) { let ans = 0; let [mi, mx] = [arrays[0][0], arrays[0].at(-1)]; for (let i = 1; i < arrays.length; ++i) { const arr = arrays[i]; const a = Math.abs(arr[0] - mx); const b = Math.abs(arr.at(-1) - mi); ans = Math.max(ans, a, b); mi = Math.min(mi, arr[0]); mx = Math.max(mx, arr.at(-1)); } return ans; };
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
Python
class Solution: def maxDistance(self, arrays: List[List[int]]) -> int: ans = 0 mi, mx = arrays[0][0], arrays[0][-1] for arr in arrays[1:]: a, b = abs(arr[0] - mx), abs(arr[-1] - mi) ans = max(ans, a, b) mi = min(mi, arr[0]) mx = max(mx, arr[-1]) return ans
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
Rust
impl Solution { pub fn max_distance(arrays: Vec<Vec<i32>>) -> i32 { let mut ans = 0; let mut mi = arrays[0][0]; let mut mx = arrays[0][arrays[0].len() - 1]; for i in 1..arrays.len() { let arr = &arrays[i]; let a = (arr[0] - mx).abs(); let b = (arr[arr.len() - 1] - mi).abs(); ans = ans.max(a).max(b); mi = mi.min(arr[0]); mx = mx.max(arr[arr.len() - 1]); } ans } }
624
Maximum Distance in Arrays
Medium
<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p> <p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p> <p>Return <em>the maximum distance</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrays = [[1],[1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == arrays.length</code></li> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arrays[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li> </ul>
Greedy; Array
TypeScript
function maxDistance(arrays: number[][]): number { let ans = 0; let [mi, mx] = [arrays[0][0], arrays[0].at(-1)!]; for (let i = 1; i < arrays.length; ++i) { const arr = arrays[i]; const a = Math.abs(arr[0] - mx); const b = Math.abs(arr.at(-1)! - mi); ans = Math.max(ans, a, b); mi = Math.min(mi, arr[0]); mx = Math.max(mx, arr.at(-1)!); } return ans; }
625
Minimum Factorization
Medium
<p>Given a positive integer num, return <em>the smallest positive integer </em><code>x</code><em> whose multiplication of each digit equals </em><code>num</code>. If there is no answer or the answer is not fit in <strong>32-bit</strong> signed integer, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 48 <strong>Output:</strong> 68 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = 15 <strong>Output:</strong> 35 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Math
C++
class Solution { public: int smallestFactorization(int num) { if (num < 2) { return num; } long long ans = 0, mul = 1; for (int i = 9; i >= 2; --i) { if (num % i == 0) { while (num % i == 0) { num /= i; ans = mul * i + ans; mul *= 10; } } } return num < 2 && ans <= INT_MAX ? ans : 0; } };
625
Minimum Factorization
Medium
<p>Given a positive integer num, return <em>the smallest positive integer </em><code>x</code><em> whose multiplication of each digit equals </em><code>num</code>. If there is no answer or the answer is not fit in <strong>32-bit</strong> signed integer, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 48 <strong>Output:</strong> 68 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = 15 <strong>Output:</strong> 35 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Math
Go
func smallestFactorization(num int) int { if num < 2 { return num } ans, mul := 0, 1 for i := 9; i >= 2; i-- { if num%i == 0 { for num%i == 0 { num /= i ans = mul*i + ans mul *= 10 } } } if num < 2 && ans <= math.MaxInt32 { return ans } return 0 }
625
Minimum Factorization
Medium
<p>Given a positive integer num, return <em>the smallest positive integer </em><code>x</code><em> whose multiplication of each digit equals </em><code>num</code>. If there is no answer or the answer is not fit in <strong>32-bit</strong> signed integer, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 48 <strong>Output:</strong> 68 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = 15 <strong>Output:</strong> 35 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Math
Java
class Solution { public int smallestFactorization(int num) { if (num < 2) { return num; } long ans = 0, mul = 1; for (int i = 9; i >= 2; --i) { if (num % i == 0) { while (num % i == 0) { num /= i; ans = mul * i + ans; mul *= 10; } } } return num < 2 && ans <= Integer.MAX_VALUE ? (int) ans : 0; } }
625
Minimum Factorization
Medium
<p>Given a positive integer num, return <em>the smallest positive integer </em><code>x</code><em> whose multiplication of each digit equals </em><code>num</code>. If there is no answer or the answer is not fit in <strong>32-bit</strong> signed integer, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 48 <strong>Output:</strong> 68 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = 15 <strong>Output:</strong> 35 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Math
Python
class Solution: def smallestFactorization(self, num: int) -> int: if num < 2: return num ans, mul = 0, 1 for i in range(9, 1, -1): while num % i == 0: num //= i ans = mul * i + ans mul *= 10 return ans if num < 2 and ans <= 2**31 - 1 else 0
626
Exchange Seats
Medium
<p>Table: <code>Seat</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | student | varchar | +-------------+---------+ id is the primary key (unique value) column for this table. Each row of this table indicates the name and the ID of a student. The ID sequence always starts from 1 and increments continuously. </pre> <p>&nbsp;</p> <p>Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.</p> <p>Return the result table ordered by <code>id</code> <strong>in ascending order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Seat table: +----+---------+ | id | student | +----+---------+ | 1 | Abbot | | 2 | Doris | | 3 | Emerson | | 4 | Green | | 5 | Jeames | +----+---------+ <strong>Output:</strong> +----+---------+ | id | student | +----+---------+ | 1 | Doris | | 2 | Abbot | | 3 | Green | | 4 | Emerson | | 5 | Jeames | +----+---------+ <strong>Explanation:</strong> Note that if the number of students is odd, there is no need to change the last one&#39;s seat. </pre>
Database
SQL
# Write your MySQL query statement below SELECT s1.id, COALESCE(s2.student, s1.student) AS student FROM Seat AS s1 LEFT JOIN Seat AS s2 ON (s1.id + 1) ^ 1 - 1 = s2.id ORDER BY 1;
627
Swap Salary
Easy
<p>Table: <code>Salary</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | id | int | | name | varchar | | sex | ENUM | | salary | int | +-------------+----------+ id is the primary key (column with unique values) for this table. The sex column is ENUM (category) value of type (&#39;m&#39;, &#39;f&#39;). The table contains information about an employee. </pre> <p>&nbsp;</p> <p>Write a solution to swap all <code>&#39;f&#39;</code> and <code>&#39;m&#39;</code> values (i.e., change all <code>&#39;f&#39;</code> values to <code>&#39;m&#39;</code> and vice versa) with a <strong>single update statement</strong> and no intermediate temporary tables.</p> <p>Note that you must write a single update statement, <strong>do not</strong> write any select statement for this problem.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Salary table: +----+------+-----+--------+ | id | name | sex | salary | +----+------+-----+--------+ | 1 | A | m | 2500 | | 2 | B | f | 1500 | | 3 | C | m | 5500 | | 4 | D | f | 500 | +----+------+-----+--------+ <strong>Output:</strong> +----+------+-----+--------+ | id | name | sex | salary | +----+------+-----+--------+ | 1 | A | f | 2500 | | 2 | B | m | 1500 | | 3 | C | f | 5500 | | 4 | D | m | 500 | +----+------+-----+--------+ <strong>Explanation:</strong> (1, A) and (3, C) were changed from &#39;m&#39; to &#39;f&#39;. (2, B) and (4, D) were changed from &#39;f&#39; to &#39;m&#39;. </pre>
Database
SQL
UPDATE salary SET sex = CASE sex WHEN 'm' THEN 'f' ELSE 'm' END;
628
Maximum Product of Three Numbers
Easy
<p>Given an integer array <code>nums</code>, <em>find three numbers whose product is maximum and return the maximum product</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 24 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [-1,-2,-3] <strong>Output:</strong> -6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math; Sorting
C++
class Solution { public: int maximumProduct(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; int b = nums[n - 1] * nums[0] * nums[1]; return max(a, b); } };
628
Maximum Product of Three Numbers
Easy
<p>Given an integer array <code>nums</code>, <em>find three numbers whose product is maximum and return the maximum product</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 24 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [-1,-2,-3] <strong>Output:</strong> -6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math; Sorting
Go
func maximumProduct(nums []int) int { sort.Ints(nums) n := len(nums) a := nums[n-1] * nums[n-2] * nums[n-3] b := nums[n-1] * nums[0] * nums[1] if a > b { return a } return b }
628
Maximum Product of Three Numbers
Easy
<p>Given an integer array <code>nums</code>, <em>find three numbers whose product is maximum and return the maximum product</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 24 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [-1,-2,-3] <strong>Output:</strong> -6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math; Sorting
Java
class Solution { public int maximumProduct(int[] nums) { Arrays.sort(nums); int n = nums.length; int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; int b = nums[n - 1] * nums[0] * nums[1]; return Math.max(a, b); } }
628
Maximum Product of Three Numbers
Easy
<p>Given an integer array <code>nums</code>, <em>find three numbers whose product is maximum and return the maximum product</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 24 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [-1,-2,-3] <strong>Output:</strong> -6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math; Sorting
Python
class Solution: def maximumProduct(self, nums: List[int]) -> int: nums.sort() a = nums[-1] * nums[-2] * nums[-3] b = nums[-1] * nums[0] * nums[1] return max(a, b)
628
Maximum Product of Three Numbers
Easy
<p>Given an integer array <code>nums</code>, <em>find three numbers whose product is maximum and return the maximum product</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 24 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [-1,-2,-3] <strong>Output:</strong> -6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math; Sorting
TypeScript
function maximumProduct(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; const a = nums[n - 1] * nums[n - 2] * nums[n - 3]; const b = nums[n - 1] * nums[0] * nums[1]; return Math.max(a, b); }
629
K Inverse Pairs Array
Hard
<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p> <p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, 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> n = 3, k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= 1000</code></li> </ul>
Dynamic Programming
C++
class Solution { public: int kInversePairs(int n, int k) { int f[k + 1]; int s[k + 2]; memset(f, 0, sizeof(f)); f[0] = 1; fill(s, s + k + 2, 1); s[0] = 0; const int mod = 1e9 + 7; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= k; ++j) { f[j] = (s[j + 1] - s[max(0, j - (i - 1))] + mod) % mod; } for (int j = 1; j <= k + 1; ++j) { s[j] = (s[j - 1] + f[j - 1]) % mod; } } return f[k]; } };
629
K Inverse Pairs Array
Hard
<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p> <p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, 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> n = 3, k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= 1000</code></li> </ul>
Dynamic Programming
Go
func kInversePairs(n int, k int) int { f := make([]int, k+1) s := make([]int, k+2) f[0] = 1 for i, x := range f { s[i+1] = s[i] + x } const mod = 1e9 + 7 for i := 1; i <= n; i++ { for j := 1; j <= k; j++ { f[j] = (s[j+1] - s[max(0, j-(i-1))] + mod) % mod } for j := 1; j <= k+1; j++ { s[j] = (s[j-1] + f[j-1]) % mod } } return f[k] }
629
K Inverse Pairs Array
Hard
<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p> <p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, 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> n = 3, k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= 1000</code></li> </ul>
Dynamic Programming
Java
class Solution { public int kInversePairs(int n, int k) { final int mod = (int) 1e9 + 7; int[] f = new int[k + 1]; int[] s = new int[k + 2]; f[0] = 1; Arrays.fill(s, 1); s[0] = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= k; ++j) { f[j] = (s[j + 1] - s[Math.max(0, j - (i - 1))] + mod) % mod; } for (int j = 1; j <= k + 1; ++j) { s[j] = (s[j - 1] + f[j - 1]) % mod; } } return f[k]; } }
629
K Inverse Pairs Array
Hard
<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p> <p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, 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> n = 3, k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= 1000</code></li> </ul>
Dynamic Programming
Python
class Solution: def kInversePairs(self, n: int, k: int) -> int: mod = 10**9 + 7 f = [1] + [0] * k s = [0] * (k + 2) for i in range(1, n + 1): for j in range(1, k + 1): f[j] = (s[j + 1] - s[max(0, j - (i - 1))]) % mod for j in range(1, k + 2): s[j] = (s[j - 1] + f[j - 1]) % mod return f[k]
629
K Inverse Pairs Array
Hard
<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p> <p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, 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> n = 3, k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= 1000</code></li> </ul>
Dynamic Programming
TypeScript
function kInversePairs(n: number, k: number): number { const f: number[] = Array(k + 1).fill(0); f[0] = 1; const s: number[] = Array(k + 2).fill(1); s[0] = 0; const mod: number = 1e9 + 7; for (let i = 1; i <= n; ++i) { for (let j = 1; j <= k; ++j) { f[j] = (s[j + 1] - s[Math.max(0, j - (i - 1))] + mod) % mod; } for (let j = 1; j <= k + 1; ++j) { s[j] = (s[j - 1] + f[j - 1]) % mod; } } return f[k]; }
630
Course Schedule III
Hard
<p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p> <p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p> <p>Return <em>the maximum number of courses that you can take</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] <strong>Output:</strong> 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day. Second, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. Third, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. The 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> courses = [[1,2]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> courses = [[3,2],[4,3]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: int scheduleCourse(vector<vector<int>>& courses) { sort(courses.begin(), courses.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); priority_queue<int> pq; int s = 0; for (auto& e : courses) { int duration = e[0], last = e[1]; pq.push(duration); s += duration; while (s > last) { s -= pq.top(); pq.pop(); } } return pq.size(); } };
630
Course Schedule III
Hard
<p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p> <p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p> <p>Return <em>the maximum number of courses that you can take</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] <strong>Output:</strong> 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day. Second, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. Third, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. The 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> courses = [[1,2]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> courses = [[3,2],[4,3]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Go
func scheduleCourse(courses [][]int) int { sort.Slice(courses, func(i, j int) bool { return courses[i][1] < courses[j][1] }) pq := &hp{} s := 0 for _, e := range courses { duration, last := e[0], e[1] s += duration pq.push(duration) for s > last { s -= pq.pop() } } return pq.Len() } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v } func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) }
630
Course Schedule III
Hard
<p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p> <p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p> <p>Return <em>the maximum number of courses that you can take</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] <strong>Output:</strong> 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day. Second, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. Third, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. The 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> courses = [[1,2]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> courses = [[3,2],[4,3]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Java
class Solution { public int scheduleCourse(int[][] courses) { Arrays.sort(courses, (a, b) -> a[1] - b[1]); PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); int s = 0; for (var e : courses) { int duration = e[0], last = e[1]; pq.offer(duration); s += duration; while (s > last) { s -= pq.poll(); } } return pq.size(); } }
630
Course Schedule III
Hard
<p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p> <p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p> <p>Return <em>the maximum number of courses that you can take</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] <strong>Output:</strong> 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day. Second, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. Third, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. The 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> courses = [[1,2]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> courses = [[3,2],[4,3]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Python
class Solution: def scheduleCourse(self, courses: List[List[int]]) -> int: courses.sort(key=lambda x: x[1]) pq = [] s = 0 for duration, last in courses: heappush(pq, -duration) s += duration while s > last: s += heappop(pq) return len(pq)
630
Course Schedule III
Hard
<p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p> <p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p> <p>Return <em>the maximum number of courses that you can take</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] <strong>Output:</strong> 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day. Second, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. Third, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. The 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> courses = [[1,2]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> courses = [[3,2],[4,3]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
TypeScript
function scheduleCourse(courses: number[][]): number { courses.sort((a, b) => a[1] - b[1]); const pq = new MaxPriorityQueue<number>(); let s = 0; for (const [duration, last] of courses) { pq.enqueue(duration); s += duration; while (s > last) { s -= pq.dequeue(); } } return pq.size(); }
632
Smallest Range Covering Elements from K Lists
Hard
<p>You have <code>k</code> lists of sorted integers in <strong>non-decreasing&nbsp;order</strong>. Find the <b>smallest</b> range that includes at least one number from each of the <code>k</code> lists.</p> <p>We define the range <code>[a, b]</code> is smaller than range <code>[c, d]</code> if <code>b - a &lt; d - c</code> <strong>or</strong> <code>a &lt; c</code> if <code>b - a == d - c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] <strong>Output:</strong> [20,24] <strong>Explanation: </strong> List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]] <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == k</code></li> <li><code>1 &lt;= k &lt;= 3500</code></li> <li><code>1 &lt;= nums[i].length &lt;= 50</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code>&nbsp;is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Sorting; Sliding Window; Heap (Priority Queue)
C++
class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { int n = 0; for (auto& v : nums) n += v.size(); vector<pair<int, int>> t(n); int k = nums.size(); for (int i = 0, j = 0; i < k; ++i) { for (int v : nums[i]) { t[j++] = {v, i}; } } sort(t.begin(), t.end()); int j = 0; unordered_map<int, int> cnt; vector<int> ans = {-1000000, 1000000}; for (int i = 0; i < n; ++i) { int b = t[i].first; int v = t[i].second; ++cnt[v]; while (cnt.size() == k) { int a = t[j].first; int w = t[j].second; int x = b - a - (ans[1] - ans[0]); if (x < 0 || (x == 0 && a < ans[0])) { ans[0] = a; ans[1] = b; } if (--cnt[w] == 0) { cnt.erase(w); } ++j; } } return ans; } };
632
Smallest Range Covering Elements from K Lists
Hard
<p>You have <code>k</code> lists of sorted integers in <strong>non-decreasing&nbsp;order</strong>. Find the <b>smallest</b> range that includes at least one number from each of the <code>k</code> lists.</p> <p>We define the range <code>[a, b]</code> is smaller than range <code>[c, d]</code> if <code>b - a &lt; d - c</code> <strong>or</strong> <code>a &lt; c</code> if <code>b - a == d - c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] <strong>Output:</strong> [20,24] <strong>Explanation: </strong> List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]] <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == k</code></li> <li><code>1 &lt;= k &lt;= 3500</code></li> <li><code>1 &lt;= nums[i].length &lt;= 50</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code>&nbsp;is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Sorting; Sliding Window; Heap (Priority Queue)
Go
func smallestRange(nums [][]int) []int { t := [][]int{} for i, x := range nums { for _, v := range x { t = append(t, []int{v, i}) } } sort.Slice(t, func(i, j int) bool { return t[i][0] < t[j][0] }) ans := []int{-1000000, 1000000} j := 0 cnt := map[int]int{} for _, x := range t { b, v := x[0], x[1] cnt[v]++ for len(cnt) == len(nums) { a, w := t[j][0], t[j][1] x := b - a - (ans[1] - ans[0]) if x < 0 || (x == 0 && a < ans[0]) { ans[0], ans[1] = a, b } cnt[w]-- if cnt[w] == 0 { delete(cnt, w) } j++ } } return ans }
632
Smallest Range Covering Elements from K Lists
Hard
<p>You have <code>k</code> lists of sorted integers in <strong>non-decreasing&nbsp;order</strong>. Find the <b>smallest</b> range that includes at least one number from each of the <code>k</code> lists.</p> <p>We define the range <code>[a, b]</code> is smaller than range <code>[c, d]</code> if <code>b - a &lt; d - c</code> <strong>or</strong> <code>a &lt; c</code> if <code>b - a == d - c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] <strong>Output:</strong> [20,24] <strong>Explanation: </strong> List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]] <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == k</code></li> <li><code>1 &lt;= k &lt;= 3500</code></li> <li><code>1 &lt;= nums[i].length &lt;= 50</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code>&nbsp;is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Sorting; Sliding Window; Heap (Priority Queue)
Java
class Solution { public int[] smallestRange(List<List<Integer>> nums) { int n = 0; for (var v : nums) { n += v.size(); } int[][] t = new int[n][2]; int k = nums.size(); for (int i = 0, j = 0; i < k; ++i) { for (int x : nums.get(i)) { t[j++] = new int[] {x, i}; } } Arrays.sort(t, (a, b) -> a[0] - b[0]); int j = 0; Map<Integer, Integer> cnt = new HashMap<>(); int[] ans = new int[] {-1000000, 1000000}; for (int[] e : t) { int b = e[0]; int v = e[1]; cnt.merge(v, 1, Integer::sum); while (cnt.size() == k) { int a = t[j][0]; int w = t[j][1]; int x = b - a - (ans[1] - ans[0]); if (x < 0 || (x == 0 && a < ans[0])) { ans[0] = a; ans[1] = b; } if (cnt.merge(w, -1, Integer::sum) == 0) { cnt.remove(w); } ++j; } } return ans; } }
632
Smallest Range Covering Elements from K Lists
Hard
<p>You have <code>k</code> lists of sorted integers in <strong>non-decreasing&nbsp;order</strong>. Find the <b>smallest</b> range that includes at least one number from each of the <code>k</code> lists.</p> <p>We define the range <code>[a, b]</code> is smaller than range <code>[c, d]</code> if <code>b - a &lt; d - c</code> <strong>or</strong> <code>a &lt; c</code> if <code>b - a == d - c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] <strong>Output:</strong> [20,24] <strong>Explanation: </strong> List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]] <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == k</code></li> <li><code>1 &lt;= k &lt;= 3500</code></li> <li><code>1 &lt;= nums[i].length &lt;= 50</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code>&nbsp;is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Sorting; Sliding Window; Heap (Priority Queue)
Python
class Solution: def smallestRange(self, nums: List[List[int]]) -> List[int]: t = [(x, i) for i, v in enumerate(nums) for x in v] t.sort() cnt = Counter() ans = [-inf, inf] j = 0 for i, (b, v) in enumerate(t): cnt[v] += 1 while len(cnt) == len(nums): a = t[j][0] x = b - a - (ans[1] - ans[0]) if x < 0 or (x == 0 and a < ans[0]): ans = [a, b] w = t[j][1] cnt[w] -= 1 if cnt[w] == 0: cnt.pop(w) j += 1 return ans
632
Smallest Range Covering Elements from K Lists
Hard
<p>You have <code>k</code> lists of sorted integers in <strong>non-decreasing&nbsp;order</strong>. Find the <b>smallest</b> range that includes at least one number from each of the <code>k</code> lists.</p> <p>We define the range <code>[a, b]</code> is smaller than range <code>[c, d]</code> if <code>b - a &lt; d - c</code> <strong>or</strong> <code>a &lt; c</code> if <code>b - a == d - c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] <strong>Output:</strong> [20,24] <strong>Explanation: </strong> List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]] <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == k</code></li> <li><code>1 &lt;= k &lt;= 3500</code></li> <li><code>1 &lt;= nums[i].length &lt;= 50</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code>&nbsp;is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Sorting; Sliding Window; Heap (Priority Queue)
Rust
impl Solution { pub fn smallest_range(nums: Vec<Vec<i32>>) -> Vec<i32> { let mut t = vec![]; for (i, x) in nums.iter().enumerate() { for &v in x { t.push((v, i)); } } t.sort_unstable(); let (mut ans, n) = (vec![-1000000, 1000000], nums.len()); let mut j = 0; let mut cnt = std::collections::HashMap::new(); for (b, v) in t.iter() { let (b, v) = (*b, *v); if let Some(x) = cnt.get_mut(&v) { *x += 1; } else { cnt.insert(v, 1); } while cnt.len() == n { let (a, w) = t[j]; let x = b - a - (ans[1] - ans[0]); if x < 0 || (x == 0 && a < ans[0]) { ans = vec![a, b]; } if let Some(x) = cnt.get_mut(&w) { *x -= 1; } if cnt[&w] == 0 { cnt.remove(&w); } j += 1; } } ans } }
633
Sum of Square Numbers
Medium
<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> c = 5 <strong>Output:</strong> true <strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> c = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; Binary Search
C++
class Solution { public: bool judgeSquareSum(int c) { long long a = 0, b = sqrt(c); while (a <= b) { long long s = a * a + b * b; if (s == c) { return true; } if (s < c) { ++a; } else { --b; } } return false; } };
633
Sum of Square Numbers
Medium
<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> c = 5 <strong>Output:</strong> true <strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> c = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; Binary Search
Go
func judgeSquareSum(c int) bool { a, b := 0, int(math.Sqrt(float64(c))) for a <= b { s := a*a + b*b if s == c { return true } if s < c { a++ } else { b-- } } return false }
633
Sum of Square Numbers
Medium
<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> c = 5 <strong>Output:</strong> true <strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> c = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; Binary Search
Java
class Solution { public boolean judgeSquareSum(int c) { long a = 0, b = (long) Math.sqrt(c); while (a <= b) { long s = a * a + b * b; if (s == c) { return true; } if (s < c) { ++a; } else { --b; } } return false; } }
633
Sum of Square Numbers
Medium
<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> c = 5 <strong>Output:</strong> true <strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> c = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; Binary Search
Python
class Solution: def judgeSquareSum(self, c: int) -> bool: a, b = 0, int(sqrt(c)) while a <= b: s = a**2 + b**2 if s == c: return True if s < c: a += 1 else: b -= 1 return False
633
Sum of Square Numbers
Medium
<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> c = 5 <strong>Output:</strong> true <strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> c = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; Binary Search
Rust
use std::cmp::Ordering; impl Solution { pub fn judge_square_sum(c: i32) -> bool { let mut a: i64 = 0; let mut b: i64 = (c as f64).sqrt() as i64; while a <= b { let s = a * a + b * b; match s.cmp(&(c as i64)) { Ordering::Equal => { return true; } Ordering::Less => { a += 1; } Ordering::Greater => { b -= 1; } } } false } }
633
Sum of Square Numbers
Medium
<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> c = 5 <strong>Output:</strong> true <strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> c = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; Binary Search
TypeScript
function judgeSquareSum(c: number): boolean { let [a, b] = [0, Math.floor(Math.sqrt(c))]; while (a <= b) { const s = a * a + b * b; if (s === c) { return true; } if (s < c) { ++a; } else { --b; } } return false; }
634
Find the Derangement of An Array
Medium
<p>In combinatorial mathematics, a <strong>derangement</strong> is a permutation of the elements of a set, such that no element appears in its original position.</p> <p>You are given an integer <code>n</code>. There is originally an array consisting of <code>n</code> integers from <code>1</code> to <code>n</code> in ascending order, return <em>the number of <strong>derangements</strong> it can generate</em>. Since the answer may be huge, 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> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Math; Dynamic Programming; Combinatorics
C++
class Solution { public: int findDerangement(int n) { long long f[n + 1]; memset(f, 0, sizeof(f)); f[0] = 1; const int mod = 1e9 + 7; for (int i = 2; i <= n; i++) { f[i] = (i - 1LL) * (f[i - 1] + f[i - 2]) % mod; } return f[n]; } };
634
Find the Derangement of An Array
Medium
<p>In combinatorial mathematics, a <strong>derangement</strong> is a permutation of the elements of a set, such that no element appears in its original position.</p> <p>You are given an integer <code>n</code>. There is originally an array consisting of <code>n</code> integers from <code>1</code> to <code>n</code> in ascending order, return <em>the number of <strong>derangements</strong> it can generate</em>. Since the answer may be huge, 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> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Math; Dynamic Programming; Combinatorics
Go
func findDerangement(n int) int { f := make([]int, n+1) f[0] = 1 const mod = 1e9 + 7 for i := 2; i <= n; i++ { f[i] = (i - 1) * (f[i-1] + f[i-2]) % mod } return f[n] }
634
Find the Derangement of An Array
Medium
<p>In combinatorial mathematics, a <strong>derangement</strong> is a permutation of the elements of a set, such that no element appears in its original position.</p> <p>You are given an integer <code>n</code>. There is originally an array consisting of <code>n</code> integers from <code>1</code> to <code>n</code> in ascending order, return <em>the number of <strong>derangements</strong> it can generate</em>. Since the answer may be huge, 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> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Math; Dynamic Programming; Combinatorics
Java
class Solution { public int findDerangement(int n) { long[] f = new long[n + 1]; f[0] = 1; final int mod = (int) 1e9 + 7; for (int i = 2; i <= n; ++i) { f[i] = (i - 1) * (f[i - 1] + f[i - 2]) % mod; } return (int) f[n]; } }
634
Find the Derangement of An Array
Medium
<p>In combinatorial mathematics, a <strong>derangement</strong> is a permutation of the elements of a set, such that no element appears in its original position.</p> <p>You are given an integer <code>n</code>. There is originally an array consisting of <code>n</code> integers from <code>1</code> to <code>n</code> in ascending order, return <em>the number of <strong>derangements</strong> it can generate</em>. Since the answer may be huge, 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> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Math; Dynamic Programming; Combinatorics
Python
class Solution: def findDerangement(self, n: int) -> int: mod = 10**9 + 7 f = [1] + [0] * n for i in range(2, n + 1): f[i] = (i - 1) * (f[i - 1] + f[i - 2]) % mod return f[n]
635
Design Log Storage System
Medium
<p>You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: <code>Year:Month:Day:Hour:Minute:Second</code>, for example, <code>2017:01:01:23:59:59</code>. All domains are zero-padded decimal numbers.</p> <p>Implement the <code>LogSystem</code> class:</p> <ul> <li><code>LogSystem()</code> Initializes the <code>LogSystem</code><b> </b>object.</li> <li><code>void put(int id, string timestamp)</code> Stores the given log <code>(id, timestamp)</code> in your storage system.</li> <li><code>int[] retrieve(string start, string end, string granularity)</code> Returns the IDs of the logs whose timestamps are within the range from <code>start</code> to <code>end</code> inclusive. <code>start</code> and <code>end</code> all have the same format as <code>timestamp</code>, and <code>granularity</code> means how precise the range should be (i.e. to the exact <code>Day</code>, <code>Minute</code>, etc.). For example, <code>start = &quot;2017:01:01:23:59:59&quot;</code>, <code>end = &quot;2017:01:02:23:59:59&quot;</code>, and <code>granularity = &quot;Day&quot;</code> means that we need to find the logs within the inclusive range from <strong>Jan. 1st 2017</strong> to <strong>Jan. 2nd 2017</strong>, and the <code>Hour</code>, <code>Minute</code>, and <code>Second</code> for each log entry can be ignored.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;LogSystem&quot;, &quot;put&quot;, &quot;put&quot;, &quot;put&quot;, &quot;retrieve&quot;, &quot;retrieve&quot;] [[], [1, &quot;2017:01:01:23:59:59&quot;], [2, &quot;2017:01:01:22:59:59&quot;], [3, &quot;2016:01:01:00:00:00&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;]] <strong>Output</strong> [null, null, null, null, [3, 2, 1], [2, 1]] <strong>Explanation</strong> LogSystem logSystem = new LogSystem(); logSystem.put(1, &quot;2017:01:01:23:59:59&quot;); logSystem.put(2, &quot;2017:01:01:22:59:59&quot;); logSystem.put(3, &quot;2016:01:01:00:00:00&quot;); // return [3,2,1], because you need to return all logs between 2016 and 2017. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;); // return [2,1], because you need to return all logs between Jan. 1, 2016 01:XX:XX and Jan. 1, 2017 23:XX:XX. // Log 3 is not returned because Jan. 1, 2016 00:00:00 comes before the start of the range. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;); </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= id &lt;= 500</code></li> <li><code>2000 &lt;= Year &lt;= 2017</code></li> <li><code>1 &lt;= Month &lt;= 12</code></li> <li><code>1 &lt;= Day &lt;= 31</code></li> <li><code>0 &lt;= Hour &lt;= 23</code></li> <li><code>0 &lt;= Minute, Second &lt;= 59</code></li> <li><code>granularity</code> is one of the values <code>[&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;, &quot;Hour&quot;, &quot;Minute&quot;, &quot;Second&quot;]</code>.</li> <li>At most <code>500</code> calls will be made to <code>put</code> and <code>retrieve</code>.</li> </ul>
Design; Hash Table; String; Ordered Set
C++
class LogSystem { public: LogSystem() { d["Year"] = 4; d["Month"] = 7; d["Day"] = 10; d["Hour"] = 13; d["Minute"] = 16; d["Second"] = 19; } void put(int id, string timestamp) { logs.push_back({id, timestamp}); } vector<int> retrieve(string start, string end, string granularity) { vector<int> ans; int i = d[granularity]; auto s = start.substr(0, i); auto e = end.substr(0, i); for (auto& [id, ts] : logs) { auto t = ts.substr(0, i); if (s <= t && t <= e) { ans.emplace_back(id); } } return ans; } private: vector<pair<int, string>> logs; unordered_map<string, int> d; }; /** * Your LogSystem object will be instantiated and called as such: * LogSystem* obj = new LogSystem(); * obj->put(id,timestamp); * vector<int> param_2 = obj->retrieve(start,end,granularity); */
635
Design Log Storage System
Medium
<p>You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: <code>Year:Month:Day:Hour:Minute:Second</code>, for example, <code>2017:01:01:23:59:59</code>. All domains are zero-padded decimal numbers.</p> <p>Implement the <code>LogSystem</code> class:</p> <ul> <li><code>LogSystem()</code> Initializes the <code>LogSystem</code><b> </b>object.</li> <li><code>void put(int id, string timestamp)</code> Stores the given log <code>(id, timestamp)</code> in your storage system.</li> <li><code>int[] retrieve(string start, string end, string granularity)</code> Returns the IDs of the logs whose timestamps are within the range from <code>start</code> to <code>end</code> inclusive. <code>start</code> and <code>end</code> all have the same format as <code>timestamp</code>, and <code>granularity</code> means how precise the range should be (i.e. to the exact <code>Day</code>, <code>Minute</code>, etc.). For example, <code>start = &quot;2017:01:01:23:59:59&quot;</code>, <code>end = &quot;2017:01:02:23:59:59&quot;</code>, and <code>granularity = &quot;Day&quot;</code> means that we need to find the logs within the inclusive range from <strong>Jan. 1st 2017</strong> to <strong>Jan. 2nd 2017</strong>, and the <code>Hour</code>, <code>Minute</code>, and <code>Second</code> for each log entry can be ignored.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;LogSystem&quot;, &quot;put&quot;, &quot;put&quot;, &quot;put&quot;, &quot;retrieve&quot;, &quot;retrieve&quot;] [[], [1, &quot;2017:01:01:23:59:59&quot;], [2, &quot;2017:01:01:22:59:59&quot;], [3, &quot;2016:01:01:00:00:00&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;]] <strong>Output</strong> [null, null, null, null, [3, 2, 1], [2, 1]] <strong>Explanation</strong> LogSystem logSystem = new LogSystem(); logSystem.put(1, &quot;2017:01:01:23:59:59&quot;); logSystem.put(2, &quot;2017:01:01:22:59:59&quot;); logSystem.put(3, &quot;2016:01:01:00:00:00&quot;); // return [3,2,1], because you need to return all logs between 2016 and 2017. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;); // return [2,1], because you need to return all logs between Jan. 1, 2016 01:XX:XX and Jan. 1, 2017 23:XX:XX. // Log 3 is not returned because Jan. 1, 2016 00:00:00 comes before the start of the range. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;); </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= id &lt;= 500</code></li> <li><code>2000 &lt;= Year &lt;= 2017</code></li> <li><code>1 &lt;= Month &lt;= 12</code></li> <li><code>1 &lt;= Day &lt;= 31</code></li> <li><code>0 &lt;= Hour &lt;= 23</code></li> <li><code>0 &lt;= Minute, Second &lt;= 59</code></li> <li><code>granularity</code> is one of the values <code>[&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;, &quot;Hour&quot;, &quot;Minute&quot;, &quot;Second&quot;]</code>.</li> <li>At most <code>500</code> calls will be made to <code>put</code> and <code>retrieve</code>.</li> </ul>
Design; Hash Table; String; Ordered Set
Go
type LogSystem struct { logs []pair d map[string]int } func Constructor() LogSystem { d := map[string]int{ "Year": 4, "Month": 7, "Day": 10, "Hour": 13, "Minute": 16, "Second": 19, } return LogSystem{[]pair{}, d} } func (this *LogSystem) Put(id int, timestamp string) { this.logs = append(this.logs, pair{id, timestamp}) } func (this *LogSystem) Retrieve(start string, end string, granularity string) (ans []int) { i := this.d[granularity] s, e := start[:i], end[:i] for _, log := range this.logs { t := log.ts[:i] if s <= t && t <= e { ans = append(ans, log.id) } } return } type pair struct { id int ts string } /** * Your LogSystem object will be instantiated and called as such: * obj := Constructor(); * obj.Put(id,timestamp); * param_2 := obj.Retrieve(start,end,granularity); */
635
Design Log Storage System
Medium
<p>You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: <code>Year:Month:Day:Hour:Minute:Second</code>, for example, <code>2017:01:01:23:59:59</code>. All domains are zero-padded decimal numbers.</p> <p>Implement the <code>LogSystem</code> class:</p> <ul> <li><code>LogSystem()</code> Initializes the <code>LogSystem</code><b> </b>object.</li> <li><code>void put(int id, string timestamp)</code> Stores the given log <code>(id, timestamp)</code> in your storage system.</li> <li><code>int[] retrieve(string start, string end, string granularity)</code> Returns the IDs of the logs whose timestamps are within the range from <code>start</code> to <code>end</code> inclusive. <code>start</code> and <code>end</code> all have the same format as <code>timestamp</code>, and <code>granularity</code> means how precise the range should be (i.e. to the exact <code>Day</code>, <code>Minute</code>, etc.). For example, <code>start = &quot;2017:01:01:23:59:59&quot;</code>, <code>end = &quot;2017:01:02:23:59:59&quot;</code>, and <code>granularity = &quot;Day&quot;</code> means that we need to find the logs within the inclusive range from <strong>Jan. 1st 2017</strong> to <strong>Jan. 2nd 2017</strong>, and the <code>Hour</code>, <code>Minute</code>, and <code>Second</code> for each log entry can be ignored.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;LogSystem&quot;, &quot;put&quot;, &quot;put&quot;, &quot;put&quot;, &quot;retrieve&quot;, &quot;retrieve&quot;] [[], [1, &quot;2017:01:01:23:59:59&quot;], [2, &quot;2017:01:01:22:59:59&quot;], [3, &quot;2016:01:01:00:00:00&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;]] <strong>Output</strong> [null, null, null, null, [3, 2, 1], [2, 1]] <strong>Explanation</strong> LogSystem logSystem = new LogSystem(); logSystem.put(1, &quot;2017:01:01:23:59:59&quot;); logSystem.put(2, &quot;2017:01:01:22:59:59&quot;); logSystem.put(3, &quot;2016:01:01:00:00:00&quot;); // return [3,2,1], because you need to return all logs between 2016 and 2017. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;); // return [2,1], because you need to return all logs between Jan. 1, 2016 01:XX:XX and Jan. 1, 2017 23:XX:XX. // Log 3 is not returned because Jan. 1, 2016 00:00:00 comes before the start of the range. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;); </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= id &lt;= 500</code></li> <li><code>2000 &lt;= Year &lt;= 2017</code></li> <li><code>1 &lt;= Month &lt;= 12</code></li> <li><code>1 &lt;= Day &lt;= 31</code></li> <li><code>0 &lt;= Hour &lt;= 23</code></li> <li><code>0 &lt;= Minute, Second &lt;= 59</code></li> <li><code>granularity</code> is one of the values <code>[&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;, &quot;Hour&quot;, &quot;Minute&quot;, &quot;Second&quot;]</code>.</li> <li>At most <code>500</code> calls will be made to <code>put</code> and <code>retrieve</code>.</li> </ul>
Design; Hash Table; String; Ordered Set
Java
class LogSystem { private List<Log> logs = new ArrayList<>(); private Map<String, Integer> d = new HashMap<>(); public LogSystem() { d.put("Year", 4); d.put("Month", 7); d.put("Day", 10); d.put("Hour", 13); d.put("Minute", 16); d.put("Second", 19); } public void put(int id, String timestamp) { logs.add(new Log(id, timestamp)); } public List<Integer> retrieve(String start, String end, String granularity) { List<Integer> ans = new ArrayList<>(); int i = d.get(granularity); String s = start.substring(0, i); String e = end.substring(0, i); for (var log : logs) { String t = log.ts.substring(0, i); if (s.compareTo(t) <= 0 && t.compareTo(e) <= 0) { ans.add(log.id); } } return ans; } } class Log { int id; String ts; Log(int id, String ts) { this.id = id; this.ts = ts; } } /** * Your LogSystem object will be instantiated and called as such: * LogSystem obj = new LogSystem(); * obj.put(id,timestamp); * List<Integer> param_2 = obj.retrieve(start,end,granularity); */
635
Design Log Storage System
Medium
<p>You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: <code>Year:Month:Day:Hour:Minute:Second</code>, for example, <code>2017:01:01:23:59:59</code>. All domains are zero-padded decimal numbers.</p> <p>Implement the <code>LogSystem</code> class:</p> <ul> <li><code>LogSystem()</code> Initializes the <code>LogSystem</code><b> </b>object.</li> <li><code>void put(int id, string timestamp)</code> Stores the given log <code>(id, timestamp)</code> in your storage system.</li> <li><code>int[] retrieve(string start, string end, string granularity)</code> Returns the IDs of the logs whose timestamps are within the range from <code>start</code> to <code>end</code> inclusive. <code>start</code> and <code>end</code> all have the same format as <code>timestamp</code>, and <code>granularity</code> means how precise the range should be (i.e. to the exact <code>Day</code>, <code>Minute</code>, etc.). For example, <code>start = &quot;2017:01:01:23:59:59&quot;</code>, <code>end = &quot;2017:01:02:23:59:59&quot;</code>, and <code>granularity = &quot;Day&quot;</code> means that we need to find the logs within the inclusive range from <strong>Jan. 1st 2017</strong> to <strong>Jan. 2nd 2017</strong>, and the <code>Hour</code>, <code>Minute</code>, and <code>Second</code> for each log entry can be ignored.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;LogSystem&quot;, &quot;put&quot;, &quot;put&quot;, &quot;put&quot;, &quot;retrieve&quot;, &quot;retrieve&quot;] [[], [1, &quot;2017:01:01:23:59:59&quot;], [2, &quot;2017:01:01:22:59:59&quot;], [3, &quot;2016:01:01:00:00:00&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;], [&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;]] <strong>Output</strong> [null, null, null, null, [3, 2, 1], [2, 1]] <strong>Explanation</strong> LogSystem logSystem = new LogSystem(); logSystem.put(1, &quot;2017:01:01:23:59:59&quot;); logSystem.put(2, &quot;2017:01:01:22:59:59&quot;); logSystem.put(3, &quot;2016:01:01:00:00:00&quot;); // return [3,2,1], because you need to return all logs between 2016 and 2017. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Year&quot;); // return [2,1], because you need to return all logs between Jan. 1, 2016 01:XX:XX and Jan. 1, 2017 23:XX:XX. // Log 3 is not returned because Jan. 1, 2016 00:00:00 comes before the start of the range. logSystem.retrieve(&quot;2016:01:01:01:01:01&quot;, &quot;2017:01:01:23:00:00&quot;, &quot;Hour&quot;); </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= id &lt;= 500</code></li> <li><code>2000 &lt;= Year &lt;= 2017</code></li> <li><code>1 &lt;= Month &lt;= 12</code></li> <li><code>1 &lt;= Day &lt;= 31</code></li> <li><code>0 &lt;= Hour &lt;= 23</code></li> <li><code>0 &lt;= Minute, Second &lt;= 59</code></li> <li><code>granularity</code> is one of the values <code>[&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;, &quot;Hour&quot;, &quot;Minute&quot;, &quot;Second&quot;]</code>.</li> <li>At most <code>500</code> calls will be made to <code>put</code> and <code>retrieve</code>.</li> </ul>
Design; Hash Table; String; Ordered Set
Python
class LogSystem: def __init__(self): self.logs = [] self.d = { "Year": 4, "Month": 7, "Day": 10, "Hour": 13, "Minute": 16, "Second": 19, } def put(self, id: int, timestamp: str) -> None: self.logs.append((id, timestamp)) def retrieve(self, start: str, end: str, granularity: str) -> List[int]: i = self.d[granularity] return [id for id, ts in self.logs if start[:i] <= ts[:i] <= end[:i]] # Your LogSystem object will be instantiated and called as such: # obj = LogSystem() # obj.put(id,timestamp) # param_2 = obj.retrieve(start,end,granularity)
636
Exclusive Time of Functions
Medium
<p>On a <strong>single-threaded</strong> CPU, we execute a program containing <code>n</code> functions. Each function has a unique ID between <code>0</code> and <code>n-1</code>.</p> <p>Function calls are <strong>stored in a <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a></strong>: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is <strong>the current function being executed</strong>. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.</p> <p>You are given a list <code>logs</code>, where <code>logs[i]</code> represents the <code>i<sup>th</sup></code> log message formatted as a string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. For example, <code>&quot;0:start:3&quot;</code> means a function call with function ID <code>0</code> <strong>started at the beginning</strong> of timestamp <code>3</code>, and <code>&quot;1:end:2&quot;</code> means a function call with function ID <code>1</code> <strong>ended at the end</strong> of timestamp <code>2</code>. Note that a function can be called <b>multiple times, possibly recursively</b>.</p> <p>A function&#39;s <strong>exclusive time</strong> is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for <code>2</code> time units and another call executing for <code>1</code> time unit, the <strong>exclusive time</strong> is <code>2 + 1 = 3</code>.</p> <p>Return <em>the <strong>exclusive time</strong> of each function in an array, where the value at the </em><code>i<sup>th</sup></code><em> index represents the exclusive time for the function with ID </em><code>i</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/0636.Exclusive%20Time%20of%20Functions/images/diag1b.png" style="width: 550px; height: 239px;" /> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;] <strong>Output:</strong> [3,4] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [8] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [7,1] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= logs.length &lt;= 500</code></li> <li><code>0 &lt;= function_id &lt; n</code></li> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>No two start events will happen at the same timestamp.</li> <li>No two end events will happen at the same timestamp.</li> <li>Each function has an <code>&quot;end&quot;</code> log for each <code>&quot;start&quot;</code> log.</li> </ul>
Stack; Array
C++
class Solution { public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> ans(n); stack<int> stk; int pre = 0; for (const auto& log : logs) { int i, cur; char c[10]; sscanf(log.c_str(), "%d:%[^:]:%d", &i, c, &cur); if (c[0] == 's') { if (stk.size()) { ans[stk.top()] += cur - pre; } stk.push(i); pre = cur; } else { ans[stk.top()] += cur - pre + 1; stk.pop(); pre = cur + 1; } } return ans; } };
636
Exclusive Time of Functions
Medium
<p>On a <strong>single-threaded</strong> CPU, we execute a program containing <code>n</code> functions. Each function has a unique ID between <code>0</code> and <code>n-1</code>.</p> <p>Function calls are <strong>stored in a <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a></strong>: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is <strong>the current function being executed</strong>. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.</p> <p>You are given a list <code>logs</code>, where <code>logs[i]</code> represents the <code>i<sup>th</sup></code> log message formatted as a string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. For example, <code>&quot;0:start:3&quot;</code> means a function call with function ID <code>0</code> <strong>started at the beginning</strong> of timestamp <code>3</code>, and <code>&quot;1:end:2&quot;</code> means a function call with function ID <code>1</code> <strong>ended at the end</strong> of timestamp <code>2</code>. Note that a function can be called <b>multiple times, possibly recursively</b>.</p> <p>A function&#39;s <strong>exclusive time</strong> is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for <code>2</code> time units and another call executing for <code>1</code> time unit, the <strong>exclusive time</strong> is <code>2 + 1 = 3</code>.</p> <p>Return <em>the <strong>exclusive time</strong> of each function in an array, where the value at the </em><code>i<sup>th</sup></code><em> index represents the exclusive time for the function with ID </em><code>i</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/0636.Exclusive%20Time%20of%20Functions/images/diag1b.png" style="width: 550px; height: 239px;" /> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;] <strong>Output:</strong> [3,4] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [8] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [7,1] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= logs.length &lt;= 500</code></li> <li><code>0 &lt;= function_id &lt; n</code></li> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>No two start events will happen at the same timestamp.</li> <li>No two end events will happen at the same timestamp.</li> <li>Each function has an <code>&quot;end&quot;</code> log for each <code>&quot;start&quot;</code> log.</li> </ul>
Stack; Array
Go
func exclusiveTime(n int, logs []string) []int { ans := make([]int, n) stk := []int{} pre := 0 for _, log := range logs { parts := strings.Split(log, ":") i, _ := strconv.Atoi(parts[0]) cur, _ := strconv.Atoi(parts[2]) if parts[1][0] == 's' { if len(stk) > 0 { ans[stk[len(stk)-1]] += cur - pre } stk = append(stk, i) pre = cur } else { ans[stk[len(stk)-1]] += cur - pre + 1 stk = stk[:len(stk)-1] pre = cur + 1 } } return ans }
636
Exclusive Time of Functions
Medium
<p>On a <strong>single-threaded</strong> CPU, we execute a program containing <code>n</code> functions. Each function has a unique ID between <code>0</code> and <code>n-1</code>.</p> <p>Function calls are <strong>stored in a <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a></strong>: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is <strong>the current function being executed</strong>. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.</p> <p>You are given a list <code>logs</code>, where <code>logs[i]</code> represents the <code>i<sup>th</sup></code> log message formatted as a string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. For example, <code>&quot;0:start:3&quot;</code> means a function call with function ID <code>0</code> <strong>started at the beginning</strong> of timestamp <code>3</code>, and <code>&quot;1:end:2&quot;</code> means a function call with function ID <code>1</code> <strong>ended at the end</strong> of timestamp <code>2</code>. Note that a function can be called <b>multiple times, possibly recursively</b>.</p> <p>A function&#39;s <strong>exclusive time</strong> is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for <code>2</code> time units and another call executing for <code>1</code> time unit, the <strong>exclusive time</strong> is <code>2 + 1 = 3</code>.</p> <p>Return <em>the <strong>exclusive time</strong> of each function in an array, where the value at the </em><code>i<sup>th</sup></code><em> index represents the exclusive time for the function with ID </em><code>i</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/0636.Exclusive%20Time%20of%20Functions/images/diag1b.png" style="width: 550px; height: 239px;" /> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;] <strong>Output:</strong> [3,4] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [8] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [7,1] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= logs.length &lt;= 500</code></li> <li><code>0 &lt;= function_id &lt; n</code></li> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>No two start events will happen at the same timestamp.</li> <li>No two end events will happen at the same timestamp.</li> <li>Each function has an <code>&quot;end&quot;</code> log for each <code>&quot;start&quot;</code> log.</li> </ul>
Stack; Array
Java
class Solution { public int[] exclusiveTime(int n, List<String> logs) { int[] ans = new int[n]; Deque<Integer> stk = new ArrayDeque<>(); int pre = 0; for (var log : logs) { var parts = log.split(":"); int i = Integer.parseInt(parts[0]); int cur = Integer.parseInt(parts[2]); if (parts[1].charAt(0) == 's') { if (!stk.isEmpty()) { ans[stk.peek()] += cur - pre; } stk.push(i); pre = cur; } else { ans[stk.pop()] += cur - pre + 1; pre = cur + 1; } } return ans; } }
636
Exclusive Time of Functions
Medium
<p>On a <strong>single-threaded</strong> CPU, we execute a program containing <code>n</code> functions. Each function has a unique ID between <code>0</code> and <code>n-1</code>.</p> <p>Function calls are <strong>stored in a <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a></strong>: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is <strong>the current function being executed</strong>. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.</p> <p>You are given a list <code>logs</code>, where <code>logs[i]</code> represents the <code>i<sup>th</sup></code> log message formatted as a string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. For example, <code>&quot;0:start:3&quot;</code> means a function call with function ID <code>0</code> <strong>started at the beginning</strong> of timestamp <code>3</code>, and <code>&quot;1:end:2&quot;</code> means a function call with function ID <code>1</code> <strong>ended at the end</strong> of timestamp <code>2</code>. Note that a function can be called <b>multiple times, possibly recursively</b>.</p> <p>A function&#39;s <strong>exclusive time</strong> is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for <code>2</code> time units and another call executing for <code>1</code> time unit, the <strong>exclusive time</strong> is <code>2 + 1 = 3</code>.</p> <p>Return <em>the <strong>exclusive time</strong> of each function in an array, where the value at the </em><code>i<sup>th</sup></code><em> index represents the exclusive time for the function with ID </em><code>i</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/0636.Exclusive%20Time%20of%20Functions/images/diag1b.png" style="width: 550px; height: 239px;" /> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;] <strong>Output:</strong> [3,4] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [8] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [7,1] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= logs.length &lt;= 500</code></li> <li><code>0 &lt;= function_id &lt; n</code></li> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>No two start events will happen at the same timestamp.</li> <li>No two end events will happen at the same timestamp.</li> <li>Each function has an <code>&quot;end&quot;</code> log for each <code>&quot;start&quot;</code> log.</li> </ul>
Stack; Array
Python
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: stk = [] ans = [0] * n pre = 0 for log in logs: i, op, t = log.split(":") i, cur = int(i), int(t) if op[0] == "s": if stk: ans[stk[-1]] += cur - pre stk.append(i) pre = cur else: ans[stk.pop()] += cur - pre + 1 pre = cur + 1 return ans
636
Exclusive Time of Functions
Medium
<p>On a <strong>single-threaded</strong> CPU, we execute a program containing <code>n</code> functions. Each function has a unique ID between <code>0</code> and <code>n-1</code>.</p> <p>Function calls are <strong>stored in a <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a></strong>: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is <strong>the current function being executed</strong>. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.</p> <p>You are given a list <code>logs</code>, where <code>logs[i]</code> represents the <code>i<sup>th</sup></code> log message formatted as a string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. For example, <code>&quot;0:start:3&quot;</code> means a function call with function ID <code>0</code> <strong>started at the beginning</strong> of timestamp <code>3</code>, and <code>&quot;1:end:2&quot;</code> means a function call with function ID <code>1</code> <strong>ended at the end</strong> of timestamp <code>2</code>. Note that a function can be called <b>multiple times, possibly recursively</b>.</p> <p>A function&#39;s <strong>exclusive time</strong> is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for <code>2</code> time units and another call executing for <code>1</code> time unit, the <strong>exclusive time</strong> is <code>2 + 1 = 3</code>.</p> <p>Return <em>the <strong>exclusive time</strong> of each function in an array, where the value at the </em><code>i<sup>th</sup></code><em> index represents the exclusive time for the function with ID </em><code>i</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/0636.Exclusive%20Time%20of%20Functions/images/diag1b.png" style="width: 550px; height: 239px;" /> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;] <strong>Output:</strong> [3,4] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [8] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;] <strong>Output:</strong> [7,1] <strong>Explanation:</strong> Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= logs.length &lt;= 500</code></li> <li><code>0 &lt;= function_id &lt; n</code></li> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>No two start events will happen at the same timestamp.</li> <li>No two end events will happen at the same timestamp.</li> <li>Each function has an <code>&quot;end&quot;</code> log for each <code>&quot;start&quot;</code> log.</li> </ul>
Stack; Array
TypeScript
function exclusiveTime(n: number, logs: string[]): number[] { const ans: number[] = Array(n).fill(0); let pre = 0; const stk: number[] = []; for (const log of logs) { const [i, op, cur] = log.split(':'); if (op[0] === 's') { if (stk.length) { ans[stk.at(-1)!] += +cur - pre; } stk.push(+i); pre = +cur; } else { ans[stk.pop()!] += +cur - pre + 1; pre = +cur + 1; } } 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
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<double> averageOfLevels(TreeNode* root) { queue<TreeNode*> q{{root}}; vector<double> ans; while (!q.empty()) { int n = q.size(); long long s = 0; for (int i = 0; i < n; ++i) { root = q.front(); q.pop(); s += root->val; if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } ans.push_back(s * 1.0 / 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
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func averageOfLevels(root *TreeNode) []float64 { q := []*TreeNode{root} ans := []float64{} for len(q) > 0 { n := len(q) s := 0 for i := 0; i < n; i++ { root = q[0] q = q[1:] s += root.Val if root.Left != nil { q = append(q, root.Left) } if root.Right != nil { q = append(q, root.Right) } } ans = append(ans, float64(s)/float64(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
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<Double> averageOfLevels(TreeNode root) { List<Double> ans = new ArrayList<>(); Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { int n = q.size(); long s = 0; for (int i = 0; i < n; ++i) { root = q.pollFirst(); s += root.val; if (root.left != null) { q.offer(root.left); } if (root.right != null) { q.offer(root.right); } } ans.add(s * 1.0 / n); } return ans; } }