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
538
Convert BST to Greater Tree
Medium
<p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p> <p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</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/0538.Convert%20BST%20to%20Greater%20Tree/images/tree.png" style="width: 500px; height: 341px;" /> <pre> <strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] <strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0,null,1] <strong>Output:</strong> [1,null,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>All the values in the tree are <strong>unique</strong>.</li> <li><code>root</code> is guaranteed to be a valid binary search tree.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1038: <a href="https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" target="_blank">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int s; public TreeNode convertBST(TreeNode root) { dfs(root); return root; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.right); s += root.val; root.val = s; dfs(root.left); } }
538
Convert BST to Greater Tree
Medium
<p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p> <p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</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/0538.Convert%20BST%20to%20Greater%20Tree/images/tree.png" style="width: 500px; height: 341px;" /> <pre> <strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] <strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0,null,1] <strong>Output:</strong> [1,null,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>All the values in the tree are <strong>unique</strong>.</li> <li><code>root</code> is guaranteed to be a valid binary search tree.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1038: <a href="https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" target="_blank">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var convertBST = function (root) { let s = 0; function dfs(root) { if (!root) { return; } dfs(root.right); s += root.val; root.val = s; dfs(root.left); } dfs(root); return root; };
538
Convert BST to Greater Tree
Medium
<p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p> <p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</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/0538.Convert%20BST%20to%20Greater%20Tree/images/tree.png" style="width: 500px; height: 341px;" /> <pre> <strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] <strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0,null,1] <strong>Output:</strong> [1,null,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>All the values in the tree are <strong>unique</strong>.</li> <li><code>root</code> is guaranteed to be a valid binary search tree.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1038: <a href="https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" target="_blank">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>
Tree; Depth-First Search; Binary Search Tree; 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 convertBST(self, root: TreeNode) -> TreeNode: def dfs(root): nonlocal s if root is None: return dfs(root.right) s += root.val root.val = s dfs(root.left) s = 0 dfs(root) return root
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
C++
class Solution { public: int findMinDifference(vector<string>& timePoints) { if (timePoints.size() > 1440) { return 0; } int n = timePoints.size(); vector<int> nums(n + 1); for (int i = 0; i < n; ++i) { int hours = stoi(timePoints[i].substr(0, 2)); int minutes = stoi(timePoints[i].substr(3, 2)); nums[i] = hours * 60 + minutes; } sort(nums.begin(), nums.begin() + n); nums[n] = nums[0] + 1440; int ans = INT_MAX; for (int i = 1; i <= n; ++i) { ans = min(ans, nums[i] - nums[i - 1]); } return ans; } };
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
Go
func findMinDifference(timePoints []string) int { if len(timePoints) > 1440 { return 0 } n := len(timePoints) nums := make([]int, n+1) for i, time := range timePoints { parts := strings.Split(time, ":") hours, _ := strconv.Atoi(parts[0]) minutes, _ := strconv.Atoi(parts[1]) nums[i] = hours*60 + minutes } sort.Ints(nums[:n]) nums[n] = nums[0] + 1440 ans := 1 << 30 for i := 1; i <= n; i++ { ans = min(ans, nums[i]-nums[i-1]) } return ans }
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
Java
class Solution { public int findMinDifference(List<String> timePoints) { if (timePoints.size() > 1440) { return 0; } int n = timePoints.size(); int[] nums = new int[n + 1]; for (int i = 0; i < n; ++i) { String[] t = timePoints.get(i).split(":"); nums[i] = Integer.parseInt(t[0]) * 60 + Integer.parseInt(t[1]); } Arrays.sort(nums, 0, n); nums[n] = nums[0] + 1440; int ans = 1 << 30; for (int i = 1; i <= n; ++i) { ans = Math.min(ans, nums[i] - nums[i - 1]); } return ans; } }
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
Python
class Solution: def findMinDifference(self, timePoints: List[str]) -> int: if len(timePoints) > 1440: return 0 nums = sorted(int(x[:2]) * 60 + int(x[3:]) for x in timePoints) nums.append(nums[0] + 1440) return min(b - a for a, b in pairwise(nums))
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
Rust
impl Solution { pub fn find_min_difference(time_points: Vec<String>) -> i32 { if time_points.len() > 1440 { return 0; } let n = time_points.len(); let mut nums: Vec<i32> = Vec::with_capacity(n + 1); for time in time_points.iter() { let parts: Vec<i32> = time.split(':').map(|s| s.parse().unwrap()).collect(); let minutes = parts[0] * 60 + parts[1]; nums.push(minutes); } nums.sort(); nums.push(nums[0] + 1440); let mut ans = i32::MAX; for i in 1..=n { ans = ans.min(nums[i] - nums[i - 1]); } ans } }
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
Swift
class Solution { func findMinDifference(_ timePoints: [String]) -> Int { if timePoints.count > 1440 { return 0 } var nums = [Int]() for t in timePoints { let time = t.split(separator: ":").map { Int($0)! } nums.append(time[0] * 60 + time[1]) } nums.sort() nums.append(nums[0] + 1440) var ans = Int.max for i in 1..<nums.count { ans = min(ans, nums[i] - nums[i - 1]) } return ans } }
539
Minimum Time Difference
Medium
Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> timePoints = ["23:59","00:00"] <strong>Output:</strong> 1 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li> </ul>
Array; Math; String; Sorting
TypeScript
function findMinDifference(timePoints: string[]): number { if (timePoints.length > 1440) { return 0; } const n = timePoints.length; const nums: number[] = Array(n + 1); for (let i = 0; i < n; ++i) { const [hours, minutes] = timePoints[i].split(':').map(Number); nums[i] = hours * 60 + minutes; } nums.sort((a, b) => a - b); nums[n] = nums[0] + 1440; let ans = 1 << 30; for (let i = 1; i <= n; ++i) { ans = Math.min(ans, nums[i] - nums[i - 1]); } return ans; }
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
C
int singleNonDuplicate(int* nums, int numsSize) { int l = 0, r = numsSize - 1; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] != nums[mid ^ 1]) { r = mid; } else { l = mid + 1; } } return nums[l]; }
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
C++
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int l = 0, r = nums.size() - 1; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] != nums[mid ^ 1]) { r = mid; } else { l = mid + 1; } } return nums[l]; } };
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
Go
func singleNonDuplicate(nums []int) int { l, r := 0, len(nums)-1 for l < r { mid := (l + r) >> 1 if nums[mid] != nums[mid^1] { r = mid } else { l = mid + 1 } } return nums[l] }
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
Java
class Solution { public int singleNonDuplicate(int[] nums) { int l = 0, r = nums.length - 1; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] != nums[mid ^ 1]) { r = mid; } else { l = mid + 1; } } return nums[l]; } }
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
Python
class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: l, r = 0, len(nums) - 1 while l < r: mid = (l + r) >> 1 if nums[mid] != nums[mid ^ 1]: r = mid else: l = mid + 1 return nums[l]
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
Rust
impl Solution { pub fn single_non_duplicate(nums: Vec<i32>) -> i32 { let mut l = 0; let mut r = nums.len() - 1; while l < r { let mid = (l + r) >> 1; if nums[mid] != nums[mid ^ 1] { r = mid; } else { l = mid + 1; } } nums[l] } }
540
Single Element in a Sorted Array
Medium
<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p> <p>Return <em>the single element that appears only once</em>.</p> <p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11] <strong>Output:</strong> 10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search
TypeScript
function singleNonDuplicate(nums: number[]): number { let [l, r] = [0, nums.length - 1]; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] !== nums[mid ^ 1]) { r = mid; } else { l = mid + 1; } } return nums[l]; }
541
Reverse String II
Easy
<p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p> <p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abcdefg", k = 2 <strong>Output:</strong> "bacdfeg" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd", k = 2 <strong>Output:</strong> "bacd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> </ul>
Two Pointers; String
C++
class Solution { public: string reverseStr(string s, int k) { int n = s.size(); for (int i = 0; i < n; i += 2 * k) { reverse(s.begin() + i, s.begin() + min(i + k, n)); } return s; } };
541
Reverse String II
Easy
<p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p> <p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abcdefg", k = 2 <strong>Output:</strong> "bacdfeg" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd", k = 2 <strong>Output:</strong> "bacd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> </ul>
Two Pointers; String
Go
func reverseStr(s string, k int) string { cs := []byte(s) n := len(cs) for i := 0; i < n; i += 2 * k { for l, r := i, min(i+k-1, n-1); l < r; l, r = l+1, r-1 { cs[l], cs[r] = cs[r], cs[l] } } return string(cs) }
541
Reverse String II
Easy
<p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p> <p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abcdefg", k = 2 <strong>Output:</strong> "bacdfeg" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd", k = 2 <strong>Output:</strong> "bacd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> </ul>
Two Pointers; String
Java
class Solution { public String reverseStr(String s, int k) { char[] cs = s.toCharArray(); int n = cs.length; for (int i = 0; i < n; i += k * 2) { for (int l = i, r = Math.min(i + k - 1, n - 1); l < r; ++l, --r) { char t = cs[l]; cs[l] = cs[r]; cs[r] = t; } } return new String(cs); } }
541
Reverse String II
Easy
<p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p> <p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abcdefg", k = 2 <strong>Output:</strong> "bacdfeg" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd", k = 2 <strong>Output:</strong> "bacd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> </ul>
Two Pointers; String
Python
class Solution: def reverseStr(self, s: str, k: int) -> str: cs = list(s) for i in range(0, len(cs), 2 * k): cs[i : i + k] = reversed(cs[i : i + k]) return "".join(cs)
541
Reverse String II
Easy
<p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p> <p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abcdefg", k = 2 <strong>Output:</strong> "bacdfeg" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abcd", k = 2 <strong>Output:</strong> "bacd" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> </ul>
Two Pointers; String
TypeScript
function reverseStr(s: string, k: number): string { const n = s.length; const cs = s.split(''); for (let i = 0; i < n; i += 2 * k) { for (let l = i, r = Math.min(i + k - 1, n - 1); l < r; l++, r--) { [cs[l], cs[r]] = [cs[r], cs[l]]; } } return cs.join(''); }
542
01 Matrix
Medium
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p> <p>The distance between two cells sharing a common edge is <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]] <strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]] <strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There is at least one <code>0</code> in <code>mat</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1765: <a href="https://leetcode.com/problems/map-of-highest-peak/description/" target="_blank">https://leetcode.com/problems/map-of-highest-peak/</a></p>
Breadth-First Search; Array; Dynamic Programming; Matrix
C++
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { int m = mat.size(), n = mat[0].size(); vector<vector<int>> ans(m, vector<int>(n, -1)); queue<pair<int, int>> q; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j] == 0) { ans[i][j] = 0; q.emplace(i, j); } } } vector<int> dirs = {-1, 0, 1, 0, -1}; while (!q.empty()) { auto p = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int x = p.first + dirs[i]; int y = p.second + dirs[i + 1]; if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { ans[x][y] = ans[p.first][p.second] + 1; q.emplace(x, y); } } } return ans; } };
542
01 Matrix
Medium
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p> <p>The distance between two cells sharing a common edge is <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]] <strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]] <strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There is at least one <code>0</code> in <code>mat</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1765: <a href="https://leetcode.com/problems/map-of-highest-peak/description/" target="_blank">https://leetcode.com/problems/map-of-highest-peak/</a></p>
Breadth-First Search; Array; Dynamic Programming; Matrix
Go
func updateMatrix(mat [][]int) [][]int { m, n := len(mat), len(mat[0]) ans := make([][]int, m) for i := range ans { ans[i] = make([]int, n) for j := range ans[i] { ans[i][j] = -1 } } type pair struct{ x, y int } var q []pair for i, row := range mat { for j, v := range row { if v == 0 { ans[i][j] = 0 q = append(q, pair{i, j}) } } } dirs := []int{-1, 0, 1, 0, -1} for len(q) > 0 { p := q[0] q = q[1:] for i := 0; i < 4; i++ { x, y := p.x+dirs[i], p.y+dirs[i+1] if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 { ans[x][y] = ans[p.x][p.y] + 1 q = append(q, pair{x, y}) } } } return ans }
542
01 Matrix
Medium
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p> <p>The distance between two cells sharing a common edge is <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]] <strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]] <strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There is at least one <code>0</code> in <code>mat</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1765: <a href="https://leetcode.com/problems/map-of-highest-peak/description/" target="_blank">https://leetcode.com/problems/map-of-highest-peak/</a></p>
Breadth-First Search; Array; Dynamic Programming; Matrix
Java
class Solution { public int[][] updateMatrix(int[][] mat) { int m = mat.length, n = mat[0].length; int[][] ans = new int[m][n]; for (int[] row : ans) { Arrays.fill(row, -1); } Deque<int[]> q = new ArrayDeque<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j] == 0) { q.offer(new int[] {i, j}); ans[i][j] = 0; } } } int[] dirs = {-1, 0, 1, 0, -1}; while (!q.isEmpty()) { int[] p = q.poll(); int i = p[0], j = p[1]; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { ans[x][y] = ans[i][j] + 1; q.offer(new int[] {x, y}); } } } return ans; } }
542
01 Matrix
Medium
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p> <p>The distance between two cells sharing a common edge is <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]] <strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]] <strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There is at least one <code>0</code> in <code>mat</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1765: <a href="https://leetcode.com/problems/map-of-highest-peak/description/" target="_blank">https://leetcode.com/problems/map-of-highest-peak/</a></p>
Breadth-First Search; Array; Dynamic Programming; Matrix
Python
class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: m, n = len(mat), len(mat[0]) ans = [[-1] * n for _ in range(m)] q = deque() for i, row in enumerate(mat): for j, x in enumerate(row): if x == 0: ans[i][j] = 0 q.append((i, j)) dirs = (-1, 0, 1, 0, -1) while q: i, j = q.popleft() for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and ans[x][y] == -1: ans[x][y] = ans[i][j] + 1 q.append((x, y)) return ans
542
01 Matrix
Medium
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p> <p>The distance between two cells sharing a common edge is <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]] <strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]] <strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There is at least one <code>0</code> in <code>mat</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1765: <a href="https://leetcode.com/problems/map-of-highest-peak/description/" target="_blank">https://leetcode.com/problems/map-of-highest-peak/</a></p>
Breadth-First Search; Array; Dynamic Programming; Matrix
Rust
use std::collections::VecDeque; impl Solution { pub fn update_matrix(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let m = mat.len(); let n = mat[0].len(); let mut ans = vec![vec![-1; n]; m]; let mut q = VecDeque::new(); for i in 0..m { for j in 0..n { if mat[i][j] == 0 { q.push_back((i, j)); ans[i][j] = 0; } } } let dirs = [-1, 0, 1, 0, -1]; while let Some((i, j)) = q.pop_front() { for k in 0..4 { let x = i as isize + dirs[k]; let y = j as isize + dirs[k + 1]; if x >= 0 && x < m as isize && y >= 0 && y < n as isize { let x = x as usize; let y = y as usize; if ans[x][y] == -1 { ans[x][y] = ans[i][j] + 1; q.push_back((x, y)); } } } } ans } }
542
01 Matrix
Medium
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p> <p>The distance between two cells sharing a common edge is <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]] <strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0542.01%20Matrix/images/01-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]] <strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There is at least one <code>0</code> in <code>mat</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1765: <a href="https://leetcode.com/problems/map-of-highest-peak/description/" target="_blank">https://leetcode.com/problems/map-of-highest-peak/</a></p>
Breadth-First Search; Array; Dynamic Programming; Matrix
TypeScript
function updateMatrix(mat: number[][]): number[][] { const [m, n] = [mat.length, mat[0].length]; const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => -1)); const q: [number, number][] = []; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (mat[i][j] === 0) { q.push([i, j]); ans[i][j] = 0; } } } const dirs: number[] = [-1, 0, 1, 0, -1]; for (const [i, j] of q) { for (let k = 0; k < 4; ++k) { const [x, y] = [i + dirs[k], j + dirs[k + 1]]; if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] === -1) { ans[x][y] = ans[i][j] + 1; q.push([x, y]); } } } return ans; }
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int dfs(struct TreeNode* root, int* ans) { if (root == NULL) { return 0; } int l = dfs(root->left, ans); int r = dfs(root->right, ans); if (l + r > *ans) { *ans = l + r; } return 1 + (l > r ? l : r); } int diameterOfBinaryTree(struct TreeNode* root) { int ans = 0; dfs(root, &ans); return ans; }
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int diameterOfBinaryTree(TreeNode* root) { int ans = 0; auto dfs = [&](this auto&& dfs, TreeNode* root) -> int { if (!root) { return 0; } int l = dfs(root->left); int r = dfs(root->right); ans = max(ans, l + r); return 1 + max(l, r); }; dfs(root); return ans; } };
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { private int ans; public int DiameterOfBinaryTree(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode root) { if (root == null) { return 0; } int l = dfs(root.left); int r = dfs(root.right); ans = Math.Max(ans, l + r); return 1 + Math.Max(l, r); } }
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func diameterOfBinaryTree(root *TreeNode) (ans int) { var dfs func(root *TreeNode) int dfs = func(root *TreeNode) int { if root == nil { return 0 } l, r := dfs(root.Left), dfs(root.Right) ans = max(ans, l+r) return 1 + max(l, r) } dfs(root) return }
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int diameterOfBinaryTree(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode root) { if (root == null) { return 0; } int l = dfs(root.left); int r = dfs(root.right); ans = Math.max(ans, l + r); return 1 + Math.max(l, r); } }
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var diameterOfBinaryTree = function (root) { let ans = 0; const dfs = root => { if (!root) { return 0; } const [l, r] = [dfs(root.left), dfs(root.right)]; ans = Math.max(ans, l + r); return 1 + Math.max(l, r); }; dfs(root); return ans; };
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 l, r = dfs(root.left), dfs(root.right) nonlocal ans ans = max(ans, l + r) return 1 + max(l, r) ans = 0 dfs(root) return ans
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn diameter_of_binary_tree(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { let mut ans = 0; fn dfs(root: Option<Rc<RefCell<TreeNode>>>, ans: &mut i32) -> i32 { match root { Some(node) => { let node = node.borrow(); let l = dfs(node.left.clone(), ans); let r = dfs(node.right.clone(), ans); *ans = (*ans).max(l + r); 1 + l.max(r) } None => 0, } } dfs(root, &mut ans); ans } }
543
Diameter of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p> <p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p> <p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</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/0543.Diameter%20of%20Binary%20Tree/images/diamtree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function diameterOfBinaryTree(root: TreeNode | null): number { let ans = 0; const dfs = (root: TreeNode | null): number => { if (!root) { return 0; } const [l, r] = [dfs(root.left), dfs(root.right)]; ans = Math.max(ans, l + r); return 1 + Math.max(l, r); }; dfs(root); return ans; }
544
Output Contest Matches
Medium
<p>During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making&nbsp;the rank <code>1</code> team play with the rank <code>n<sup>th</sup></code> team, which is a good strategy to make the contest more interesting.</p> <p>Given <code>n</code> teams, return <em>their final contest matches in the form of a string</em>.</p> <p>The <code>n</code> teams are labeled from <code>1</code> to <code>n</code>, which represents their initial rank (i.e., Rank <code>1</code> is the strongest team and Rank <code>n</code> is the weakest team).</p> <p>We will use parentheses <code>&#39;(&#39;</code>, and <code>&#39;)&#39;</code> and commas <code>&#39;,&#39;</code> to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> &quot;((1,4),(2,3))&quot; <strong>Explanation:</strong> In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together. And we got (1, 4),(2, 3). In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them. And we got the final answer ((1,4),(2,3)). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> &quot;(((1,8),(4,5)),((2,7),(3,6)))&quot; <strong>Explanation:</strong> First round: (1, 8),(2, 7),(3, 6),(4, 5) Second round: ((1, 8),(4, 5)),((2, 7),(3, 6)) Third round: (((1, 8),(4, 5)),((2, 7),(3, 6))) Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == 2<sup>x</sup></code> where <code>x</code> in in the range <code>[1, 12]</code>.</li> </ul>
Recursion; String; Simulation
C++
class Solution { public: string findContestMatch(int n) { vector<string> s(n); for (int i = 0; i < n; ++i) { s[i] = to_string(i + 1); } for (; n > 1; n >>= 1) { for (int i = 0; i < n >> 1; ++i) { s[i] = "(" + s[i] + "," + s[n - i - 1] + ")"; } } return s[0]; } };
544
Output Contest Matches
Medium
<p>During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making&nbsp;the rank <code>1</code> team play with the rank <code>n<sup>th</sup></code> team, which is a good strategy to make the contest more interesting.</p> <p>Given <code>n</code> teams, return <em>their final contest matches in the form of a string</em>.</p> <p>The <code>n</code> teams are labeled from <code>1</code> to <code>n</code>, which represents their initial rank (i.e., Rank <code>1</code> is the strongest team and Rank <code>n</code> is the weakest team).</p> <p>We will use parentheses <code>&#39;(&#39;</code>, and <code>&#39;)&#39;</code> and commas <code>&#39;,&#39;</code> to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> &quot;((1,4),(2,3))&quot; <strong>Explanation:</strong> In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together. And we got (1, 4),(2, 3). In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them. And we got the final answer ((1,4),(2,3)). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> &quot;(((1,8),(4,5)),((2,7),(3,6)))&quot; <strong>Explanation:</strong> First round: (1, 8),(2, 7),(3, 6),(4, 5) Second round: ((1, 8),(4, 5)),((2, 7),(3, 6)) Third round: (((1, 8),(4, 5)),((2, 7),(3, 6))) Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == 2<sup>x</sup></code> where <code>x</code> in in the range <code>[1, 12]</code>.</li> </ul>
Recursion; String; Simulation
Go
func findContestMatch(n int) string { s := make([]string, n) for i := 0; i < n; i++ { s[i] = strconv.Itoa(i + 1) } for ; n > 1; n >>= 1 { for i := 0; i < n>>1; i++ { s[i] = fmt.Sprintf("(%s,%s)", s[i], s[n-i-1]) } } return s[0] }
544
Output Contest Matches
Medium
<p>During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making&nbsp;the rank <code>1</code> team play with the rank <code>n<sup>th</sup></code> team, which is a good strategy to make the contest more interesting.</p> <p>Given <code>n</code> teams, return <em>their final contest matches in the form of a string</em>.</p> <p>The <code>n</code> teams are labeled from <code>1</code> to <code>n</code>, which represents their initial rank (i.e., Rank <code>1</code> is the strongest team and Rank <code>n</code> is the weakest team).</p> <p>We will use parentheses <code>&#39;(&#39;</code>, and <code>&#39;)&#39;</code> and commas <code>&#39;,&#39;</code> to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> &quot;((1,4),(2,3))&quot; <strong>Explanation:</strong> In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together. And we got (1, 4),(2, 3). In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them. And we got the final answer ((1,4),(2,3)). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> &quot;(((1,8),(4,5)),((2,7),(3,6)))&quot; <strong>Explanation:</strong> First round: (1, 8),(2, 7),(3, 6),(4, 5) Second round: ((1, 8),(4, 5)),((2, 7),(3, 6)) Third round: (((1, 8),(4, 5)),((2, 7),(3, 6))) Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == 2<sup>x</sup></code> where <code>x</code> in in the range <code>[1, 12]</code>.</li> </ul>
Recursion; String; Simulation
Java
class Solution { public String findContestMatch(int n) { String[] s = new String[n]; for (int i = 0; i < n; ++i) { s[i] = String.valueOf(i + 1); } for (; n > 1; n >>= 1) { for (int i = 0; i < n >> 1; ++i) { s[i] = String.format("(%s,%s)", s[i], s[n - i - 1]); } } return s[0]; } }
544
Output Contest Matches
Medium
<p>During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making&nbsp;the rank <code>1</code> team play with the rank <code>n<sup>th</sup></code> team, which is a good strategy to make the contest more interesting.</p> <p>Given <code>n</code> teams, return <em>their final contest matches in the form of a string</em>.</p> <p>The <code>n</code> teams are labeled from <code>1</code> to <code>n</code>, which represents their initial rank (i.e., Rank <code>1</code> is the strongest team and Rank <code>n</code> is the weakest team).</p> <p>We will use parentheses <code>&#39;(&#39;</code>, and <code>&#39;)&#39;</code> and commas <code>&#39;,&#39;</code> to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> &quot;((1,4),(2,3))&quot; <strong>Explanation:</strong> In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together. And we got (1, 4),(2, 3). In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them. And we got the final answer ((1,4),(2,3)). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> &quot;(((1,8),(4,5)),((2,7),(3,6)))&quot; <strong>Explanation:</strong> First round: (1, 8),(2, 7),(3, 6),(4, 5) Second round: ((1, 8),(4, 5)),((2, 7),(3, 6)) Third round: (((1, 8),(4, 5)),((2, 7),(3, 6))) Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == 2<sup>x</sup></code> where <code>x</code> in in the range <code>[1, 12]</code>.</li> </ul>
Recursion; String; Simulation
Python
class Solution: def findContestMatch(self, n: int) -> str: s = [str(i + 1) for i in range(n)] while n > 1: for i in range(n >> 1): s[i] = f"({s[i]},{s[n - i - 1]})" n >>= 1 return s[0]
544
Output Contest Matches
Medium
<p>During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making&nbsp;the rank <code>1</code> team play with the rank <code>n<sup>th</sup></code> team, which is a good strategy to make the contest more interesting.</p> <p>Given <code>n</code> teams, return <em>their final contest matches in the form of a string</em>.</p> <p>The <code>n</code> teams are labeled from <code>1</code> to <code>n</code>, which represents their initial rank (i.e., Rank <code>1</code> is the strongest team and Rank <code>n</code> is the weakest team).</p> <p>We will use parentheses <code>&#39;(&#39;</code>, and <code>&#39;)&#39;</code> and commas <code>&#39;,&#39;</code> to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> &quot;((1,4),(2,3))&quot; <strong>Explanation:</strong> In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together. And we got (1, 4),(2, 3). In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them. And we got the final answer ((1,4),(2,3)). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> &quot;(((1,8),(4,5)),((2,7),(3,6)))&quot; <strong>Explanation:</strong> First round: (1, 8),(2, 7),(3, 6),(4, 5) Second round: ((1, 8),(4, 5)),((2, 7),(3, 6)) Third round: (((1, 8),(4, 5)),((2, 7),(3, 6))) Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == 2<sup>x</sup></code> where <code>x</code> in in the range <code>[1, 12]</code>.</li> </ul>
Recursion; String; Simulation
TypeScript
function findContestMatch(n: number): string { const s: string[] = Array.from({ length: n }, (_, i) => (i + 1).toString()); for (; n > 1; n >>= 1) { for (let i = 0; i < n >> 1; ++i) { s[i] = `(${s[i]},${s[n - i - 1]})`; } } return s[0]; }
545
Boundary of Binary Tree
Medium
<p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p> <p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p> <ul> <li>The root node&#39;s left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li> <li>If a node is in the left boundary and has a left child, then the left child is in the left boundary.</li> <li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li> <li>The leftmost leaf is <strong>not</strong> in the left boundary.</li> </ul> <p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root&#39;s right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p> <p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p> <p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</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/0545.Boundary%20of%20Binary%20Tree/images/boundary1.jpg" style="width: 299px; height: 290px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4] <strong>Output:</strong> [1,3,4,2] <b>Explanation:</b> - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root&#39;s right child 2 -&gt; 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0545.Boundary%20of%20Binary%20Tree/images/boundary2.jpg" style="width: 599px; height: 411px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10] <strong>Output:</strong> [1,2,4,7,8,9,10,6,3] <b>Explanation:</b> - The left boundary follows the path starting from the root&#39;s left child 2 -&gt; 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root&#39;s right child 3 -&gt; 6 -&gt; 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. </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; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> boundaryOfBinaryTree(TreeNode* root) { auto dfs = [&](this auto&& dfs, vector<int>& nums, TreeNode* root, int i) -> void { if (!root) { return; } if (i == 0) { if (root->left != root->right) { nums.push_back(root->val); if (root->left) { dfs(nums, root->left, i); } else { dfs(nums, root->right, i); } } } else if (i == 1) { if (root->left == root->right) { nums.push_back(root->val); } else { dfs(nums, root->left, i); dfs(nums, root->right, i); } } else { if (root->left != root->right) { nums.push_back(root->val); if (root->right) { dfs(nums, root->right, i); } else { dfs(nums, root->left, i); } } } }; vector<int> ans = {root->val}; if (root->left == root->right) { return ans; } vector<int> left, right, leaves; dfs(left, root->left, 0); dfs(leaves, root, 1); dfs(right, root->right, 2); ans.insert(ans.end(), left.begin(), left.end()); ans.insert(ans.end(), leaves.begin(), leaves.end()); ans.insert(ans.end(), right.rbegin(), right.rend()); return ans; } };
545
Boundary of Binary Tree
Medium
<p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p> <p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p> <ul> <li>The root node&#39;s left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li> <li>If a node is in the left boundary and has a left child, then the left child is in the left boundary.</li> <li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li> <li>The leftmost leaf is <strong>not</strong> in the left boundary.</li> </ul> <p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root&#39;s right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p> <p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p> <p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</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/0545.Boundary%20of%20Binary%20Tree/images/boundary1.jpg" style="width: 299px; height: 290px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4] <strong>Output:</strong> [1,3,4,2] <b>Explanation:</b> - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root&#39;s right child 2 -&gt; 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0545.Boundary%20of%20Binary%20Tree/images/boundary2.jpg" style="width: 599px; height: 411px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10] <strong>Output:</strong> [1,2,4,7,8,9,10,6,3] <b>Explanation:</b> - The left boundary follows the path starting from the root&#39;s left child 2 -&gt; 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root&#39;s right child 3 -&gt; 6 -&gt; 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. </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; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func boundaryOfBinaryTree(root *TreeNode) []int { ans := []int{root.Val} if root.Left == root.Right { return ans } left, leaves, right := []int{}, []int{}, []int{} var dfs func(nums *[]int, root *TreeNode, i int) dfs = func(nums *[]int, root *TreeNode, i int) { if root == nil { return } if i == 0 { if root.Left != root.Right { *nums = append(*nums, root.Val) if root.Left != nil { dfs(nums, root.Left, i) } else { dfs(nums, root.Right, i) } } } else if i == 1 { if root.Left == root.Right { *nums = append(*nums, root.Val) } else { dfs(nums, root.Left, i) dfs(nums, root.Right, i) } } else { if root.Left != root.Right { *nums = append(*nums, root.Val) if root.Right != nil { dfs(nums, root.Right, i) } else { dfs(nums, root.Left, i) } } } } dfs(&left, root.Left, 0) dfs(&leaves, root, 1) dfs(&right, root.Right, 2) ans = append(ans, left...) ans = append(ans, leaves...) for i := len(right) - 1; i >= 0; i-- { ans = append(ans, right[i]) } return ans }
545
Boundary of Binary Tree
Medium
<p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p> <p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p> <ul> <li>The root node&#39;s left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li> <li>If a node is in the left boundary and has a left child, then the left child is in the left boundary.</li> <li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li> <li>The leftmost leaf is <strong>not</strong> in the left boundary.</li> </ul> <p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root&#39;s right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p> <p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p> <p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</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/0545.Boundary%20of%20Binary%20Tree/images/boundary1.jpg" style="width: 299px; height: 290px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4] <strong>Output:</strong> [1,3,4,2] <b>Explanation:</b> - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root&#39;s right child 2 -&gt; 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0545.Boundary%20of%20Binary%20Tree/images/boundary2.jpg" style="width: 599px; height: 411px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10] <strong>Output:</strong> [1,2,4,7,8,9,10,6,3] <b>Explanation:</b> - The left boundary follows the path starting from the root&#39;s left child 2 -&gt; 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root&#39;s right child 3 -&gt; 6 -&gt; 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. </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; Binary Tree
Java
class Solution { public List<Integer> boundaryOfBinaryTree(TreeNode root) { List<Integer> ans = new ArrayList<>(); ans.add(root.val); if (root.left == root.right) { return ans; } List<Integer> left = new ArrayList<>(); List<Integer> leaves = new ArrayList<>(); List<Integer> right = new ArrayList<>(); dfs(left, root.left, 0); dfs(leaves, root, 1); dfs(right, root.right, 2); ans.addAll(left); ans.addAll(leaves); Collections.reverse(right); ans.addAll(right); return ans; } private void dfs(List<Integer> nums, TreeNode root, int i) { if (root == null) { return; } if (i == 0) { if (root.left != root.right) { nums.add(root.val); if (root.left != null) { dfs(nums, root.left, i); } else { dfs(nums, root.right, i); } } } else if (i == 1) { if (root.left == root.right) { nums.add(root.val); } else { dfs(nums, root.left, i); dfs(nums, root.right, i); } } else { if (root.left != root.right) { nums.add(root.val); if (root.right != null) { dfs(nums, root.right, i); } else { dfs(nums, root.left, i); } } } } }
545
Boundary of Binary Tree
Medium
<p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p> <p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p> <ul> <li>The root node&#39;s left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li> <li>If a node is in the left boundary and has a left child, then the left child is in the left boundary.</li> <li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li> <li>The leftmost leaf is <strong>not</strong> in the left boundary.</li> </ul> <p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root&#39;s right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p> <p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p> <p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</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/0545.Boundary%20of%20Binary%20Tree/images/boundary1.jpg" style="width: 299px; height: 290px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4] <strong>Output:</strong> [1,3,4,2] <b>Explanation:</b> - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root&#39;s right child 2 -&gt; 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0545.Boundary%20of%20Binary%20Tree/images/boundary2.jpg" style="width: 599px; height: 411px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10] <strong>Output:</strong> [1,2,4,7,8,9,10,6,3] <b>Explanation:</b> - The left boundary follows the path starting from the root&#39;s left child 2 -&gt; 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root&#39;s right child 3 -&gt; 6 -&gt; 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. </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; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[]} */ var boundaryOfBinaryTree = function (root) { const ans = [root.val]; if (root.left === root.right) { return ans; } const left = []; const leaves = []; const right = []; const dfs = function (nums, root, i) { if (!root) { return; } if (i === 0) { if (root.left !== root.right) { nums.push(root.val); if (root.left) { dfs(nums, root.left, i); } else { dfs(nums, root.right, i); } } } else if (i === 1) { if (root.left === root.right) { nums.push(root.val); } else { dfs(nums, root.left, i); dfs(nums, root.right, i); } } else { if (root.left !== root.right) { nums.push(root.val); if (root.right) { dfs(nums, root.right, i); } else { dfs(nums, root.left, i); } } } }; dfs(left, root.left, 0); dfs(leaves, root, 1); dfs(right, root.right, 2); return ans.concat(left).concat(leaves).concat(right.reverse()); };
545
Boundary of Binary Tree
Medium
<p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p> <p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p> <ul> <li>The root node&#39;s left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li> <li>If a node is in the left boundary and has a left child, then the left child is in the left boundary.</li> <li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li> <li>The leftmost leaf is <strong>not</strong> in the left boundary.</li> </ul> <p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root&#39;s right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p> <p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p> <p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</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/0545.Boundary%20of%20Binary%20Tree/images/boundary1.jpg" style="width: 299px; height: 290px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4] <strong>Output:</strong> [1,3,4,2] <b>Explanation:</b> - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root&#39;s right child 2 -&gt; 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0545.Boundary%20of%20Binary%20Tree/images/boundary2.jpg" style="width: 599px; height: 411px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10] <strong>Output:</strong> [1,2,4,7,8,9,10,6,3] <b>Explanation:</b> - The left boundary follows the path starting from the root&#39;s left child 2 -&gt; 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root&#39;s right child 3 -&gt; 6 -&gt; 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. </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; 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 boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]: def dfs(nums: List[int], root: Optional[TreeNode], i: int): if root is None: return if i == 0: if root.left != root.right: nums.append(root.val) if root.left: dfs(nums, root.left, i) else: dfs(nums, root.right, i) elif i == 1: if root.left == root.right: nums.append(root.val) else: dfs(nums, root.left, i) dfs(nums, root.right, i) else: if root.left != root.right: nums.append(root.val) if root.right: dfs(nums, root.right, i) else: dfs(nums, root.left, i) ans = [root.val] if root.left == root.right: return ans left, leaves, right = [], [], [] dfs(left, root.left, 0) dfs(leaves, root, 1) dfs(right, root.right, 2) ans += left + leaves + right[::-1] return ans
545
Boundary of Binary Tree
Medium
<p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p> <p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p> <ul> <li>The root node&#39;s left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li> <li>If a node is in the left boundary and has a left child, then the left child is in the left boundary.</li> <li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li> <li>The leftmost leaf is <strong>not</strong> in the left boundary.</li> </ul> <p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root&#39;s right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p> <p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p> <p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</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/0545.Boundary%20of%20Binary%20Tree/images/boundary1.jpg" style="width: 299px; height: 290px;" /> <pre> <strong>Input:</strong> root = [1,null,2,3,4] <strong>Output:</strong> [1,3,4,2] <b>Explanation:</b> - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root&#39;s right child 2 -&gt; 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0545.Boundary%20of%20Binary%20Tree/images/boundary2.jpg" style="width: 599px; height: 411px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10] <strong>Output:</strong> [1,2,4,7,8,9,10,6,3] <b>Explanation:</b> - The left boundary follows the path starting from the root&#39;s left child 2 -&gt; 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root&#39;s right child 3 -&gt; 6 -&gt; 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. </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; 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 boundaryOfBinaryTree(root: TreeNode | null): number[] { const ans: number[] = [root.val]; if (root.left === root.right) { return ans; } const left: number[] = []; const leaves: number[] = []; const right: number[] = []; const dfs = function (nums: number[], root: TreeNode | null, i: number) { if (!root) { return; } if (i === 0) { if (root.left !== root.right) { nums.push(root.val); if (root.left) { dfs(nums, root.left, i); } else { dfs(nums, root.right, i); } } } else if (i === 1) { if (root.left === root.right) { nums.push(root.val); } else { dfs(nums, root.left, i); dfs(nums, root.right, i); } } else { if (root.left !== root.right) { nums.push(root.val); if (root.right) { dfs(nums, root.right, i); } else { dfs(nums, root.left, i); } } } }; dfs(left, root.left, 0); dfs(leaves, root, 1); dfs(right, root.right, 2); return ans.concat(left).concat(leaves).concat(right.reverse()); }
546
Remove Boxes
Hard
<p>You are given several <code>boxes</code> with different colors represented by different positive numbers.</p> <p>You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of <code>k</code> boxes, <code>k &gt;= 1</code>), remove them and get <code>k * k</code> points.</p> <p>Return <em>the maximum points you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> boxes = [1,3,2,2,2,3,4,3,1] <strong>Output:</strong> 23 <strong>Explanation:</strong> [1, 3, 2, 2, 2, 3, 4, 3, 1] ----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points) ----&gt; [1, 3, 3, 3, 1] (1*1=1 points) ----&gt; [1, 1] (3*3=9 points) ----&gt; [] (2*2=4 points) </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> boxes = [1,1,1] <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> boxes = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= boxes.length &lt;= 100</code></li> <li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li> </ul>
Memoization; Array; Dynamic Programming
C++
class Solution { public: int removeBoxes(vector<int>& boxes) { int n = boxes.size(); vector<vector<vector<int>>> f(n, vector<vector<int>>(n, vector<int>(n))); function<int(int, int, int)> dfs; dfs = [&](int i, int j, int k) { if (i > j) return 0; while (i < j && boxes[j] == boxes[j - 1]) { --j; ++k; } if (f[i][j][k]) return f[i][j][k]; int ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1); for (int h = i; h < j; ++h) { if (boxes[h] == boxes[j]) { ans = max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1)); } } f[i][j][k] = ans; return ans; }; return dfs(0, n - 1, 0); } };
546
Remove Boxes
Hard
<p>You are given several <code>boxes</code> with different colors represented by different positive numbers.</p> <p>You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of <code>k</code> boxes, <code>k &gt;= 1</code>), remove them and get <code>k * k</code> points.</p> <p>Return <em>the maximum points you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> boxes = [1,3,2,2,2,3,4,3,1] <strong>Output:</strong> 23 <strong>Explanation:</strong> [1, 3, 2, 2, 2, 3, 4, 3, 1] ----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points) ----&gt; [1, 3, 3, 3, 1] (1*1=1 points) ----&gt; [1, 1] (3*3=9 points) ----&gt; [] (2*2=4 points) </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> boxes = [1,1,1] <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> boxes = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= boxes.length &lt;= 100</code></li> <li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li> </ul>
Memoization; Array; Dynamic Programming
Go
func removeBoxes(boxes []int) int { n := len(boxes) f := make([][][]int, n) for i := range f { f[i] = make([][]int, n) for j := range f[i] { f[i][j] = make([]int, n) } } var dfs func(i, j, k int) int dfs = func(i, j, k int) int { if i > j { return 0 } for i < j && boxes[j] == boxes[j-1] { j, k = j-1, k+1 } if f[i][j][k] > 0 { return f[i][j][k] } ans := dfs(i, j-1, 0) + (k+1)*(k+1) for h := i; h < j; h++ { if boxes[h] == boxes[j] { ans = max(ans, dfs(h+1, j-1, 0)+dfs(i, h, k+1)) } } f[i][j][k] = ans return ans } return dfs(0, n-1, 0) }
546
Remove Boxes
Hard
<p>You are given several <code>boxes</code> with different colors represented by different positive numbers.</p> <p>You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of <code>k</code> boxes, <code>k &gt;= 1</code>), remove them and get <code>k * k</code> points.</p> <p>Return <em>the maximum points you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> boxes = [1,3,2,2,2,3,4,3,1] <strong>Output:</strong> 23 <strong>Explanation:</strong> [1, 3, 2, 2, 2, 3, 4, 3, 1] ----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points) ----&gt; [1, 3, 3, 3, 1] (1*1=1 points) ----&gt; [1, 1] (3*3=9 points) ----&gt; [] (2*2=4 points) </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> boxes = [1,1,1] <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> boxes = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= boxes.length &lt;= 100</code></li> <li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li> </ul>
Memoization; Array; Dynamic Programming
Java
class Solution { private int[][][] f; private int[] b; public int removeBoxes(int[] boxes) { b = boxes; int n = b.length; f = new int[n][n][n]; return dfs(0, n - 1, 0); } private int dfs(int i, int j, int k) { if (i > j) { return 0; } while (i < j && b[j] == b[j - 1]) { --j; ++k; } if (f[i][j][k] > 0) { return f[i][j][k]; } int ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1); for (int h = i; h < j; ++h) { if (b[h] == b[j]) { ans = Math.max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1)); } } f[i][j][k] = ans; return ans; } }
546
Remove Boxes
Hard
<p>You are given several <code>boxes</code> with different colors represented by different positive numbers.</p> <p>You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of <code>k</code> boxes, <code>k &gt;= 1</code>), remove them and get <code>k * k</code> points.</p> <p>Return <em>the maximum points you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> boxes = [1,3,2,2,2,3,4,3,1] <strong>Output:</strong> 23 <strong>Explanation:</strong> [1, 3, 2, 2, 2, 3, 4, 3, 1] ----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points) ----&gt; [1, 3, 3, 3, 1] (1*1=1 points) ----&gt; [1, 1] (3*3=9 points) ----&gt; [] (2*2=4 points) </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> boxes = [1,1,1] <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> boxes = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= boxes.length &lt;= 100</code></li> <li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li> </ul>
Memoization; Array; Dynamic Programming
Python
class Solution: def removeBoxes(self, boxes: List[int]) -> int: @cache def dfs(i, j, k): if i > j: return 0 while i < j and boxes[j] == boxes[j - 1]: j, k = j - 1, k + 1 ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1) for h in range(i, j): if boxes[h] == boxes[j]: ans = max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1)) return ans n = len(boxes) ans = dfs(0, n - 1, 0) dfs.cache_clear() return ans
547
Number of Provinces
Medium
<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p> <p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p> <p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p> <p>Return <em>the total number of <strong>provinces</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/0547.Number%20of%20Provinces/images/graph1.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0547.Number%20of%20Provinces/images/graph2.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>n == isConnected.length</code></li> <li><code>n == isConnected[i].length</code></li> <li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li> <li><code>isConnected[i][i] == 1</code></li> <li><code>isConnected[i][j] == isConnected[j][i]</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
C++
class Solution { public: int findCircleNum(vector<vector<int>>& isConnected) { int n = isConnected.size(); int ans = 0; bool vis[n]; memset(vis, false, sizeof(vis)); auto dfs = [&](this auto&& dfs, int i) -> void { vis[i] = true; for (int j = 0; j < n; ++j) { if (!vis[j] && isConnected[i][j]) { dfs(j); } } }; for (int i = 0; i < n; ++i) { if (!vis[i]) { dfs(i); ++ans; } } return ans; } };
547
Number of Provinces
Medium
<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p> <p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p> <p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p> <p>Return <em>the total number of <strong>provinces</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/0547.Number%20of%20Provinces/images/graph1.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0547.Number%20of%20Provinces/images/graph2.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>n == isConnected.length</code></li> <li><code>n == isConnected[i].length</code></li> <li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li> <li><code>isConnected[i][i] == 1</code></li> <li><code>isConnected[i][j] == isConnected[j][i]</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Go
func findCircleNum(isConnected [][]int) (ans int) { n := len(isConnected) vis := make([]bool, n) var dfs func(int) dfs = func(i int) { vis[i] = true for j, x := range isConnected[i] { if !vis[j] && x == 1 { dfs(j) } } } for i, v := range vis { if !v { ans++ dfs(i) } } return }
547
Number of Provinces
Medium
<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p> <p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p> <p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p> <p>Return <em>the total number of <strong>provinces</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/0547.Number%20of%20Provinces/images/graph1.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0547.Number%20of%20Provinces/images/graph2.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>n == isConnected.length</code></li> <li><code>n == isConnected[i].length</code></li> <li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li> <li><code>isConnected[i][i] == 1</code></li> <li><code>isConnected[i][j] == isConnected[j][i]</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Java
class Solution { private int[][] g; private boolean[] vis; public int findCircleNum(int[][] isConnected) { g = isConnected; int n = g.length; vis = new boolean[n]; int ans = 0; for (int i = 0; i < n; ++i) { if (!vis[i]) { dfs(i); ++ans; } } return ans; } private void dfs(int i) { vis[i] = true; for (int j = 0; j < g.length; ++j) { if (!vis[j] && g[i][j] == 1) { dfs(j); } } } }
547
Number of Provinces
Medium
<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p> <p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p> <p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p> <p>Return <em>the total number of <strong>provinces</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/0547.Number%20of%20Provinces/images/graph1.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0547.Number%20of%20Provinces/images/graph2.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>n == isConnected.length</code></li> <li><code>n == isConnected[i].length</code></li> <li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li> <li><code>isConnected[i][i] == 1</code></li> <li><code>isConnected[i][j] == isConnected[j][i]</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Python
class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: def dfs(i: int): vis[i] = True for j, x in enumerate(isConnected[i]): if not vis[j] and x: dfs(j) n = len(isConnected) vis = [False] * n ans = 0 for i in range(n): if not vis[i]: dfs(i) ans += 1 return ans
547
Number of Provinces
Medium
<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p> <p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p> <p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p> <p>Return <em>the total number of <strong>provinces</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/0547.Number%20of%20Provinces/images/graph1.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0547.Number%20of%20Provinces/images/graph2.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>n == isConnected.length</code></li> <li><code>n == isConnected[i].length</code></li> <li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li> <li><code>isConnected[i][i] == 1</code></li> <li><code>isConnected[i][j] == isConnected[j][i]</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Rust
impl Solution { fn dfs(is_connected: &mut Vec<Vec<i32>>, vis: &mut Vec<bool>, i: usize) { vis[i] = true; for j in 0..is_connected.len() { if vis[j] || is_connected[i][j] == 0 { continue; } Self::dfs(is_connected, vis, j); } } pub fn find_circle_num(mut is_connected: Vec<Vec<i32>>) -> i32 { let n = is_connected.len(); let mut vis = vec![false; n]; let mut res = 0; for i in 0..n { if vis[i] { continue; } res += 1; Self::dfs(&mut is_connected, &mut vis, i); } res } }
547
Number of Provinces
Medium
<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p> <p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p> <p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p> <p>Return <em>the total number of <strong>provinces</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/0547.Number%20of%20Provinces/images/graph1.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0547.Number%20of%20Provinces/images/graph2.jpg" style="width: 222px; height: 142px;" /> <pre> <strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>n == isConnected.length</code></li> <li><code>n == isConnected[i].length</code></li> <li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li> <li><code>isConnected[i][i] == 1</code></li> <li><code>isConnected[i][j] == isConnected[j][i]</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
TypeScript
function findCircleNum(isConnected: number[][]): number { const n = isConnected.length; const vis: boolean[] = Array(n).fill(false); const dfs = (i: number) => { vis[i] = true; for (let j = 0; j < n; ++j) { if (!vis[j] && isConnected[i][j]) { dfs(j); } } }; let ans = 0; for (let i = 0; i < n; ++i) { if (!vis[i]) { dfs(i); ++ans; } } return ans; }
548
Split Array with Equal Sum
Hard
<p>Given an integer array <code>nums</code> of length <code>n</code>, return <code>true</code> if there is a triplet <code>(i, j, k)</code> which satisfies the following conditions:</p> <ul> <li><code>0 &lt; i, i + 1 &lt; j, j + 1 &lt; k &lt; n - 1</code></li> <li>The sum of subarrays <code>(0, i - 1)</code>, <code>(i + 1, j - 1)</code>, <code>(j + 1, k - 1)</code> and <code>(k + 1, n - 1)</code> is equal.</li> </ul> A subarray <code>(l, r)</code> represents a slice of the original array starting from the element indexed <code>l</code> to the element indexed <code>r</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n ==&nbsp;nums.length</code></li> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
C++
class Solution { public: bool splitArray(vector<int>& nums) { int n = nums.size(); vector<int> s(n + 1); for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i]; for (int j = 3; j < n - 3; ++j) { unordered_set<int> seen; for (int i = 1; i < j - 1; ++i) if (s[i] == s[j] - s[i + 1]) seen.insert(s[i]); for (int k = j + 2; k < n - 1; ++k) if (s[n] - s[k + 1] == s[k] - s[j + 1] && seen.count(s[n] - s[k + 1])) return true; } return false; } };
548
Split Array with Equal Sum
Hard
<p>Given an integer array <code>nums</code> of length <code>n</code>, return <code>true</code> if there is a triplet <code>(i, j, k)</code> which satisfies the following conditions:</p> <ul> <li><code>0 &lt; i, i + 1 &lt; j, j + 1 &lt; k &lt; n - 1</code></li> <li>The sum of subarrays <code>(0, i - 1)</code>, <code>(i + 1, j - 1)</code>, <code>(j + 1, k - 1)</code> and <code>(k + 1, n - 1)</code> is equal.</li> </ul> A subarray <code>(l, r)</code> represents a slice of the original array starting from the element indexed <code>l</code> to the element indexed <code>r</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n ==&nbsp;nums.length</code></li> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Go
func splitArray(nums []int) bool { n := len(nums) s := make([]int, n+1) for i, v := range nums { s[i+1] = s[i] + v } for j := 3; j < n-3; j++ { seen := map[int]bool{} for i := 1; i < j-1; i++ { if s[i] == s[j]-s[i+1] { seen[s[i]] = true } } for k := j + 2; k < n-1; k++ { if s[n]-s[k+1] == s[k]-s[j+1] && seen[s[n]-s[k+1]] { return true } } } return false }
548
Split Array with Equal Sum
Hard
<p>Given an integer array <code>nums</code> of length <code>n</code>, return <code>true</code> if there is a triplet <code>(i, j, k)</code> which satisfies the following conditions:</p> <ul> <li><code>0 &lt; i, i + 1 &lt; j, j + 1 &lt; k &lt; n - 1</code></li> <li>The sum of subarrays <code>(0, i - 1)</code>, <code>(i + 1, j - 1)</code>, <code>(j + 1, k - 1)</code> and <code>(k + 1, n - 1)</code> is equal.</li> </ul> A subarray <code>(l, r)</code> represents a slice of the original array starting from the element indexed <code>l</code> to the element indexed <code>r</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n ==&nbsp;nums.length</code></li> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Java
class Solution { public boolean splitArray(int[] nums) { int n = nums.length; int[] s = new int[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } for (int j = 3; j < n - 3; ++j) { Set<Integer> seen = new HashSet<>(); for (int i = 1; i < j - 1; ++i) { if (s[i] == s[j] - s[i + 1]) { seen.add(s[i]); } } for (int k = j + 2; k < n - 1; ++k) { if (s[n] - s[k + 1] == s[k] - s[j + 1] && seen.contains(s[n] - s[k + 1])) { return true; } } } return false; } }
548
Split Array with Equal Sum
Hard
<p>Given an integer array <code>nums</code> of length <code>n</code>, return <code>true</code> if there is a triplet <code>(i, j, k)</code> which satisfies the following conditions:</p> <ul> <li><code>0 &lt; i, i + 1 &lt; j, j + 1 &lt; k &lt; n - 1</code></li> <li>The sum of subarrays <code>(0, i - 1)</code>, <code>(i + 1, j - 1)</code>, <code>(j + 1, k - 1)</code> and <code>(k + 1, n - 1)</code> is equal.</li> </ul> A subarray <code>(l, r)</code> represents a slice of the original array starting from the element indexed <code>l</code> to the element indexed <code>r</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n ==&nbsp;nums.length</code></li> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Python
class Solution: def splitArray(self, nums: List[int]) -> bool: n = len(nums) s = [0] * (n + 1) for i, v in enumerate(nums): s[i + 1] = s[i] + v for j in range(3, n - 3): seen = set() for i in range(1, j - 1): if s[i] == s[j] - s[i + 1]: seen.add(s[i]) for k in range(j + 2, n - 1): if s[n] - s[k + 1] == s[k] - s[j + 1] and s[n] - s[k + 1] in seen: return True return False
549
Binary Tree Longest Consecutive Sequence II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest consecutive path in the tree</em>.</p> <p>A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.</p> <ul> <li>For example, <code>[1,2,3,4]</code> and <code>[4,3,2,1]</code> are both considered valid, but the path <code>[1,2,4,3]</code> is not valid.</li> </ul> <p>On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.</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/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest consecutive path is [1, 2] or [2, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest consecutive path is [1, 2, 3] or [3, 2, 1]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int ans; int longestConsecutive(TreeNode* root) { ans = 0; dfs(root); return ans; } vector<int> dfs(TreeNode* root) { if (!root) return {0, 0}; int incr = 1, decr = 1; auto left = dfs(root->left); auto right = dfs(root->right); if (root->left) { if (root->left->val + 1 == root->val) incr = left[0] + 1; if (root->left->val - 1 == root->val) decr = left[1] + 1; } if (root->right) { if (root->right->val + 1 == root->val) incr = max(incr, right[0] + 1); if (root->right->val - 1 == root->val) decr = max(decr, right[1] + 1); } ans = max(ans, incr + decr - 1); return {incr, decr}; } };
549
Binary Tree Longest Consecutive Sequence II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest consecutive path in the tree</em>.</p> <p>A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.</p> <ul> <li>For example, <code>[1,2,3,4]</code> and <code>[4,3,2,1]</code> are both considered valid, but the path <code>[1,2,4,3]</code> is not valid.</li> </ul> <p>On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.</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/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest consecutive path is [1, 2] or [2, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest consecutive path is [1, 2, 3] or [3, 2, 1]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func longestConsecutive(root *TreeNode) int { ans := 0 var dfs func(root *TreeNode) []int dfs = func(root *TreeNode) []int { if root == nil { return []int{0, 0} } incr, decr := 1, 1 left := dfs(root.Left) right := dfs(root.Right) if root.Left != nil { if root.Left.Val+1 == root.Val { incr = left[0] + 1 } if root.Left.Val-1 == root.Val { decr = left[1] + 1 } } if root.Right != nil { if root.Right.Val+1 == root.Val { incr = max(incr, right[0]+1) } if root.Right.Val-1 == root.Val { decr = max(decr, right[1]+1) } } ans = max(ans, incr+decr-1) return []int{incr, decr} } dfs(root) return ans }
549
Binary Tree Longest Consecutive Sequence II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest consecutive path in the tree</em>.</p> <p>A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.</p> <ul> <li>For example, <code>[1,2,3,4]</code> and <code>[4,3,2,1]</code> are both considered valid, but the path <code>[1,2,4,3]</code> is not valid.</li> </ul> <p>On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.</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/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest consecutive path is [1, 2] or [2, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest consecutive path is [1, 2, 3] or [3, 2, 1]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int longestConsecutive(TreeNode root) { ans = 0; dfs(root); return ans; } private int[] dfs(TreeNode root) { if (root == null) { return new int[] {0, 0}; } int incr = 1, decr = 1; int[] left = dfs(root.left); int[] right = dfs(root.right); if (root.left != null) { if (root.left.val + 1 == root.val) { incr = left[0] + 1; } if (root.left.val - 1 == root.val) { decr = left[1] + 1; } } if (root.right != null) { if (root.right.val + 1 == root.val) { incr = Math.max(incr, right[0] + 1); } if (root.right.val - 1 == root.val) { decr = Math.max(decr, right[1] + 1); } } ans = Math.max(ans, incr + decr - 1); return new int[] {incr, decr}; } }
549
Binary Tree Longest Consecutive Sequence II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest consecutive path in the tree</em>.</p> <p>A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.</p> <ul> <li>For example, <code>[1,2,3,4]</code> and <code>[4,3,2,1]</code> are both considered valid, but the path <code>[1,2,4,3]</code> is not valid.</li> </ul> <p>On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.</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/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest consecutive path is [1, 2] or [2, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/images/consec2-2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest consecutive path is [1, 2, 3] or [3, 2, 1]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def longestConsecutive(self, root: TreeNode) -> int: def dfs(root): if root is None: return [0, 0] nonlocal ans incr = decr = 1 i1, d1 = dfs(root.left) i2, d2 = dfs(root.right) if root.left: if root.left.val + 1 == root.val: incr = i1 + 1 if root.left.val - 1 == root.val: decr = d1 + 1 if root.right: if root.right.val + 1 == root.val: incr = max(incr, i2 + 1) if root.right.val - 1 == root.val: decr = max(decr, d2 + 1) ans = max(ans, incr + decr - 1) return [incr, decr] ans = 0 dfs(root) return ans
550
Game Play Analysis IV
Medium
<p>Table: <code>Activity</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key (combination of columns with unique values) of this table. This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. </pre> <p> </p> <p>Write a solution to report the <strong>fraction</strong> of players that logged in again on the day after the day they first logged in, <strong>rounded to 2 decimal places</strong>. In other words, you need to determine the number of players who logged in on the day immediately following their initial login, and divide it by the number of total players.</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> Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-03-02 | 6 | | 2 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ <strong>Output:</strong> +-----------+ | fraction | +-----------+ | 0.33 | +-----------+ <strong>Explanation:</strong> Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33 </pre>
Database
Python
import pandas as pd def gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame: activity["first"] = activity.groupby("player_id").event_date.transform(min) activity_2nd_day = activity[ activity["first"] + pd.DateOffset(1) == activity["event_date"] ] return pd.DataFrame( {"fraction": [round(len(activity_2nd_day) / activity.player_id.nunique(), 2)]} )
550
Game Play Analysis IV
Medium
<p>Table: <code>Activity</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key (combination of columns with unique values) of this table. This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. </pre> <p> </p> <p>Write a solution to report the <strong>fraction</strong> of players that logged in again on the day after the day they first logged in, <strong>rounded to 2 decimal places</strong>. In other words, you need to determine the number of players who logged in on the day immediately following their initial login, and divide it by the number of total players.</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> Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-03-02 | 6 | | 2 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ <strong>Output:</strong> +-----------+ | fraction | +-----------+ | 0.33 | +-----------+ <strong>Explanation:</strong> Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33 </pre>
Database
SQL
# Write your MySQL query statement below SELECT ROUND(AVG(b.event_date IS NOT NULL), 2) AS fraction FROM ( SELECT player_id, MIN(event_date) AS event_date FROM Activity GROUP BY 1 ) AS a LEFT JOIN Activity AS b ON a.player_id = b.player_id AND DATEDIFF(a.event_date, b.event_date) = -1;
551
Student Attendance Record I
Easy
<p>You are given a string <code>s</code> representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>The student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Return <code>true</code><em> if the student is eligible for an attendance award, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLP&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The student has fewer than 2 absences and was never late 3 or more consecutive days. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLL&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;P&#39;</code>.</li> </ul>
String
C++
class Solution { public: bool checkRecord(string s) { return count(s.begin(), s.end(), 'A') < 2 && s.find("LLL") == string::npos; } };
551
Student Attendance Record I
Easy
<p>You are given a string <code>s</code> representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>The student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Return <code>true</code><em> if the student is eligible for an attendance award, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLP&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The student has fewer than 2 absences and was never late 3 or more consecutive days. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLL&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;P&#39;</code>.</li> </ul>
String
Go
func checkRecord(s string) bool { return strings.Count(s, "A") < 2 && !strings.Contains(s, "LLL") }
551
Student Attendance Record I
Easy
<p>You are given a string <code>s</code> representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>The student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Return <code>true</code><em> if the student is eligible for an attendance award, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLP&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The student has fewer than 2 absences and was never late 3 or more consecutive days. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLL&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;P&#39;</code>.</li> </ul>
String
Java
class Solution { public boolean checkRecord(String s) { return s.indexOf("A") == s.lastIndexOf("A") && !s.contains("LLL"); } }
551
Student Attendance Record I
Easy
<p>You are given a string <code>s</code> representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>The student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Return <code>true</code><em> if the student is eligible for an attendance award, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLP&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The student has fewer than 2 absences and was never late 3 or more consecutive days. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLL&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;P&#39;</code>.</li> </ul>
String
Python
class Solution: def checkRecord(self, s: str) -> bool: return s.count('A') < 2 and 'LLL' not in s
551
Student Attendance Record I
Easy
<p>You are given a string <code>s</code> representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>The student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Return <code>true</code><em> if the student is eligible for an attendance award, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLP&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The student has fewer than 2 absences and was never late 3 or more consecutive days. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PPALLL&quot; <strong>Output:</strong> false <strong>Explanation:</strong> The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;P&#39;</code>.</li> </ul>
String
TypeScript
function checkRecord(s: string): boolean { return s.indexOf('A') === s.lastIndexOf('A') && s.indexOf('LLL') === -1; }
552
Student Attendance Record II
Hard
<p>An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>Any student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of possible attendance records of length</em> <code>n</code><em> that make a student eligible for an attendance award. The answer may be very large, so return it <strong>modulo</strong> </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 8 records with length 2 that are eligible for an award: &quot;PP&quot;, &quot;AP&quot;, &quot;PA&quot;, &quot;LP&quot;, &quot;PL&quot;, &quot;AL&quot;, &quot;LA&quot;, &quot;LL&quot; Only &quot;AA&quot; is not eligible because there are 2 absences (there need to be fewer than 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 10101 <strong>Output:</strong> 183236316 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Dynamic Programming
C++
class Solution { public: int checkRecord(int n) { int f[n][2][3]; memset(f, -1, sizeof(f)); const int mod = 1e9 + 7; auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int { if (i >= n) { return 1; } if (f[i][j][k] != -1) { return f[i][j][k]; } int ans = dfs(i + 1, j, 0); if (j == 0) { ans = (ans + dfs(i + 1, j + 1, 0)) % mod; } if (k < 2) { ans = (ans + dfs(i + 1, j, k + 1)) % mod; } return f[i][j][k] = ans; }; return dfs(0, 0, 0); } };
552
Student Attendance Record II
Hard
<p>An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>Any student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of possible attendance records of length</em> <code>n</code><em> that make a student eligible for an attendance award. The answer may be very large, so return it <strong>modulo</strong> </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 8 records with length 2 that are eligible for an award: &quot;PP&quot;, &quot;AP&quot;, &quot;PA&quot;, &quot;LP&quot;, &quot;PL&quot;, &quot;AL&quot;, &quot;LA&quot;, &quot;LL&quot; Only &quot;AA&quot; is not eligible because there are 2 absences (there need to be fewer than 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 10101 <strong>Output:</strong> 183236316 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Dynamic Programming
Go
func checkRecord(n int) int { f := make([][][]int, n) for i := range f { f[i] = make([][]int, 2) for j := range f[i] { f[i][j] = make([]int, 3) for k := range f[i][j] { f[i][j][k] = -1 } } } const mod = 1e9 + 7 var dfs func(i, j, k int) int dfs = func(i, j, k int) int { if i >= n { return 1 } if f[i][j][k] != -1 { return f[i][j][k] } ans := dfs(i+1, j, 0) if j == 0 { ans = (ans + dfs(i+1, j+1, 0)) % mod } if k < 2 { ans = (ans + dfs(i+1, j, k+1)) % mod } f[i][j][k] = ans return ans } return dfs(0, 0, 0) }
552
Student Attendance Record II
Hard
<p>An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>Any student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of possible attendance records of length</em> <code>n</code><em> that make a student eligible for an attendance award. The answer may be very large, so return it <strong>modulo</strong> </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 8 records with length 2 that are eligible for an award: &quot;PP&quot;, &quot;AP&quot;, &quot;PA&quot;, &quot;LP&quot;, &quot;PL&quot;, &quot;AL&quot;, &quot;LA&quot;, &quot;LL&quot; Only &quot;AA&quot; is not eligible because there are 2 absences (there need to be fewer than 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 10101 <strong>Output:</strong> 183236316 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Dynamic Programming
Java
class Solution { private final int mod = (int) 1e9 + 7; private int n; private Integer[][][] f; public int checkRecord(int n) { this.n = n; f = new Integer[n][2][3]; return dfs(0, 0, 0); } private int dfs(int i, int j, int k) { if (i >= n) { return 1; } if (f[i][j][k] != null) { return f[i][j][k]; } int ans = dfs(i + 1, j, 0); if (j == 0) { ans = (ans + dfs(i + 1, j + 1, 0)) % mod; } if (k < 2) { ans = (ans + dfs(i + 1, j, k + 1)) % mod; } return f[i][j][k] = ans; } }
552
Student Attendance Record II
Hard
<p>An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p> <ul> <li><code>&#39;A&#39;</code>: Absent.</li> <li><code>&#39;L&#39;</code>: Late.</li> <li><code>&#39;P&#39;</code>: Present.</li> </ul> <p>Any student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p> <ul> <li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li> <li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of possible attendance records of length</em> <code>n</code><em> that make a student eligible for an attendance award. The answer may be very large, so return it <strong>modulo</strong> </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 8 records with length 2 that are eligible for an award: &quot;PP&quot;, &quot;AP&quot;, &quot;PA&quot;, &quot;LP&quot;, &quot;PL&quot;, &quot;AL&quot;, &quot;LA&quot;, &quot;LL&quot; Only &quot;AA&quot; is not eligible because there are 2 absences (there need to be fewer than 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 10101 <strong>Output:</strong> 183236316 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Dynamic Programming
Python
class Solution: def checkRecord(self, n: int) -> int: @cache def dfs(i, j, k): if i >= n: return 1 ans = 0 if j == 0: ans += dfs(i + 1, j + 1, 0) if k < 2: ans += dfs(i + 1, j, k + 1) ans += dfs(i + 1, j, 0) return ans % mod mod = 10**9 + 7 ans = dfs(0, 0, 0) dfs.cache_clear() return ans
553
Optimal Division
Medium
<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p> <ul> <li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li> </ul> <p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p> <p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p> <p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1000,100,10,2] <strong>Output:</strong> &quot;1000/(100/10/2)&quot; <strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority. So you should return &quot;1000/(100/10/2)&quot;. Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> &quot;2/(3/4)&quot; <strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>2 &lt;= nums[i] &lt;= 1000</code></li> <li>There is only one optimal division for the given input.</li> </ul>
Array; Math; Dynamic Programming
C++
class Solution { public: string optimalDivision(vector<int>& nums) { int n = nums.size(); if (n == 1) return to_string(nums[0]); if (n == 2) return to_string(nums[0]) + "/" + to_string(nums[1]); string ans = to_string(nums[0]) + "/("; for (int i = 1; i < n - 1; i++) ans.append(to_string(nums[i]) + "/"); ans.append(to_string(nums[n - 1]) + ")"); return ans; } };
553
Optimal Division
Medium
<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p> <ul> <li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li> </ul> <p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p> <p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p> <p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1000,100,10,2] <strong>Output:</strong> &quot;1000/(100/10/2)&quot; <strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority. So you should return &quot;1000/(100/10/2)&quot;. Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> &quot;2/(3/4)&quot; <strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>2 &lt;= nums[i] &lt;= 1000</code></li> <li>There is only one optimal division for the given input.</li> </ul>
Array; Math; Dynamic Programming
Go
func optimalDivision(nums []int) string { n := len(nums) if n == 1 { return strconv.Itoa(nums[0]) } if n == 2 { return fmt.Sprintf("%d/%d", nums[0], nums[1]) } ans := &strings.Builder{} ans.WriteString(fmt.Sprintf("%d/(", nums[0])) for _, num := range nums[1 : n-1] { ans.WriteString(strconv.Itoa(num)) ans.WriteByte('/') } ans.WriteString(fmt.Sprintf("%d)", nums[n-1])) return ans.String() }
553
Optimal Division
Medium
<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p> <ul> <li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li> </ul> <p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p> <p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p> <p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1000,100,10,2] <strong>Output:</strong> &quot;1000/(100/10/2)&quot; <strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority. So you should return &quot;1000/(100/10/2)&quot;. Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> &quot;2/(3/4)&quot; <strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>2 &lt;= nums[i] &lt;= 1000</code></li> <li>There is only one optimal division for the given input.</li> </ul>
Array; Math; Dynamic Programming
Java
class Solution { public String optimalDivision(int[] nums) { int n = nums.length; if (n == 1) { return nums[0] + ""; } if (n == 2) { return nums[0] + "/" + nums[1]; } StringBuilder ans = new StringBuilder(nums[0] + "/("); for (int i = 1; i < n - 1; ++i) { ans.append(nums[i] + "/"); } ans.append(nums[n - 1] + ")"); return ans.toString(); } }
553
Optimal Division
Medium
<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p> <ul> <li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li> </ul> <p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p> <p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p> <p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1000,100,10,2] <strong>Output:</strong> &quot;1000/(100/10/2)&quot; <strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority. So you should return &quot;1000/(100/10/2)&quot;. Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> &quot;2/(3/4)&quot; <strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>2 &lt;= nums[i] &lt;= 1000</code></li> <li>There is only one optimal division for the given input.</li> </ul>
Array; Math; Dynamic Programming
Python
class Solution: def optimalDivision(self, nums: List[int]) -> str: n = len(nums) if n == 1: return str(nums[0]) if n == 2: return f'{nums[0]}/{nums[1]}' return f'{nums[0]}/({"/".join(map(str, nums[1:]))})'
553
Optimal Division
Medium
<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p> <ul> <li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li> </ul> <p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p> <p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p> <p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1000,100,10,2] <strong>Output:</strong> &quot;1000/(100/10/2)&quot; <strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority. So you should return &quot;1000/(100/10/2)&quot;. Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> &quot;2/(3/4)&quot; <strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>2 &lt;= nums[i] &lt;= 1000</code></li> <li>There is only one optimal division for the given input.</li> </ul>
Array; Math; Dynamic Programming
Rust
impl Solution { pub fn optimal_division(nums: Vec<i32>) -> String { let n = nums.len(); match n { 1 => nums[0].to_string(), 2 => nums[0].to_string() + "/" + &nums[1].to_string(), _ => { let mut res = nums[0].to_string(); res.push_str("/("); for i in 1..n { res.push_str(&nums[i].to_string()); res.push('/'); } res.pop(); res.push(')'); res } } } }
553
Optimal Division
Medium
<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p> <ul> <li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li> </ul> <p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p> <p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p> <p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1000,100,10,2] <strong>Output:</strong> &quot;1000/(100/10/2)&quot; <strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority. So you should return &quot;1000/(100/10/2)&quot;. Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> &quot;2/(3/4)&quot; <strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>2 &lt;= nums[i] &lt;= 1000</code></li> <li>There is only one optimal division for the given input.</li> </ul>
Array; Math; Dynamic Programming
TypeScript
function optimalDivision(nums: number[]): string { const n = nums.length; const res = nums.join('/'); if (n > 2) { const index = res.indexOf('/') + 1; return `${res.slice(0, index)}(${res.slice(index)})`; } return res; }
554
Brick Wall
Medium
<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p> <p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p> <p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</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/0554.Brick%20Wall/images/a.png" style="width: 400px; height: 384px;" /> <pre> <strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wall = [[1],[1],[1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == wall.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li> <li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li> <li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int leastBricks(vector<vector<int>>& wall) { unordered_map<int, int> cnt; for (const auto& row : wall) { int s = 0; for (int i = 0; i + 1 < row.size(); ++i) { s += row[i]; cnt[s]++; } } int mx = 0; for (const auto& [_, x] : cnt) { mx = max(mx, x); } return wall.size() - mx; } };
554
Brick Wall
Medium
<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p> <p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p> <p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</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/0554.Brick%20Wall/images/a.png" style="width: 400px; height: 384px;" /> <pre> <strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wall = [[1],[1],[1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == wall.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li> <li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li> <li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Go
func leastBricks(wall [][]int) int { cnt := map[int]int{} for _, row := range wall { s := 0 for _, x := range row[:len(row)-1] { s += x cnt[s]++ } } mx := 0 for _, x := range cnt { mx = max(mx, x) } return len(wall) - mx }
554
Brick Wall
Medium
<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p> <p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p> <p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</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/0554.Brick%20Wall/images/a.png" style="width: 400px; height: 384px;" /> <pre> <strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wall = [[1],[1],[1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == wall.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li> <li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li> <li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Java
class Solution { public int leastBricks(List<List<Integer>> wall) { Map<Integer, Integer> cnt = new HashMap<>(); for (var row : wall) { int s = 0; for (int i = 0; i + 1 < row.size(); ++i) { s += row.get(i); cnt.merge(s, 1, Integer::sum); } } int mx = 0; for (var x : cnt.values()) { mx = Math.max(mx, x); } return wall.size() - mx; } }
554
Brick Wall
Medium
<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p> <p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p> <p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</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/0554.Brick%20Wall/images/a.png" style="width: 400px; height: 384px;" /> <pre> <strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wall = [[1],[1],[1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == wall.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li> <li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li> <li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
JavaScript
/** * @param {number[][]} wall * @return {number} */ var leastBricks = function (wall) { const cnt = new Map(); for (const row of wall) { let s = 0; for (let i = 0; i + 1 < row.length; ++i) { s += row[i]; cnt.set(s, (cnt.get(s) || 0) + 1); } } const mx = Math.max(...cnt.values(), 0); return wall.length - mx; };
554
Brick Wall
Medium
<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p> <p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p> <p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</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/0554.Brick%20Wall/images/a.png" style="width: 400px; height: 384px;" /> <pre> <strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wall = [[1],[1],[1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == wall.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li> <li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li> <li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Python
class Solution: def leastBricks(self, wall: List[List[int]]) -> int: cnt = Counter() for row in wall: s = 0 for x in row[:-1]: s += x cnt[s] += 1 return len(wall) - max(cnt.values(), default=0)
554
Brick Wall
Medium
<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p> <p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p> <p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</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/0554.Brick%20Wall/images/a.png" style="width: 400px; height: 384px;" /> <pre> <strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> wall = [[1],[1],[1]] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == wall.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li> <li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li> <li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
TypeScript
function leastBricks(wall: number[][]): number { const cnt: Map<number, number> = new Map(); for (const row of wall) { let s = 0; for (let i = 0; i + 1 < row.length; ++i) { s += row[i]; cnt.set(s, (cnt.get(s) || 0) + 1); } } const mx = Math.max(...cnt.values(), 0); return wall.length - mx; }
555
Split Concatenated Strings
Medium
<p>You are given an array of strings <code>strs</code>. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops</p> <p>Return <em>the lexicographically largest string after cutting the loop, which will make the looped string into a regular one</em>.</p> <p>Specifically, to find the lexicographically largest string, you need to experience two phases:</p> <ol> <li>Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.</li> <li>Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.</li> </ol> <p>And your job is to find the lexicographically largest one among all the possible regular strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;,&quot;xyz&quot;] <strong>Output:</strong> &quot;zyxcba&quot; <strong>Explanation:</strong> You can get the looped string &quot;-abcxyz-&quot;, &quot;-abczyx-&quot;, &quot;-cbaxyz-&quot;, &quot;-cbazyx-&quot;, where &#39;-&#39; represents the looped status. The answer string came from the fourth looped one, where you could cut from the middle character &#39;a&#39; and get &quot;zyxcba&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;] <strong>Output:</strong> &quot;cba&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 1000</code></li> <li><code>1 &lt;= strs[i].length &lt;= 1000</code></li> <li><code>1 &lt;= sum(strs[i].length) &lt;= 1000</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String
C++
class Solution { public: string splitLoopedString(vector<string>& strs) { for (auto& s : strs) { string t{s.rbegin(), s.rend()}; s = max(s, t); } int n = strs.size(); string ans = ""; for (int i = 0; i < strs.size(); ++i) { auto& s = strs[i]; string t; for (int j = i + 1; j < n; ++j) { t += strs[j]; } for (int j = 0; j < i; ++j) { t += strs[j]; } for (int j = 0; j < s.size(); ++j) { auto a = s.substr(j); auto b = s.substr(0, j); auto cur = a + t + b; if (ans < cur) { ans = cur; } reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); cur = b + t + a; if (ans < cur) { ans = cur; } } } return ans; } };
555
Split Concatenated Strings
Medium
<p>You are given an array of strings <code>strs</code>. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops</p> <p>Return <em>the lexicographically largest string after cutting the loop, which will make the looped string into a regular one</em>.</p> <p>Specifically, to find the lexicographically largest string, you need to experience two phases:</p> <ol> <li>Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.</li> <li>Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.</li> </ol> <p>And your job is to find the lexicographically largest one among all the possible regular strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;,&quot;xyz&quot;] <strong>Output:</strong> &quot;zyxcba&quot; <strong>Explanation:</strong> You can get the looped string &quot;-abcxyz-&quot;, &quot;-abczyx-&quot;, &quot;-cbaxyz-&quot;, &quot;-cbazyx-&quot;, where &#39;-&#39; represents the looped status. The answer string came from the fourth looped one, where you could cut from the middle character &#39;a&#39; and get &quot;zyxcba&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;] <strong>Output:</strong> &quot;cba&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 1000</code></li> <li><code>1 &lt;= strs[i].length &lt;= 1000</code></li> <li><code>1 &lt;= sum(strs[i].length) &lt;= 1000</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String
Go
func splitLoopedString(strs []string) (ans string) { for i, s := range strs { t := reverse(s) if s < t { strs[i] = t } } for i, s := range strs { sb := &strings.Builder{} for _, w := range strs[i+1:] { sb.WriteString(w) } for _, w := range strs[:i] { sb.WriteString(w) } t := sb.String() for j := 0; j < len(s); j++ { a, b := s[j:], s[0:j] cur := a + t + b if ans < cur { ans = cur } cur = reverse(b) + t + reverse(a) if ans < cur { ans = cur } } } return ans } func reverse(s string) string { t := []byte(s) for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 { t[i], t[j] = t[j], t[i] } return string(t) }
555
Split Concatenated Strings
Medium
<p>You are given an array of strings <code>strs</code>. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops</p> <p>Return <em>the lexicographically largest string after cutting the loop, which will make the looped string into a regular one</em>.</p> <p>Specifically, to find the lexicographically largest string, you need to experience two phases:</p> <ol> <li>Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.</li> <li>Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.</li> </ol> <p>And your job is to find the lexicographically largest one among all the possible regular strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;,&quot;xyz&quot;] <strong>Output:</strong> &quot;zyxcba&quot; <strong>Explanation:</strong> You can get the looped string &quot;-abcxyz-&quot;, &quot;-abczyx-&quot;, &quot;-cbaxyz-&quot;, &quot;-cbazyx-&quot;, where &#39;-&#39; represents the looped status. The answer string came from the fourth looped one, where you could cut from the middle character &#39;a&#39; and get &quot;zyxcba&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;] <strong>Output:</strong> &quot;cba&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 1000</code></li> <li><code>1 &lt;= strs[i].length &lt;= 1000</code></li> <li><code>1 &lt;= sum(strs[i].length) &lt;= 1000</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String
Java
class Solution { public String splitLoopedString(String[] strs) { int n = strs.length; for (int i = 0; i < n; ++i) { String s = strs[i]; String t = new StringBuilder(s).reverse().toString(); if (s.compareTo(t) < 0) { strs[i] = t; } } String ans = ""; for (int i = 0; i < n; ++i) { String s = strs[i]; StringBuilder sb = new StringBuilder(); for (int j = i + 1; j < n; ++j) { sb.append(strs[j]); } for (int j = 0; j < i; ++j) { sb.append(strs[j]); } String t = sb.toString(); for (int j = 0; j < s.length(); ++j) { String a = s.substring(j); String b = s.substring(0, j); String cur = a + t + b; if (ans.compareTo(cur) < 0) { ans = cur; } cur = new StringBuilder(b) .reverse() .append(t) .append(new StringBuilder(a).reverse().toString()) .toString(); if (ans.compareTo(cur) < 0) { ans = cur; } } } return ans; } }
555
Split Concatenated Strings
Medium
<p>You are given an array of strings <code>strs</code>. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops</p> <p>Return <em>the lexicographically largest string after cutting the loop, which will make the looped string into a regular one</em>.</p> <p>Specifically, to find the lexicographically largest string, you need to experience two phases:</p> <ol> <li>Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.</li> <li>Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.</li> </ol> <p>And your job is to find the lexicographically largest one among all the possible regular strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;,&quot;xyz&quot;] <strong>Output:</strong> &quot;zyxcba&quot; <strong>Explanation:</strong> You can get the looped string &quot;-abcxyz-&quot;, &quot;-abczyx-&quot;, &quot;-cbaxyz-&quot;, &quot;-cbazyx-&quot;, where &#39;-&#39; represents the looped status. The answer string came from the fourth looped one, where you could cut from the middle character &#39;a&#39; and get &quot;zyxcba&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;abc&quot;] <strong>Output:</strong> &quot;cba&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 1000</code></li> <li><code>1 &lt;= strs[i].length &lt;= 1000</code></li> <li><code>1 &lt;= sum(strs[i].length) &lt;= 1000</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String
Python
class Solution: def splitLoopedString(self, strs: List[str]) -> str: strs = [s[::-1] if s[::-1] > s else s for s in strs] ans = ''.join(strs) for i, s in enumerate(strs): t = ''.join(strs[i + 1 :]) + ''.join(strs[:i]) for j in range(len(s)): a = s[j:] b = s[:j] ans = max(ans, a + t + b) ans = max(ans, b[::-1] + t + a[::-1]) return ans
556
Next Greater Element III
Medium
<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p> <p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 12 <strong>Output:</strong> 21 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 21 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; String
C++
class Solution { public: int nextGreaterElement(int n) { string s = to_string(n); n = s.size(); int i = n - 2, j = n - 1; for (; i >= 0 && s[i] >= s[i + 1]; --i) ; if (i < 0) return -1; for (; s[i] >= s[j]; --j) ; swap(s[i], s[j]); reverse(s.begin() + i + 1, s.end()); long ans = stol(s); return ans > INT_MAX ? -1 : ans; } };
556
Next Greater Element III
Medium
<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p> <p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 12 <strong>Output:</strong> 21 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 21 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; String
Go
func nextGreaterElement(n int) int { s := []byte(strconv.Itoa(n)) n = len(s) i, j := n-2, n-1 for ; i >= 0 && s[i] >= s[i+1]; i-- { } if i < 0 { return -1 } for ; j >= 0 && s[i] >= s[j]; j-- { } s[i], s[j] = s[j], s[i] for i, j = i+1, n-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } ans, _ := strconv.Atoi(string(s)) if ans > math.MaxInt32 { return -1 } return ans }
556
Next Greater Element III
Medium
<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p> <p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 12 <strong>Output:</strong> 21 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 21 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; String
Java
class Solution { public int nextGreaterElement(int n) { char[] cs = String.valueOf(n).toCharArray(); n = cs.length; int i = n - 2, j = n - 1; for (; i >= 0 && cs[i] >= cs[i + 1]; --i) ; if (i < 0) { return -1; } for (; cs[i] >= cs[j]; --j) ; swap(cs, i, j); reverse(cs, i + 1, n - 1); long ans = Long.parseLong(String.valueOf(cs)); return ans > Integer.MAX_VALUE ? -1 : (int) ans; } private void swap(char[] cs, int i, int j) { char t = cs[i]; cs[i] = cs[j]; cs[j] = t; } private void reverse(char[] cs, int i, int j) { for (; i < j; ++i, --j) { swap(cs, i, j); } } }
556
Next Greater Element III
Medium
<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p> <p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 12 <strong>Output:</strong> 21 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 21 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Two Pointers; String
Python
class Solution: def nextGreaterElement(self, n: int) -> int: cs = list(str(n)) n = len(cs) i, j = n - 2, n - 1 while i >= 0 and cs[i] >= cs[i + 1]: i -= 1 if i < 0: return -1 while cs[i] >= cs[j]: j -= 1 cs[i], cs[j] = cs[j], cs[i] cs[i + 1 :] = cs[i + 1 :][::-1] ans = int(''.join(cs)) return -1 if ans > 2**31 - 1 else ans
557
Reverse Words in a String III
Easy
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Let&#39;s take LeetCode contest&quot; <strong>Output:</strong> &quot;s&#39;teL ekat edoCteeL tsetnoc&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Mr Ding&quot; <strong>Output:</strong> &quot;rM gniD&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> contains printable <strong>ASCII</strong> characters.</li> <li><code>s</code> does not contain any leading or trailing spaces.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li>All the words in <code>s</code> are separated by a single space.</li> </ul>
Two Pointers; String
C++
class Solution { public: string reverseWords(string s) { stringstream ss(s); string t; string ans; while (ss >> t) { reverse(t.begin(), t.end()); ans += t; ans.push_back(' '); } ans.pop_back(); return ans; } };
557
Reverse Words in a String III
Easy
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Let&#39;s take LeetCode contest&quot; <strong>Output:</strong> &quot;s&#39;teL ekat edoCteeL tsetnoc&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Mr Ding&quot; <strong>Output:</strong> &quot;rM gniD&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> contains printable <strong>ASCII</strong> characters.</li> <li><code>s</code> does not contain any leading or trailing spaces.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li>All the words in <code>s</code> are separated by a single space.</li> </ul>
Two Pointers; String
Go
func reverseWords(s string) string { words := strings.Fields(s) for i, w := range words { t := []byte(w) slices.Reverse(t) words[i] = string(t) } return strings.Join(words, " ") }
557
Reverse Words in a String III
Easy
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Let&#39;s take LeetCode contest&quot; <strong>Output:</strong> &quot;s&#39;teL ekat edoCteeL tsetnoc&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Mr Ding&quot; <strong>Output:</strong> &quot;rM gniD&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> contains printable <strong>ASCII</strong> characters.</li> <li><code>s</code> does not contain any leading or trailing spaces.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li>All the words in <code>s</code> are separated by a single space.</li> </ul>
Two Pointers; String
Java
class Solution { public String reverseWords(String s) { String[] words = s.split(" "); for (int i = 0; i < words.length; ++i) { words[i] = new StringBuilder(words[i]).reverse().toString(); } return String.join(" ", words); } }