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
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int calculateMinimumHP(int[][] dungeon) { int m = dungeon.length, n = dungeon[0].length; int[][] dp = new int[m + 1][n + 1]; for (var e : dp) { Arrays.fill(e, 1 << 30); } dp[m][n - 1] = dp[m - 1][n] = 1; for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); } } return dp[0][0]; } }
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m, n = len(dungeon), len(dungeon[0]) dp = [[inf] * (n + 1) for _ in range(m + 1)] dp[m][n - 1] = dp[m - 1][n] = 1 for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]) return dp[0][0]
175
Combine Two Tables
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | personId | int | | lastName | varchar | | firstName | varchar | +-------------+---------+ personId is the primary key (column with unique values) for this table. This table contains information about the ID of some persons and their first and last names. </pre> <p>&nbsp;</p> <p>Table: <code>Address</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | addressId | int | | personId | int | | city | varchar | | state | varchar | +-------------+---------+ addressId is the primary key (column with unique values) for this table. Each row of this table contains information about the city and state of one person with ID = PersonId. </pre> <p>&nbsp;</p> <p>Write a solution to report the first name, last name, city, and state of each person in the <code>Person</code> table. If the address of a <code>personId</code> is not present in the <code>Address</code> table, report <code>null</code> instead.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----------+----------+-----------+ | personId | lastName | firstName | +----------+----------+-----------+ | 1 | Wang | Allen | | 2 | Alice | Bob | +----------+----------+-----------+ Address table: +-----------+----------+---------------+------------+ | addressId | personId | city | state | +-----------+----------+---------------+------------+ | 1 | 2 | New York City | New York | | 2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ <strong>Output:</strong> +-----------+----------+---------------+----------+ | firstName | lastName | city | state | +-----------+----------+---------------+----------+ | Allen | Wang | Null | Null | | Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ <strong>Explanation:</strong> There is no address in the address table for the personId = 1 so we return null in their city and state. addressId = 1 contains information about the address of personId = 2. </pre>
Database
Python
import pandas as pd def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame: return pd.merge(left=person, right=address, how="left", on="personId")[ ["firstName", "lastName", "city", "state"] ]
175
Combine Two Tables
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | personId | int | | lastName | varchar | | firstName | varchar | +-------------+---------+ personId is the primary key (column with unique values) for this table. This table contains information about the ID of some persons and their first and last names. </pre> <p>&nbsp;</p> <p>Table: <code>Address</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | addressId | int | | personId | int | | city | varchar | | state | varchar | +-------------+---------+ addressId is the primary key (column with unique values) for this table. Each row of this table contains information about the city and state of one person with ID = PersonId. </pre> <p>&nbsp;</p> <p>Write a solution to report the first name, last name, city, and state of each person in the <code>Person</code> table. If the address of a <code>personId</code> is not present in the <code>Address</code> table, report <code>null</code> instead.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----------+----------+-----------+ | personId | lastName | firstName | +----------+----------+-----------+ | 1 | Wang | Allen | | 2 | Alice | Bob | +----------+----------+-----------+ Address table: +-----------+----------+---------------+------------+ | addressId | personId | city | state | +-----------+----------+---------------+------------+ | 1 | 2 | New York City | New York | | 2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ <strong>Output:</strong> +-----------+----------+---------------+----------+ | firstName | lastName | city | state | +-----------+----------+---------------+----------+ | Allen | Wang | Null | Null | | Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ <strong>Explanation:</strong> There is no address in the address table for the personId = 1 so we return null in their city and state. addressId = 1 contains information about the address of personId = 2. </pre>
Database
SQL
# Write your MySQL query statement below SELECT firstName, lastName, city, state FROM Person LEFT JOIN Address USING (personId);
176
Second Highest Salary
Medium
<p>Table: <code>Employee</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values) for this table. Each row of this table contains information about the salary of an employee. </pre> <p>&nbsp;</p> <p>Write a solution to find&nbsp;the second highest <strong>distinct</strong> salary from the <code>Employee</code> table. If there is no second highest salary,&nbsp;return&nbsp;<code>null (return&nbsp;None in Pandas)</code>.</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> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ <strong>Output:</strong> +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ <strong>Output:</strong> +---------------------+ | SecondHighestSalary | +---------------------+ | null | +---------------------+ </pre>
Database
Python
import pandas as pd def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame: # Drop any duplicate salary values to avoid counting duplicates as separate salary ranks unique_salaries = employee["salary"].drop_duplicates() # Sort the unique salaries in descending order and get the second highest salary second_highest = ( unique_salaries.nlargest(2).iloc[-1] if len(unique_salaries) >= 2 else None ) # If the second highest salary doesn't exist (e.g., there are fewer than two unique salaries), return None if second_highest is None: return pd.DataFrame({"SecondHighestSalary": [None]}) # Create a DataFrame with the second highest salary result_df = pd.DataFrame({"SecondHighestSalary": [second_highest]}) return result_df
176
Second Highest Salary
Medium
<p>Table: <code>Employee</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values) for this table. Each row of this table contains information about the salary of an employee. </pre> <p>&nbsp;</p> <p>Write a solution to find&nbsp;the second highest <strong>distinct</strong> salary from the <code>Employee</code> table. If there is no second highest salary,&nbsp;return&nbsp;<code>null (return&nbsp;None in Pandas)</code>.</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> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ <strong>Output:</strong> +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ <strong>Output:</strong> +---------------------+ | SecondHighestSalary | +---------------------+ | null | +---------------------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT ( SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1, 1 ) AS SecondHighestSalary;
177
Nth Highest Salary
Medium
<p>Table: <code>Employee</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values) for this table. Each row of this table contains information about the salary of an employee. </pre> <p>&nbsp;</p> <p>Write a solution to find the <code>n<sup>th</sup></code> highest <strong>distinct</strong> salary from the <code>Employee</code> table. If there are less than <code>n</code> distinct salaries, return&nbsp;<code>null</code>.</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> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ n = 2 <strong>Output:</strong> +------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+ </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ n = 2 <strong>Output:</strong> +------------------------+ | getNthHighestSalary(2) | +------------------------+ | null | +------------------------+ </pre>
Database
Python
import pandas as pd def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame: unique_salaries = employee.salary.unique() if len(unique_salaries) < N: return pd.DataFrame([np.NaN], columns=[f"getNthHighestSalary({N})"]) else: salary = sorted(unique_salaries, reverse=True)[N - 1] return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"])
177
Nth Highest Salary
Medium
<p>Table: <code>Employee</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values) for this table. Each row of this table contains information about the salary of an employee. </pre> <p>&nbsp;</p> <p>Write a solution to find the <code>n<sup>th</sup></code> highest <strong>distinct</strong> salary from the <code>Employee</code> table. If there are less than <code>n</code> distinct salaries, return&nbsp;<code>null</code>.</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> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ n = 2 <strong>Output:</strong> +------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+ </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ n = 2 <strong>Output:</strong> +------------------------+ | getNthHighestSalary(2) | +------------------------+ | null | +------------------------+ </pre>
Database
SQL
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN SET N = N - 1; RETURN ( # Write your MySQL query statement below. SELECT ( SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET N ) ); END
178
Rank Scores
Medium
<p>Table: <code>Scores</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | score | decimal | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains the score of a game. Score is a floating point value with two decimal places. </pre> <p>&nbsp;</p> <p>Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:</p> <ul> <li>The scores should be ranked from the highest to the lowest.</li> <li>If there is a tie between two scores, both should have the same ranking.</li> <li>After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.</li> </ul> <p>Return the result table ordered by <code>score</code> in descending order.</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> Scores table: +----+-------+ | id | score | +----+-------+ | 1 | 3.50 | | 2 | 3.65 | | 3 | 4.00 | | 4 | 3.85 | | 5 | 4.00 | | 6 | 3.65 | +----+-------+ <strong>Output:</strong> +-------+------+ | score | rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+ </pre>
Database
Python
import pandas as pd def order_scores(scores: pd.DataFrame) -> pd.DataFrame: # Use the rank method to assign ranks to the scores in descending order with no gaps scores["rank"] = scores["score"].rank(method="dense", ascending=False) # Drop id column & Sort the DataFrame by score in descending order result_df = scores.drop("id", axis=1).sort_values(by="score", ascending=False) return result_df
178
Rank Scores
Medium
<p>Table: <code>Scores</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | score | decimal | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains the score of a game. Score is a floating point value with two decimal places. </pre> <p>&nbsp;</p> <p>Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:</p> <ul> <li>The scores should be ranked from the highest to the lowest.</li> <li>If there is a tie between two scores, both should have the same ranking.</li> <li>After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.</li> </ul> <p>Return the result table ordered by <code>score</code> in descending order.</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> Scores table: +----+-------+ | id | score | +----+-------+ | 1 | 3.50 | | 2 | 3.65 | | 3 | 4.00 | | 4 | 3.85 | | 5 | 4.00 | | 6 | 3.65 | +----+-------+ <strong>Output:</strong> +-------+------+ | score | rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT score, DENSE_RANK() OVER (ORDER BY score DESC) AS 'rank' FROM Scores;
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
C++
class Solution { public: string largestNumber(vector<int>& nums) { vector<string> vs; for (int v : nums) vs.push_back(to_string(v)); sort(vs.begin(), vs.end(), [](string& a, string& b) { return a + b > b + a; }); if (vs[0] == "0") return "0"; string ans; for (string v : vs) ans += v; return ans; } };
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
C#
using System; using System.Globalization; using System.Collections.Generic; using System.Linq; using System.Text; public class Comparer: IComparer<string> { public int Compare(string left, string right) { return Compare(left, right, 0, 0); } private int Compare(string left, string right, int lBegin, int rBegin) { var len = Math.Min(left.Length - lBegin, right.Length - rBegin); for (var i = 0; i < len; ++i) { if (left[lBegin + i] != right[rBegin + i]) { return left[lBegin + i] < right[rBegin + i] ? -1 : 1; } } if (left.Length - lBegin == right.Length - rBegin) { return 0; } if (left.Length - lBegin > right.Length - rBegin) { return Compare(left, right, lBegin + len, rBegin); } else { return Compare(left, right, lBegin, rBegin + len); } } } public class Solution { public string LargestNumber(int[] nums) { var sb = new StringBuilder(); var strs = nums.Select(n => n.ToString(CultureInfo.InvariantCulture)).OrderByDescending(s => s, new Comparer()); var nonZeroOccurred = false; foreach (var str in strs) { if (!nonZeroOccurred && str == "0") continue; sb.Append(str); nonZeroOccurred = true; } return sb.Length == 0 ? "0" : sb.ToString(); } }
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
Go
func largestNumber(nums []int) string { vs := make([]string, len(nums)) for i, v := range nums { vs[i] = strconv.Itoa(v) } sort.Slice(vs, func(i, j int) bool { return vs[i]+vs[j] > vs[j]+vs[i] }) if vs[0] == "0" { return "0" } return strings.Join(vs, "") }
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
Java
class Solution { public String largestNumber(int[] nums) { List<String> vs = new ArrayList<>(); for (int v : nums) { vs.add(v + ""); } vs.sort((a, b) -> (b + a).compareTo(a + b)); if ("0".equals(vs.get(0))) { return "0"; } return String.join("", vs); } }
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
JavaScript
function largestNumber(nums) { nums.sort((a, b) => { const [ab, ba] = [String(a) + String(b), String(b) + String(a)]; return +ba - +ab; }); return nums[0] ? nums.join('') : '0'; }
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
Python
class Solution: def largestNumber(self, nums: List[int]) -> str: nums = [str(v) for v in nums] nums.sort(key=cmp_to_key(lambda a, b: 1 if a + b < b + a else -1)) return "0" if nums[0] == "0" else "".join(nums)
179
Largest Number
Medium
<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p> <p>Since the result may be very large, so you need to return a string instead of an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,2] <strong>Output:</strong> &quot;210&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,30,34,5,9] <strong>Output:</strong> &quot;9534330&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; String; Sorting
TypeScript
function largestNumber(nums: number[]): string { nums.sort((a, b) => { const [ab, ba] = [String(a) + String(b), String(b) + String(a)]; return +ba - +ab; }); return nums[0] ? nums.join('') : '0'; }
180
Consecutive Numbers
Medium
<p>Table: <code>Logs</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ In SQL, id is the primary key for this table. id is an autoincrement column starting from 1. </pre> <p>&nbsp;</p> <p>Find all numbers that appear at least three times consecutively.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Logs table: +----+-----+ | id | num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+ <strong>Output:</strong> +-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+ <strong>Explanation:</strong> 1 is the only number that appears consecutively for at least three times. </pre>
Database
Python
import pandas as pd def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: all_the_same = lambda lst: lst.nunique() == 1 logs["is_consecutive"] = ( logs["num"].rolling(window=3, center=True, min_periods=3).apply(all_the_same) ) return ( logs.query("is_consecutive == 1.0")[["num"]] .drop_duplicates() .rename(columns={"num": "ConsecutiveNums"}) )
180
Consecutive Numbers
Medium
<p>Table: <code>Logs</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ In SQL, id is the primary key for this table. id is an autoincrement column starting from 1. </pre> <p>&nbsp;</p> <p>Find all numbers that appear at least three times consecutively.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Logs table: +----+-----+ | id | num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+ <strong>Output:</strong> +-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+ <strong>Explanation:</strong> 1 is the only number that appears consecutively for at least three times. </pre>
Database
SQL
# Write your MySQL query statement below SELECT DISTINCT l2.num AS ConsecutiveNums FROM Logs AS l1 JOIN Logs AS l2 ON l1.id = l2.id - 1 AND l1.num = l2.num JOIN Logs AS l3 ON l2.id = l3.id - 1 AND l2.num = l3.num;
181
Employees Earning More Than Their Managers
Easy
<p>Table: <code>Employee</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | salary | int | | managerId | int | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager. </pre> <p>&nbsp;</p> <p>Write a solution&nbsp;to find the employees who earn more than their managers.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+-------+--------+-----------+ | id | name | salary | managerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | Null | | 4 | Max | 90000 | Null | +----+-------+--------+-----------+ <strong>Output:</strong> +----------+ | Employee | +----------+ | Joe | +----------+ <strong>Explanation:</strong> Joe is the only employee who earns more than his manager. </pre>
Database
Python
import pandas as pd def find_employees(employee: pd.DataFrame) -> pd.DataFrame: merged = employee.merge( employee, left_on="managerId", right_on="id", suffixes=("", "_manager") ) result = merged[merged["salary"] > merged["salary_manager"]][["name"]] result.columns = ["Employee"] return result
181
Employees Earning More Than Their Managers
Easy
<p>Table: <code>Employee</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | salary | int | | managerId | int | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager. </pre> <p>&nbsp;</p> <p>Write a solution&nbsp;to find the employees who earn more than their managers.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+-------+--------+-----------+ | id | name | salary | managerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | Null | | 4 | Max | 90000 | Null | +----+-------+--------+-----------+ <strong>Output:</strong> +----------+ | Employee | +----------+ | Joe | +----------+ <strong>Explanation:</strong> Joe is the only employee who earns more than his manager. </pre>
Database
SQL
# Write your MySQL query statement below SELECT e1.name Employee FROM Employee e1 JOIN Employee e2 ON e1.managerId = e2.id WHERE e1.salary > e2.salary;
182
Duplicate Emails
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains an email. The emails will not contain uppercase letters. </pre> <p>&nbsp;</p> <p>Write a solution to report all the duplicate emails. Note that it&#39;s guaranteed that the email&nbsp;field is not NULL.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----+---------+ | id | email | +----+---------+ | 1 | a@b.com | | 2 | c@d.com | | 3 | a@b.com | +----+---------+ <strong>Output:</strong> +---------+ | Email | +---------+ | a@b.com | +---------+ <strong>Explanation:</strong> a@b.com is repeated two times. </pre>
Database
Python
import pandas as pd def duplicate_emails(person: pd.DataFrame) -> pd.DataFrame: results = pd.DataFrame() results = person.loc[person.duplicated(subset=["email"]), ["email"]] return results.drop_duplicates()
182
Duplicate Emails
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains an email. The emails will not contain uppercase letters. </pre> <p>&nbsp;</p> <p>Write a solution to report all the duplicate emails. Note that it&#39;s guaranteed that the email&nbsp;field is not NULL.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----+---------+ | id | email | +----+---------+ | 1 | a@b.com | | 2 | c@d.com | | 3 | a@b.com | +----+---------+ <strong>Output:</strong> +---------+ | Email | +---------+ | a@b.com | +---------+ <strong>Explanation:</strong> a@b.com is repeated two times. </pre>
Database
SQL
# Write your MySQL query statement below SELECT email FROM Person GROUP BY 1 HAVING COUNT(1) > 1;
183
Customers Who Never Order
Easy
<p>Table: <code>Customers</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID and name of a customer. </pre> <p>&nbsp;</p> <p>Table: <code>Orders</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | customerId | int | +-------------+------+ id is the primary key (column with unique values) for this table. customerId is a foreign key (reference columns) of the ID from the Customers table. Each row of this table indicates the ID of an order and the ID of the customer who ordered it. </pre> <p>&nbsp;</p> <p>Write a solution to find all customers who never order anything.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Customers table: +----+-------+ | id | name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+ Orders table: +----+------------+ | id | customerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+ <strong>Output:</strong> +-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+ </pre>
Database
Python
import pandas as pd def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column. df = customers[~customers["id"].isin(orders["customerId"])] # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'. df = df[["name"]].rename(columns={"name": "Customers"}) return df
183
Customers Who Never Order
Easy
<p>Table: <code>Customers</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID and name of a customer. </pre> <p>&nbsp;</p> <p>Table: <code>Orders</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | customerId | int | +-------------+------+ id is the primary key (column with unique values) for this table. customerId is a foreign key (reference columns) of the ID from the Customers table. Each row of this table indicates the ID of an order and the ID of the customer who ordered it. </pre> <p>&nbsp;</p> <p>Write a solution to find all customers who never order anything.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Customers table: +----+-------+ | id | name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+ Orders table: +----+------------+ | id | customerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+ <strong>Output:</strong> +-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT name AS Customers FROM Customers WHERE id NOT IN ( SELECT customerId FROM Orders );
184
Department Highest Salary
Medium
<p>Table: <code>Employee</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | id | int | | name | varchar | | salary | int | | departmentId | int | +--------------+---------+ id is the primary key (column with unique values) for this table. departmentId is a foreign key (reference columns) of the ID from the <code>Department </code>table. Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. </pre> <p>&nbsp;</p> <p>Table: <code>Department</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. It is guaranteed that department name is not <code>NULL.</code> Each row of this table indicates the ID of a department and its name. </pre> <p>&nbsp;</p> <p>Write a solution to find employees who have the highest salary in each of the departments.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+-------+--------+--------------+ | id | name | salary | departmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Jim | 90000 | 1 | | 3 | Henry | 80000 | 2 | | 4 | Sam | 60000 | 2 | | 5 | Max | 90000 | 1 | +----+-------+--------+--------------+ Department table: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ <strong>Output:</strong> +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Jim | 90000 | | Sales | Henry | 80000 | | IT | Max | 90000 | +------------+----------+--------+ <strong>Explanation:</strong> Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department. </pre>
Database
Python
import pandas as pd def department_highest_salary( employee: pd.DataFrame, department: pd.DataFrame ) -> pd.DataFrame: # Merge the two tables on departmentId and department id merged = employee.merge(department, left_on='departmentId', right_on='id') # Find the maximum salary for each department max_salaries = merged.groupby('departmentId')['salary'].transform('max') # Filter employees who have the highest salary in their department top_earners = merged[merged['salary'] == max_salaries] # Select required columns and rename them result = top_earners[['name_y', 'name_x', 'salary']].copy() result.columns = ['Department', 'Employee', 'Salary'] return result
184
Department Highest Salary
Medium
<p>Table: <code>Employee</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | id | int | | name | varchar | | salary | int | | departmentId | int | +--------------+---------+ id is the primary key (column with unique values) for this table. departmentId is a foreign key (reference columns) of the ID from the <code>Department </code>table. Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. </pre> <p>&nbsp;</p> <p>Table: <code>Department</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. It is guaranteed that department name is not <code>NULL.</code> Each row of this table indicates the ID of a department and its name. </pre> <p>&nbsp;</p> <p>Write a solution to find employees who have the highest salary in each of the departments.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+-------+--------+--------------+ | id | name | salary | departmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Jim | 90000 | 1 | | 3 | Henry | 80000 | 2 | | 4 | Sam | 60000 | 2 | | 5 | Max | 90000 | 1 | +----+-------+--------+--------------+ Department table: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ <strong>Output:</strong> +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Jim | 90000 | | Sales | Henry | 80000 | | IT | Max | 90000 | +------------+----------+--------+ <strong>Explanation:</strong> Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department. </pre>
Database
SQL
# Write your MySQL query statement below SELECT d.name AS department, e.name AS employee, salary FROM Employee AS e JOIN Department AS d ON e.departmentId = d.id WHERE (d.id, salary) IN ( SELECT departmentId, MAX(salary) FROM Employee GROUP BY 1 );
185
Department Top Three Salaries
Hard
<p>Table: <code>Employee</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | id | int | | name | varchar | | salary | int | | departmentId | int | +--------------+---------+ id is the primary key (column with unique values) for this table. departmentId is a foreign key (reference column) of the ID from the <code>Department </code>table. Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. </pre> <p>&nbsp;</p> <p>Table: <code>Department</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID of a department and its name. </pre> <p>&nbsp;</p> <p>A company&#39;s executives are interested in seeing who earns the most money in each of the company&#39;s departments. A <strong>high earner</strong> in a department is an employee who has a salary in the <strong>top three unique</strong> salaries for that department.</p> <p>Write a solution to find the employees who are <strong>high earners</strong> in each of the departments.</p> <p>Return the result table <strong>in any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+-------+--------+--------------+ | id | name | salary | departmentId | +----+-------+--------+--------------+ | 1 | Joe | 85000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 | | 5 | Janet | 69000 | 1 | | 6 | Randy | 85000 | 1 | | 7 | Will | 70000 | 1 | +----+-------+--------+--------------+ Department table: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ <strong>Output:</strong> +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | IT | Joe | 85000 | | IT | Randy | 85000 | | IT | Will | 70000 | | Sales | Henry | 80000 | | Sales | Sam | 60000 | +------------+----------+--------+ <strong>Explanation:</strong> In the IT department: - Max earns the highest unique salary - Both Randy and Joe earn the second-highest unique salary - Will earns the third-highest unique salary In the Sales department: - Henry earns the highest salary - Sam earns the second-highest salary - There is no third-highest salary as there are only two employees </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>There are no employees with the <strong>exact</strong> same name, salary <em>and</em> department.</li> </ul>
Database
Python
import pandas as pd def top_three_salaries( employee: pd.DataFrame, department: pd.DataFrame ) -> pd.DataFrame: salary_cutoff = ( employee.drop_duplicates(["salary", "departmentId"]) .groupby("departmentId")["salary"] .nlargest(3) .groupby("departmentId") .min() ) employee["Department"] = department.set_index("id")["name"][ employee["departmentId"] ].values employee["cutoff"] = salary_cutoff[employee["departmentId"]].values return employee[employee["salary"] >= employee["cutoff"]].rename( columns={"name": "Employee", "salary": "Salary"} )[["Department", "Employee", "Salary"]]
185
Department Top Three Salaries
Hard
<p>Table: <code>Employee</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | id | int | | name | varchar | | salary | int | | departmentId | int | +--------------+---------+ id is the primary key (column with unique values) for this table. departmentId is a foreign key (reference column) of the ID from the <code>Department </code>table. Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. </pre> <p>&nbsp;</p> <p>Table: <code>Department</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID of a department and its name. </pre> <p>&nbsp;</p> <p>A company&#39;s executives are interested in seeing who earns the most money in each of the company&#39;s departments. A <strong>high earner</strong> in a department is an employee who has a salary in the <strong>top three unique</strong> salaries for that department.</p> <p>Write a solution to find the employees who are <strong>high earners</strong> in each of the departments.</p> <p>Return the result table <strong>in any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Employee table: +----+-------+--------+--------------+ | id | name | salary | departmentId | +----+-------+--------+--------------+ | 1 | Joe | 85000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 | | 5 | Janet | 69000 | 1 | | 6 | Randy | 85000 | 1 | | 7 | Will | 70000 | 1 | +----+-------+--------+--------------+ Department table: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ <strong>Output:</strong> +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | IT | Joe | 85000 | | IT | Randy | 85000 | | IT | Will | 70000 | | Sales | Henry | 80000 | | Sales | Sam | 60000 | +------------+----------+--------+ <strong>Explanation:</strong> In the IT department: - Max earns the highest unique salary - Both Randy and Joe earn the second-highest unique salary - Will earns the third-highest unique salary In the Sales department: - Henry earns the highest salary - Sam earns the second-highest salary - There is no third-highest salary as there are only two employees </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>There are no employees with the <strong>exact</strong> same name, salary <em>and</em> department.</li> </ul>
Database
SQL
SELECT Department.NAME AS Department, Employee.NAME AS Employee, Salary FROM Employee, Department WHERE Employee.DepartmentId = Department.Id AND ( SELECT COUNT(DISTINCT e2.Salary) FROM Employee AS e2 WHERE e2.Salary > Employee.Salary AND Employee.DepartmentId = e2.DepartmentId ) < 3;
186
Reverse Words in a String II
Medium
<p>Given a character array <code>s</code>, reverse the order of the <strong>words</strong>.</p> <p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by a single space.</p> <p>Your code must solve the problem&nbsp;<strong>in-place,</strong> i.e. without allocating extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] <strong>Output:</strong> ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["a"] <strong>Output:</strong> ["a"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is an English letter (uppercase or lowercase), digit, or space <code>&#39; &#39;</code>.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li><code>s</code> does not contain leading or trailing spaces.</li> <li>All the words in <code>s</code> are guaranteed to be separated by a single space.</li> </ul>
Two Pointers; String
C++
class Solution { public: void reverseWords(vector<char>& s) { auto reverse = [&](int i, int j) { for (; i < j; ++i, --j) { swap(s[i], s[j]); } }; int n = s.size(); for (int i = 0, j = 0; j < n; ++j) { if (s[j] == ' ') { reverse(i, j - 1); i = j + 1; } else if (j == n - 1) { reverse(i, j); } } reverse(0, n - 1); } };
186
Reverse Words in a String II
Medium
<p>Given a character array <code>s</code>, reverse the order of the <strong>words</strong>.</p> <p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by a single space.</p> <p>Your code must solve the problem&nbsp;<strong>in-place,</strong> i.e. without allocating extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] <strong>Output:</strong> ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["a"] <strong>Output:</strong> ["a"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is an English letter (uppercase or lowercase), digit, or space <code>&#39; &#39;</code>.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li><code>s</code> does not contain leading or trailing spaces.</li> <li>All the words in <code>s</code> are guaranteed to be separated by a single space.</li> </ul>
Two Pointers; String
Go
func reverseWords(s []byte) { reverse := func(i, j int) { for ; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } i, n := 0, len(s) for j, c := range s { if c == ' ' { reverse(i, j-1) i = j + 1 } else if j == n-1 { reverse(i, j) } } reverse(0, n-1) }
186
Reverse Words in a String II
Medium
<p>Given a character array <code>s</code>, reverse the order of the <strong>words</strong>.</p> <p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by a single space.</p> <p>Your code must solve the problem&nbsp;<strong>in-place,</strong> i.e. without allocating extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] <strong>Output:</strong> ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["a"] <strong>Output:</strong> ["a"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is an English letter (uppercase or lowercase), digit, or space <code>&#39; &#39;</code>.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li><code>s</code> does not contain leading or trailing spaces.</li> <li>All the words in <code>s</code> are guaranteed to be separated by a single space.</li> </ul>
Two Pointers; String
Java
class Solution { public void reverseWords(char[] s) { int n = s.length; for (int i = 0, j = 0; j < n; ++j) { if (s[j] == ' ') { reverse(s, i, j - 1); i = j + 1; } else if (j == n - 1) { reverse(s, i, j); } } reverse(s, 0, n - 1); } private void reverse(char[] s, int i, int j) { for (; i < j; ++i, --j) { char t = s[i]; s[i] = s[j]; s[j] = t; } } }
186
Reverse Words in a String II
Medium
<p>Given a character array <code>s</code>, reverse the order of the <strong>words</strong>.</p> <p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by a single space.</p> <p>Your code must solve the problem&nbsp;<strong>in-place,</strong> i.e. without allocating extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] <strong>Output:</strong> ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["a"] <strong>Output:</strong> ["a"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is an English letter (uppercase or lowercase), digit, or space <code>&#39; &#39;</code>.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li><code>s</code> does not contain leading or trailing spaces.</li> <li>All the words in <code>s</code> are guaranteed to be separated by a single space.</li> </ul>
Two Pointers; String
Python
class Solution: def reverseWords(self, s: List[str]) -> None: def reverse(i: int, j: int): while i < j: s[i], s[j] = s[j], s[i] i, j = i + 1, j - 1 i, n = 0, len(s) for j, c in enumerate(s): if c == " ": reverse(i, j - 1) i = j + 1 elif j == n - 1: reverse(i, j) reverse(0, n - 1)
186
Reverse Words in a String II
Medium
<p>Given a character array <code>s</code>, reverse the order of the <strong>words</strong>.</p> <p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by a single space.</p> <p>Your code must solve the problem&nbsp;<strong>in-place,</strong> i.e. without allocating extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] <strong>Output:</strong> ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["a"] <strong>Output:</strong> ["a"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is an English letter (uppercase or lowercase), digit, or space <code>&#39; &#39;</code>.</li> <li>There is <strong>at least one</strong> word in <code>s</code>.</li> <li><code>s</code> does not contain leading or trailing spaces.</li> <li>All the words in <code>s</code> are guaranteed to be separated by a single space.</li> </ul>
Two Pointers; String
TypeScript
/** Do not return anything, modify s in-place instead. */ function reverseWords(s: string[]): void { const n = s.length; const reverse = (i: number, j: number): void => { for (; i < j; ++i, --j) { [s[i], s[j]] = [s[j], s[i]]; } }; for (let i = 0, j = 0; j <= n; ++j) { if (s[j] === ' ') { reverse(i, j - 1); i = j + 1; } else if (j === n - 1) { reverse(i, j); } } reverse(0, n - 1); }
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
C++
class Solution { public: vector<string> findRepeatedDnaSequences(string s) { unordered_map<string, int> cnt; vector<string> ans; for (int i = 0, n = s.size() - 10 + 1; i < n; ++i) { auto t = s.substr(i, 10); if (++cnt[t] == 2) { ans.emplace_back(t); } } return ans; } };
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
C#
public class Solution { public IList<string> FindRepeatedDnaSequences(string s) { var cnt = new Dictionary<string, int>(); var ans = new List<string>(); for (int i = 0; i < s.Length - 10 + 1; ++i) { var t = s.Substring(i, 10); if (!cnt.ContainsKey(t)) { cnt[t] = 0; } if (++cnt[t] == 2) { ans.Add(t); } } return ans; } }
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
Go
func findRepeatedDnaSequences(s string) (ans []string) { cnt := map[string]int{} for i := 0; i < len(s)-10+1; i++ { t := s[i : i+10] cnt[t]++ if cnt[t] == 2 { ans = append(ans, t) } } return }
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
Java
class Solution { public List<String> findRepeatedDnaSequences(String s) { Map<String, Integer> cnt = new HashMap<>(); List<String> ans = new ArrayList<>(); for (int i = 0; i < s.length() - 10 + 1; ++i) { String t = s.substring(i, i + 10); if (cnt.merge(t, 1, Integer::sum) == 2) { ans.add(t); } } return ans; } }
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
JavaScript
/** * @param {string} s * @return {string[]} */ var findRepeatedDnaSequences = function (s) { const cnt = new Map(); const ans = []; for (let i = 0; i < s.length - 10 + 1; ++i) { const t = s.slice(i, i + 10); cnt.set(t, (cnt.get(t) || 0) + 1); if (cnt.get(t) === 2) { ans.push(t); } } return ans; };
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
Python
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: cnt = Counter() ans = [] for i in range(len(s) - 10 + 1): t = s[i : i + 10] cnt[t] += 1 if cnt[t] == 2: ans.append(t) return ans
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
Rust
use std::collections::HashMap; impl Solution { pub fn find_repeated_dna_sequences(s: String) -> Vec<String> { if s.len() < 10 { return vec![]; } let mut cnt = HashMap::new(); let mut ans = Vec::new(); for i in 0..s.len() - 9 { let t = &s[i..i + 10]; let count = cnt.entry(t).or_insert(0); *count += 1; if *count == 2 { ans.push(t.to_string()); } } ans } }
187
Repeated DNA Sequences
Medium
<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <ul> <li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li> </ul> <p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p> <p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" <strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "AAAAAAAAAAAAA" <strong>Output:</strong> ["AAAAAAAAAA"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li> </ul>
Bit Manipulation; Hash Table; String; Sliding Window; Hash Function; Rolling Hash
TypeScript
function findRepeatedDnaSequences(s: string): string[] { const n = s.length; const cnt: Map<string, number> = new Map(); const ans: string[] = []; for (let i = 0; i <= n - 10; ++i) { const t = s.slice(i, i + 10); cnt.set(t, (cnt.get(t) ?? 0) + 1); if (cnt.get(t) === 2) { ans.push(t); } } return ans; }
188
Best Time to Buy and Sell Stock IV
Hard
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [2,4,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 100</code></li> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>0 &lt;= prices[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); int f[n][k + 1][2]; memset(f, -1, sizeof(f)); function<int(int, int, int)> dfs = [&](int i, int j, int k) -> int { if (i >= n) { return 0; } if (f[i][j][k] != -1) { return f[i][j][k]; } int ans = dfs(i + 1, j, k); if (k) { ans = max(ans, prices[i] + dfs(i + 1, j, 0)); } else if (j) { ans = max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); } return f[i][j][k] = ans; }; return dfs(0, k, 0); } };
188
Best Time to Buy and Sell Stock IV
Hard
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [2,4,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 100</code></li> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>0 &lt;= prices[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { private int[,,] f; private int[] prices; private int n; public int MaxProfit(int k, int[] prices) { n = prices.Length; f = new int[n, k + 1, 2]; this.prices = prices; for (int i = 0; i < n; ++i) { for (int j = 0; j <= k; ++j) { f[i, j, 0] = -1; f[i, j, 1] = -1; } } return dfs(0, k, 0); } private int dfs(int i, int j, int k) { if (i >= n) { return 0; } if (f[i, j, k] != -1) { return f[i, j, k]; } int ans = dfs(i + 1, j, k); if (k > 0) { ans = Math.Max(ans, prices[i] + dfs(i + 1, j, 0)); } else if (j > 0) { ans = Math.Max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); } return f[i, j, k] = ans; } }
188
Best Time to Buy and Sell Stock IV
Hard
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [2,4,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 100</code></li> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>0 &lt;= prices[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Go
func maxProfit(k int, prices []int) int { n := len(prices) f := make([][][2]int, n) for i := range f { f[i] = make([][2]int, k+1) for j := range f[i] { f[i][j] = [2]int{-1, -1} } } var dfs func(i, j, k int) int dfs = func(i, j, k int) int { if i >= n { return 0 } if f[i][j][k] != -1 { return f[i][j][k] } ans := dfs(i+1, j, k) if k > 0 { ans = max(ans, prices[i]+dfs(i+1, j, 0)) } else if j > 0 { ans = max(ans, -prices[i]+dfs(i+1, j-1, 1)) } f[i][j][k] = ans return ans } return dfs(0, k, 0) }
188
Best Time to Buy and Sell Stock IV
Hard
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [2,4,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 100</code></li> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>0 &lt;= prices[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private Integer[][][] f; private int[] prices; private int n; public int maxProfit(int k, int[] prices) { n = prices.length; this.prices = prices; f = new Integer[n][k + 1][2]; return dfs(0, k, 0); } private int dfs(int i, int j, int k) { if (i >= n) { return 0; } if (f[i][j][k] != null) { return f[i][j][k]; } int ans = dfs(i + 1, j, k); if (k > 0) { ans = Math.max(ans, prices[i] + dfs(i + 1, j, 0)); } else if (j > 0) { ans = Math.max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); } return f[i][j][k] = ans; } }
188
Best Time to Buy and Sell Stock IV
Hard
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [2,4,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 100</code></li> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>0 &lt;= prices[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if i >= len(prices): return 0 ans = dfs(i + 1, j, k) if k: ans = max(ans, prices[i] + dfs(i + 1, j, 0)) elif j: ans = max(ans, -prices[i] + dfs(i + 1, j - 1, 1)) return ans return dfs(0, k, 0)
188
Best Time to Buy and Sell Stock IV
Hard
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [2,4,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 100</code></li> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>0 &lt;= prices[i] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxProfit(k: number, prices: number[]): number { const n = prices.length; const f = Array.from({ length: n }, () => Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => -1)), ); const dfs = (i: number, j: number, k: number): number => { if (i >= n) { return 0; } if (f[i][j][k] !== -1) { return f[i][j][k]; } let ans = dfs(i + 1, j, k); if (k) { ans = Math.max(ans, prices[i] + dfs(i + 1, j, 0)); } else if (j) { ans = Math.max(ans, -prices[i] + dfs(i + 1, j - 1, 1)); } return (f[i][j][k] = ans); }; return dfs(0, k, 0); }
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
C++
class Solution { public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k %= n; reverse(nums.begin(), nums.end()); reverse(nums.begin(), nums.begin() + k); reverse(nums.begin() + k, nums.end()); } };
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
C#
public class Solution { private int[] nums; public void Rotate(int[] nums, int k) { this.nums = nums; int n = nums.Length; k %= n; reverse(0, n - 1); reverse(0, k - 1); reverse(k, n - 1); } private void reverse(int i, int j) { for (; i < j; ++i, --j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } }
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
Go
func rotate(nums []int, k int) { n := len(nums) k %= n reverse := func(i, j int) { for ; i < j; i, j = i+1, j-1 { nums[i], nums[j] = nums[j], nums[i] } } reverse(0, n-1) reverse(0, k-1) reverse(k, n-1) }
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
Java
class Solution { private int[] nums; public void rotate(int[] nums, int k) { this.nums = nums; int n = nums.length; k %= n; reverse(0, n - 1); reverse(0, k - 1); reverse(k, n - 1); } private void reverse(int i, int j) { for (; i < j; ++i, --j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } }
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
JavaScript
/** * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ var rotate = function (nums, k) { const n = nums.length; k %= n; const reverse = (i, j) => { for (; i < j; ++i, --j) { [nums[i], nums[j]] = [nums[j], nums[i]]; } }; reverse(0, n - 1); reverse(0, k - 1); reverse(k, n - 1); };
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
Python
class Solution: def rotate(self, nums: List[int], k: int) -> None: def reverse(i: int, j: int): while i < j: nums[i], nums[j] = nums[j], nums[i] i, j = i + 1, j - 1 n = len(nums) k %= n reverse(0, n - 1) reverse(0, k - 1) reverse(k, n - 1)
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
Rust
impl Solution { pub fn rotate(nums: &mut Vec<i32>, k: i32) { let n = nums.len(); let k = (k as usize) % n; nums.reverse(); nums[..k].reverse(); nums[k..].reverse(); } }
189
Rotate Array
Medium
<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3 <strong>Output:</strong> [5,6,7,1,2,3,4] <strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-100,3,99], k = 2 <strong>Output:</strong> [3,99,-1,-100] <strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] </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>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li> <li>Could you do it in-place with <code>O(1)</code> extra space?</li> </ul>
Array; Math; Two Pointers
TypeScript
/** Do not return anything, modify nums in-place instead. */ function rotate(nums: number[], k: number): void { const n: number = nums.length; k %= n; const reverse = (i: number, j: number): void => { for (; i < j; ++i, --j) { const t: number = nums[i]; nums[i] = nums[j]; nums[j] = t; } }; reverse(0, n - 1); reverse(0, k - 1); reverse(k, n - 1); }
190
Reverse Bits
Easy
<p>Reverse bits of a given 32 bits signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 43261596</span></p> <p><strong>Output:</strong> <span class="example-io">964176192</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>43261596</td> <td>00000010100101000001111010011100</td> </tr> <tr> <td>964176192</td> <td>00111001011110000010100101000000</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483644</span></p> <p><strong>Output:</strong> <span class="example-io">1073741822</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>2147483644</td> <td>01111111111111111111111111111100</td> </tr> <tr> <td>1073741822</td> <td>00111111111111111111111111111110</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>31</sup> - 2</code></li> <li><code>n</code> is even.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>
Bit Manipulation; Divide and Conquer
C++
class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t ans = 0; for (int i = 0; i < 32 && n; ++i) { ans |= (n & 1) << (31 - i); n >>= 1; } return ans; } };
190
Reverse Bits
Easy
<p>Reverse bits of a given 32 bits signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 43261596</span></p> <p><strong>Output:</strong> <span class="example-io">964176192</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>43261596</td> <td>00000010100101000001111010011100</td> </tr> <tr> <td>964176192</td> <td>00111001011110000010100101000000</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483644</span></p> <p><strong>Output:</strong> <span class="example-io">1073741822</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>2147483644</td> <td>01111111111111111111111111111100</td> </tr> <tr> <td>1073741822</td> <td>00111111111111111111111111111110</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>31</sup> - 2</code></li> <li><code>n</code> is even.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>
Bit Manipulation; Divide and Conquer
Go
func reverseBits(n uint32) (ans uint32) { for i := 0; i < 32; i++ { ans |= (n & 1) << (31 - i) n >>= 1 } return }
190
Reverse Bits
Easy
<p>Reverse bits of a given 32 bits signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 43261596</span></p> <p><strong>Output:</strong> <span class="example-io">964176192</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>43261596</td> <td>00000010100101000001111010011100</td> </tr> <tr> <td>964176192</td> <td>00111001011110000010100101000000</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483644</span></p> <p><strong>Output:</strong> <span class="example-io">1073741822</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>2147483644</td> <td>01111111111111111111111111111100</td> </tr> <tr> <td>1073741822</td> <td>00111111111111111111111111111110</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>31</sup> - 2</code></li> <li><code>n</code> is even.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>
Bit Manipulation; Divide and Conquer
Java
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int ans = 0; for (int i = 0; i < 32 && n != 0; ++i) { ans |= (n & 1) << (31 - i); n >>>= 1; } return ans; } }
190
Reverse Bits
Easy
<p>Reverse bits of a given 32 bits signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 43261596</span></p> <p><strong>Output:</strong> <span class="example-io">964176192</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>43261596</td> <td>00000010100101000001111010011100</td> </tr> <tr> <td>964176192</td> <td>00111001011110000010100101000000</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483644</span></p> <p><strong>Output:</strong> <span class="example-io">1073741822</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>2147483644</td> <td>01111111111111111111111111111100</td> </tr> <tr> <td>1073741822</td> <td>00111111111111111111111111111110</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>31</sup> - 2</code></li> <li><code>n</code> is even.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>
Bit Manipulation; Divide and Conquer
JavaScript
/** * @param {number} n - a positive integer * @return {number} - a positive integer */ var reverseBits = function (n) { let ans = 0; for (let i = 0; i < 32 && n; ++i) { ans |= (n & 1) << (31 - i); n >>= 1; } return ans >>> 0; };
190
Reverse Bits
Easy
<p>Reverse bits of a given 32 bits signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 43261596</span></p> <p><strong>Output:</strong> <span class="example-io">964176192</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>43261596</td> <td>00000010100101000001111010011100</td> </tr> <tr> <td>964176192</td> <td>00111001011110000010100101000000</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483644</span></p> <p><strong>Output:</strong> <span class="example-io">1073741822</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>2147483644</td> <td>01111111111111111111111111111100</td> </tr> <tr> <td>1073741822</td> <td>00111111111111111111111111111110</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>31</sup> - 2</code></li> <li><code>n</code> is even.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>
Bit Manipulation; Divide and Conquer
Python
class Solution: def reverseBits(self, n: int) -> int: ans = 0 for i in range(32): ans |= (n & 1) << (31 - i) n >>= 1 return ans
190
Reverse Bits
Easy
<p>Reverse bits of a given 32 bits signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 43261596</span></p> <p><strong>Output:</strong> <span class="example-io">964176192</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>43261596</td> <td>00000010100101000001111010011100</td> </tr> <tr> <td>964176192</td> <td>00111001011110000010100101000000</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483644</span></p> <p><strong>Output:</strong> <span class="example-io">1073741822</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>Integer</th> <th>Binary</th> </tr> <tr> <td>2147483644</td> <td>01111111111111111111111111111100</td> </tr> <tr> <td>1073741822</td> <td>00111111111111111111111111111110</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>31</sup> - 2</code></li> <li><code>n</code> is even.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>
Bit Manipulation; Divide and Conquer
Rust
impl Solution { pub fn reverse_bits(mut n: u32) -> u32 { let mut ans = 0; for i in 0..32 { ans |= (n & 1) << (31 - i); n >>= 1; } ans } }
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
C
int hammingWeight(uint32_t n) { int ans = 0; while (n) { n &= n - 1; ans++; } return ans; }
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
C++
class Solution { public: int hammingWeight(uint32_t n) { int ans = 0; while (n) { n &= n - 1; ++ans; } return ans; } };
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
Go
func hammingWeight(num uint32) int { ans := 0 for num != 0 { num &= num - 1 ans++ } return ans }
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
Java
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ans = 0; while (n != 0) { n &= n - 1; ++ans; } return ans; } }
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
JavaScript
/** * @param {number} n - a positive integer * @return {number} */ var hammingWeight = function (n) { let ans = 0; while (n) { n &= n - 1; ++ans; } return ans; };
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
Kotlin
class Solution { fun hammingWeight(n: Int): Int { var count = 0 var num = n while (num != 0) { num = num and (num - 1) count++ } return count } }
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
Python
class Solution: def hammingWeight(self, n: int) -> int: ans = 0 while n: n &= n - 1 ans += 1 return ans
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
Rust
impl Solution { pub fn hammingWeight(n: u32) -> i32 { n.count_ones() as i32 } }
191
Number of 1 Bits
Easy
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 11</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1011</strong> has a total of three set bits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 128</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>10000000</strong> has a total of one set bit.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p> <p><strong>Output:</strong> <span class="example-io">30</span></p> <p><strong>Explanation:</strong></p> <p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Bit Manipulation; Divide and Conquer
TypeScript
function hammingWeight(n: number): number { let ans: number = 0; while (n !== 0) { ans++; n &= n - 1; } return ans; }
192
Word Frequency
Medium
<p>Write a bash script to calculate the <span data-keyword="frequency-textfile">frequency</span> of each word in a text file <code>words.txt</code>.</p> <p>For simplicity sake, you may assume:</p> <ul> <li><code>words.txt</code> contains only lowercase characters and space <code>&#39; &#39;</code> characters.</li> <li>Each word must consist of lowercase characters only.</li> <li>Words are separated by one or more whitespace characters.</li> </ul> <p><strong class="example">Example:</strong></p> <p>Assume that <code>words.txt</code> has the following content:</p> <pre> the day is sunny the the the sunny is is </pre> <p>Your script should output the following, sorted by descending frequency:</p> <pre> the 4 is 3 sunny 2 day 1 </pre> <p><b>Note:</b></p> <ul> <li>Don&#39;t worry about handling ties, it is guaranteed that each word&#39;s frequency count is unique.</li> <li>Could you write it in one-line using <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html">Unix pipes</a>?</li> </ul>
Shell
Bash
# Read from the file words.txt and output the word frequency list to stdout. cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}'
193
Valid Phone Numbers
Easy
<p>Given a text file <code>file.txt</code> that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.</p> <p>You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)</p> <p>You may also assume each line in the text file must not contain leading or trailing white spaces.</p> <p><strong class="example">Example:</strong></p> <p>Assume that <code>file.txt</code> has the following content:</p> <pre> 987-123-4567 123 456 7890 (123) 456-7890 </pre> <p>Your script should output the following valid phone numbers:</p> <pre> 987-123-4567 (123) 456-7890 </pre>
Shell
Bash
# Read from the file file.txt and output all valid phone numbers to stdout. awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt
194
Transpose File
Medium
<p>Given a text file <code>file.txt</code>, transpose its content.</p> <p>You may assume that each row has the same number of columns, and each field is separated by the <code>&#39; &#39;</code> character.</p> <p><strong class="example">Example:</strong></p> <p>If <code>file.txt</code> has the following content:</p> <pre> name age alice 21 ryan 30 </pre> <p>Output the following:</p> <pre> name alice ryan age 21 30 </pre>
Shell
Bash
# Read from the file file.txt and print its transposed content to stdout. awk ' { for (i=1; i<=NF; i++) { if(NR == 1) { res[i] = re$i } else { res[i] = res[i]" "$i } } }END { for (i=1;i<=NF;i++) { print res[i] } } ' file.txt
195
Tenth Line
Easy
<p>Given a text file&nbsp;<code>file.txt</code>, print&nbsp;just the 10th line of the&nbsp;file.</p> <p><strong class="example">Example:</strong></p> <p>Assume that <code>file.txt</code> has the following content:</p> <pre> Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 </pre> <p>Your script should output the tenth line, which is:</p> <pre> Line 10 </pre> <div class="spoilers"><b>Note:</b><br /> 1. If the file contains less than 10 lines, what should you output?<br /> 2. There&#39;s at least three different solutions. Try to explore all possibilities.</div>
Shell
Bash
# Read from the file file.txt and output the tenth line to stdout. sed -n 10p file.txt
196
Delete Duplicate Emails
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains an email. The emails will not contain uppercase letters. </pre> <p>&nbsp;</p> <p>Write a solution to<strong> delete</strong> all duplicate emails, keeping only one unique email with the smallest <code>id</code>.</p> <p>For SQL users, please note that you are supposed to write a <code>DELETE</code> statement and not a <code>SELECT</code> one.</p> <p>For Pandas users, please note that you are supposed to modify <code>Person</code> in place.</p> <p>After running your script, the answer shown is the <code>Person</code> table. The driver will first compile and run your piece of code and then show the <code>Person</code> table. The final order of the <code>Person</code> table <strong>does not matter</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----+------------------+ | id | email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | | 3 | john@example.com | +----+------------------+ <strong>Output:</strong> +----+------------------+ | id | email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | +----+------------------+ <strong>Explanation:</strong> john@example.com is repeated two times. We keep the row with the smallest Id = 1. </pre>
Database
Python
import pandas as pd # Modify Person in place def delete_duplicate_emails(person: pd.DataFrame) -> None: # Sort the rows based on id (Ascending order) person.sort_values(by="id", ascending=True, inplace=True) # Drop the duplicates based on email. person.drop_duplicates(subset="email", keep="first", inplace=True)
196
Delete Duplicate Emails
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains an email. The emails will not contain uppercase letters. </pre> <p>&nbsp;</p> <p>Write a solution to<strong> delete</strong> all duplicate emails, keeping only one unique email with the smallest <code>id</code>.</p> <p>For SQL users, please note that you are supposed to write a <code>DELETE</code> statement and not a <code>SELECT</code> one.</p> <p>For Pandas users, please note that you are supposed to modify <code>Person</code> in place.</p> <p>After running your script, the answer shown is the <code>Person</code> table. The driver will first compile and run your piece of code and then show the <code>Person</code> table. The final order of the <code>Person</code> table <strong>does not matter</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----+------------------+ | id | email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | | 3 | john@example.com | +----+------------------+ <strong>Output:</strong> +----+------------------+ | id | email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | +----+------------------+ <strong>Explanation:</strong> john@example.com is repeated two times. We keep the row with the smallest Id = 1. </pre>
Database
SQL
# Write your MySQL query statement below DELETE FROM Person WHERE id NOT IN (SELECT MIN(id) FROM (SELECT * FROM Person) AS p GROUP BY email);
197
Rising Temperature
Easy
<p>Table: <code>Weather</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id is the column with unique values for this table. There are no different rows with the same recordDate. This table contains information about the temperature on a certain day. </pre> <p>&nbsp;</p> <p>Write a solution to find all dates&#39; <code>id</code> with higher temperatures compared to its previous dates (yesterday).</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Weather table: +----+------------+-------------+ | id | recordDate | temperature | +----+------------+-------------+ | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 | +----+------------+-------------+ <strong>Output:</strong> +----+ | id | +----+ | 2 | | 4 | +----+ <strong>Explanation:</strong> In 2015-01-02, the temperature was higher than the previous day (10 -&gt; 25). In 2015-01-04, the temperature was higher than the previous day (20 -&gt; 30). </pre>
Database
Python
import pandas as pd def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame: weather.sort_values(by="recordDate", inplace=True) return weather[ (weather.temperature.diff() > 0) & (weather.recordDate.diff().dt.days == 1) ][["id"]]
197
Rising Temperature
Easy
<p>Table: <code>Weather</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id is the column with unique values for this table. There are no different rows with the same recordDate. This table contains information about the temperature on a certain day. </pre> <p>&nbsp;</p> <p>Write a solution to find all dates&#39; <code>id</code> with higher temperatures compared to its previous dates (yesterday).</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Weather table: +----+------------+-------------+ | id | recordDate | temperature | +----+------------+-------------+ | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 | +----+------------+-------------+ <strong>Output:</strong> +----+ | id | +----+ | 2 | | 4 | +----+ <strong>Explanation:</strong> In 2015-01-02, the temperature was higher than the previous day (10 -&gt; 25). In 2015-01-04, the temperature was higher than the previous day (20 -&gt; 30). </pre>
Database
SQL
# Write your MySQL query statement below SELECT w1.id FROM Weather AS w1 JOIN Weather AS w2 ON DATEDIFF(w1.recordDate, w2.recordDate) = 1 AND w1.temperature > w2.temperature;
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); int f[n]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i) -> int { if (i >= n) { return 0; } if (f[i] < 0) { f[i] = max(nums[i] + dfs(i + 2), dfs(i + 1)); } return f[i]; }; return dfs(0); } };
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
Go
func rob(nums []int) int { n := len(nums) f := make([]int, n) for i := range f { f[i] = -1 } var dfs func(int) int dfs = func(i int) int { if i >= n { return 0 } if f[i] < 0 { f[i] = max(nums[i]+dfs(i+2), dfs(i+1)) } return f[i] } return dfs(0) }
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private Integer[] f; private int[] nums; public int rob(int[] nums) { this.nums = nums; f = new Integer[nums.length]; return dfs(0); } private int dfs(int i) { if (i >= nums.length) { return 0; } if (f[i] == null) { f[i] = Math.max(nums[i] + dfs(i + 2), dfs(i + 1)); } return f[i]; } }
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
JavaScript
function rob(nums) { const n = nums.length; const f = Array(n).fill(-1); const dfs = i => { if (i >= n) { return 0; } if (f[i] < 0) { f[i] = Math.max(nums[i] + dfs(i + 2), dfs(i + 1)); } return f[i]; }; return dfs(0); }
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def rob(self, nums: List[int]) -> int: @cache def dfs(i: int) -> int: if i >= len(nums): return 0 return max(nums[i] + dfs(i + 2), dfs(i + 1)) return dfs(0)
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn rob(nums: Vec<i32>) -> i32 { fn dfs(i: usize, nums: &Vec<i32>, f: &mut Vec<i32>) -> i32 { if i >= nums.len() { return 0; } if f[i] < 0 { f[i] = (nums[i] + dfs(i + 2, nums, f)).max(dfs(i + 1, nums, f)); } f[i] } let n = nums.len(); let mut f = vec![-1; n]; dfs(0, &nums, &mut f) } }
198
House Robber
Medium
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p> <p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 400</code></li> </ul>
Array; Dynamic Programming
TypeScript
function rob(nums: number[]): number { const n = nums.length; const f: number[] = Array(n).fill(-1); const dfs = (i: number): number => { if (i >= n) { return 0; } if (f[i] < 0) { f[i] = Math.max(nums[i] + dfs(i + 2), dfs(i + 1)); } return f[i]; }; return dfs(0); }
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> ans; if (!root) { return ans; } queue<TreeNode*> q{{root}}; while (q.size()) { ans.push_back(q.front()->val); for (int k = q.size(); k; --k) { auto node = q.front(); q.pop(); if (node->right) { q.push(node->right); } if (node->left) { q.push(node->left); } } } return ans; } };
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func rightSideView(root *TreeNode) (ans []int) { if root == nil { return } q := []*TreeNode{root} for len(q) > 0 { ans = append(ans, q[0].Val) for k := len(q); k > 0; k-- { node := q[0] q = q[1:] if node.Right != nil { q = append(q, node.Right) } if node.Left != nil { q = append(q, node.Left) } } } return }
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> ans = new ArrayList<>(); if (root == null) { return ans; } Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { ans.add(q.peekFirst().val); for (int k = q.size(); k > 0; --k) { TreeNode node = q.poll(); if (node.right != null) { q.offer(node.right); } if (node.left != null) { q.offer(node.left); } } } return ans; } }
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[]} */ var rightSideView = function (root) { const ans = []; if (!root) { return ans; } const q = [root]; while (q.length > 0) { ans.push(q[0].val); const nq = []; for (const { left, right } of q) { if (right) { nq.push(right); } if (left) { nq.push(left); } } q.length = 0; q.push(...nq); } return ans; };
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: ans = [] if root is None: return ans q = deque([root]) while q: ans.append(q[0].val) for _ in range(len(q)): node = q.popleft() if node.right: q.append(node.right) if node.left: q.append(node.left) return ans
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { let mut ans = vec![]; if root.is_none() { return ans; } let mut q = VecDeque::new(); q.push_back(root); while !q.is_empty() { let k = q.len(); ans.push(q[0].as_ref().unwrap().borrow().val); for _ in 0..k { if let Some(node) = q.pop_front().unwrap() { let mut node = node.borrow_mut(); if node.right.is_some() { q.push_back(node.right.take()); } if node.left.is_some() { q.push_back(node.left.take()); } } } } ans } }
199
Binary Tree Right Side View
Medium
<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,5,null,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpd5jn43fs-1.png" style="width: 400px; height: 207px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,null,null,null,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,4,5]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/images/tmpkpe40xeh-1.png" style="width: 400px; height: 214px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function rightSideView(root: TreeNode | null): number[] { const ans: number[] = []; if (!root) { return ans; } const q: TreeNode[] = [root]; while (q.length > 0) { ans.push(q[0].val); const nq: TreeNode[] = []; for (const { left, right } of q) { if (right) { nq.push(right); } if (left) { nq.push(left); } } q.length = 0; q.push(...nq); } return ans; }
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
C++
class Solution { public: int numIslands(vector<vector<char>>& grid) { int m = grid.size(); int n = grid[0].size(); int ans = 0; int dirs[5] = {-1, 0, 1, 0, -1}; function<void(int, int)> dfs = [&](int i, int j) { grid[i][j] = '0'; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { dfs(x, y); } } }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '1') { dfs(i, j); ++ans; } } } return ans; } };
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
C#
using System; using System.Collections.Generic; using System.Linq; public class Solution { public int NumIslands(char[][] grid) { var queue = new Queue<Tuple<int, int>>(); var lenI = grid.Length; var lenJ = lenI == 0 ? 0 : grid[0].Length; var paths = new int[,] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; var result = 0; for (var i = 0; i < lenI; ++i) { for (var j = 0; j < lenJ; ++j) { if (grid[i][j] == '1') { ++result; grid[i][j] = '0'; queue.Enqueue(Tuple.Create(i, j)); while (queue.Any()) { var position = queue.Dequeue(); for (var k = 0; k < 4; ++k) { var next = Tuple.Create(position.Item1 + paths[k, 0], position.Item2 + paths[k, 1]); if (next.Item1 >= 0 && next.Item1 < lenI && next.Item2 >= 0 && next.Item2 < lenJ && grid[next.Item1][next.Item2] == '1') { grid[next.Item1][next.Item2] = '0'; queue.Enqueue(next); } } } } } } return result; } }
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Go
func numIslands(grid [][]byte) int { m, n := len(grid), len(grid[0]) var dfs func(i, j int) dfs = func(i, j int) { grid[i][j] = '0' dirs := []int{-1, 0, 1, 0, -1} for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' { dfs(x, y) } } } ans := 0 for i := 0; i < m; i++ { for j := 0; j < n; j++ { if grid[i][j] == '1' { dfs(i, j) ans++ } } } return ans }
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Java
class Solution { private char[][] grid; private int m; private int n; public int numIslands(char[][] grid) { m = grid.length; n = grid[0].length; this.grid = grid; int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '1') { dfs(i, j); ++ans; } } } return ans; } private void dfs(int i, int j) { grid[i][j] = '0'; int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k]; int y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { dfs(x, y); } } } }
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Python
class Solution: def numIslands(self, grid: List[List[str]]) -> int: def dfs(i, j): grid[i][j] = '0' for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': dfs(x, y) ans = 0 dirs = (-1, 0, 1, 0, -1) m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == '1': dfs(i, j) ans += 1 return ans
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Rust
const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; impl Solution { pub fn num_islands(grid: Vec<Vec<char>>) -> i32 { fn dfs(grid: &mut Vec<Vec<char>>, i: usize, j: usize) { grid[i][j] = '0'; for k in 0..4 { let x = (i as i32) + DIRS[k]; let y = (j as i32) + DIRS[k + 1]; if x >= 0 && (x as usize) < grid.len() && y >= 0 && (y as usize) < grid[0].len() && grid[x as usize][y as usize] == '1' { dfs(grid, x as usize, y as usize); } } } let mut grid = grid; let mut ans = 0; for i in 0..grid.len() { for j in 0..grid[0].len() { if grid[i][j] == '1' { dfs(&mut grid, i, j); ans += 1; } } } ans } }
200
Number of Islands
Medium
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p> <p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
TypeScript
function numIslands(grid: string[][]): number { const m = grid.length; const n = grid[0].length; let ans = 0; const dfs = (i: number, j: number) => { if (grid[i]?.[j] !== '1') { return; } grid[i][j] = '0'; dfs(i + 1, j); dfs(i - 1, j); dfs(i, j + 1); dfs(i, j - 1); }; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (grid[i][j] === '1') { dfs(i, j); ++ans; } } } return ans; }