id int64 1 2.61k | slug stringlengths 3 79 | title stringlengths 3 79 | difficulty stringclasses 3
values | content stringlengths 230 5.69k | c++ stringlengths 395 3.62k | prompt_nl stringlengths 60 3.82k | prompt stringlengths 133 4.1k |
|---|---|---|---|---|---|---|---|
1,181 | before-and-after-puzzle | Before and After Puzzle | Medium | Given a list of `phrases`, generate a list of Before and After puzzles.
A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.
_Before and After puzzles_ are phrases that are formed by mergin... |
```cpp
#include <vector>
#include <string>
#include <unordered_map>
#include <set>
std::vector<std::string> beforeAndAfterPuzzles(std::vector<std::string>& phrases) {
std::unordered_map<std::string, std::set<std::string>> firstWordMap;
std::set<std::string> result;
for (const std::string& phrase : ph... | Given a list of `phrases`, generate a list of Before and After puzzles.
A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.
_Before and After puzzles_ are phrases that are formed by mergin... | Continue the following C++ code:
class Solution {
public:
/**
* Given a list of `phrases`, generate a list of Before and After puzzles.
*
* A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a... |
2,464 | minimum-subarrays-in-a-valid-split | Minimum Subarrays in a Valid Split | Medium | You are given an integer array `nums`.
Splitting of an integer array `nums` into **subarrays** is **valid** if:
* the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and
* each element of `nums` belongs to exactly one subarray.
Return _the **minimum** number of ... |
```cpp
#include <numeric>
int min_valid_subarrays(vector<int>& nums) {
int count = 0;
for (int i = 0; i < nums.size(); i++) {
while (i < nums.size() && std::gcd(nums[i], nums.back()) == 1) {
i++;
}
if (i < nums.size()) {
count++;
nums.pop_back();
... | You are given an integer array `nums`.
Splitting of an integer array `nums` into **subarrays** is **valid** if:
* the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and
* each element of `nums` belongs to exactly one subarray.
Return _the **minimum** number of ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an integer array `nums`.
*
* Splitting of an integer array `nums` into **subarrays** is **valid** if:
*
* * the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and
* * each e... |
214 | shortest-palindrome | Shortest Palindrome | Hard | You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
Return _the shortest palindrome you can find by performing this transformation_.
**Example 1:**
**Input:** s = "aacecaaa"
**Output:** "aaacecaaa"
**Example 2:**
**Input:** s = "abcd"
**Output:** "dcbabcd"
**Constr... |
```cpp
#include <string>
std::string shortestPalindrome(std::string s) {
int n = s.size();
std::string rev_s = s;
std::reverse(rev_s.begin(), rev_s.end());
for (int i = 0; i < n; ++i) {
if(s.substr(0, n - i) == rev_s.substr(i))
return rev_s.substr(0, i) + s;
}
retu... | You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
Return _the shortest palindrome you can find by performing this transformation_. | Continue the following C++ code:
class Solution {
public:
/**
* You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
*
* Return _the shortest palindrome you can find by performing this transformation_.
*/
|
1,861 | rotating-the-box | Rotating the Box | Medium | You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following:
* A stone `'#'`
* A stationary obstacle `'*'`
* Empty `'.'`
The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u... |
```cpp
int min_boxes_touching_floor(int n) {
return (n + 1) / 2;
}
```
The algorithm is fairly simple, since the room is a perfect cube, we can place the boxes on the floor in an alternating pattern. We place a box in one corner, then skip one unit and place another box, then skip another unit and so ... | You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following:
* A stone `'#'`
* A stationary obstacle `'*'`
* Empty `'.'`
The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following:
*
* * A stone `'#'`
* * A stationary obstacle `'*'`
* * Empty `'.'`
*
* The box is rotated **90 degree... |
1,870 | minimum-speed-to-arrive-on-time | Minimum Speed to Arrive on Time | Medium | You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
E... |
```cpp
int minSpeedOnTime(vector<int>& dist, double hour) {
double max_time = hour - dist.size() + 1;
double lower = 1.0, upper = 1e7;
while (upper - lower >= 1e-9) {
double mid = (lower + upper) / 2;
double time_taken = 0.0;
for (int i = 0; i < dist.size(); ++i) {
t... | You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
E... | Continue the following C++ code:
class Solution {
public:
/**
* You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]`... |
1,772 | sort-features-by-popularity | Sort Features by Popularity | Medium | You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... |
```cpp
#include <set>
const int MOD = 1e9 + 7;
int createSortedArray(vector<int>& instructions) {
multiset<int> s;
int cost = 0;
for (int i : instructions) {
s.insert(i);
int less_than = distance(s.begin(), s.lower_bound(i));
int greater_than = distance(s.upper_bound(i), s.en... | You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... | Continue the following C++ code:
class Solution {
public:
/**
* You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a strin... |
939 | minimum-area-rectangle | Minimum Area Rectangle | Medium | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
**Example 1:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]... |
```cpp
#include <vector>
#define MOD 1000000007
int findValidPermutations(const std::string& s) {
int n = s.size();
std::vector<long long> dp(n + 2, 0);
dp[0] = 1;
for (char c : s) {
std::vector<long long> new_dp(n + 2, 0);
if (c == 'I') {
for (int i = 0; i < n; ++i) {... | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. | Continue the following C++ code:
class Solution {
public:
/**
* You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
*
* Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `... |
2,338 | count-the-number-of-ideal-arrays | Count the Number of Ideal Arrays | Hard | You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array.
A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold:
* Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`.
* Every `arr[i]` is divisible by `arr[i - ... |
```cpp
int numOfArrays(int n, int maxValue) {
const int mod = 1e9 + 7;
vector<int> dp(maxValue + 1, 0);
for (int i = 1; i <= maxValue; i++) {
dp[i] = i;
}
for (int i = 1; i < n; i++) {
for (int j = maxValue; j > 0; j--) {
dp[j] = (dp[j] + dp[j - 1]) % mod;
... | You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array.
A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold:
* Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`.
* Every `arr[i]` is divisible by `arr[i - ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array.
*
* A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold:
*
* * Every `arr[i]` is a value from ... |
1,682 | longest-palindromic-subsequence-ii | Longest Palindromic Subsequence II | Medium | A subsequence of a string `s` is considered a **good palindromic subsequence** if:
* It is a subsequence of `s`.
* It is a palindrome (has the same value if reversed).
* It has an **even** length.
* No two consecutive characters are equal, except the two middle ones.
For example, if `s = "abcabcabb "`, then `... |
```cpp
#include <vector>
#include <algorithm>
using namespace std;
vector<int> mostVisited(int n, vector<int>& rounds) {
vector<int> visited(n + 1, 0);
for (int i = 1; i < rounds.size(); i++) {
int start = rounds[i - 1], end = rounds[i];
while (start != end) {
visited[star... | A subsequence of a string `s` is considered a **good palindromic subsequence** if:
* It is a subsequence of `s`.
* It is a palindrome (has the same value if reversed).
* It has an **even** length.
* No two consecutive characters are equal, except the two middle ones.
For example, if `s = "abcabcabb "`, then `... | Continue the following C++ code:
class Solution {
public:
/**
* A subsequence of a string `s` is considered a **good palindromic subsequence** if:
*
* * It is a subsequence of `s`.
* * It is a palindrome (has the same value if reversed).
* * It has an **even** length.
* * No two consecutive charact... |
503 | next-greater-element-ii | Next Greater Element II | Medium | Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circu... |
```cpp
#include <vector>
#include <stack>
std::vector<int> nextGreaterElements(std::vector<int>& nums) {
std::vector<int> result(nums.size(), -1);
std::stack<int> s;
for (int i = 0; i < nums.size() * 2; ++i) {
int index = i % nums.size();
while (!s.empty() && nums[s.top()] < nums[inde... | Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circu... | Continue the following C++ code:
class Solution {
public:
/**
* Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
*
* The **next greater number** of a number `x` is the first greater number to ... |
2,536 | increment-submatrices-by-one | Increment Submatrices by One | Medium | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... |
```cpp
#include <vector>
std::vector<std::vector<int>> applyQueries(int n, std::vector<std::vector<int>>& queries) {
std::vector<std::vector<int>> mat(n, std::vector<int>(n, 0));
for (auto& query : queries) {
for (int i = query[0]; i <= query[2]; ++i) {
for (int j = query[1]; j <= que... | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | Continue the following C++ code:
class Solution {
public:
/**
* You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
*
* You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you shou... |
2,185 | counting-words-with-a-given-prefix | Counting Words With a Given Prefix | Easy | You are given an array of strings `words` and a string `pref`.
Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_.
A **prefix** of a string `s` is any leading contiguous substring of `s`.
**Example 1:**
**Input:** words = \[ "pay ", "**at**tention ", "practice ", "**at**tend "\], `pre... |
```cpp
int count_prefixes(vector<string>& words, string pref) {
int count = 0;
for(const auto& word : words) {
if(word.find(pref) == 0) {
count++;
}
}
return count;
}
```
The algorithm iterates through the list of words and checks if the word starts with the giv... | You are given an array of strings `words` and a string `pref`.
Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_.
A **prefix** of a string `s` is any leading contiguous substring of `s`. | Continue the following C++ code:
class Solution {
public:
/**
* You are given an array of strings `words` and a string `pref`.
*
* Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_.
*
* A **prefix** of a string `s` is any leading contiguous substring of `s`.
*/
|
1,668 | maximum-repeating-substring | Maximum Repeating Substring | Easy | For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating v... |
```cpp
int longestAwesomeSubstring(std::string s) {
int n = s.length();
int maxLen = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j <= n; ++j) {
std::string substr = s.substr(i, j - i);
if (isAwesome(substr)) {
maxLen = std::max(maxLen, j - i);
... | For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating v... | Continue the following C++ code:
class Solution {
public:
/**
* For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` ... |
1,258 | synonymous-sentences | Synonymous Sentences | Medium | You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`.
Return _all possible synonymous sentences **sorted lexicographically**_.
**Example 1:**
**Input:** synonyms = \[\[ "happy ", "joy "\],\[... |
```cpp
#include <vector>
#include <string>
#include <set>
#include <map>
using namespace std;
void generateSentencesHelper(int index, vector<string>& words, map<string, set<string>>& synonyms, vector<string>& result, string curSentence) {
if (index == words.size()) {
result.push_back(curSentence);
... | You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`.
Return _all possible synonymous sentences **sorted lexicographically**_. | Continue the following C++ code:
class Solution {
public:
/**
* You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`.
*
* Return _all possible synonymous sentences **sorted lexicographic... |
1,673 | find-the-most-competitive-subsequence | Find the Most Competitive Subsequence | Medium | Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence `a` is more **competitive** than a subsequence ... |
```cpp
#include <vector>
#include <stack>
std::vector<int> mostCompetitive(std::vector<int>& nums, int k) {
std::stack<int> stk;
int n = nums.size();
for (int i = 0; i < n; i++) {
while (!stk.empty() && stk.top() > nums[i] && stk.size() + n - i > k) {
stk.pop();
}
i... | Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence `a` is more **competitive** than a subsequence ... | Continue the following C++ code:
class Solution {
public:
/**
* Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
*
* An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
*... |
2,156 | find-substring-with-given-hash-value | Find Substring With Given Hash Value | Hard | The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function:
* `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`.
Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`.... |
```cpp
bool aliceWins(std::vector<int> &stones) {
int sum = 0, count[3] = {0};
for (int stone : stones) {
sum += stone;
count[stone % 3]++;
}
if (sum % 3) {
return count[sum % 3] % 2 == 1;
}
return count[1] % 2 == 0 || count[2] % 2 == 0 || count[1] == 0 || count[2] =... | The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function:
* `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`.
Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`.... | Continue the following C++ code:
class Solution {
public:
/**
* The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function:
*
* * `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`.
*
* Where `val(s[i])` repre... |
694 | number-of-distinct-islands | Number of Distinct Islands | Medium | You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if and only if one island can be translated (and ... |
```cpp
#include<vector>
#include<set>
using namespace std;
void dfs(vector<vector<int>>& grid, int i, int j, int i0, int j0, vector<pair<int, int>>& shape) {
if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1) {
grid[i][j] = 2;
shape.push_back({i - i0, j - j0});
... | You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if and only if one island can be translated (and ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
*
* An island is considered t... |
1,660 | correct-a-binary-tree | Correct a Binary Tree | Medium | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... |
```cpp
#include <string>
std::string thousandSeparator(int n) {
std::string result = std::to_string(n);
int count = 0;
for (int i = result.size() - 1; i > 0; --i) {
count++;
if (count % 3 == 0) {
result.insert(i, ".");
}
}
return result;
}
```
The a... | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Continue the following C++ code:
class Solution {
public:
/**
* You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
*
* Given the root of the binary tree with this def... |
1,268 | search-suggestions-system | Search Suggestions System | Medium | You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix ret... |
```cpp
#include <vector>
#include <string>
#include <algorithm>
std::vector<std::vector<std::string>> suggestedProducts(std::vector<std::string>& products, std::string searchWord) {
std::vector<std::vector<std::string>> result;
std::sort(products.begin(), products.end());
for (int i = 0; i < sear... | You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix ret... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an array of strings `products` and a string `searchWord`.
*
* Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `s... |
1,697 | checking-existence-of-edge-length-limited-paths | Checking Existence of Edge Length Limited Paths | Hard | An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e... |
```cpp
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {
unordered_map<int, vector<pair<int, int>>> graph;
for (auto& edge : edgeList) {
graph[edge[0]].empla... | An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e... | Continue the following C++ code:
class Solution {
public:
/**
* An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
*
* Given an array `querie... |
2,503 | maximum-number-of-points-from-grid-queries | Maximum Number of Points From Grid Queries | Hard | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... |
```cpp
#include <vector>
#include <set>
#include <utility>
using namespace std;
vector<int> traverseMatrix(vector<vector<int>>& grid, const vector<int>& queries, int m, int n) {
vector<int> dx = {-1, 0, 1, 0};
vector<int> dy = {0, 1, 0, -1};
vector<int> answer(queries.size(), 0);
for (int k = 0;... | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
*
* Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
*
... |
2,322 | minimum-score-after-removals-on-a-tree | Minimum Score After Removals on a Tree | Hard | There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica... |
```cpp
#include <vector>
using namespace std;
int dfs(int node, int parent, vector<int>& xor_values, vector<vector<int>>& tree) {
int xor_value = xor_values[node];
for (int child : tree[node]) {
if (child != parent) {
xor_value ^= dfs(child, node, xor_values, tree);
}
}
... | There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica... | Continue the following C++ code:
class Solution {
public:
/**
* There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
*
* You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D ... |
2,243 | calculate-digit-sum-of-a-string | Calculate Digit Sum of a String | Easy | You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i... |
```cpp
bool isAOnlyBeforeB(const std::string& s) {
int lastIndexA = -1;
for (size_t i = 0; i < s.length(); ++i) {
if (s[i] == 'a') {
lastIndexA = i;
} else if (s[i] == 'b' && lastIndexA > -1) {
return false;
}
}
return true;
}
```
The algorit... | You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i... | Continue the following C++ code:
class Solution {
public:
/**
* You are given a string `s` consisting of digits and an integer `k`.
*
* A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
*
* 1. **Divide** `s` into **consecutive groups** of size `k` such th... |
988 | smallest-string-starting-from-leaf | Smallest String Starting From Leaf | Medium | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller... |
```cpp
#include <cstdlib>
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) {}
};
bool flipEqu... | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller... | Continue the following C++ code:
class Solution {
public:
/**
* You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
*
* Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
*... |
1,655 | distribute-repeating-integers | Distribute Repeating Integers | Hard | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... |
```cpp
#include <vector>
#include <unordered_map>
#include <algorithm>
bool canDistribute(std::vector<int>& nums, std::vector<int>& quantity) {
std::unordered_map<int, int> counts;
for (int num : nums) {
counts[num]++;
}
std::vector<int> values;
for (auto& p : counts) {
values... | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. ... |
850 | rectangle-area-ii | Rectangle Area II | Hard | You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**.
Calculate the **total area** covered by all `rectangles` ... |
```cpp
#include <vector>
#include <set>
using namespace std;
int rectangleArea(vector<vector<int>>& rectangles) {
const int64_t mod = 1e9 + 7;
int n = rectangles.size();
vector<int> X, Y;
for (const auto &rect : rectangles) {
X.push_back(rect[0]);
X.push_back(rect[2]);
Y.pu... | You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**.
Calculate the **total area** covered by all `rectangles` ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right c... |
2,423 | remove-letter-to-equalize-frequency | Remove Letter To Equalize Frequency | Easy | You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal.
Return `true` _if it is possible to remove one letter so that the frequency of... |
```cpp
#include <unordered_map>
bool canEqualFrequency(std::string word) {
std::unordered_map<char, int> freq;
for (char c : word) {
freq[c]++;
}
std::unordered_map<int, int> count_freq;
for (auto &[c, f] : freq) {
count_freq[f]++;
}
if (count_freq.size() != 2... | You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal.
Return `true` _if it is possible to remove one letter so that the frequency of... | Continue the following C++ code:
class Solution {
public:
/**
* You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal.
*
* Retu... |
2,285 | maximum-total-importance-of-roads | Maximum Total Importance of Roads | Medium | You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`.
You need to assign each city with an integ... |
```cpp
class BitSet {
private:
vector<unsigned> bits;
public:
BitSet(size_t size) : bits(size / 32 + 1, 0) {}
void set(size_t index) { bits[index / 32] |= (1 << (index % 32)); }
bool get(size_t index) const { return (bits[index / 32] & (1 << (index % 32))) != 0; }
};
```
... | You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`.
You need to assign each city with an integ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
*
* You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road co... |
728 | self-dividing-numbers | Self Dividing Numbers | Easy | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... |
```cpp
#include <vector>
bool isSelfDividing(int num) {
int n = num;
while (n) {
int digit = n % 10;
if (digit == 0 || num % digit != 0)
return false;
n /= 10;
}
return true;
}
std::vector<int> selfDividingNumbers(int left, int right) {
std::vector<int> res... | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | Continue the following C++ code:
class Solution {
public:
/**
* A **self-dividing number** is a number that is divisible by every digit it contains.
*
* * For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
*
* A **self-dividing number** is not allow... |
1,005 | maximize-sum-of-array-after-k-negations | Maximize Sum Of Array After K Negations | Easy | Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it i... |
```cpp
bool isUnivalued(TreeNode* root, int val = -1) {
if (!root) return true;
if (val == -1) val = root->val;
return root->val == val && isUnivalued(root->left, val) && isUnivalued(root->right, val);
}
```
The algorithm first checks if the root node is null, if it is, the function returns tr... | Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it i... | Continue the following C++ code:
class Solution {
public:
/**
* Given an integer array `nums` and an integer `k`, modify the array in the following way:
*
* * choose an index `i` and replace `nums[i]` with `-nums[i]`.
*
* You should apply this process exactly `k` times. You may choose the same index `i` mu... |
1,753 | maximum-score-from-removing-stones | Maximum Score From Removing Stones | Medium | You are playing a solitaire game with **three piles** of stones of sizes `a`ββββββ, `b`,ββββββ and `c`ββββββ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... |
```cpp
#include <vector>
#include <queue>
#include <utility>
using std::vector;
using std::pair;
using std::priority_queue;
int minimumEffortPath(vector<vector<int>>& heights) {
const vector<pair<int, int>> directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int rows = heights.size();
int cols = heights... | You are playing a solitaire game with **three piles** of stones of sizes `a`ββββββ, `b`,ββββββ and `c`ββββββ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... | Continue the following C++ code:
class Solution {
public:
/**
* You are playing a solitaire game with **three piles** of stones of sizes `a`ββββββ, `b`,ββββββ and `c`ββββββ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops ... |
438 | find-all-anagrams-in-a-string | Find All Anagrams in a String | Medium | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... |
```cpp
#include <vector>
#include <string>
std::vector<int> findAnagrams(std::string s, std::string p) {
std::vector<int> result;
if (s.size() < p.size()) return result;
std::vector<int> s_count(26, 0), p_count(26, 0);
for (char c : p) p_count[c - 'a']++;
for (int i = 0; i < s.size(); i++) {... | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. | Continue the following C++ code:
class Solution {
public:
/**
* Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
*
* An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase,... |
82 | remove-duplicates-from-sorted-list-ii | Remove Duplicates from Sorted List II | Medium | Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,2,3,3,4,4,5\]
**Output:** \[1,2,5\]
**Example 2:**
**Input:** head = \[1,1,1,2,3\]
**Outpu... |
```cpp
class ListNode {
public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* deleteDuplicates(ListNode* head) {
ListNode dummy(0);
dummy.next = head;
ListNode *prev = &dummy, *curr = head;
while (curr) {
while (curr->next && curr->val == curr... | Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. | Continue the following C++ code:
class Solution {
public:
/**
* Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
*/
|
374 | guess-number-higher-or-lower | Guess Number Higher or Lower | Easy | We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible re... |
```cpp
int guessNumber(int n) {
int low = 1, high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
int result = guess(mid);
if (result == 0) {
return mid;
} else if (result < 0) {
high = mid - 1;
} else {
low = mid + 1;... | We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible re... | Continue the following C++ code:
class Solution {
public:
/**
* We are playing the Guess Game. The game is as follows:
*
* I pick a number from `1` to `n`. You have to guess which number I picked.
*
* Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
... |
1,814 | count-nice-pairs-in-an-array | Count Nice Pairs in an Array | Medium | You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nu... |
```cpp
int maxResult(vector<int>& nums, int k) {
int n = nums.size();
deque<int> dq;
vector<int> dp(n);
dp[0] = nums[0];
dq.push_back(0);
for (int i = 1; i < n; ++i) {
while (!dq.empty() && dq.front() < i - k) {
dq.pop_front();
}
dp[i] ... | You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nu... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all o... |
322 | coin-change | Coin Change | Medium | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may a... |
```cpp
#include <vector>
#include <algorithm>
int coinChange(std::vector<int>& coins, int amount) {
std::vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 0; i < coins.size(); i++) {
for (int j = coins[i]; j <= amount; j++) {
dp[j] = std::min(dp[j], dp[j - coins[... | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may a... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
*
* Return _the fewest number of coins that you need to make up that amount_. If that amount of money ... |
1,560 | most-visited-sector-in-a-circular-track | Most Visited Sector in a Circular Track | Easy | Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ... |
```cpp
int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {
int count = 0;
for (int i = 0; i < startTime.size(); i++) {
if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
count++;
}
}
return count;
}
```
The algorithm consists ... | Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ... | Continue the following C++ code:
class Solution {
public:
/**
* Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - ... |
2,018 | check-if-word-can-be-placed-in-crossword | Check if Word Can Be Placed In Crossword | Medium | You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells.
A word can be placed **horizontally** (left to right **or** righ... |
```cpp
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int minWastedSpace(vector<int>& packages, vector<vector<int>>& boxes) {
constexpr int MOD = 1e9 + 7;
sort(packages.begin(), packages.end());
long long total_package_size = 0;
for (int package_size : packages)
... | You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells.
A word can be placed **horizontally** (left to right **or** righ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells... |
937 | reorder-data-in-log-files | Reorder Data in Log Files | Medium | You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.
* **Digit-logs**: All words (except the identifier) consist of digits... |
```cpp
#include <vector>
#include <stack>
class StockSpanner {
public:
std::vector<int> prices;
std::stack<int> index_stack;
StockSpanner() {}
int next(int price) {
while (!index_stack.empty() && prices[index_stack.top()] <= price) {
index_stack.pop();
}
int s... | You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.
* **Digit-logs**: All words (except the identifier) consist of digits... | Continue the following C++ code:
class Solution {
public:
/**
* You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
*
* There are two types of logs:
*
* * **Letter-logs**: All words (except the identifier) consist of lowercase English... |
897 | increasing-order-search-tree | Increasing Order Search Tree | Easy | Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\]
**Output:** \[1,null,2,null,3,null,4,nul... |
```cpp
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
bool isPalindrome(int n) {
int rev = 0, orig = n;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return orig == rev;... | Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. | Continue the following C++ code:
class Solution {
public:
/**
* Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
*/
|
312 | burst-balloons | Burst Balloons | Hard | You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ... |
```cpp
int maxCoins(vector<int>& nums) {
int n = nums.size();
nums.insert(nums.begin(), 1);
nums.push_back(1);
vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
for (int len = 1; len <= n; len++) {
for (int left = 1; left <= n - len + 1; left++) {
int right = left + len... | You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ... | Continue the following C++ code:
class Solution {
public:
/**
* You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
*
* If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * n... |
1,461 | check-if-a-string-contains-all-binary-codes-of-size-k | Check If a String Contains All Binary Codes of Size K | Medium | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f... |
```cpp
int countOrders(int n) {
long long MOD = 1e9 + 7;
long long ans = 1;
for (int i = 1; i <= n; ++i) {
ans = ans * (2 * i - 1) * i % MOD;
}
return ans;
}
```
We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 de... | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. | Continue the following C++ code:
class Solution {
public:
/**
* Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
*/
|
1,732 | find-the-highest-altitude | Find the Highest Altitude | Easy | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <=... |
```cpp
int min_operations(int n) {
int operations = 0;
while (n > 0) {
if (n % 2 == 0) {
n /= 2;
} else {
n--;
}
operations++;
}
return operations;
}
```
The algorithm initializes a variable `operations` to store the number of operati... | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <=... | Continue the following C++ code:
class Solution {
public:
/**
* There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
*
* You are given an integer array `gain` of length `n` where `gain[i]` is the **... |
272 | closest-binary-search-tree-value-ii | Closest Binary Search Tree Value II | Hard | Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**.
You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`.
**Example 1:*... |
```cpp
#include <vector>
#include <queue>
#include <cmath>
#include <cstdlib>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
};
vector<int> closestKValues(TreeNode* root, double target, int k) {
vector<int> values;
priority_queue<pair<double, int>> maxHeap;
... | Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**.
You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`. | Continue the following C++ code:
class Solution {
public:
/**
* Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**.
*
* You are **guaranteed** to have only one unique set... |
348 | design-tic-tac-toe | Design Tic-Tac-Toe | Medium | Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players:
1. A move is guaranteed to be valid and is placed on an empty block.
2. Once a winning condition is reached, no more moves are allowed.
3. A player who succeeds in placing `n` of their marks in a horizontal, vertical, o... |
```cpp
class TicTacToe {
public:
vector<int> rows, cols;
int diagonal, anti_diagonal, n;
TicTacToe(int n) {
this->n = n;
rows = vector<int>(n, 0);
cols = vector<int>(n, 0);
diagonal = 0;
anti_diagonal = 0;
}
int move(int row, int col, int player) {
... | Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players:
1. A move is guaranteed to be valid and is placed on an empty block.
2. Once a winning condition is reached, no more moves are allowed.
3. A player who succeeds in placing `n` of their marks in a horizontal, vertical, o... | Continue the following C++ code:
class Solution {
public:
/**
* Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players:
*
* 1. A move is guaranteed to be valid and is placed on an empty block.
* 2. Once a winning condition is reached, no more moves are allowed.
* 3.... |
682 | baseball-game | Baseball Game | Easy | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... |
```cpp
#include <vector>
#include <string>
int calPoints(std::vector<std::string>& ops) {
std::vector<int> record;
for (const std::string& op : ops) {
if (op == "+") {
record.push_back(record[record.size() - 1] + record[record.size() - 2]);
} else if (op == "D") {
r... | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | Continue the following C++ code:
class Solution {
public:
/**
* You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
*
* You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the rec... |
2,387 | median-of-a-row-wise-sorted-matrix | Median of a Row Wise Sorted Matrix | Medium | Given an `m x n` matrix `grid` containing an **odd** number of integers where each row is sorted in **non-decreasing** order, return _the **median** of the matrix_.
You must solve the problem in less than `O(m * n)` time complexity.
**Example 1:**
**Input:** grid = \[\[1,1,2\],\[2,3,3\],\[1,3,4\]\]
**Output:** 2
**E... |
```cpp
int findMedian(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int low = 1, high = 1e6;
while (low < high) {
int mid = low + (high - low) / 2;
int count = 0;
for (int i = 0; i < m; ++i) {
count += upper_bound(grid[i].begin(), grid[i].end... | Given an `m x n` matrix `grid` containing an **odd** number of integers where each row is sorted in **non-decreasing** order, return _the **median** of the matrix_.
You must solve the problem in less than `O(m * n)` time complexity. | Continue the following C++ code:
class Solution {
public:
/**
* Given an `m x n` matrix `grid` containing an **odd** number of integers where each row is sorted in **non-decreasing** order, return _the **median** of the matrix_.
*
* You must solve the problem in less than `O(m * n)` time complexity.
*/
|
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- -