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
581
Shortest Unsorted Continuous Subarray
Medium
<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p> <p>Return <em>the shortest such subarray and output its length</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,4,8,10,9,15] <strong>Output:</strong> 5 <strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
Python
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: arr = sorted(nums) l, r = 0, len(nums) - 1 while l <= r and nums[l] == arr[l]: l += 1 while l <= r and nums[r] == arr[r]: r -= 1 return r - l + 1
581
Shortest Unsorted Continuous Subarray
Medium
<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p> <p>Return <em>the shortest such subarray and output its length</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,4,8,10,9,15] <strong>Output:</strong> 5 <strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
Rust
impl Solution { pub fn find_unsorted_subarray(nums: Vec<i32>) -> i32 { let mut arr = nums.clone(); arr.sort(); let mut l = 0usize; while l < nums.len() && nums[l] == arr[l] { l += 1; } if l == nums.len() { return 0; } let mut r = nums.len() - 1; while r > l && nums[r] == arr[r] { r -= 1; } (r - l + 1) as i32 } }
581
Shortest Unsorted Continuous Subarray
Medium
<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p> <p>Return <em>the shortest such subarray and output its length</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,4,8,10,9,15] <strong>Output:</strong> 5 <strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
TypeScript
function findUnsortedSubarray(nums: number[]): number { const arr = [...nums]; arr.sort((a, b) => a - b); let [l, r] = [0, arr.length - 1]; while (l <= r && arr[l] === nums[l]) { ++l; } while (l <= r && arr[r] === nums[r]) { --r; } return r - l + 1; }
582
Kill Process
Medium
<p>You have <code>n</code> processes forming a rooted tree structure. You are given two integer arrays <code>pid</code> and <code>ppid</code>, where <code>pid[i]</code> is the ID of the <code>i<sup>th</sup></code> process and <code>ppid[i]</code> is the ID of the <code>i<sup>th</sup></code> process&#39;s parent process.</p> <p>Each process has only <strong>one parent process</strong> but may have multiple children processes. Only one process has <code>ppid[i] = 0</code>, which means this process has <strong>no parent process</strong> (the root of the tree).</p> <p>When a process is <strong>killed</strong>, all of its children processes will also be killed.</p> <p>Given an integer <code>kill</code> representing the ID of a process you want to kill, return <em>a list of the IDs of the processes that will be killed. You may return the answer in <strong>any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0582.Kill%20Process/images/ptree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 <strong>Output:</strong> [5,10] <strong>Explanation:</strong>&nbsp;The processes colored in red are the processes that should be killed. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pid = [1], ppid = [0], kill = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pid.length</code></li> <li><code>n == ppid.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= pid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ppid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li>Only one process has no parent.</li> <li>All the values of <code>pid</code> are <strong>unique</strong>.</li> <li><code>kill</code> is <strong>guaranteed</strong> to be in <code>pid</code>.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Array; Hash Table
C++
class Solution { public: vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) { unordered_map<int, vector<int>> g; int n = pid.size(); for (int i = 0; i < n; ++i) { g[ppid[i]].push_back(pid[i]); } vector<int> ans; function<void(int)> dfs = [&](int i) { ans.push_back(i); for (int j : g[i]) { dfs(j); } }; dfs(kill); return ans; } };
582
Kill Process
Medium
<p>You have <code>n</code> processes forming a rooted tree structure. You are given two integer arrays <code>pid</code> and <code>ppid</code>, where <code>pid[i]</code> is the ID of the <code>i<sup>th</sup></code> process and <code>ppid[i]</code> is the ID of the <code>i<sup>th</sup></code> process&#39;s parent process.</p> <p>Each process has only <strong>one parent process</strong> but may have multiple children processes. Only one process has <code>ppid[i] = 0</code>, which means this process has <strong>no parent process</strong> (the root of the tree).</p> <p>When a process is <strong>killed</strong>, all of its children processes will also be killed.</p> <p>Given an integer <code>kill</code> representing the ID of a process you want to kill, return <em>a list of the IDs of the processes that will be killed. You may return the answer in <strong>any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0582.Kill%20Process/images/ptree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 <strong>Output:</strong> [5,10] <strong>Explanation:</strong>&nbsp;The processes colored in red are the processes that should be killed. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pid = [1], ppid = [0], kill = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pid.length</code></li> <li><code>n == ppid.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= pid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ppid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li>Only one process has no parent.</li> <li>All the values of <code>pid</code> are <strong>unique</strong>.</li> <li><code>kill</code> is <strong>guaranteed</strong> to be in <code>pid</code>.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Array; Hash Table
Go
func killProcess(pid []int, ppid []int, kill int) (ans []int) { g := map[int][]int{} for i, p := range ppid { g[p] = append(g[p], pid[i]) } var dfs func(int) dfs = func(i int) { ans = append(ans, i) for _, j := range g[i] { dfs(j) } } dfs(kill) return }
582
Kill Process
Medium
<p>You have <code>n</code> processes forming a rooted tree structure. You are given two integer arrays <code>pid</code> and <code>ppid</code>, where <code>pid[i]</code> is the ID of the <code>i<sup>th</sup></code> process and <code>ppid[i]</code> is the ID of the <code>i<sup>th</sup></code> process&#39;s parent process.</p> <p>Each process has only <strong>one parent process</strong> but may have multiple children processes. Only one process has <code>ppid[i] = 0</code>, which means this process has <strong>no parent process</strong> (the root of the tree).</p> <p>When a process is <strong>killed</strong>, all of its children processes will also be killed.</p> <p>Given an integer <code>kill</code> representing the ID of a process you want to kill, return <em>a list of the IDs of the processes that will be killed. You may return the answer in <strong>any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0582.Kill%20Process/images/ptree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 <strong>Output:</strong> [5,10] <strong>Explanation:</strong>&nbsp;The processes colored in red are the processes that should be killed. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pid = [1], ppid = [0], kill = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pid.length</code></li> <li><code>n == ppid.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= pid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ppid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li>Only one process has no parent.</li> <li>All the values of <code>pid</code> are <strong>unique</strong>.</li> <li><code>kill</code> is <strong>guaranteed</strong> to be in <code>pid</code>.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Array; Hash Table
Java
class Solution { private Map<Integer, List<Integer>> g = new HashMap<>(); private List<Integer> ans = new ArrayList<>(); public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) { int n = pid.size(); for (int i = 0; i < n; ++i) { g.computeIfAbsent(ppid.get(i), k -> new ArrayList<>()).add(pid.get(i)); } dfs(kill); return ans; } private void dfs(int i) { ans.add(i); for (int j : g.getOrDefault(i, Collections.emptyList())) { dfs(j); } } }
582
Kill Process
Medium
<p>You have <code>n</code> processes forming a rooted tree structure. You are given two integer arrays <code>pid</code> and <code>ppid</code>, where <code>pid[i]</code> is the ID of the <code>i<sup>th</sup></code> process and <code>ppid[i]</code> is the ID of the <code>i<sup>th</sup></code> process&#39;s parent process.</p> <p>Each process has only <strong>one parent process</strong> but may have multiple children processes. Only one process has <code>ppid[i] = 0</code>, which means this process has <strong>no parent process</strong> (the root of the tree).</p> <p>When a process is <strong>killed</strong>, all of its children processes will also be killed.</p> <p>Given an integer <code>kill</code> representing the ID of a process you want to kill, return <em>a list of the IDs of the processes that will be killed. You may return the answer in <strong>any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0582.Kill%20Process/images/ptree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 <strong>Output:</strong> [5,10] <strong>Explanation:</strong>&nbsp;The processes colored in red are the processes that should be killed. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pid = [1], ppid = [0], kill = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pid.length</code></li> <li><code>n == ppid.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= pid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ppid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li>Only one process has no parent.</li> <li>All the values of <code>pid</code> are <strong>unique</strong>.</li> <li><code>kill</code> is <strong>guaranteed</strong> to be in <code>pid</code>.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Array; Hash Table
Python
class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: def dfs(i: int): ans.append(i) for j in g[i]: dfs(j) g = defaultdict(list) for i, p in zip(pid, ppid): g[p].append(i) ans = [] dfs(kill) return ans
582
Kill Process
Medium
<p>You have <code>n</code> processes forming a rooted tree structure. You are given two integer arrays <code>pid</code> and <code>ppid</code>, where <code>pid[i]</code> is the ID of the <code>i<sup>th</sup></code> process and <code>ppid[i]</code> is the ID of the <code>i<sup>th</sup></code> process&#39;s parent process.</p> <p>Each process has only <strong>one parent process</strong> but may have multiple children processes. Only one process has <code>ppid[i] = 0</code>, which means this process has <strong>no parent process</strong> (the root of the tree).</p> <p>When a process is <strong>killed</strong>, all of its children processes will also be killed.</p> <p>Given an integer <code>kill</code> representing the ID of a process you want to kill, return <em>a list of the IDs of the processes that will be killed. You may return the answer in <strong>any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0582.Kill%20Process/images/ptree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 <strong>Output:</strong> [5,10] <strong>Explanation:</strong>&nbsp;The processes colored in red are the processes that should be killed. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pid = [1], ppid = [0], kill = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pid.length</code></li> <li><code>n == ppid.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= pid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ppid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li>Only one process has no parent.</li> <li>All the values of <code>pid</code> are <strong>unique</strong>.</li> <li><code>kill</code> is <strong>guaranteed</strong> to be in <code>pid</code>.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Array; Hash Table
Rust
use std::collections::HashMap; impl Solution { pub fn kill_process(pid: Vec<i32>, ppid: Vec<i32>, kill: i32) -> Vec<i32> { let mut g: HashMap<i32, Vec<i32>> = HashMap::new(); let mut ans: Vec<i32> = Vec::new(); let n = pid.len(); for i in 0..n { g.entry(ppid[i]).or_insert(Vec::new()).push(pid[i]); } Self::dfs(&mut ans, &g, kill); ans } fn dfs(ans: &mut Vec<i32>, g: &HashMap<i32, Vec<i32>>, i: i32) { ans.push(i); if let Some(children) = g.get(&i) { for &j in children { Self::dfs(ans, g, j); } } } }
582
Kill Process
Medium
<p>You have <code>n</code> processes forming a rooted tree structure. You are given two integer arrays <code>pid</code> and <code>ppid</code>, where <code>pid[i]</code> is the ID of the <code>i<sup>th</sup></code> process and <code>ppid[i]</code> is the ID of the <code>i<sup>th</sup></code> process&#39;s parent process.</p> <p>Each process has only <strong>one parent process</strong> but may have multiple children processes. Only one process has <code>ppid[i] = 0</code>, which means this process has <strong>no parent process</strong> (the root of the tree).</p> <p>When a process is <strong>killed</strong>, all of its children processes will also be killed.</p> <p>Given an integer <code>kill</code> representing the ID of a process you want to kill, return <em>a list of the IDs of the processes that will be killed. You may return the answer in <strong>any order</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0582.Kill%20Process/images/ptree.jpg" style="width: 207px; height: 302px;" /> <pre> <strong>Input:</strong> pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 <strong>Output:</strong> [5,10] <strong>Explanation:</strong>&nbsp;The processes colored in red are the processes that should be killed. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pid = [1], ppid = [0], kill = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == pid.length</code></li> <li><code>n == ppid.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= pid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ppid[i] &lt;= 5 * 10<sup>4</sup></code></li> <li>Only one process has no parent.</li> <li>All the values of <code>pid</code> are <strong>unique</strong>.</li> <li><code>kill</code> is <strong>guaranteed</strong> to be in <code>pid</code>.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Array; Hash Table
TypeScript
function killProcess(pid: number[], ppid: number[], kill: number): number[] { const g: Map<number, number[]> = new Map(); for (let i = 0; i < pid.length; ++i) { if (!g.has(ppid[i])) { g.set(ppid[i], []); } g.get(ppid[i])?.push(pid[i]); } const ans: number[] = []; const dfs = (i: number) => { ans.push(i); for (const j of g.get(i) ?? []) { dfs(j); } }; dfs(kill); return ans; }
583
Delete Operation for Two Strings
Medium
<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p> <p>In one <strong>step</strong>, you can delete exactly one character in either string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot; <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li> <li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int minDistance(string word1, string word2) { int m = word1.length(), n = word2.length(); vector<vector<int>> f(m + 1, vector<int>(n + 1)); for (int i = 0; i <= m; ++i) { f[i][0] = i; } for (int j = 0; j <= n; ++j) { f[0][j] = j; } for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { char a = word1[i - 1]; char b = word2[j - 1]; if (a == b) { f[i][j] = f[i - 1][j - 1]; } else { f[i][j] = min(f[i - 1][j], f[i][j - 1]) + 1; } } } return f[m][n]; } };
583
Delete Operation for Two Strings
Medium
<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p> <p>In one <strong>step</strong>, you can delete exactly one character in either string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot; <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li> <li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Go
func minDistance(word1 string, word2 string) int { m, n := len(word1), len(word2) f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) f[i][0] = i } for j := 1; j <= n; j++ { f[0][j] = j } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { a, b := word1[i-1], word2[j-1] if a == b { f[i][j] = f[i-1][j-1] } else { f[i][j] = 1 + min(f[i-1][j], f[i][j-1]) } } } return f[m][n] }
583
Delete Operation for Two Strings
Medium
<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p> <p>In one <strong>step</strong>, you can delete exactly one character in either string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot; <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li> <li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Java
class Solution { public int minDistance(String word1, String word2) { int m = word1.length(), n = word2.length(); int[][] f = new int[m + 1][n + 1]; for (int i = 0; i <= m; ++i) { f[i][0] = i; } for (int j = 0; j <= n; ++j) { f[0][j] = j; } for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { char a = word1.charAt(i - 1); char b = word2.charAt(j - 1); if (a == b) { f[i][j] = f[i - 1][j - 1]; } else { f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + 1; } } } return f[m][n]; } }
583
Delete Operation for Two Strings
Medium
<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p> <p>In one <strong>step</strong>, you can delete exactly one character in either string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot; <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li> <li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Python
class Solution: def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) f = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): f[i][0] = i for j in range(1, n + 1): f[0][j] = j for i, a in enumerate(word1, 1): for j, b in enumerate(word2, 1): if a == b: f[i][j] = f[i - 1][j - 1] else: f[i][j] = min(f[i - 1][j], f[i][j - 1]) + 1 return f[m][n]
583
Delete Operation for Two Strings
Medium
<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p> <p>In one <strong>step</strong>, you can delete exactly one character in either string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot; <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li> <li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Rust
impl Solution { pub fn min_distance(word1: String, word2: String) -> i32 { let m = word1.len(); let n = word2.len(); let s: Vec<char> = word1.chars().collect(); let t: Vec<char> = word2.chars().collect(); let mut f = vec![vec![0; n + 1]; m + 1]; for i in 0..=m { f[i][0] = i as i32; } for j in 0..=n { f[0][j] = j as i32; } for i in 1..=m { for j in 1..=n { let a = s[i - 1]; let b = t[j - 1]; if a == b { f[i][j] = f[i - 1][j - 1]; } else { f[i][j] = std::cmp::min(f[i - 1][j], f[i][j - 1]) + 1; } } } f[m][n] } }
583
Delete Operation for Two Strings
Medium
<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p> <p>In one <strong>step</strong>, you can delete exactly one character in either string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot; <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li> <li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li> </ul>
String; Dynamic Programming
TypeScript
function minDistance(word1: string, word2: string): number { const m = word1.length; const n = word2.length; const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); for (let i = 1; i <= m; ++i) { f[i][0] = i; } for (let j = 1; j <= n; ++j) { f[0][j] = j; } for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { if (word1[i - 1] === word2[j - 1]) { f[i][j] = f[i - 1][j - 1]; } else { f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + 1; } } } return f[m][n]; }
584
Find Customer Referee
Easy
<p>Table: <code>Customer</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+ In SQL, id is the primary key column for this table. Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them. </pre> <p>&nbsp;</p> <p>Find the names of the customer that are either:</p> <ol> <li><strong>referred by</strong>&nbsp;any&nbsp;customer with&nbsp;<code>id != 2</code>.</li> <li><strong>not referred by</strong> any customer.</li> </ol> <p>Return the result table in <strong>any 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> Customer table: +----+------+------------+ | id | name | referee_id | +----+------+------------+ | 1 | Will | null | | 2 | Jane | null | | 3 | Alex | 2 | | 4 | Bill | null | | 5 | Zack | 1 | | 6 | Mark | 2 | +----+------+------------+ <strong>Output:</strong> +------+ | name | +------+ | Will | | Jane | | Bill | | Zack | +------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT name FROM Customer WHERE IFNULL(referee_id, 0) != 2;
585
Investments in 2016
Medium
<p>Table: <code>Insurance</code></p> <pre> +-------------+-------+ | Column Name | Type | +-------------+-------+ | pid | int | | tiv_2015 | float | | tiv_2016 | float | | lat | float | | lon | float | +-------------+-------+ pid is the primary key (column with unique values) for this table. Each row of this table contains information about one policy where: pid is the policyholder&#39;s policy ID. tiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016. lat is the latitude of the policy holder&#39;s city. It&#39;s guaranteed that lat is not NULL. lon is the longitude of the policy holder&#39;s city. It&#39;s guaranteed that lon is not NULL. </pre> <p>&nbsp;</p> <p>Write a solution to report the sum of all total investment values in 2016 <code>tiv_2016</code>, for all policyholders who:</p> <ul> <li>have the same <code>tiv_2015</code> value as one or more other policyholders, and</li> <li>are not located in the same city as any other policyholder (i.e., the (<code>lat, lon</code>) attribute pairs must be unique).</li> </ul> <p>Round <code>tiv_2016</code> to <strong>two decimal places</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> Insurance table: +-----+----------+----------+-----+-----+ | pid | tiv_2015 | tiv_2016 | lat | lon | +-----+----------+----------+-----+-----+ | 1 | 10 | 5 | 10 | 10 | | 2 | 20 | 20 | 20 | 20 | | 3 | 10 | 30 | 20 | 20 | | 4 | 10 | 40 | 40 | 40 | +-----+----------+----------+-----+-----+ <strong>Output:</strong> +----------+ | tiv_2016 | +----------+ | 45.00 | +----------+ <strong>Explanation:</strong> The first record in the table, like the last record, meets both of the two criteria. The tiv_2015 value 10 is the same as the third and fourth records, and its location is unique. The second record does not meet any of the two criteria. Its tiv_2015 is not like any other policyholders and its location is the same as the third record, which makes the third record fail, too. So, the result is the sum of tiv_2016 of the first and last record, which is 45. </pre>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT tiv_2016, COUNT(1) OVER (PARTITION BY tiv_2015) AS cnt1, COUNT(1) OVER (PARTITION BY lat, lon) AS cnt2 FROM Insurance ) SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016 FROM T WHERE cnt1 > 1 AND cnt2 = 1;
586
Customer Placing the Largest Number of Orders
Easy
<p>Table: <code>Orders</code></p> <pre> +-----------------+----------+ | Column Name | Type | +-----------------+----------+ | order_number | int | | customer_number | int | +-----------------+----------+ order_number is the primary key (column with unique values) for this table. This table contains information about the order ID and the customer ID. </pre> <p>&nbsp;</p> <p>Write a solution to find the <code>customer_number</code> for the customer who has placed <strong>the largest number of orders</strong>.</p> <p>The test cases are generated so that <strong>exactly one customer</strong> will have placed more orders than any other customer.</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> Orders table: +--------------+-----------------+ | order_number | customer_number | +--------------+-----------------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 3 | +--------------+-----------------+ <strong>Output:</strong> +-----------------+ | customer_number | +-----------------+ | 3 | +-----------------+ <strong>Explanation:</strong> The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. So the result is customer_number 3. </pre> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if more than one customer has the largest number of orders, can you find all the <code>customer_number</code> in this case?</p>
Database
SQL
# Write your MySQL query statement below SELECT customer_number FROM orders GROUP BY customer_number ORDER BY COUNT(1) DESC LIMIT 1;
587
Erect the Fence
Hard
<p>You are given an array <code>trees</code> where <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of a tree in the garden.</p> <p>Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if <strong>all the trees are enclosed</strong>.</p> <p>Return <em>the coordinates of trees that are exactly located on the fence perimeter</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect2-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] <strong>Output:</strong> [[1,1],[2,0],[4,2],[3,3],[2,4]] <strong>Explanation:</strong> All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect1-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,2],[2,2],[4,2]] <strong>Output:</strong> [[4,2],[2,2],[1,2]] <strong>Explanation:</strong> The fence forms a line that passes through all the trees. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= trees.length &lt;= 3000</code></li> <li><code>trees[i].length == 2</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li> <li>All the given positions are <strong>unique</strong>.</li> </ul>
Geometry; Array; Math
C++
class Solution { public: vector<vector<int>> outerTrees(vector<vector<int>>& trees) { int n = trees.size(); if (n < 4) return trees; sort(trees.begin(), trees.end()); vector<int> vis(n); vector<int> stk(n + 10); int cnt = 1; for (int i = 1; i < n; ++i) { while (cnt > 1 && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) vis[stk[--cnt]] = false; vis[i] = true; stk[cnt++] = i; } int m = cnt; for (int i = n - 1; i >= 0; --i) { if (vis[i]) continue; while (cnt > m && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) --cnt; stk[cnt++] = i; } vector<vector<int>> ans; for (int i = 0; i < cnt - 1; ++i) ans.push_back(trees[stk[i]]); return ans; } int cross(vector<int>& a, vector<int>& b, vector<int>& c) { return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); } };
587
Erect the Fence
Hard
<p>You are given an array <code>trees</code> where <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of a tree in the garden.</p> <p>Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if <strong>all the trees are enclosed</strong>.</p> <p>Return <em>the coordinates of trees that are exactly located on the fence perimeter</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect2-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] <strong>Output:</strong> [[1,1],[2,0],[4,2],[3,3],[2,4]] <strong>Explanation:</strong> All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect1-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,2],[2,2],[4,2]] <strong>Output:</strong> [[4,2],[2,2],[1,2]] <strong>Explanation:</strong> The fence forms a line that passes through all the trees. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= trees.length &lt;= 3000</code></li> <li><code>trees[i].length == 2</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li> <li>All the given positions are <strong>unique</strong>.</li> </ul>
Geometry; Array; Math
Go
func outerTrees(trees [][]int) [][]int { n := len(trees) if n < 4 { return trees } sort.Slice(trees, func(i, j int) bool { if trees[i][0] == trees[j][0] { return trees[i][1] < trees[j][1] } return trees[i][0] < trees[j][0] }) cross := func(i, j, k int) int { a, b, c := trees[i], trees[j], trees[k] return (b[0]-a[0])*(c[1]-b[1]) - (b[1]-a[1])*(c[0]-b[0]) } vis := make([]bool, n) stk := []int{0} for i := 1; i < n; i++ { for len(stk) > 1 && cross(stk[len(stk)-1], stk[len(stk)-2], i) < 0 { vis[stk[len(stk)-1]] = false stk = stk[:len(stk)-1] } vis[i] = true stk = append(stk, i) } m := len(stk) for i := n - 1; i >= 0; i-- { if vis[i] { continue } for len(stk) > m && cross(stk[len(stk)-1], stk[len(stk)-2], i) < 0 { stk = stk[:len(stk)-1] } stk = append(stk, i) } var ans [][]int for i := 0; i < len(stk)-1; i++ { ans = append(ans, trees[stk[i]]) } return ans }
587
Erect the Fence
Hard
<p>You are given an array <code>trees</code> where <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of a tree in the garden.</p> <p>Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if <strong>all the trees are enclosed</strong>.</p> <p>Return <em>the coordinates of trees that are exactly located on the fence perimeter</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect2-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] <strong>Output:</strong> [[1,1],[2,0],[4,2],[3,3],[2,4]] <strong>Explanation:</strong> All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect1-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,2],[2,2],[4,2]] <strong>Output:</strong> [[4,2],[2,2],[1,2]] <strong>Explanation:</strong> The fence forms a line that passes through all the trees. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= trees.length &lt;= 3000</code></li> <li><code>trees[i].length == 2</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li> <li>All the given positions are <strong>unique</strong>.</li> </ul>
Geometry; Array; Math
Java
class Solution { public int[][] outerTrees(int[][] trees) { int n = trees.length; if (n < 4) { return trees; } Arrays.sort(trees, (a, b) -> { return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]; }); boolean[] vis = new boolean[n]; int[] stk = new int[n + 10]; int cnt = 1; for (int i = 1; i < n; ++i) { while (cnt > 1 && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) { vis[stk[--cnt]] = false; } vis[i] = true; stk[cnt++] = i; } int m = cnt; for (int i = n - 1; i >= 0; --i) { if (vis[i]) { continue; } while (cnt > m && cross(trees[stk[cnt - 1]], trees[stk[cnt - 2]], trees[i]) < 0) { --cnt; } stk[cnt++] = i; } int[][] ans = new int[cnt - 1][2]; for (int i = 0; i < ans.length; ++i) { ans[i] = trees[stk[i]]; } return ans; } private int cross(int[] a, int[] b, int[] c) { return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); } }
587
Erect the Fence
Hard
<p>You are given an array <code>trees</code> where <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of a tree in the garden.</p> <p>Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if <strong>all the trees are enclosed</strong>.</p> <p>Return <em>the coordinates of trees that are exactly located on the fence perimeter</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect2-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] <strong>Output:</strong> [[1,1],[2,0],[4,2],[3,3],[2,4]] <strong>Explanation:</strong> All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect1-plane.jpg" style="width: 400px; height: 393px;" /> <pre> <strong>Input:</strong> trees = [[1,2],[2,2],[4,2]] <strong>Output:</strong> [[4,2],[2,2],[1,2]] <strong>Explanation:</strong> The fence forms a line that passes through all the trees. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= trees.length &lt;= 3000</code></li> <li><code>trees[i].length == 2</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li> <li>All the given positions are <strong>unique</strong>.</li> </ul>
Geometry; Array; Math
Python
class Solution: def outerTrees(self, trees: List[List[int]]) -> List[List[int]]: def cross(i, j, k): a, b, c = trees[i], trees[j], trees[k] return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) n = len(trees) if n < 4: return trees trees.sort() vis = [False] * n stk = [0] for i in range(1, n): while len(stk) > 1 and cross(stk[-2], stk[-1], i) < 0: vis[stk.pop()] = False vis[i] = True stk.append(i) m = len(stk) for i in range(n - 2, -1, -1): if vis[i]: continue while len(stk) > m and cross(stk[-2], stk[-1], i) < 0: stk.pop() stk.append(i) stk.pop() return [trees[i] for i in stk]
588
Design In-Memory File System
Hard
<p>Design a data structure that simulates an in-memory file system.</p> <p>Implement the FileSystem class:</p> <ul> <li><code>FileSystem()</code> Initializes the object of the system.</li> <li><code>List&lt;String&gt; ls(String path)</code> <ul> <li>If <code>path</code> is a file path, returns a list that only contains this file&#39;s name.</li> <li>If <code>path</code> is a directory path, returns the list of file and directory names <strong>in this directory</strong>.</li> </ul> The answer should in <strong>lexicographic order</strong>.</li> <li><code>void mkdir(String path)</code> Makes a new directory according to the given <code>path</code>. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well.</li> <li><code>void addContentToFile(String filePath, String content)</code> <ul> <li>If <code>filePath</code> does not exist, creates that file containing given <code>content</code>.</li> <li>If <code>filePath</code> already exists, appends the given <code>content</code> to original content.</li> </ul> </li> <li><code>String readContentFromFile(String filePath)</code> Returns the content in the file at <code>filePath</code>.</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/0500-0599/0588.Design%20In-Memory%20File%20System/images/filesystem.png" style="width: 650px; height: 315px;" /> <pre> <strong>Input</strong> [&quot;FileSystem&quot;, &quot;ls&quot;, &quot;mkdir&quot;, &quot;addContentToFile&quot;, &quot;ls&quot;, &quot;readContentFromFile&quot;] [[], [&quot;/&quot;], [&quot;/a/b/c&quot;], [&quot;/a/b/c/d&quot;, &quot;hello&quot;], [&quot;/&quot;], [&quot;/a/b/c/d&quot;]] <strong>Output</strong> [null, [], null, null, [&quot;a&quot;], &quot;hello&quot;] <strong>Explanation</strong> FileSystem fileSystem = new FileSystem(); fileSystem.ls(&quot;/&quot;); // return [] fileSystem.mkdir(&quot;/a/b/c&quot;); fileSystem.addContentToFile(&quot;/a/b/c/d&quot;, &quot;hello&quot;); fileSystem.ls(&quot;/&quot;); // return [&quot;a&quot;] fileSystem.readContentFromFile(&quot;/a/b/c/d&quot;); // return &quot;hello&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= path.length,&nbsp;filePath.length &lt;= 100</code></li> <li><code>path</code> and <code>filePath</code>&nbsp;are absolute paths which begin with <code>&#39;/&#39;</code>&nbsp;and do not end with <code>&#39;/&#39;</code>&nbsp;except that the path is just&nbsp;<code>&quot;/&quot;</code>.</li> <li>You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory.</li> <li>You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist.</li> <li>You can assume that the parent directory for the file in <code>addContentToFile</code> will exist.</li> <li><code>1 &lt;= content.length &lt;= 50</code></li> <li>At most <code>300</code> calls will be made to <code>ls</code>, <code>mkdir</code>,&nbsp;<code>addContentToFile</code>, and&nbsp;<code>readContentFromFile</code>.</li> </ul>
Design; Trie; Hash Table; String; Sorting
Go
type Trie struct { name string isFile bool content strings.Builder children map[string]*Trie } func newTrie() *Trie { m := map[string]*Trie{} return &Trie{children: m} } func (this *Trie) insert(path string, isFile bool) *Trie { node := this ps := strings.Split(path, "/") for _, p := range ps[1:] { if _, ok := node.children[p]; !ok { node.children[p] = newTrie() } node, _ = node.children[p] } node.isFile = isFile if isFile { node.name = ps[len(ps)-1] } return node } func (this *Trie) search(path string) *Trie { if path == "/" { return this } node := this ps := strings.Split(path, "/") for _, p := range ps[1:] { if _, ok := node.children[p]; !ok { return nil } node, _ = node.children[p] } return node } type FileSystem struct { root *Trie } func Constructor() FileSystem { root := newTrie() return FileSystem{root} } func (this *FileSystem) Ls(path string) []string { var ans []string node := this.root.search(path) if node == nil { return ans } if node.isFile { ans = append(ans, node.name) return ans } for v := range node.children { ans = append(ans, v) } sort.Strings(ans) return ans } func (this *FileSystem) Mkdir(path string) { this.root.insert(path, false) } func (this *FileSystem) AddContentToFile(filePath string, content string) { node := this.root.insert(filePath, true) node.content.WriteString(content) } func (this *FileSystem) ReadContentFromFile(filePath string) string { node := this.root.search(filePath) return node.content.String() } /** * Your FileSystem object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Ls(path); * obj.Mkdir(path); * obj.AddContentToFile(filePath,content); * param_4 := obj.ReadContentFromFile(filePath); */
588
Design In-Memory File System
Hard
<p>Design a data structure that simulates an in-memory file system.</p> <p>Implement the FileSystem class:</p> <ul> <li><code>FileSystem()</code> Initializes the object of the system.</li> <li><code>List&lt;String&gt; ls(String path)</code> <ul> <li>If <code>path</code> is a file path, returns a list that only contains this file&#39;s name.</li> <li>If <code>path</code> is a directory path, returns the list of file and directory names <strong>in this directory</strong>.</li> </ul> The answer should in <strong>lexicographic order</strong>.</li> <li><code>void mkdir(String path)</code> Makes a new directory according to the given <code>path</code>. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well.</li> <li><code>void addContentToFile(String filePath, String content)</code> <ul> <li>If <code>filePath</code> does not exist, creates that file containing given <code>content</code>.</li> <li>If <code>filePath</code> already exists, appends the given <code>content</code> to original content.</li> </ul> </li> <li><code>String readContentFromFile(String filePath)</code> Returns the content in the file at <code>filePath</code>.</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/0500-0599/0588.Design%20In-Memory%20File%20System/images/filesystem.png" style="width: 650px; height: 315px;" /> <pre> <strong>Input</strong> [&quot;FileSystem&quot;, &quot;ls&quot;, &quot;mkdir&quot;, &quot;addContentToFile&quot;, &quot;ls&quot;, &quot;readContentFromFile&quot;] [[], [&quot;/&quot;], [&quot;/a/b/c&quot;], [&quot;/a/b/c/d&quot;, &quot;hello&quot;], [&quot;/&quot;], [&quot;/a/b/c/d&quot;]] <strong>Output</strong> [null, [], null, null, [&quot;a&quot;], &quot;hello&quot;] <strong>Explanation</strong> FileSystem fileSystem = new FileSystem(); fileSystem.ls(&quot;/&quot;); // return [] fileSystem.mkdir(&quot;/a/b/c&quot;); fileSystem.addContentToFile(&quot;/a/b/c/d&quot;, &quot;hello&quot;); fileSystem.ls(&quot;/&quot;); // return [&quot;a&quot;] fileSystem.readContentFromFile(&quot;/a/b/c/d&quot;); // return &quot;hello&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= path.length,&nbsp;filePath.length &lt;= 100</code></li> <li><code>path</code> and <code>filePath</code>&nbsp;are absolute paths which begin with <code>&#39;/&#39;</code>&nbsp;and do not end with <code>&#39;/&#39;</code>&nbsp;except that the path is just&nbsp;<code>&quot;/&quot;</code>.</li> <li>You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory.</li> <li>You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist.</li> <li>You can assume that the parent directory for the file in <code>addContentToFile</code> will exist.</li> <li><code>1 &lt;= content.length &lt;= 50</code></li> <li>At most <code>300</code> calls will be made to <code>ls</code>, <code>mkdir</code>,&nbsp;<code>addContentToFile</code>, and&nbsp;<code>readContentFromFile</code>.</li> </ul>
Design; Trie; Hash Table; String; Sorting
Java
class Trie { String name; boolean isFile; StringBuilder content = new StringBuilder(); Map<String, Trie> children = new HashMap<>(); Trie insert(String path, boolean isFile) { Trie node = this; String[] ps = path.split("/"); for (int i = 1; i < ps.length; ++i) { String p = ps[i]; if (!node.children.containsKey(p)) { node.children.put(p, new Trie()); } node = node.children.get(p); } node.isFile = isFile; if (isFile) { node.name = ps[ps.length - 1]; } return node; } Trie search(String path) { Trie node = this; String[] ps = path.split("/"); for (int i = 1; i < ps.length; ++i) { String p = ps[i]; if (!node.children.containsKey(p)) { return null; } node = node.children.get(p); } return node; } } class FileSystem { private Trie root = new Trie(); public FileSystem() { } public List<String> ls(String path) { List<String> ans = new ArrayList<>(); Trie node = root.search(path); if (node == null) { return ans; } if (node.isFile) { ans.add(node.name); return ans; } for (String v : node.children.keySet()) { ans.add(v); } Collections.sort(ans); return ans; } public void mkdir(String path) { root.insert(path, false); } public void addContentToFile(String filePath, String content) { Trie node = root.insert(filePath, true); node.content.append(content); } public String readContentFromFile(String filePath) { Trie node = root.search(filePath); return node.content.toString(); } } /** * Your FileSystem object will be instantiated and called as such: * FileSystem obj = new FileSystem(); * List<String> param_1 = obj.ls(path); * obj.mkdir(path); * obj.addContentToFile(filePath,content); * String param_4 = obj.readContentFromFile(filePath); */
588
Design In-Memory File System
Hard
<p>Design a data structure that simulates an in-memory file system.</p> <p>Implement the FileSystem class:</p> <ul> <li><code>FileSystem()</code> Initializes the object of the system.</li> <li><code>List&lt;String&gt; ls(String path)</code> <ul> <li>If <code>path</code> is a file path, returns a list that only contains this file&#39;s name.</li> <li>If <code>path</code> is a directory path, returns the list of file and directory names <strong>in this directory</strong>.</li> </ul> The answer should in <strong>lexicographic order</strong>.</li> <li><code>void mkdir(String path)</code> Makes a new directory according to the given <code>path</code>. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well.</li> <li><code>void addContentToFile(String filePath, String content)</code> <ul> <li>If <code>filePath</code> does not exist, creates that file containing given <code>content</code>.</li> <li>If <code>filePath</code> already exists, appends the given <code>content</code> to original content.</li> </ul> </li> <li><code>String readContentFromFile(String filePath)</code> Returns the content in the file at <code>filePath</code>.</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/0500-0599/0588.Design%20In-Memory%20File%20System/images/filesystem.png" style="width: 650px; height: 315px;" /> <pre> <strong>Input</strong> [&quot;FileSystem&quot;, &quot;ls&quot;, &quot;mkdir&quot;, &quot;addContentToFile&quot;, &quot;ls&quot;, &quot;readContentFromFile&quot;] [[], [&quot;/&quot;], [&quot;/a/b/c&quot;], [&quot;/a/b/c/d&quot;, &quot;hello&quot;], [&quot;/&quot;], [&quot;/a/b/c/d&quot;]] <strong>Output</strong> [null, [], null, null, [&quot;a&quot;], &quot;hello&quot;] <strong>Explanation</strong> FileSystem fileSystem = new FileSystem(); fileSystem.ls(&quot;/&quot;); // return [] fileSystem.mkdir(&quot;/a/b/c&quot;); fileSystem.addContentToFile(&quot;/a/b/c/d&quot;, &quot;hello&quot;); fileSystem.ls(&quot;/&quot;); // return [&quot;a&quot;] fileSystem.readContentFromFile(&quot;/a/b/c/d&quot;); // return &quot;hello&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= path.length,&nbsp;filePath.length &lt;= 100</code></li> <li><code>path</code> and <code>filePath</code>&nbsp;are absolute paths which begin with <code>&#39;/&#39;</code>&nbsp;and do not end with <code>&#39;/&#39;</code>&nbsp;except that the path is just&nbsp;<code>&quot;/&quot;</code>.</li> <li>You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory.</li> <li>You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist.</li> <li>You can assume that the parent directory for the file in <code>addContentToFile</code> will exist.</li> <li><code>1 &lt;= content.length &lt;= 50</code></li> <li>At most <code>300</code> calls will be made to <code>ls</code>, <code>mkdir</code>,&nbsp;<code>addContentToFile</code>, and&nbsp;<code>readContentFromFile</code>.</li> </ul>
Design; Trie; Hash Table; String; Sorting
Python
class Trie: def __init__(self): self.name = None self.isFile = False self.content = [] self.children = {} def insert(self, path, isFile): node = self ps = path.split('/') for p in ps[1:]: if p not in node.children: node.children[p] = Trie() node = node.children[p] node.isFile = isFile if isFile: node.name = ps[-1] return node def search(self, path): node = self if path == '/': return node ps = path.split('/') for p in ps[1:]: if p not in node.children: return None node = node.children[p] return node class FileSystem: def __init__(self): self.root = Trie() def ls(self, path: str) -> List[str]: node = self.root.search(path) if node is None: return [] if node.isFile: return [node.name] return sorted(node.children.keys()) def mkdir(self, path: str) -> None: self.root.insert(path, False) def addContentToFile(self, filePath: str, content: str) -> None: node = self.root.insert(filePath, True) node.content.append(content) def readContentFromFile(self, filePath: str) -> str: node = self.root.search(filePath) return ''.join(node.content) # Your FileSystem object will be instantiated and called as such: # obj = FileSystem() # param_1 = obj.ls(path) # obj.mkdir(path) # obj.addContentToFile(filePath,content) # param_4 = obj.readContentFromFile(filePath)
589
N-ary Tree Preorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,3,5,6,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
C
/** * Definition for a Node. * struct Node { * int val; * int numChildren; * struct Node** children; * }; */ /** * Note: The returned array must be malloced, assume caller calls free(). */ void dfs(struct Node* root, int* ans, int* i) { if (!root) { return; } ans[(*i)++] = root->val; for (int j = 0; j < root->numChildren; j++) { dfs(root->children[j], ans, i); } } int* preorder(struct Node* root, int* returnSize) { int* ans = malloc(sizeof(int) * 10000); *returnSize = 0; dfs(root, ans, returnSize); return ans; }
589
N-ary Tree Preorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,3,5,6,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
C++
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<int> preorder(Node* root) { vector<int> ans; function<void(Node*)> dfs = [&](Node* root) { if (!root) { return; } ans.push_back(root->val); for (auto& child : root->children) { dfs(child); } }; dfs(root); return ans; } };
589
N-ary Tree Preorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,3,5,6,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
Go
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ func preorder(root *Node) (ans []int) { var dfs func(*Node) dfs = func(root *Node) { if root == nil { return } ans = append(ans, root.Val) for _, child := range root.Children { dfs(child) } } dfs(root) return }
589
N-ary Tree Preorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,3,5,6,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
Java
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { private List<Integer> ans = new ArrayList<>(); public List<Integer> preorder(Node root) { dfs(root); return ans; } private void dfs(Node root) { if (root == null) { return; } ans.add(root.val); for (Node child : root.children) { dfs(child); } } }
589
N-ary Tree Preorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,3,5,6,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
Python
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: "Node") -> List[int]: def dfs(root): if root is None: return ans.append(root.val) for child in root.children: dfs(child) ans = [] dfs(root) return ans
589
N-ary Tree Preorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,3,5,6,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
TypeScript
/** * Definition for node. * class Node { * val: number * children: Node[] * constructor(val?: number) { * this.val = (val===undefined ? 0 : val) * this.children = [] * } * } */ function preorder(root: Node | null): number[] { const ans: number[] = []; const dfs = (root: Node | null) => { if (!root) { return; } ans.push(root.val); for (const child of root.children) { dfs(child); } }; dfs(root); return ans; }
590
N-ary Tree Postorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [5,6,3,2,4,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
C++
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<int> postorder(Node* root) { vector<int> ans; function<void(Node*)> dfs = [&](Node* root) { if (!root) { return; } for (auto& child : root->children) { dfs(child); } ans.push_back(root->val); }; dfs(root); return ans; } };
590
N-ary Tree Postorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [5,6,3,2,4,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
Go
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ func postorder(root *Node) (ans []int) { var dfs func(*Node) dfs = func(root *Node) { if root == nil { return } for _, child := range root.Children { dfs(child) } ans = append(ans, root.Val) } dfs(root) return }
590
N-ary Tree Postorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [5,6,3,2,4,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
Java
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { private List<Integer> ans = new ArrayList<>(); public List<Integer> postorder(Node root) { dfs(root); return ans; } private void dfs(Node root) { if (root == null) { return; } for (Node child : root.children) { dfs(child); } ans.add(root.val); } }
590
N-ary Tree Postorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [5,6,3,2,4,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
Python
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def postorder(self, root: 'Node') -> List[int]: def dfs(root): if root is None: return for child in root.children: dfs(child) ans.append(root.val) ans = [] dfs(root) return ans
590
N-ary Tree Postorder Traversal
Easy
<p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p> <p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [5,6,3,2,4,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
Stack; Tree; Depth-First Search
TypeScript
/** * Definition for node. * class Node { * val: number * children: Node[] * constructor(val?: number) { * this.val = (val===undefined ? 0 : val) * this.children = [] * } * } */ function postorder(root: Node | null): number[] { const ans: number[] = []; const dfs = (root: Node | null) => { if (!root) { return; } for (const child of root.children) { dfs(child); } ans.push(root.val); }; dfs(root); return ans; }
591
Tag Validator
Hard
<p>Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.</p> <p>A code snippet is valid if all the following rules hold:</p> <ol> <li>The code must be wrapped in a <b>valid closed tag</b>. Otherwise, the code is invalid.</li> <li>A <b>closed tag</b> (not necessarily valid) has exactly the following format : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Among them, <code>&lt;TAG_NAME&gt;</code> is the start tag, and <code>&lt;/TAG_NAME&gt;</code> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is <b>valid</b> if and only if the TAG_NAME and TAG_CONTENT are valid.</li> <li>A <b>valid</b> <code>TAG_NAME</code> only contain <b>upper-case letters</b>, and has length in range [1,9]. Otherwise, the <code>TAG_NAME</code> is <b>invalid</b>.</li> <li>A <b>valid</b> <code>TAG_CONTENT</code> may contain other <b>valid closed tags</b>, <b>cdata</b> and any characters (see note1) <b>EXCEPT</b> unmatched <code>&lt;</code>, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the <code>TAG_CONTENT</code> is <b>invalid</b>.</li> <li>A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.</li> <li>A <code>&lt;</code> is unmatched if you cannot find a subsequent <code>&gt;</code>. And when you find a <code>&lt;</code> or <code>&lt;/</code>, all the subsequent characters until the next <code>&gt;</code> should be parsed as TAG_NAME (not necessarily valid).</li> <li>The cdata has the following format : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. The range of <code>CDATA_CONTENT</code> is defined as the characters between <code>&lt;![CDATA[</code> and the <b>first subsequent</b> <code>]]&gt;</code>.</li> <li><code>CDATA_CONTENT</code> may contain <b>any characters</b>. The function of cdata is to forbid the validator to parse <code>CDATA_CONTENT</code>, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as <b>regular characters</b>.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;&gt;&gt; ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We first separate the code into : start_tag|tag_content|end_tag. start_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b> end_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b> tag_content could also be separated into : text1|cdata|text2. text1 -&gt; <b>&quot;&gt;&gt; ![cdata[]] &quot;</b> cdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, where the CDATA_CONTENT is <b>&quot;&lt;div&gt;]&gt;&quot;</b> text2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b> The reason why start_tag is NOT <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> is because of the rule 6. The reason why cdata is NOT <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> is because of the rule 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;A&gt; &lt;B&gt; &lt;/A&gt; &lt;/B&gt;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Unbalanced. If &quot;&lt;A&gt;&quot; is closed, then &quot;&lt;B&gt;&quot; must be unmatched, and vice versa. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= code.length &lt;= 500</code></li> <li><code>code</code> consists of English letters, digits, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, and <code>&#39; &#39;</code>.</li> </ul>
Stack; String
C++
class Solution { public: bool isValid(string code) { stack<string> stk; for (int i = 0; i < code.size(); ++i) { if (i && stk.empty()) return false; if (code.substr(i, 9) == "<![CDATA[") { i = code.find("]]>", i + 9); if (i < 0) return false; i += 2; } else if (code.substr(i, 2) == "</") { int j = i + 2; i = code.find('>', j); if (i < 0) return false; string t = code.substr(j, i - j); if (!check(t) || stk.empty() || stk.top() != t) return false; stk.pop(); } else if (code.substr(i, 1) == "<") { int j = i + 1; i = code.find('>', j); if (i < 0) return false; string t = code.substr(j, i - j); if (!check(t)) return false; stk.push(t); } } return stk.empty(); } bool check(string tag) { int n = tag.size(); if (n < 1 || n > 9) return false; for (char& c : tag) if (!isupper(c)) return false; return true; } };
591
Tag Validator
Hard
<p>Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.</p> <p>A code snippet is valid if all the following rules hold:</p> <ol> <li>The code must be wrapped in a <b>valid closed tag</b>. Otherwise, the code is invalid.</li> <li>A <b>closed tag</b> (not necessarily valid) has exactly the following format : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Among them, <code>&lt;TAG_NAME&gt;</code> is the start tag, and <code>&lt;/TAG_NAME&gt;</code> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is <b>valid</b> if and only if the TAG_NAME and TAG_CONTENT are valid.</li> <li>A <b>valid</b> <code>TAG_NAME</code> only contain <b>upper-case letters</b>, and has length in range [1,9]. Otherwise, the <code>TAG_NAME</code> is <b>invalid</b>.</li> <li>A <b>valid</b> <code>TAG_CONTENT</code> may contain other <b>valid closed tags</b>, <b>cdata</b> and any characters (see note1) <b>EXCEPT</b> unmatched <code>&lt;</code>, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the <code>TAG_CONTENT</code> is <b>invalid</b>.</li> <li>A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.</li> <li>A <code>&lt;</code> is unmatched if you cannot find a subsequent <code>&gt;</code>. And when you find a <code>&lt;</code> or <code>&lt;/</code>, all the subsequent characters until the next <code>&gt;</code> should be parsed as TAG_NAME (not necessarily valid).</li> <li>The cdata has the following format : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. The range of <code>CDATA_CONTENT</code> is defined as the characters between <code>&lt;![CDATA[</code> and the <b>first subsequent</b> <code>]]&gt;</code>.</li> <li><code>CDATA_CONTENT</code> may contain <b>any characters</b>. The function of cdata is to forbid the validator to parse <code>CDATA_CONTENT</code>, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as <b>regular characters</b>.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;&gt;&gt; ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We first separate the code into : start_tag|tag_content|end_tag. start_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b> end_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b> tag_content could also be separated into : text1|cdata|text2. text1 -&gt; <b>&quot;&gt;&gt; ![cdata[]] &quot;</b> cdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, where the CDATA_CONTENT is <b>&quot;&lt;div&gt;]&gt;&quot;</b> text2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b> The reason why start_tag is NOT <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> is because of the rule 6. The reason why cdata is NOT <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> is because of the rule 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;A&gt; &lt;B&gt; &lt;/A&gt; &lt;/B&gt;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Unbalanced. If &quot;&lt;A&gt;&quot; is closed, then &quot;&lt;B&gt;&quot; must be unmatched, and vice versa. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= code.length &lt;= 500</code></li> <li><code>code</code> consists of English letters, digits, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, and <code>&#39; &#39;</code>.</li> </ul>
Stack; String
Go
func isValid(code string) bool { var stk []string for i := 0; i < len(code); i++ { if i > 0 && len(stk) == 0 { return false } if strings.HasPrefix(code[i:], "<![CDATA[") { n := strings.Index(code[i+9:], "]]>") if n == -1 { return false } i += n + 11 } else if strings.HasPrefix(code[i:], "</") { if len(stk) == 0 { return false } j := i + 2 n := strings.IndexByte(code[j:], '>') if n == -1 { return false } t := code[j : j+n] last := stk[len(stk)-1] stk = stk[:len(stk)-1] if !check(t) || last != t { return false } i += n + 2 } else if strings.HasPrefix(code[i:], "<") { j := i + 1 n := strings.IndexByte(code[j:], '>') if n == -1 { return false } t := code[j : j+n] if !check(t) { return false } stk = append(stk, t) i += n + 1 } } return len(stk) == 0 } func check(tag string) bool { n := len(tag) if n < 1 || n > 9 { return false } for _, c := range tag { if c < 'A' || c > 'Z' { return false } } return true }
591
Tag Validator
Hard
<p>Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.</p> <p>A code snippet is valid if all the following rules hold:</p> <ol> <li>The code must be wrapped in a <b>valid closed tag</b>. Otherwise, the code is invalid.</li> <li>A <b>closed tag</b> (not necessarily valid) has exactly the following format : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Among them, <code>&lt;TAG_NAME&gt;</code> is the start tag, and <code>&lt;/TAG_NAME&gt;</code> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is <b>valid</b> if and only if the TAG_NAME and TAG_CONTENT are valid.</li> <li>A <b>valid</b> <code>TAG_NAME</code> only contain <b>upper-case letters</b>, and has length in range [1,9]. Otherwise, the <code>TAG_NAME</code> is <b>invalid</b>.</li> <li>A <b>valid</b> <code>TAG_CONTENT</code> may contain other <b>valid closed tags</b>, <b>cdata</b> and any characters (see note1) <b>EXCEPT</b> unmatched <code>&lt;</code>, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the <code>TAG_CONTENT</code> is <b>invalid</b>.</li> <li>A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.</li> <li>A <code>&lt;</code> is unmatched if you cannot find a subsequent <code>&gt;</code>. And when you find a <code>&lt;</code> or <code>&lt;/</code>, all the subsequent characters until the next <code>&gt;</code> should be parsed as TAG_NAME (not necessarily valid).</li> <li>The cdata has the following format : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. The range of <code>CDATA_CONTENT</code> is defined as the characters between <code>&lt;![CDATA[</code> and the <b>first subsequent</b> <code>]]&gt;</code>.</li> <li><code>CDATA_CONTENT</code> may contain <b>any characters</b>. The function of cdata is to forbid the validator to parse <code>CDATA_CONTENT</code>, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as <b>regular characters</b>.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;&gt;&gt; ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We first separate the code into : start_tag|tag_content|end_tag. start_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b> end_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b> tag_content could also be separated into : text1|cdata|text2. text1 -&gt; <b>&quot;&gt;&gt; ![cdata[]] &quot;</b> cdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, where the CDATA_CONTENT is <b>&quot;&lt;div&gt;]&gt;&quot;</b> text2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b> The reason why start_tag is NOT <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> is because of the rule 6. The reason why cdata is NOT <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> is because of the rule 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;A&gt; &lt;B&gt; &lt;/A&gt; &lt;/B&gt;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Unbalanced. If &quot;&lt;A&gt;&quot; is closed, then &quot;&lt;B&gt;&quot; must be unmatched, and vice versa. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= code.length &lt;= 500</code></li> <li><code>code</code> consists of English letters, digits, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, and <code>&#39; &#39;</code>.</li> </ul>
Stack; String
Java
class Solution { public boolean isValid(String code) { Deque<String> stk = new ArrayDeque<>(); for (int i = 0; i < code.length(); ++i) { if (i > 0 && stk.isEmpty()) { return false; } if (code.startsWith("<![CDATA[", i)) { i = code.indexOf("]]>", i + 9); if (i < 0) { return false; } i += 2; } else if (code.startsWith("</", i)) { int j = i + 2; i = code.indexOf(">", j); if (i < 0) { return false; } String t = code.substring(j, i); if (!check(t) || stk.isEmpty() || !stk.pop().equals(t)) { return false; } } else if (code.startsWith("<", i)) { int j = i + 1; i = code.indexOf(">", j); if (i < 0) { return false; } String t = code.substring(j, i); if (!check(t)) { return false; } stk.push(t); } } return stk.isEmpty(); } private boolean check(String tag) { int n = tag.length(); if (n < 1 || n > 9) { return false; } for (char c : tag.toCharArray()) { if (!Character.isUpperCase(c)) { return false; } } return true; } }
591
Tag Validator
Hard
<p>Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.</p> <p>A code snippet is valid if all the following rules hold:</p> <ol> <li>The code must be wrapped in a <b>valid closed tag</b>. Otherwise, the code is invalid.</li> <li>A <b>closed tag</b> (not necessarily valid) has exactly the following format : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Among them, <code>&lt;TAG_NAME&gt;</code> is the start tag, and <code>&lt;/TAG_NAME&gt;</code> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is <b>valid</b> if and only if the TAG_NAME and TAG_CONTENT are valid.</li> <li>A <b>valid</b> <code>TAG_NAME</code> only contain <b>upper-case letters</b>, and has length in range [1,9]. Otherwise, the <code>TAG_NAME</code> is <b>invalid</b>.</li> <li>A <b>valid</b> <code>TAG_CONTENT</code> may contain other <b>valid closed tags</b>, <b>cdata</b> and any characters (see note1) <b>EXCEPT</b> unmatched <code>&lt;</code>, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the <code>TAG_CONTENT</code> is <b>invalid</b>.</li> <li>A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.</li> <li>A <code>&lt;</code> is unmatched if you cannot find a subsequent <code>&gt;</code>. And when you find a <code>&lt;</code> or <code>&lt;/</code>, all the subsequent characters until the next <code>&gt;</code> should be parsed as TAG_NAME (not necessarily valid).</li> <li>The cdata has the following format : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. The range of <code>CDATA_CONTENT</code> is defined as the characters between <code>&lt;![CDATA[</code> and the <b>first subsequent</b> <code>]]&gt;</code>.</li> <li><code>CDATA_CONTENT</code> may contain <b>any characters</b>. The function of cdata is to forbid the validator to parse <code>CDATA_CONTENT</code>, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as <b>regular characters</b>.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;&gt;&gt; ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We first separate the code into : start_tag|tag_content|end_tag. start_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b> end_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b> tag_content could also be separated into : text1|cdata|text2. text1 -&gt; <b>&quot;&gt;&gt; ![cdata[]] &quot;</b> cdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, where the CDATA_CONTENT is <b>&quot;&lt;div&gt;]&gt;&quot;</b> text2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b> The reason why start_tag is NOT <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> is because of the rule 6. The reason why cdata is NOT <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> is because of the rule 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;A&gt; &lt;B&gt; &lt;/A&gt; &lt;/B&gt;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Unbalanced. If &quot;&lt;A&gt;&quot; is closed, then &quot;&lt;B&gt;&quot; must be unmatched, and vice versa. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= code.length &lt;= 500</code></li> <li><code>code</code> consists of English letters, digits, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, and <code>&#39; &#39;</code>.</li> </ul>
Stack; String
Python
class Solution: def isValid(self, code: str) -> bool: def check(tag): return 1 <= len(tag) <= 9 and all(c.isupper() for c in tag) stk = [] i, n = 0, len(code) while i < n: if i and not stk: return False if code[i : i + 9] == '<![CDATA[': i = code.find(']]>', i + 9) if i < 0: return False i += 2 elif code[i : i + 2] == '</': j = i + 2 i = code.find('>', j) if i < 0: return False t = code[j:i] if not check(t) or not stk or stk.pop() != t: return False elif code[i] == '<': j = i + 1 i = code.find('>', j) if i < 0: return False t = code[j:i] if not check(t): return False stk.append(t) i += 1 return not stk
591
Tag Validator
Hard
<p>Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.</p> <p>A code snippet is valid if all the following rules hold:</p> <ol> <li>The code must be wrapped in a <b>valid closed tag</b>. Otherwise, the code is invalid.</li> <li>A <b>closed tag</b> (not necessarily valid) has exactly the following format : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Among them, <code>&lt;TAG_NAME&gt;</code> is the start tag, and <code>&lt;/TAG_NAME&gt;</code> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is <b>valid</b> if and only if the TAG_NAME and TAG_CONTENT are valid.</li> <li>A <b>valid</b> <code>TAG_NAME</code> only contain <b>upper-case letters</b>, and has length in range [1,9]. Otherwise, the <code>TAG_NAME</code> is <b>invalid</b>.</li> <li>A <b>valid</b> <code>TAG_CONTENT</code> may contain other <b>valid closed tags</b>, <b>cdata</b> and any characters (see note1) <b>EXCEPT</b> unmatched <code>&lt;</code>, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the <code>TAG_CONTENT</code> is <b>invalid</b>.</li> <li>A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.</li> <li>A <code>&lt;</code> is unmatched if you cannot find a subsequent <code>&gt;</code>. And when you find a <code>&lt;</code> or <code>&lt;/</code>, all the subsequent characters until the next <code>&gt;</code> should be parsed as TAG_NAME (not necessarily valid).</li> <li>The cdata has the following format : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. The range of <code>CDATA_CONTENT</code> is defined as the characters between <code>&lt;![CDATA[</code> and the <b>first subsequent</b> <code>]]&gt;</code>.</li> <li><code>CDATA_CONTENT</code> may contain <b>any characters</b>. The function of cdata is to forbid the validator to parse <code>CDATA_CONTENT</code>, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as <b>regular characters</b>.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;DIV&gt;&gt;&gt; ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We first separate the code into : start_tag|tag_content|end_tag. start_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b> end_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b> tag_content could also be separated into : text1|cdata|text2. text1 -&gt; <b>&quot;&gt;&gt; ![cdata[]] &quot;</b> cdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, where the CDATA_CONTENT is <b>&quot;&lt;div&gt;]&gt;&quot;</b> text2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b> The reason why start_tag is NOT <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> is because of the rule 6. The reason why cdata is NOT <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> is because of the rule 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> code = &quot;&lt;A&gt; &lt;B&gt; &lt;/A&gt; &lt;/B&gt;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Unbalanced. If &quot;&lt;A&gt;&quot; is closed, then &quot;&lt;B&gt;&quot; must be unmatched, and vice versa. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= code.length &lt;= 500</code></li> <li><code>code</code> consists of English letters, digits, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, and <code>&#39; &#39;</code>.</li> </ul>
Stack; String
Rust
impl Solution { pub fn is_valid(code: String) -> bool { fn check(tag: &str) -> bool { let n = tag.len(); n >= 1 && n <= 9 && tag.as_bytes().iter().all(|b| b.is_ascii_uppercase()) } let mut stk = Vec::new(); let mut i = 0; while i < code.len() { if i > 0 && stk.is_empty() { return false; } if code[i..].starts_with("<![CDATA[") { match code[i + 9..].find("]]>") { Some(n) => { i += n + 11; } None => { return false; } }; } else if code[i..].starts_with("</") { let j = i + 2; match code[j..].find('>') { Some(n) => { let t = &code[j..j + n]; if !check(t) || stk.is_empty() || stk.pop().unwrap() != t { return false; } i += n + 2; } None => { return false; } }; } else if code[i..].starts_with("<") { let j = i + 1; match code[j..].find('>') { Some(n) => { let t = &code[j..j + n]; if !check(t) { return false; } stk.push(t); } None => { return false; } }; } i += 1; } stk.is_empty() } }
592
Fraction Addition and Subtraction
Medium
<p>Given a string <code>expression</code> representing an expression of fraction addition and subtraction, return the calculation result in string format.</p> <p>The final result should be an <a href="https://en.wikipedia.org/wiki/Irreducible_fraction" target="_blank">irreducible fraction</a>. If your final result is an integer, change it to the format of a fraction that has a denominator <code>1</code>. So in this case, <code>2</code> should be converted to <code>2/1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2&quot; <strong>Output:</strong> &quot;0/1&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2+1/3&quot; <strong>Output:</strong> &quot;1/3&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;1/3-1/2&quot; <strong>Output:</strong> &quot;-1/6&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The input string only contains <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. So does the output.</li> <li>Each fraction (input and output) has the format <code>&plusmn;numerator/denominator</code>. If the first input fraction or the output is positive, then <code>&#39;+&#39;</code> will be omitted.</li> <li>The input only contains valid <strong>irreducible fractions</strong>, where the <strong>numerator</strong> and <strong>denominator</strong> of each fraction will always be in the range <code>[1, 10]</code>. If the denominator is <code>1</code>, it means this fraction is actually an integer in a fraction format defined above.</li> <li>The number of given fractions will be in the range <code>[1, 10]</code>.</li> <li>The numerator and denominator of the <strong>final result</strong> are guaranteed to be valid and in the range of <strong>32-bit</strong> int.</li> </ul>
Math; String; Simulation
Go
func fractionAddition(expression string) string { x, y := 0, 6*7*8*9*10 if unicode.IsDigit(rune(expression[0])) { expression = "+" + expression } i, n := 0, len(expression) for i < n { sign := 1 if expression[i] == '-' { sign = -1 } i++ j := i for j < n && expression[j] != '+' && expression[j] != '-' { j++ } s := expression[i:j] t := strings.Split(s, "/") a, _ := strconv.Atoi(t[0]) b, _ := strconv.Atoi(t[1]) x += sign * a * y / b i = j } z := gcd(abs(x), y) x /= z y /= z return fmt.Sprintf("%d/%d", x, y) } func abs(x int) int { if x < 0 { return -x } return x } func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) }
592
Fraction Addition and Subtraction
Medium
<p>Given a string <code>expression</code> representing an expression of fraction addition and subtraction, return the calculation result in string format.</p> <p>The final result should be an <a href="https://en.wikipedia.org/wiki/Irreducible_fraction" target="_blank">irreducible fraction</a>. If your final result is an integer, change it to the format of a fraction that has a denominator <code>1</code>. So in this case, <code>2</code> should be converted to <code>2/1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2&quot; <strong>Output:</strong> &quot;0/1&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2+1/3&quot; <strong>Output:</strong> &quot;1/3&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;1/3-1/2&quot; <strong>Output:</strong> &quot;-1/6&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The input string only contains <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. So does the output.</li> <li>Each fraction (input and output) has the format <code>&plusmn;numerator/denominator</code>. If the first input fraction or the output is positive, then <code>&#39;+&#39;</code> will be omitted.</li> <li>The input only contains valid <strong>irreducible fractions</strong>, where the <strong>numerator</strong> and <strong>denominator</strong> of each fraction will always be in the range <code>[1, 10]</code>. If the denominator is <code>1</code>, it means this fraction is actually an integer in a fraction format defined above.</li> <li>The number of given fractions will be in the range <code>[1, 10]</code>.</li> <li>The numerator and denominator of the <strong>final result</strong> are guaranteed to be valid and in the range of <strong>32-bit</strong> int.</li> </ul>
Math; String; Simulation
Java
class Solution { public String fractionAddition(String expression) { int x = 0, y = 6 * 7 * 8 * 9 * 10; if (Character.isDigit(expression.charAt(0))) { expression = "+" + expression; } int i = 0, n = expression.length(); while (i < n) { int sign = expression.charAt(i) == '-' ? -1 : 1; ++i; int j = i; while (j < n && expression.charAt(j) != '+' && expression.charAt(j) != '-') { ++j; } String s = expression.substring(i, j); String[] t = s.split("/"); int a = Integer.parseInt(t[0]), b = Integer.parseInt(t[1]); x += sign * a * y / b; i = j; } int z = gcd(Math.abs(x), y); x /= z; y /= z; return x + "/" + y; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
592
Fraction Addition and Subtraction
Medium
<p>Given a string <code>expression</code> representing an expression of fraction addition and subtraction, return the calculation result in string format.</p> <p>The final result should be an <a href="https://en.wikipedia.org/wiki/Irreducible_fraction" target="_blank">irreducible fraction</a>. If your final result is an integer, change it to the format of a fraction that has a denominator <code>1</code>. So in this case, <code>2</code> should be converted to <code>2/1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2&quot; <strong>Output:</strong> &quot;0/1&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2+1/3&quot; <strong>Output:</strong> &quot;1/3&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;1/3-1/2&quot; <strong>Output:</strong> &quot;-1/6&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The input string only contains <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. So does the output.</li> <li>Each fraction (input and output) has the format <code>&plusmn;numerator/denominator</code>. If the first input fraction or the output is positive, then <code>&#39;+&#39;</code> will be omitted.</li> <li>The input only contains valid <strong>irreducible fractions</strong>, where the <strong>numerator</strong> and <strong>denominator</strong> of each fraction will always be in the range <code>[1, 10]</code>. If the denominator is <code>1</code>, it means this fraction is actually an integer in a fraction format defined above.</li> <li>The number of given fractions will be in the range <code>[1, 10]</code>.</li> <li>The numerator and denominator of the <strong>final result</strong> are guaranteed to be valid and in the range of <strong>32-bit</strong> int.</li> </ul>
Math; String; Simulation
JavaScript
/** * @param {string} expression * @return {string} */ var fractionAddition = function (expression) { let x = 0, y = 1; if (!expression.startsWith('-') && !expression.startsWith('+')) { expression = '+' + expression; } let i = 0; const n = expression.length; while (i < n) { const sign = expression[i] === '-' ? -1 : 1; i++; let j = i; while (j < n && expression[j] !== '+' && expression[j] !== '-') { j++; } const [a, b] = expression.slice(i, j).split('/').map(Number); x = x * b + sign * a * y; y *= b; i = j; } const gcd = (a, b) => { while (b !== 0) { [a, b] = [b, a % b]; } return Math.abs(a); }; const z = gcd(x, y); x = Math.floor(x / z); y = Math.floor(y / z); return `${x}/${y}`; };
592
Fraction Addition and Subtraction
Medium
<p>Given a string <code>expression</code> representing an expression of fraction addition and subtraction, return the calculation result in string format.</p> <p>The final result should be an <a href="https://en.wikipedia.org/wiki/Irreducible_fraction" target="_blank">irreducible fraction</a>. If your final result is an integer, change it to the format of a fraction that has a denominator <code>1</code>. So in this case, <code>2</code> should be converted to <code>2/1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2&quot; <strong>Output:</strong> &quot;0/1&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;-1/2+1/2+1/3&quot; <strong>Output:</strong> &quot;1/3&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;1/3-1/2&quot; <strong>Output:</strong> &quot;-1/6&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The input string only contains <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. So does the output.</li> <li>Each fraction (input and output) has the format <code>&plusmn;numerator/denominator</code>. If the first input fraction or the output is positive, then <code>&#39;+&#39;</code> will be omitted.</li> <li>The input only contains valid <strong>irreducible fractions</strong>, where the <strong>numerator</strong> and <strong>denominator</strong> of each fraction will always be in the range <code>[1, 10]</code>. If the denominator is <code>1</code>, it means this fraction is actually an integer in a fraction format defined above.</li> <li>The number of given fractions will be in the range <code>[1, 10]</code>.</li> <li>The numerator and denominator of the <strong>final result</strong> are guaranteed to be valid and in the range of <strong>32-bit</strong> int.</li> </ul>
Math; String; Simulation
Python
class Solution: def fractionAddition(self, expression: str) -> str: x, y = 0, 6 * 7 * 8 * 9 * 10 if expression[0].isdigit(): expression = '+' + expression i, n = 0, len(expression) while i < n: sign = -1 if expression[i] == '-' else 1 i += 1 j = i while j < n and expression[j] not in '+-': j += 1 s = expression[i:j] a, b = s.split('/') x += sign * int(a) * y // int(b) i = j z = gcd(x, y) x //= z y //= z return f'{x}/{y}'
593
Valid Square
Medium
<p>Given the coordinates of four points in 2D space <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code>, return <code>true</code> <em>if the four points construct a square</em>.</p> <p>The coordinate of a point <code>p<sub>i</sub></code> is represented as <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The input is <strong>not</strong> given in any order.</p> <p>A <strong>valid square</strong> has four equal sides with positive length and four equal angles (90-degree angles).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>p1.length == p2.length == p3.length == p4.length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
C++
class Solution { public: bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) { return check(p1, p2, p3) && check(p1, p3, p4) && check(p1, p2, p4) && check(p2, p3, p4); } bool check(vector<int>& a, vector<int>& b, vector<int>& c) { int x1 = a[0], y1 = a[1]; int x2 = b[0], y2 = b[1]; int x3 = c[0], y3 = c[1]; int d1 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int d2 = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3); int d3 = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3); if (d1 == d2 && d1 + d2 == d3 && d1 > 0) return true; if (d1 == d3 && d1 + d3 == d2 && d1 > 0) return true; if (d2 == d3 && d2 + d3 == d1 && d2 > 0) return true; return false; } };
593
Valid Square
Medium
<p>Given the coordinates of four points in 2D space <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code>, return <code>true</code> <em>if the four points construct a square</em>.</p> <p>The coordinate of a point <code>p<sub>i</sub></code> is represented as <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The input is <strong>not</strong> given in any order.</p> <p>A <strong>valid square</strong> has four equal sides with positive length and four equal angles (90-degree angles).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>p1.length == p2.length == p3.length == p4.length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
Go
func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { check := func(a, b, c []int) bool { x1, y1 := a[0], a[1] x2, y2 := b[0], b[1] x3, y3 := c[0], c[1] d1 := (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) d2 := (x1-x3)*(x1-x3) + (y1-y3)*(y1-y3) d3 := (x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) if d1 == d2 && d1+d2 == d3 && d1 > 0 { return true } if d1 == d3 && d1+d3 == d2 && d1 > 0 { return true } if d2 == d3 && d2+d3 == d1 && d2 > 0 { return true } return false } return check(p1, p2, p3) && check(p1, p3, p4) && check(p1, p2, p4) && check(p2, p3, p4) }
593
Valid Square
Medium
<p>Given the coordinates of four points in 2D space <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code>, return <code>true</code> <em>if the four points construct a square</em>.</p> <p>The coordinate of a point <code>p<sub>i</sub></code> is represented as <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The input is <strong>not</strong> given in any order.</p> <p>A <strong>valid square</strong> has four equal sides with positive length and four equal angles (90-degree angles).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>p1.length == p2.length == p3.length == p4.length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
Java
class Solution { public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { return check(p1, p2, p3) && check(p1, p3, p4) && check(p1, p2, p4) && check(p2, p3, p4); } private boolean check(int[] a, int[] b, int[] c) { int x1 = a[0], y1 = a[1]; int x2 = b[0], y2 = b[1]; int x3 = c[0], y3 = c[1]; int d1 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int d2 = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3); int d3 = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3); if (d1 == d2 && d1 + d2 == d3 && d1 > 0) { return true; } if (d1 == d3 && d1 + d3 == d2 && d1 > 0) { return true; } if (d2 == d3 && d2 + d3 == d1 && d2 > 0) { return true; } return false; } }
593
Valid Square
Medium
<p>Given the coordinates of four points in 2D space <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code>, return <code>true</code> <em>if the four points construct a square</em>.</p> <p>The coordinate of a point <code>p<sub>i</sub></code> is represented as <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The input is <strong>not</strong> given in any order.</p> <p>A <strong>valid square</strong> has four equal sides with positive length and four equal angles (90-degree angles).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>p1.length == p2.length == p3.length == p4.length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
Python
class Solution: def validSquare( self, p1: List[int], p2: List[int], p3: List[int], p4: List[int] ) -> bool: def check(a, b, c): (x1, y1), (x2, y2), (x3, y3) = a, b, c d1 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) d2 = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3) d3 = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3) return any( [ d1 == d2 and d1 + d2 == d3 and d1, d2 == d3 and d2 + d3 == d1 and d2, d1 == d3 and d1 + d3 == d2 and d1, ] ) return ( check(p1, p2, p3) and check(p2, p3, p4) and check(p1, p3, p4) and check(p1, p2, p4) )
594
Longest Harmonious Subsequence
Easy
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p> <p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No harmonic subsequence exists.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Counting; Sorting; Sliding Window
C++
class Solution { public: int findLHS(vector<int>& nums) { unordered_map<int, int> cnt; for (int x : nums) { ++cnt[x]; } int ans = 0; for (auto& [x, c] : cnt) { if (cnt.contains(x + 1)) { ans = max(ans, c + cnt[x + 1]); } } return ans; } };
594
Longest Harmonious Subsequence
Easy
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p> <p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No harmonic subsequence exists.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Counting; Sorting; Sliding Window
Go
func findLHS(nums []int) (ans int) { cnt := map[int]int{} for _, x := range nums { cnt[x]++ } for x, c := range cnt { if c1, ok := cnt[x+1]; ok { ans = max(ans, c+c1) } } return }
594
Longest Harmonious Subsequence
Easy
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p> <p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No harmonic subsequence exists.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Counting; Sorting; Sliding Window
Java
class Solution { public int findLHS(int[] nums) { Map<Integer, Integer> cnt = new HashMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); } int ans = 0; for (var e : cnt.entrySet()) { int x = e.getKey(), c = e.getValue(); if (cnt.containsKey(x + 1)) { ans = Math.max(ans, c + cnt.get(x + 1)); } } return ans; } }
594
Longest Harmonious Subsequence
Easy
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p> <p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No harmonic subsequence exists.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Counting; Sorting; Sliding Window
Python
class Solution: def findLHS(self, nums: List[int]) -> int: cnt = Counter(nums) return max((c + cnt[x + 1] for x, c in cnt.items() if cnt[x + 1]), default=0)
594
Longest Harmonious Subsequence
Easy
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p> <p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No harmonic subsequence exists.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Counting; Sorting; Sliding Window
Rust
use std::collections::HashMap; impl Solution { pub fn find_lhs(nums: Vec<i32>) -> i32 { let mut cnt = HashMap::new(); for &x in &nums { *cnt.entry(x).or_insert(0) += 1; } let mut ans = 0; for (&x, &c) in &cnt { if let Some(&y) = cnt.get(&(x + 1)) { ans = ans.max(c + y); } } ans } }
594
Longest Harmonious Subsequence
Easy
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p> <p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No harmonic subsequence exists.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Counting; Sorting; Sliding Window
TypeScript
function findLHS(nums: number[]): number { const cnt: Record<number, number> = {}; for (const x of nums) { cnt[x] = (cnt[x] || 0) + 1; } let ans = 0; for (const [x, c] of Object.entries(cnt)) { const y = +x + 1; if (cnt[y]) { ans = Math.max(ans, c + cnt[y]); } } return ans; }
595
Big Countries
Easy
<p>Table: <code>World</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | name | varchar | | continent | varchar | | area | int | | population | int | | gdp | bigint | +-------------+---------+ name is the primary key (column with unique values) for this table. Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value. </pre> <p>&nbsp;</p> <p>A country is <strong>big</strong> if:</p> <ul> <li>it has an area of at least&nbsp;three million (i.e., <code>3000000 km<sup>2</sup></code>), or</li> <li>it has a population of at least&nbsp;twenty-five million (i.e., <code>25000000</code>).</li> </ul> <p>Write a solution to find the name, population, and area of the <strong>big countries</strong>.</p> <p>Return the result table in <strong>any 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> World table: +-------------+-----------+---------+------------+--------------+ | name | continent | area | population | gdp | +-------------+-----------+---------+------------+--------------+ | Afghanistan | Asia | 652230 | 25500100 | 20343000000 | | Albania | Europe | 28748 | 2831741 | 12960000000 | | Algeria | Africa | 2381741 | 37100000 | 188681000000 | | Andorra | Europe | 468 | 78115 | 3712000000 | | Angola | Africa | 1246700 | 20609294 | 100990000000 | +-------------+-----------+---------+------------+--------------+ <strong>Output:</strong> +-------------+------------+---------+ | name | population | area | +-------------+------------+---------+ | Afghanistan | 25500100 | 652230 | | Algeria | 37100000 | 2381741 | +-------------+------------+---------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT name, population, area FROM World WHERE area >= 3000000 OR population >= 25000000;
596
Classes With at Least 5 Students
Easy
<p>Table: <code>Courses</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | student | varchar | | class | varchar | +-------------+---------+ (student, class) is the primary key (combination of columns with unique values) for this table. Each row of this table indicates the name of a student and the class in which they are enrolled. </pre> <p>&nbsp;</p> <p>Write a solution to find all the classes that have <strong>at least five students</strong>.</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> Courses table: +---------+----------+ | student | class | +---------+----------+ | A | Math | | B | English | | C | Math | | D | Biology | | E | Math | | F | Computer | | G | Math | | H | Math | | I | Math | +---------+----------+ <strong>Output:</strong> +---------+ | class | +---------+ | Math | +---------+ <strong>Explanation:</strong> - Math has 6 students, so we include it. - English has 1 student, so we do not include it. - Biology has 1 student, so we do not include it. - Computer has 1 student, so we do not include it. </pre>
Database
SQL
# Write your MySQL query statement below SELECT class FROM Courses GROUP BY 1 HAVING COUNT(1) >= 5;
597
Friend Requests I Overall Acceptance Rate
Easy
<p>Table: <code>FriendRequest</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | sender_id | int | | send_to_id | int | | request_date | date | +----------------+---------+ This table may contain duplicates (In other words, there is no primary key for this table in SQL). This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date of the request. </pre> <p>&nbsp;</p> <p>Table: <code>RequestAccepted</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | requester_id | int | | accepter_id | int | | accept_date | date | +----------------+---------+ This table may contain duplicates (In other words, there is no primary key for this table in SQL). This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted. </pre> <p>&nbsp;</p> <p>Find the overall acceptance rate of requests, which is the number of acceptance divided by the number of requests. Return the answer rounded to 2 decimals places.</p> <p><strong>Note that:</strong></p> <ul> <li>The accepted requests are not necessarily from the table <code>friend_request</code>. In this case, Count the total accepted requests (no matter whether they are in the original requests), and divide it by the number of requests to get the acceptance rate.</li> <li>It is possible that a sender sends multiple requests to the same receiver, and a request could be accepted more than once. In this case, the &lsquo;duplicated&rsquo; requests or acceptances are only counted once.</li> <li>If there are no requests at all, you should return 0.00 as the <code>accept_rate</code>.</li> </ul> <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> FriendRequest table: +-----------+------------+--------------+ | sender_id | send_to_id | request_date | +-----------+------------+--------------+ | 1 | 2 | 2016/06/01 | | 1 | 3 | 2016/06/01 | | 1 | 4 | 2016/06/01 | | 2 | 3 | 2016/06/02 | | 3 | 4 | 2016/06/09 | +-----------+------------+--------------+ RequestAccepted table: +--------------+-------------+-------------+ | requester_id | accepter_id | accept_date | +--------------+-------------+-------------+ | 1 | 2 | 2016/06/03 | | 1 | 3 | 2016/06/08 | | 2 | 3 | 2016/06/08 | | 3 | 4 | 2016/06/09 | | 3 | 4 | 2016/06/10 | +--------------+-------------+-------------+ <strong>Output:</strong> +-------------+ | accept_rate | +-------------+ | 0.8 | +-------------+ <strong>Explanation:</strong> There are 4 unique accepted requests, and there are 5 requests in total. So the rate is 0.80. </pre> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you find the acceptance rate for every month?</li> <li>Could you find the cumulative acceptance rate for every day?</li> </ul>
Database
SQL
# Write your MySQL query statement below SELECT ROUND( IFNULL( ( SELECT COUNT(DISTINCT requester_id, accepter_id) FROM RequestAccepted ) / (SELECT COUNT(DISTINCT sender_id, send_to_id) FROM FriendRequest), 0 ), 2 ) AS accept_rate;
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
C++
class Solution { public: int maxCount(int m, int n, vector<vector<int>>& ops) { for (const auto& op : ops) { m = min(m, op[0]); n = min(n, op[1]); } return m * n; } };
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
Go
func maxCount(m int, n int, ops [][]int) int { for _, op := range ops { m = min(m, op[0]) n = min(n, op[1]) } return m * n }
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
Java
class Solution { public int maxCount(int m, int n, int[][] ops) { for (int[] op : ops) { m = Math.min(m, op[0]); n = Math.min(n, op[1]); } return m * n; } }
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
JavaScript
/** * @param {number} m * @param {number} n * @param {number[][]} ops * @return {number} */ var maxCount = function (m, n, ops) { for (const [a, b] of ops) { m = Math.min(m, a); n = Math.min(n, b); } return m * n; };
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
Python
class Solution: def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: for a, b in ops: m = min(m, a) n = min(n, b) return m * n
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
Rust
impl Solution { pub fn max_count(mut m: i32, mut n: i32, ops: Vec<Vec<i32>>) -> i32 { for op in ops { m = m.min(op[0]); n = n.min(op[1]); } m * n } }
598
Range Addition II
Easy
<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p> <p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0598.Range%20Addition%20II/images/ex1.jpg" style="width: 750px; height: 176px;" /> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, ops = [] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li> <li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li> <li><code>ops[i].length == 2</code></li> <li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li> <li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li> </ul>
Array; Math
TypeScript
function maxCount(m: number, n: number, ops: number[][]): number { for (const [a, b] of ops) { m = Math.min(m, a); n = Math.min(n, b); } return m * n; }
599
Minimum Index Sum of Two Lists
Easy
<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p> <p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p> <p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p> <p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The only common string is &quot;Shogun&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;] <strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;] <strong>Explanation:</strong> There are three common strings: &quot;happy&quot; with index sum = (0 + 1) = 1. &quot;sad&quot; with index sum = (1 + 0) = 1. &quot;good&quot; with index sum = (2 + 2) = 4. The strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li> <li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li> <li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li> <li>All the strings of <code>list1</code> are <strong>unique</strong>.</li> <li>All the strings of <code>list2</code> are <strong>unique</strong>.</li> <li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li> </ul>
Array; Hash Table; String
C++
class Solution { public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { unordered_map<string, int> d; for (int i = 0; i < list2.size(); ++i) { d[list2[i]] = i; } vector<string> ans; int mi = INT_MAX; for (int i = 0; i < list1.size(); ++i) { if (d.contains(list1[i])) { int j = d[list1[i]]; if (i + j < mi) { mi = i + j; ans.clear(); ans.push_back(list1[i]); } else if (i + j == mi) { ans.push_back(list1[i]); } } } return ans; } };
599
Minimum Index Sum of Two Lists
Easy
<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p> <p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p> <p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p> <p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The only common string is &quot;Shogun&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;] <strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;] <strong>Explanation:</strong> There are three common strings: &quot;happy&quot; with index sum = (0 + 1) = 1. &quot;sad&quot; with index sum = (1 + 0) = 1. &quot;good&quot; with index sum = (2 + 2) = 4. The strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li> <li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li> <li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li> <li>All the strings of <code>list1</code> are <strong>unique</strong>.</li> <li>All the strings of <code>list2</code> are <strong>unique</strong>.</li> <li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li> </ul>
Array; Hash Table; String
Go
func findRestaurant(list1 []string, list2 []string) []string { d := map[string]int{} for i, s := range list2 { d[s] = i } ans := []string{} mi := 1 << 30 for i, s := range list1 { if j, ok := d[s]; ok { if i+j < mi { mi = i + j ans = []string{s} } else if i+j == mi { ans = append(ans, s) } } } return ans }
599
Minimum Index Sum of Two Lists
Easy
<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p> <p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p> <p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p> <p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The only common string is &quot;Shogun&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;] <strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;] <strong>Explanation:</strong> There are three common strings: &quot;happy&quot; with index sum = (0 + 1) = 1. &quot;sad&quot; with index sum = (1 + 0) = 1. &quot;good&quot; with index sum = (2 + 2) = 4. The strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li> <li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li> <li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li> <li>All the strings of <code>list1</code> are <strong>unique</strong>.</li> <li>All the strings of <code>list2</code> are <strong>unique</strong>.</li> <li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li> </ul>
Array; Hash Table; String
Java
class Solution { public String[] findRestaurant(String[] list1, String[] list2) { Map<String, Integer> d = new HashMap<>(); for (int i = 0; i < list2.length; ++i) { d.put(list2[i], i); } List<String> ans = new ArrayList<>(); int mi = 1 << 30; for (int i = 0; i < list1.length; ++i) { if (d.containsKey(list1[i])) { int j = d.get(list1[i]); if (i + j < mi) { mi = i + j; ans.clear(); ans.add(list1[i]); } else if (i + j == mi) { ans.add(list1[i]); } } } return ans.toArray(new String[0]); } }
599
Minimum Index Sum of Two Lists
Easy
<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p> <p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p> <p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p> <p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The only common string is &quot;Shogun&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;] <strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;] <strong>Explanation:</strong> There are three common strings: &quot;happy&quot; with index sum = (0 + 1) = 1. &quot;sad&quot; with index sum = (1 + 0) = 1. &quot;good&quot; with index sum = (2 + 2) = 4. The strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li> <li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li> <li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li> <li>All the strings of <code>list1</code> are <strong>unique</strong>.</li> <li>All the strings of <code>list2</code> are <strong>unique</strong>.</li> <li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li> </ul>
Array; Hash Table; String
Python
class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: d = {s: i for i, s in enumerate(list2)} ans = [] mi = inf for i, s in enumerate(list1): if s in d: j = d[s] if i + j < mi: mi = i + j ans = [s] elif i + j == mi: ans.append(s) return ans
599
Minimum Index Sum of Two Lists
Easy
<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p> <p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p> <p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p> <p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The only common string is &quot;Shogun&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;] <strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;] <strong>Explanation:</strong> There are three common strings: &quot;happy&quot; with index sum = (0 + 1) = 1. &quot;sad&quot; with index sum = (1 + 0) = 1. &quot;good&quot; with index sum = (2 + 2) = 4. The strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li> <li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li> <li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li> <li>All the strings of <code>list1</code> are <strong>unique</strong>.</li> <li>All the strings of <code>list2</code> are <strong>unique</strong>.</li> <li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li> </ul>
Array; Hash Table; String
Rust
use std::collections::HashMap; impl Solution { pub fn find_restaurant(list1: Vec<String>, list2: Vec<String>) -> Vec<String> { let mut d = HashMap::new(); for (i, s) in list2.iter().enumerate() { d.insert(s, i); } let mut ans = Vec::new(); let mut mi = std::i32::MAX; for (i, s) in list1.iter().enumerate() { if let Some(&j) = d.get(s) { if (i as i32 + j as i32) < mi { mi = i as i32 + j as i32; ans = vec![s.clone()]; } else if (i as i32 + j as i32) == mi { ans.push(s.clone()); } } } ans } }
599
Minimum Index Sum of Two Lists
Easy
<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p> <p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p> <p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p> <p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The only common string is &quot;Shogun&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;] <strong>Output:</strong> [&quot;Shogun&quot;] <strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;] <strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;] <strong>Explanation:</strong> There are three common strings: &quot;happy&quot; with index sum = (0 + 1) = 1. &quot;sad&quot; with index sum = (1 + 0) = 1. &quot;good&quot; with index sum = (2 + 2) = 4. The strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li> <li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li> <li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li> <li>All the strings of <code>list1</code> are <strong>unique</strong>.</li> <li>All the strings of <code>list2</code> are <strong>unique</strong>.</li> <li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li> </ul>
Array; Hash Table; String
TypeScript
function findRestaurant(list1: string[], list2: string[]): string[] { const d = new Map<string, number>(list2.map((s, i) => [s, i])); let mi = Infinity; const ans: string[] = []; list1.forEach((s, i) => { if (d.has(s)) { const j = d.get(s)!; if (i + j < mi) { mi = i + j; ans.length = 0; ans.push(s); } else if (i + j === mi) { ans.push(s); } } }); return ans; }
600
Non-negative Integers without Consecutive Ones
Hard
<p>Given a positive integer <code>n</code>, return the number of the integers in the range <code>[0, n]</code> whose binary representations <strong>do not</strong> contain consecutive ones.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> Here are the non-negative integers &lt;= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Dynamic Programming
C++
class Solution { public: int findIntegers(int n) { int m = 32 - __builtin_clz(n); int f[m][2]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i, int pre, bool limit) -> int { if (i < 0) { return 1; } if (!limit && f[i][pre] != -1) { return f[i][pre]; } int up = limit ? (n >> i & 1) : 1; int ans = 0; for (int j = 0; j <= up; ++j) { if (j && pre) { continue; } ans += dfs(i - 1, j, limit && j == up); } if (!limit) { f[i][pre] = ans; } return ans; }; return dfs(m - 1, 0, true); } };
600
Non-negative Integers without Consecutive Ones
Hard
<p>Given a positive integer <code>n</code>, return the number of the integers in the range <code>[0, n]</code> whose binary representations <strong>do not</strong> contain consecutive ones.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> Here are the non-negative integers &lt;= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Dynamic Programming
Go
func findIntegers(n int) int { m := bits.Len(uint(n)) f := make([][2]int, m) for i := range f { f[i] = [2]int{-1, -1} } var dfs func(i, pre int, limit bool) int dfs = func(i, pre int, limit bool) int { if i < 0 { return 1 } if !limit && f[i][pre] != -1 { return f[i][pre] } up := 1 if limit { up = n >> i & 1 } ans := 0 for j := 0; j <= up; j++ { if j == 1 && pre == 1 { continue } ans += dfs(i-1, j, limit && j == up) } if !limit { f[i][pre] = ans } return ans } return dfs(m-1, 0, true) }
600
Non-negative Integers without Consecutive Ones
Hard
<p>Given a positive integer <code>n</code>, return the number of the integers in the range <code>[0, n]</code> whose binary representations <strong>do not</strong> contain consecutive ones.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> Here are the non-negative integers &lt;= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Dynamic Programming
Java
class Solution { private int n; private Integer[][] f; public int findIntegers(int n) { this.n = n; int m = Integer.SIZE - Integer.numberOfLeadingZeros(n); f = new Integer[m][2]; return dfs(m - 1, 0, true); } private int dfs(int i, int pre, boolean limit) { if (i < 0) { return 1; } if (!limit && f[i][pre] != null) { return f[i][pre]; } int up = limit ? (n >> i & 1) : 1; int ans = 0; for (int j = 0; j <= up; ++j) { if (j == 1 && pre == 1) { continue; } ans += dfs(i - 1, j, limit && j == up); } if (!limit) { f[i][pre] = ans; } return ans; } }
600
Non-negative Integers without Consecutive Ones
Hard
<p>Given a positive integer <code>n</code>, return the number of the integers in the range <code>[0, n]</code> whose binary representations <strong>do not</strong> contain consecutive ones.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> Here are the non-negative integers &lt;= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Dynamic Programming
Python
class Solution: def findIntegers(self, n: int) -> int: @cache def dfs(i: int, pre: int, limit: bool) -> int: if i < 0: return 1 up = (n >> i & 1) if limit else 1 ans = 0 for j in range(up + 1): if pre and j: continue ans += dfs(i - 1, j, limit and j == up) return ans return dfs(n.bit_length() - 1, 0, True)
600
Non-negative Integers without Consecutive Ones
Hard
<p>Given a positive integer <code>n</code>, return the number of the integers in the range <code>[0, n]</code> whose binary representations <strong>do not</strong> contain consecutive ones.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> Here are the non-negative integers &lt;= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Dynamic Programming
TypeScript
function findIntegers(n: number): number { const m = n.toString(2).length; const f: number[][] = Array.from({ length: m }, () => Array(2).fill(-1)); const dfs = (i: number, pre: number, limit: boolean): number => { if (i < 0) { return 1; } if (!limit && f[i][pre] !== -1) { return f[i][pre]; } const up = limit ? (n >> i) & 1 : 1; let ans = 0; for (let j = 0; j <= up; ++j) { if (pre === 1 && j === 1) { continue; } ans += dfs(i - 1, j, limit && j === up); } if (!limit) { f[i][pre] = ans; } return ans; }; return dfs(m - 1, 0, true); }
601
Human Traffic of Stadium
Hard
<p>Table: <code>Stadium</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | visit_date | date | | people | int | +---------------+---------+ visit_date is the column with unique values for this table. Each row of this table contains the visit date and visit id to the stadium with the number of people during the visit. As the id increases, the date increases as well. </pre> <p>&nbsp;</p> <p>Write a solution to display the records with three or more rows with <strong>consecutive</strong> <code>id</code>&#39;s, and the number of people is greater than or equal to 100 for each.</p> <p>Return the result table ordered by <code>visit_date</code> in <strong>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> Stadium table: +------+------------+-----------+ | id | visit_date | people | +------+------------+-----------+ | 1 | 2017-01-01 | 10 | | 2 | 2017-01-02 | 109 | | 3 | 2017-01-03 | 150 | | 4 | 2017-01-04 | 99 | | 5 | 2017-01-05 | 145 | | 6 | 2017-01-06 | 1455 | | 7 | 2017-01-07 | 199 | | 8 | 2017-01-09 | 188 | +------+------------+-----------+ <strong>Output:</strong> +------+------------+-----------+ | id | visit_date | people | +------+------------+-----------+ | 5 | 2017-01-05 | 145 | | 6 | 2017-01-06 | 1455 | | 7 | 2017-01-07 | 199 | | 8 | 2017-01-09 | 188 | +------+------------+-----------+ <strong>Explanation:</strong> The four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has &gt;= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7. The rows with ids 2 and 3 are not included because we need at least three consecutive ids. </pre>
Database
SQL
# Write your MySQL query statement below WITH S AS ( SELECT *, id - (ROW_NUMBER() OVER (ORDER BY id)) AS rk FROM Stadium WHERE people >= 100 ), T AS (SELECT *, COUNT(1) OVER (PARTITION BY rk) AS cnt FROM S) SELECT id, visit_date, people FROM T WHERE cnt >= 3 ORDER BY 1;
602
Friend Requests II Who Has the Most Friends
Medium
<p>Table: <code>RequestAccepted</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | requester_id | int | | accepter_id | int | | accept_date | date | +----------------+---------+ (requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table. This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted. </pre> <p>&nbsp;</p> <p>Write a solution to find the people who have the most friends and the most friends number.</p> <p>The test cases are generated so that only one person has the most friends.</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> RequestAccepted table: +--------------+-------------+-------------+ | requester_id | accepter_id | accept_date | +--------------+-------------+-------------+ | 1 | 2 | 2016/06/03 | | 1 | 3 | 2016/06/08 | | 2 | 3 | 2016/06/08 | | 3 | 4 | 2016/06/09 | +--------------+-------------+-------------+ <strong>Output:</strong> +----+-----+ | id | num | +----+-----+ | 3 | 3 | +----+-----+ <strong>Explanation:</strong> The person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others. </pre> <p>&nbsp;</p> <p><strong>Follow up:</strong> In the real world, multiple people could have the same most number of friends. Could you find all these people in this case?</p>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT requester_id, accepter_id FROM RequestAccepted UNION ALL SELECT accepter_id, requester_id FROM RequestAccepted ) SELECT requester_id AS id, COUNT(1) AS num FROM T GROUP BY 1 ORDER BY 2 DESC LIMIT 1;
603
Consecutive Available Seats
Easy
<p>Table: <code>Cinema</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | seat_id | int | | free | bool | +-------------+------+ seat_id is an auto-increment column for this table. Each row of this table indicates whether the i<sup>th</sup> seat is free or not. 1 means free while 0 means occupied. </pre> <p>&nbsp;</p> <p>Find all the consecutive available seats in the cinema.</p> <p>Return the result table <strong>ordered</strong> by <code>seat_id</code> <strong>in ascending order</strong>.</p> <p>The test cases are generated so that more than two seats are consecutively available.</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> Cinema table: +---------+------+ | seat_id | free | +---------+------+ | 1 | 1 | | 2 | 0 | | 3 | 1 | | 4 | 1 | | 5 | 1 | +---------+------+ <strong>Output:</strong> +---------+ | seat_id | +---------+ | 3 | | 4 | | 5 | +---------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT DISTINCT a.seat_id FROM Cinema AS a JOIN Cinema AS b ON ABS(a.seat_id - b.seat_id) = 1 AND a.free AND b.free ORDER BY 1;
604
Design Compressed String Iterator
Easy
<p>Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.</p> <p>Implement the&nbsp;StringIterator class:</p> <ul> <li><code>next()</code>&nbsp;Returns <strong>the next character</strong> if the original string still has uncompressed characters, otherwise returns a <strong>white space</strong>.</li> <li><code>hasNext()</code>&nbsp;Returns true if&nbsp;there is any letter needs to be uncompressed in the original string, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;StringIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[&quot;L1e2t1C1o1d1e1&quot;], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, &quot;L&quot;, &quot;e&quot;, &quot;e&quot;, &quot;t&quot;, &quot;C&quot;, &quot;o&quot;, true, &quot;d&quot;, true] <strong>Explanation</strong> StringIterator stringIterator = new StringIterator(&quot;L1e2t1C1o1d1e1&quot;); stringIterator.next(); // return &quot;L&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;t&quot; stringIterator.next(); // return &quot;C&quot; stringIterator.next(); // return &quot;o&quot; stringIterator.hasNext(); // return True stringIterator.next(); // return &quot;d&quot; stringIterator.hasNext(); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;compressedString.length &lt;= 1000</code></li> <li><code>compressedString</code> consists of lower-case an upper-case English letters and digits.</li> <li>The number of a single character repetitions in&nbsp;<code>compressedString</code> is in the range <code>[1, 10^9]</code></li> <li>At most <code>100</code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul>
Design; Array; String; Iterator
C++
class StringIterator { public: StringIterator(string compressedString) { int n = compressedString.size(); int i = 0; while (i < n) { char c = compressedString[i]; int x = 0; while (++i < n && isdigit(compressedString[i])) { x = x * 10 + (compressedString[i] - '0'); } d.push_back({c, x}); } } char next() { if (!hasNext()) return ' '; char ans = d[p].first; if (--d[p].second == 0) { ++p; } return ans; } bool hasNext() { return p < d.size() && d[p].second > 0; } private: vector<pair<char, int>> d; int p = 0; }; /** * Your StringIterator object will be instantiated and called as such: * StringIterator* obj = new StringIterator(compressedString); * char param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
604
Design Compressed String Iterator
Easy
<p>Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.</p> <p>Implement the&nbsp;StringIterator class:</p> <ul> <li><code>next()</code>&nbsp;Returns <strong>the next character</strong> if the original string still has uncompressed characters, otherwise returns a <strong>white space</strong>.</li> <li><code>hasNext()</code>&nbsp;Returns true if&nbsp;there is any letter needs to be uncompressed in the original string, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;StringIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[&quot;L1e2t1C1o1d1e1&quot;], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, &quot;L&quot;, &quot;e&quot;, &quot;e&quot;, &quot;t&quot;, &quot;C&quot;, &quot;o&quot;, true, &quot;d&quot;, true] <strong>Explanation</strong> StringIterator stringIterator = new StringIterator(&quot;L1e2t1C1o1d1e1&quot;); stringIterator.next(); // return &quot;L&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;t&quot; stringIterator.next(); // return &quot;C&quot; stringIterator.next(); // return &quot;o&quot; stringIterator.hasNext(); // return True stringIterator.next(); // return &quot;d&quot; stringIterator.hasNext(); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;compressedString.length &lt;= 1000</code></li> <li><code>compressedString</code> consists of lower-case an upper-case English letters and digits.</li> <li>The number of a single character repetitions in&nbsp;<code>compressedString</code> is in the range <code>[1, 10^9]</code></li> <li>At most <code>100</code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul>
Design; Array; String; Iterator
Go
type pair struct { c byte x int } type StringIterator struct { d []pair p int } func Constructor(compressedString string) StringIterator { n := len(compressedString) i := 0 d := []pair{} for i < n { c := compressedString[i] x := 0 i++ for i < n && compressedString[i] >= '0' && compressedString[i] <= '9' { x = x*10 + int(compressedString[i]-'0') i++ } d = append(d, pair{c, x}) } return StringIterator{d, 0} } func (this *StringIterator) Next() byte { if !this.HasNext() { return ' ' } ans := this.d[this.p].c this.d[this.p].x-- if this.d[this.p].x == 0 { this.p++ } return ans } func (this *StringIterator) HasNext() bool { return this.p < len(this.d) && this.d[this.p].x > 0 } /** * Your StringIterator object will be instantiated and called as such: * obj := Constructor(compressedString); * param_1 := obj.Next(); * param_2 := obj.HasNext(); */
604
Design Compressed String Iterator
Easy
<p>Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.</p> <p>Implement the&nbsp;StringIterator class:</p> <ul> <li><code>next()</code>&nbsp;Returns <strong>the next character</strong> if the original string still has uncompressed characters, otherwise returns a <strong>white space</strong>.</li> <li><code>hasNext()</code>&nbsp;Returns true if&nbsp;there is any letter needs to be uncompressed in the original string, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;StringIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[&quot;L1e2t1C1o1d1e1&quot;], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, &quot;L&quot;, &quot;e&quot;, &quot;e&quot;, &quot;t&quot;, &quot;C&quot;, &quot;o&quot;, true, &quot;d&quot;, true] <strong>Explanation</strong> StringIterator stringIterator = new StringIterator(&quot;L1e2t1C1o1d1e1&quot;); stringIterator.next(); // return &quot;L&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;t&quot; stringIterator.next(); // return &quot;C&quot; stringIterator.next(); // return &quot;o&quot; stringIterator.hasNext(); // return True stringIterator.next(); // return &quot;d&quot; stringIterator.hasNext(); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;compressedString.length &lt;= 1000</code></li> <li><code>compressedString</code> consists of lower-case an upper-case English letters and digits.</li> <li>The number of a single character repetitions in&nbsp;<code>compressedString</code> is in the range <code>[1, 10^9]</code></li> <li>At most <code>100</code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul>
Design; Array; String; Iterator
Java
class StringIterator { private List<Node> d = new ArrayList<>(); private int p; public StringIterator(String compressedString) { int n = compressedString.length(); int i = 0; while (i < n) { char c = compressedString.charAt(i); int x = 0; while (++i < n && Character.isDigit(compressedString.charAt(i))) { x = x * 10 + (compressedString.charAt(i) - '0'); } d.add(new Node(c, x)); } } public char next() { if (!hasNext()) { return ' '; } char ans = d.get(p).c; if (--d.get(p).x == 0) { ++p; } return ans; } public boolean hasNext() { return p < d.size() && d.get(p).x > 0; } } class Node { char c; int x; Node(char c, int x) { this.c = c; this.x = x; } } /** * Your StringIterator object will be instantiated and called as such: * StringIterator obj = new StringIterator(compressedString); * char param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
604
Design Compressed String Iterator
Easy
<p>Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.</p> <p>Implement the&nbsp;StringIterator class:</p> <ul> <li><code>next()</code>&nbsp;Returns <strong>the next character</strong> if the original string still has uncompressed characters, otherwise returns a <strong>white space</strong>.</li> <li><code>hasNext()</code>&nbsp;Returns true if&nbsp;there is any letter needs to be uncompressed in the original string, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;StringIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[&quot;L1e2t1C1o1d1e1&quot;], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, &quot;L&quot;, &quot;e&quot;, &quot;e&quot;, &quot;t&quot;, &quot;C&quot;, &quot;o&quot;, true, &quot;d&quot;, true] <strong>Explanation</strong> StringIterator stringIterator = new StringIterator(&quot;L1e2t1C1o1d1e1&quot;); stringIterator.next(); // return &quot;L&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;t&quot; stringIterator.next(); // return &quot;C&quot; stringIterator.next(); // return &quot;o&quot; stringIterator.hasNext(); // return True stringIterator.next(); // return &quot;d&quot; stringIterator.hasNext(); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;compressedString.length &lt;= 1000</code></li> <li><code>compressedString</code> consists of lower-case an upper-case English letters and digits.</li> <li>The number of a single character repetitions in&nbsp;<code>compressedString</code> is in the range <code>[1, 10^9]</code></li> <li>At most <code>100</code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul>
Design; Array; String; Iterator
Python
class StringIterator: def __init__(self, compressedString: str): self.d = [] self.p = 0 n = len(compressedString) i = 0 while i < n: c = compressedString[i] x = 0 i += 1 while i < n and compressedString[i].isdigit(): x = x * 10 + int(compressedString[i]) i += 1 self.d.append([c, x]) def next(self) -> str: if not self.hasNext(): return ' ' ans = self.d[self.p][0] self.d[self.p][1] -= 1 if self.d[self.p][1] == 0: self.p += 1 return ans def hasNext(self) -> bool: return self.p < len(self.d) and self.d[self.p][1] > 0 # Your StringIterator object will be instantiated and called as such: # obj = StringIterator(compressedString) # param_1 = obj.next() # param_2 = obj.hasNext()
604
Design Compressed String Iterator
Easy
<p>Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.</p> <p>Implement the&nbsp;StringIterator class:</p> <ul> <li><code>next()</code>&nbsp;Returns <strong>the next character</strong> if the original string still has uncompressed characters, otherwise returns a <strong>white space</strong>.</li> <li><code>hasNext()</code>&nbsp;Returns true if&nbsp;there is any letter needs to be uncompressed in the original string, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;StringIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[&quot;L1e2t1C1o1d1e1&quot;], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, &quot;L&quot;, &quot;e&quot;, &quot;e&quot;, &quot;t&quot;, &quot;C&quot;, &quot;o&quot;, true, &quot;d&quot;, true] <strong>Explanation</strong> StringIterator stringIterator = new StringIterator(&quot;L1e2t1C1o1d1e1&quot;); stringIterator.next(); // return &quot;L&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;e&quot; stringIterator.next(); // return &quot;t&quot; stringIterator.next(); // return &quot;C&quot; stringIterator.next(); // return &quot;o&quot; stringIterator.hasNext(); // return True stringIterator.next(); // return &quot;d&quot; stringIterator.hasNext(); // return True </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;compressedString.length &lt;= 1000</code></li> <li><code>compressedString</code> consists of lower-case an upper-case English letters and digits.</li> <li>The number of a single character repetitions in&nbsp;<code>compressedString</code> is in the range <code>[1, 10^9]</code></li> <li>At most <code>100</code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul>
Design; Array; String; Iterator
TypeScript
class StringIterator { private d: [string, number][] = []; private p: number = 0; constructor(compressedString: string) { const n = compressedString.length; let i = 0; while (i < n) { const c = compressedString[i]; let x = 0; i++; while (i < n && !isNaN(Number(compressedString[i]))) { x = x * 10 + Number(compressedString[i]); i++; } this.d.push([c, x]); } } next(): string { if (!this.hasNext()) { return ' '; } const ans = this.d[this.p][0]; this.d[this.p][1]--; if (this.d[this.p][1] === 0) { this.p++; } return ans; } hasNext(): boolean { return this.p < this.d.length && this.d[this.p][1] > 0; } } /** * Your StringIterator object will be instantiated and called as such: * var obj = new StringIterator(compressedString) * var param_1 = obj.next() * var param_2 = obj.hasNext() */
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
C++
class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int m = flowerbed.size(); for (int i = 0; i < m; ++i) { int l = i == 0 ? 0 : flowerbed[i - 1]; int r = i == m - 1 ? 0 : flowerbed[i + 1]; if (l + flowerbed[i] + r == 0) { flowerbed[i] = 1; --n; } } return n <= 0; } };
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
Go
func canPlaceFlowers(flowerbed []int, n int) bool { m := len(flowerbed) for i, v := range flowerbed { l, r := 0, 0 if i > 0 { l = flowerbed[i-1] } if i < m-1 { r = flowerbed[i+1] } if l+v+r == 0 { flowerbed[i] = 1 n-- } } return n <= 0 }
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
Java
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int m = flowerbed.length; for (int i = 0; i < m; ++i) { int l = i == 0 ? 0 : flowerbed[i - 1]; int r = i == m - 1 ? 0 : flowerbed[i + 1]; if (l + flowerbed[i] + r == 0) { flowerbed[i] = 1; --n; } } return n <= 0; } }
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
PHP
class Solution { /** * @param Integer[] $flowerbed * @param Integer $n * @return Boolean */ function canPlaceFlowers($flowerbed, $n) { array_push($flowerbed, 0); array_unshift($flowerbed, 0); for ($i = 1; $i < count($flowerbed) - 1; $i++) { if ($flowerbed[$i] === 0) { if ($flowerbed[$i - 1] === 0 && $flowerbed[$i + 1] === 0) { $flowerbed[$i] = 1; $n--; } } } return $n <= 0; } }
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
Python
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: flowerbed = [0] + flowerbed + [0] for i in range(1, len(flowerbed) - 1): if sum(flowerbed[i - 1 : i + 2]) == 0: flowerbed[i] = 1 n -= 1 return n <= 0
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
Rust
impl Solution { pub fn can_place_flowers(flowerbed: Vec<i32>, n: i32) -> bool { let (mut flowers, mut cnt) = (vec![0], 0); flowers.append(&mut flowerbed.clone()); flowers.push(0); for i in 1..flowers.len() - 1 { let (l, r) = (flowers[i - 1], flowers[i + 1]); if l + flowers[i] + r == 0 { flowers[i] = 1; cnt += 1; } } cnt >= n } }
605
Can Place Flowers
Easy
<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p> <p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li> <li>There are no two adjacent flowers in <code>flowerbed</code>.</li> <li><code>0 &lt;= n &lt;= flowerbed.length</code></li> </ul>
Greedy; Array
TypeScript
function canPlaceFlowers(flowerbed: number[], n: number): boolean { const m = flowerbed.length; for (let i = 0; i < m; ++i) { const l = i === 0 ? 0 : flowerbed[i - 1]; const r = i === m - 1 ? 0 : flowerbed[i + 1]; if (l + flowerbed[i] + r === 0) { flowerbed[i] = 1; --n; } } return n <= 0; }
606
Construct String from Binary Tree
Medium
<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p> <ul> <li> <p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p> </li> <li> <p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p> <ul> <li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li> <li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li> </ul> </li> <li> <p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p> <p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p> </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/0606.Construct%20String%20from%20Binary%20Tree/images/cons1-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,4] <strong>Output:</strong> &quot;1(2(4))(3)&quot; <strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/images/cons2-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> &quot;1(2()(4))(3)&quot; <strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child. </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; String; 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: string tree2str(TreeNode* root) { if (!root) return ""; if (!root->left && !root->right) return to_string(root->val); if (!root->right) return to_string(root->val) + "(" + tree2str(root->left) + ")"; return to_string(root->val) + "(" + tree2str(root->left) + ")(" + tree2str(root->right) + ")"; } };
606
Construct String from Binary Tree
Medium
<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p> <ul> <li> <p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p> </li> <li> <p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p> <ul> <li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li> <li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li> </ul> </li> <li> <p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p> <p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p> </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/0606.Construct%20String%20from%20Binary%20Tree/images/cons1-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,4] <strong>Output:</strong> &quot;1(2(4))(3)&quot; <strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/images/cons2-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> &quot;1(2()(4))(3)&quot; <strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child. </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; String; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func tree2str(root *TreeNode) string { if root == nil { return "" } if root.Left == nil && root.Right == nil { return strconv.Itoa(root.Val) } if root.Right == nil { return strconv.Itoa(root.Val) + "(" + tree2str(root.Left) + ")" } return strconv.Itoa(root.Val) + "(" + tree2str(root.Left) + ")(" + tree2str(root.Right) + ")" }
606
Construct String from Binary Tree
Medium
<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p> <ul> <li> <p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p> </li> <li> <p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p> <ul> <li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li> <li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li> </ul> </li> <li> <p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p> <p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p> </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/0606.Construct%20String%20from%20Binary%20Tree/images/cons1-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,4] <strong>Output:</strong> &quot;1(2(4))(3)&quot; <strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/images/cons2-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> &quot;1(2()(4))(3)&quot; <strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child. </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; String; 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 String tree2str(TreeNode root) { if (root == null) { return ""; } if (root.left == null && root.right == null) { return root.val + ""; } if (root.right == null) { return root.val + "(" + tree2str(root.left) + ")"; } return root.val + "(" + tree2str(root.left) + ")(" + tree2str(root.right) + ")"; } }
606
Construct String from Binary Tree
Medium
<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p> <ul> <li> <p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p> </li> <li> <p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p> <ul> <li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li> <li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li> </ul> </li> <li> <p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p> <p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p> </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/0606.Construct%20String%20from%20Binary%20Tree/images/cons1-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,4] <strong>Output:</strong> &quot;1(2(4))(3)&quot; <strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/images/cons2-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> &quot;1(2()(4))(3)&quot; <strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child. </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; String; 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 tree2str(self, root: Optional[TreeNode]) -> str: def dfs(root): if root is None: return '' if root.left is None and root.right is None: return str(root.val) if root.right is None: return f'{root.val}({dfs(root.left)})' return f'{root.val}({dfs(root.left)})({dfs(root.right)})' return dfs(root)
606
Construct String from Binary Tree
Medium
<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p> <ul> <li> <p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p> </li> <li> <p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p> <ul> <li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li> <li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li> </ul> </li> <li> <p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p> <p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p> </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/0606.Construct%20String%20from%20Binary%20Tree/images/cons1-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,4] <strong>Output:</strong> &quot;1(2(4))(3)&quot; <strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/images/cons2-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> &quot;1(2()(4))(3)&quot; <strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child. </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; String; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, res: &mut String) { if let Some(node) = root { let node = node.borrow(); res.push_str(node.val.to_string().as_str()); if node.left.is_none() && node.right.is_none() { return; } res.push('('); if node.left.is_some() { Self::dfs(&node.left, res); } res.push(')'); if node.right.is_some() { res.push('('); Self::dfs(&node.right, res); res.push(')'); } } } pub fn tree2str(root: Option<Rc<RefCell<TreeNode>>>) -> String { let mut res = String::new(); Self::dfs(&root, &mut res); res } }
606
Construct String from Binary Tree
Medium
<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p> <ul> <li> <p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p> </li> <li> <p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p> <ul> <li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li> <li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li> </ul> </li> <li> <p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p> <p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p> </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/0606.Construct%20String%20from%20Binary%20Tree/images/cons1-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,4] <strong>Output:</strong> &quot;1(2(4))(3)&quot; <strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/images/cons2-tree.jpg" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,4] <strong>Output:</strong> &quot;1(2()(4))(3)&quot; <strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child. </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; String; 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 tree2str(root: TreeNode | null): string { if (root == null) { return ''; } if (root.left == null && root.right == null) { return `${root.val}`; } return `${root.val}(${root.left ? tree2str(root.left) : ''})${ root.right ? `(${tree2str(root.right)})` : '' }`; }
607
Sales Person
Easy
<p>Table: <code>SalesPerson</code></p> <pre> +-----------------+---------+ | Column Name | Type | +-----------------+---------+ | sales_id | int | | name | varchar | | salary | int | | commission_rate | int | | hire_date | date | +-----------------+---------+ sales_id is the primary key (column with unique values) for this table. Each row of this table indicates the name and the ID of a salesperson alongside their salary, commission rate, and hire date. </pre> <p>&nbsp;</p> <p>Table: <code>Company</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | com_id | int | | name | varchar | | city | varchar | +-------------+---------+ com_id is the primary key (column with unique values) for this table. Each row of this table indicates the name and the ID of a company and the city in which the company is located. </pre> <p>&nbsp;</p> <p>Table: <code>Orders</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | order_id | int | | order_date | date | | com_id | int | | sales_id | int | | amount | int | +-------------+------+ order_id is the primary key (column with unique values) for this table. com_id is a foreign key (reference column) to com_id from the Company table. sales_id is a foreign key (reference column) to sales_id from the SalesPerson table. Each row of this table contains information about one order. This includes the ID of the company, the ID of the salesperson, the date of the order, and the amount paid. </pre> <p>&nbsp;</p> <p>Write a solution to find the names of all the salespersons who did not have any orders related to the company with the name <strong>&quot;RED&quot;</strong>.</p> <p>Return the result table in <strong>any 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> SalesPerson table: +----------+------+--------+-----------------+------------+ | sales_id | name | salary | commission_rate | hire_date | +----------+------+--------+-----------------+------------+ | 1 | John | 100000 | 6 | 4/1/2006 | | 2 | Amy | 12000 | 5 | 5/1/2010 | | 3 | Mark | 65000 | 12 | 12/25/2008 | | 4 | Pam | 25000 | 25 | 1/1/2005 | | 5 | Alex | 5000 | 10 | 2/3/2007 | +----------+------+--------+-----------------+------------+ Company table: +--------+--------+----------+ | com_id | name | city | +--------+--------+----------+ | 1 | RED | Boston | | 2 | ORANGE | New York | | 3 | YELLOW | Boston | | 4 | GREEN | Austin | +--------+--------+----------+ Orders table: +----------+------------+--------+----------+--------+ | order_id | order_date | com_id | sales_id | amount | +----------+------------+--------+----------+--------+ | 1 | 1/1/2014 | 3 | 4 | 10000 | | 2 | 2/1/2014 | 4 | 5 | 5000 | | 3 | 3/1/2014 | 1 | 1 | 50000 | | 4 | 4/1/2014 | 1 | 4 | 25000 | +----------+------------+--------+----------+--------+ <strong>Output:</strong> +------+ | name | +------+ | Amy | | Mark | | Alex | +------+ <strong>Explanation:</strong> According to orders 3 and 4 in the Orders table, it is easy to tell that only salesperson John and Pam have sales to company RED, so we report all the other names in the table salesperson. </pre>
Database
SQL
# Write your MySQL query statement below SELECT s.name FROM SalesPerson AS s LEFT JOIN Orders USING (sales_id) LEFT JOIN Company AS c USING (com_id) GROUP BY sales_id HAVING IFNULL(SUM(c.name = 'RED'), 0) = 0;
608
Tree Node
Medium
<p>Table: <code>Tree</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | p_id | int | +-------------+------+ id is the column with unique values for this table. Each row of this table contains information about the id of a node and the id of its parent node in a tree. The given structure is always a valid tree. </pre> <p>&nbsp;</p> <p>Each node in the tree can be one of three types:</p> <ul> <li><strong>&quot;Leaf&quot;</strong>: if the node is a leaf node.</li> <li><strong>&quot;Root&quot;</strong>: if the node is the root of the tree.</li> <li><strong>&quot;Inner&quot;</strong>: If the node is neither a leaf node nor a root node.</li> </ul> <p>Write a solution to report the type of each node in the tree.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</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/0608.Tree%20Node/images/tree1.jpg" style="width: 304px; height: 224px;" /> <pre> <strong>Input:</strong> Tree table: +----+------+ | id | p_id | +----+------+ | 1 | null | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 2 | +----+------+ <strong>Output:</strong> +----+-------+ | id | type | +----+-------+ | 1 | Root | | 2 | Inner | | 3 | Leaf | | 4 | Leaf | | 5 | Leaf | +----+-------+ <strong>Explanation:</strong> Node 1 is the root node because its parent node is null and it has child nodes 2 and 3. Node 2 is an inner node because it has parent node 1 and child node 4 and 5. Nodes 3, 4, and 5 are leaf nodes because they have parent nodes and they do not have child nodes. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0608.Tree%20Node/images/tree2.jpg" style="width: 64px; height: 65px;" /> <pre> <strong>Input:</strong> Tree table: +----+------+ | id | p_id | +----+------+ | 1 | null | +----+------+ <strong>Output:</strong> +----+-------+ | id | type | +----+-------+ | 1 | Root | +----+-------+ <strong>Explanation:</strong> If there is only one node on the tree, you only need to output its root attributes. </pre> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/binary-tree-nodes/description/" target="_blank"> 3054: Binary Tree Nodes.</a></p>
Database
SQL
# Write your MySQL query statement below SELECT id, CASE WHEN p_id IS NULL THEN 'Root' WHEN id IN (SELECT p_id FROM Tree) THEN 'Inner' ELSE 'Leaf' END AS type FROM Tree;
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
C++
class Solution { public: vector<vector<string>> findDuplicate(vector<string>& paths) { unordered_map<string, vector<string>> d; for (auto& p : paths) { auto ps = split(p, ' '); for (int i = 1; i < ps.size(); ++i) { int j = ps[i].find('('); auto content = ps[i].substr(j + 1, ps[i].size() - j - 2); auto name = ps[0] + '/' + ps[i].substr(0, j); d[content].push_back(name); } } vector<vector<string>> ans; for (auto& [_, e] : d) { if (e.size() > 1) { ans.push_back(e); } } return ans; } vector<string> split(string& s, char c) { vector<string> res; stringstream ss(s); string t; while (getline(ss, t, c)) { res.push_back(t); } return res; } };