Given two strings, determine the number of times the first one appears as a subsequence in the second one. A subsequence is created by eliminating any number of characters from a string (possibly 0) without changing the order of the characters retained.
Example
s1 = "ABC"
s2 = "ABCBABC"
The string s1 appears 5 times as a subsequence in s2 at 1-indexed positions (1,2,3), (1,2,7), (1,4,7), (1,6,7), (5,6,7). Answer: 5.
Constraints
- length of
s1= 3 - 1 ≤ length of
s2≤ 5·10⁵ - both strings consist of uppercase English letters A-Z.
解法
一维 DP。dp[i] 表示 s1 前 i 个字符作为 s2 已扫描前缀子序列的方案数。遍历 s2 的每个字符 c,对满足 s1[i-1] == c 的位置更新 dp[i] += dp[i-1];i 倒序遍历保证每个 s2 字符只用一次。时间 O(n · m),空间 O(n)。
def get_subsequence_count(s1, s2):
n = len(s1)
if n > len(s2):
return 0
dp = [0] * (n + 1)
dp[0] = 1
for c in s2:
for i in range(n, 0, -1):
if s1[i-1] == c:
dp[i] += dp[i-1]
return dp[n]class Solution {
static long getSubsequenceCount(String s1, String s2) {
int n = s1.length(), m = s2.length();
if (n > m) return 0;
long[] dp = new long[n + 1];
dp[0] = 1;
for (int j = 0; j < m; j++) {
char c = s2.charAt(j);
for (int i = n; i >= 1; i--)
if (s1.charAt(i - 1) == c) dp[i] += dp[i - 1];
}
return dp[n];
}
}long long getSubsequenceCount(string s1, string s2) {
int n = s1.size(), m = s2.size();
if (n > m) return 0;
vector<long long> dp(n + 1, 0);
dp[0] = 1;
for (int j = 0; j < m; j++) {
char c = s2[j];
for (int i = n; i >= 1; i--)
if (s1[i - 1] == c) dp[i] += dp[i - 1];
}
return dp[n];
}Given n machine learning models, each with cost cost[i] and a binary string featureAvailability[i] of length 2 indicating support for two features A and B:
"00"neither feature"01"feature A only"10"feature B only"11"both features
A set of models is k-capable if the count of models supporting feature A is ≥ k AND the count of models supporting feature B is ≥ k. For each k from 1 to n, return the minimum total cost of a k-capable set; if no such set exists, return -1 at that position.
Example
n = 6
cost = [3, 6, 9, 1, 2, 5]
featureAvailability = ["10", "01", "11", "01", "11", "10"]
Answer: [2, 6, 15, 26, -1, -1].
Constraints
- 1 ≤ n ≤ 10³
- 1 ≤ cost[i] ≤ 10⁴
featureAvailability[i]is a binary string of length 2.
解法
按类型分桶:T11(同时支持 A 和 B)、T10(只支持 B)、T01(只支持 A),忽略 T00。每桶按 cost 升序排序并构造前缀和 S11、S10、S01。目标 k:从 T11 选 j 个(同时贡献 A 和 B 各 j),再分别从 T01 和 T10 各补 k-j 个(j < k 时)。固定 j 的最小代价:
cost(k, j) = S11[j] + S01[max(k-j,0)] + S10[max(k-j,0)]
要求 j ≤ |T11|、k-j ≤ |T01|、k-j ≤ |T10|。在合法区间 [max(0, k-|T01|, k-|T10|), min(k, |T11|)] 内取最小。时间 O(n²),空间 O(n)。
def get_minimum_cost(cost, feature_availability):
t11, t10, t01 = [], [], []
for c, s in zip(cost, feature_availability):
if s == "11":
t11.append(c)
elif s == "10":
t10.append(c)
elif s == "01":
t01.append(c)
t11.sort(); t10.sort(); t01.sort()
def prefix(a):
p = [0] * (len(a) + 1)
for i, x in enumerate(a):
p[i+1] = p[i] + x
return p
P11, P10, P01 = prefix(t11), prefix(t10), prefix(t01)
n = len(cost)
ans = []
for k in range(1, n + 1):
best = None
jmin = max(0, k - len(t01), k - len(t10))
jmax = min(k, len(t11))
for j in range(jmin, jmax + 1):
r = k - j
c = P11[j] + P01[r] + P10[r]
if best is None or c < best:
best = c
ans.append(best if best is not None else -1)
return ansclass Solution {
static int[] getMinimumCost(int[] cost, String[] feature) {
int n = cost.length;
List<Integer> t11 = new ArrayList<>(), t10 = new ArrayList<>(), t01 = new ArrayList<>();
for (int i = 0; i < n; i++) {
String s = feature[i];
if (s.equals("11")) t11.add(cost[i]);
else if (s.equals("10")) t10.add(cost[i]);
else if (s.equals("01")) t01.add(cost[i]);
}
Collections.sort(t11); Collections.sort(t10); Collections.sort(t01);
long[] P11 = prefix(t11), P10 = prefix(t10), P01 = prefix(t01);
int[] ans = new int[n];
for (int k = 1; k <= n; k++) {
long best = Long.MAX_VALUE;
int jmin = Math.max(0, Math.max(k - t01.size(), k - t10.size()));
int jmax = Math.min(k, t11.size());
for (int j = jmin; j <= jmax; j++) {
int r = k - j;
long c = P11[j] + P01[r] + P10[r];
if (c < best) best = c;
}
ans[k - 1] = best == Long.MAX_VALUE ? -1 : (int) best;
}
return ans;
}
static long[] prefix(List<Integer> a) {
long[] p = new long[a.size() + 1];
for (int i = 0; i < a.size(); i++) p[i + 1] = p[i] + a.get(i);
return p;
}
}vector<int> getMinimumCost(vector<int>& cost, vector<string>& feature) {
int n = cost.size();
vector<int> t11, t10, t01;
for (int i = 0; i < n; i++) {
if (feature[i] == "11") t11.push_back(cost[i]);
else if (feature[i] == "10") t10.push_back(cost[i]);
else if (feature[i] == "01") t01.push_back(cost[i]);
}
sort(t11.begin(), t11.end());
sort(t10.begin(), t10.end());
sort(t01.begin(), t01.end());
auto prefix = [](vector<int>& a) {
vector<long long> p(a.size() + 1, 0);
for (size_t i = 0; i < a.size(); i++) p[i + 1] = p[i] + a[i];
return p;
};
auto P11 = prefix(t11), P10 = prefix(t10), P01 = prefix(t01);
vector<int> ans(n);
for (int k = 1; k <= n; k++) {
long long best = LLONG_MAX;
int jmin = max({0, k - (int)t01.size(), k - (int)t10.size()});
int jmax = min(k, (int)t11.size());
for (int j = jmin; j <= jmax; j++) {
int r = k - j;
long long c = P11[j] + P01[r] + P10[r];
if (c < best) best = c;
}
ans[k - 1] = best == LLONG_MAX ? -1 : (int) best;
}
return ans;
}Given an array of integers, for each element determine whether that element occurs earlier in the array and whether it occurs later in the array. Create two strings of binary digits. In the first string, each character is a 1 if the value at that index also occurs earlier in the array, or 0 if not. In the second string, each character is a 1 if the value at that index occurs later in the array, or 0 if not. Return an array of two strings where the first string is related to lower indices and the second to higher.
Function Description
Complete the function bitPattern in the editor below.
bitPattern has the following parameter(s):
int num[n]: an array of integers Returnsstring[2]: an array of 2 strings as described Input Format for Custom Testing Input from stdin will be processed as follows and passed to the function. The first line contains an integer n, the size of the array num. Each of the next n lines contains an integer num[i].
Constraints
1 ≤ n ≤ 10⁴⁰ ≤ num[i] ≤ 10⁴
解法
两遍扫描:从左到右用 HashSet 标记已出现过的值,构造第一个字符串(出现过为 '1');从右到左同样构造第二个。复杂度 O(n)。
def bitPattern(num):
n = len(num)
seen = set()
left = [''] * n
for i in range(n):
left[i] = '1' if num[i] in seen else '0'
seen.add(num[i])
seen.clear()
right = [''] * n
for i in range(n - 1, -1, -1):
right[i] = '1' if num[i] in seen else '0'
seen.add(num[i])
return [''.join(left), ''.join(right)]class Solution {
public String[] bitPattern(int[] num) {
int n = num.length;
java.util.HashSet<Integer> seen = new java.util.HashSet<>();
char[] left = new char[n], right = new char[n];
for (int i = 0; i < n; i++) {
left[i] = seen.contains(num[i]) ? '1' : '0';
seen.add(num[i]);
}
seen.clear();
for (int i = n - 1; i >= 0; i--) {
right[i] = seen.contains(num[i]) ? '1' : '0';
seen.add(num[i]);
}
return new String[]{new String(left), new String(right)};
}
}class Solution {
public:
vector<string> bitPattern(vector<int>& num) {
int n = num.size();
unordered_set<int> seen;
string left(n, '0'), right(n, '0');
for (int i = 0; i < n; ++i) {
if (seen.count(num[i])) left[i] = '1';
seen.insert(num[i]);
}
seen.clear();
for (int i = n - 1; i >= 0; --i) {
if (seen.count(num[i])) right[i] = '1';
seen.insert(num[i]);
}
return {left, right};
}
};给一组文本 texts 和一组小写关键词 spamWords。对每条文本,若包含任意一个 spamWords(大小写不敏感、整词匹配)则标记 "spam",否则 "not_spam",按原顺序返回结果数组。
Example 1
Input:
texts = ["Free prize worth millions", "Ten tips for a carefree lifestyle"]
spamWords = ["free", "money", "win", "millions"]
Output:
["spam", "not_spam"]
Explanation: :)
You are given an integer array nums and an integer goal.
You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).
Return the minimum possible value of abs(sum - goal).
Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
Constraints
1 ≤ nums.length ≤ 40-10⁷ ≤ nums[i] ≤ 10⁷-10⁹ ≤ goal ≤ 10⁹
Example 1
Input:
nums = [5, -7, 3, 5]
goal = 6
Output:
0
Explanation: Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0.
Example 2
Input:
nums = [7, -9, 15, -2]
goal = -5
Output:
1
Explanation: Choose the subsequence [7, -9, -2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
Example 3
Input:
nums = [1, 2, 3]
goal = -7
Output:
7
Explanation: No subsequence can get closer than an absolute difference of 7 from the goal.
You are given an undirected tree with n nodes labeled from 0 to n - 1.
The tree is defined by n - 1 edges.
Each node represents a branch office. You are also given a binary array
opportunityData of size n, where:
opportunityData[i] = 1means branchicontains important data.opportunityData[i] = 0means it does not. You may start at any node. You can traverse edges in both directions. You must start and end at the same node. Special Rule: When you are at a node, you can collect data from all nodes within distance≤ 2edges from your current location. Return the minimum number of edges you must traverse to collect all important data.
Constraints
2 ≤ n ≤ 10⁵edges.length == n - 1- The input graph is a valid tree
opportunityData[i]is either0or1
Example 1
Input:
n = 11
edges = [[0,1],[0,2],[0,6],[1,3],[1,4],[3,10],[6,7],[7,8],[8,9]]
opportunityData = [0,0,1,1,0,0,0,0,0,1,1]
Output:
6
Explanation:
Nodes 2, 3, 9, and 10 contain important data.
One optimal strategy:
- Start at node
1. - From node
1, collect data at3and10(within distance 2). - Travel to node
0and collect2. - Travel toward node
7to collect9. - Return to the starting node.
Total edges traversed =
6.
A challenge in a programming competition requires the construction of a sequence using a specified number of integers within a range. The sequence must be strictly increasing at first and then strictly decreasing. The goal is to maximize the sequence array elements starting from the beginning. For example, [4,5,4,3,2] beats [3,4,5,4,3] because its first element is larger, and [4,5,6,5,4] beats [4,5,4,3,2] because its third element is larger. Given the length of the sequence and the range of integers, return the winning sequence. If it is not possible to construct such a sequence, return -1.
Constraints
N/A
Example 1
Input:
n = 5
lo = 1
hi = 2
Output:
[-1]
Explanation: It is not possible to construct a sequence that is strictly increasing and then strictly decreasing with the given range of integers.
Example 2
Input:
n = 5
lo = 4
hi = 11
Output:
[10, 11, 10, 9, 8]
Explanation: N/A
Example 3
Input:
n = 6
lo = 5
hi = 10
Output:
[9, 10, 9, 8, 7, 6]
Explanation: N/A
Given a rectangle with dimensions (h,w). Count the minimum number of operations to make its dimensions reduce to (h1, w1).
An operation is to fold the rectangle paper along any of its side.
Function Description
Complete the function countMinimumOperations in the editor.
countMinimumOperations has the following parameters:
-
int h: the original height of the rectangle
-
int w: the original width of the rectangle
-
int h1: the reduced height of the rectangle
-
int w1: the reduced width of the rectangle Returnsint: the minimum number of operations required
Constraints
h1 ≤ hw1 ≤ w
Example 1
Input:
h = 8
w = 4
h1 = 6
w1 = 1
Output:
3
Explanation: (Feel free to lmk if you find anything wrong in this explanation Many thanks in advance! :) To reduce the dimensions from (8,4) to (6,1), the following operations can be performed:
- Fold along the width to reduce the width from 4 to 2 (1 operation).
- Fold along the width again to reduce the width from 2 to 1 (1 operation).
- Fold along the height to reduce the height from 8 to 6 (1 operation). Therefore, a total of 3 operations are required.
Given a list of numbers, count the number of numbers in the range [l,r] such that the number does not contain duplicate digits.
Constraints
N/A
Example 1
Input:
numbers = [1, 2, 11, 55, 989, 51, 60, 7007]
l = 1
r = 5
Output:
2
Explanation: In the given range [1,5], the numbers 1 and 2 do not contain any duplicate digits, so the answer is 2. (Explanation may not be 100% correct. For reference only. If you find anything wrong, pls feel free to lmk! Many thanks in advance!)
Example 2
Input:
numbers = [1, 2, 11, 55, 989, 51, 60, 7007]
l = 0
r = 7
Output:
4
Explanation: In the given range [0,7], the numbers 1, 2, 5 (from 51), and 6 (from 60) do not contain any duplicate digits, so the answer is 4. (Explanation may not be 100% correct. For reference only. If you find anything wrong, pls feel free to lmk! Many thanks in advance!)
Example 3
Input:
numbers = [1, 2, 11, 55, 989, 51, 60, 7007]
l = 5
r = 7
Output:
2
Explanation: In the given range [5,7], the numbers 5 (from 51) and 6 (from 60) do not contain any duplicate digits, so the answer is 2. (Explanation may not be 100% correct. For reference only. If you find anything wrong, pls feel free to lmk! Many thanks in advance!)
Count substrings that satisfy the following two conditions:
- Count of
1sand count of0sis equal. - Should be a block of
0sfollowed by a block of1sor vice versa. Examples of such substrings are"0011","01","10","1100". You can count repetitions, for example,"10101"has 4 such substrings:"10","01","10","01". Function Description Complete the functioncountSubstringsin the editor.countSubstringshas the following parameter: String s: the binary string to be checked Returns int: the number of substrings that satisfy the conditions
Constraints
N/A
Example 1
Input:
s = "10101"
Output:
4
Explanation:
The string "10101" contains the following substrings that satisfy the conditions:
"10": A block of1followed by a block of0."01": A block of0followed by a block of1."10": Another block of1followed by a block of0."01": Another block of0followed by a block of1. There are a total of 4 such substrings, so the answer is 4.
题面残缺。按示例反推:给整数数组 arr,找出所有有序对 (arr[i], arr[j]) (i < j) 满足 min(|x - y|, |x + y|) ≤ max(|x|, |y|),按原顺序返回。
Example 1
Input:
arr = [2, 5, -3]
Output:
[[2, -3], [5, -3]]
Explanation: An educated guess - The pairs that satisfy the given conditions are:
- (2, -3): min(|2 - (-3)|, |2 + (-3)|) = min(5, 1) = 1 = max(2, 3) = 3
- (5, -3): min(|5 - (-3)|, |5 + (-3)|) = min(8, 2) = 2 = max(5, 3) = 5
给两个字符串 x 和 y,找出最长的字符串 s,使得 s 既是 x 的子序列,又是 y 的连续子串。返回最长长度。
Example 1
Input:
x = "hackerranks"
y = "hackers"
Output:
7
Explanation:
The entire string "hackers" is a substring of y and also a subsequence of x (characters appear in order). The maximum length is 7.
A game's shaders are rendered using two GPUs: a and b. There is a string s,
which represents that for the f shader in which a GPU is used.
If shader[i] = "a" then the GPU a is used for the ith shader.
If shader[i] = "b" then the GPU b is used in the ith shader.
The idleness of this dual GPU system is defined as the maximum number of shaders for which
the same GPU is used consecutively. For example, for the string shader = "aalbbbaa",
for the first 2 seconds, GPU a is used then for the next 3 seconds, GPU b is used, then for 1 second,
GPU a is used. Hence, the idleness of the system is 3.
In order to reduce the idleness of the system, the following operation can be used at most
switchCount times.
- Select any index
iof the stringshader. Ifshader[i] = "a"then change it toshader[i] = "b"and vice versa. Find the minimum possible idleness of the system that can be achieved by applying the operations optimally. Function Description Complete the functionfindMinimumIdlenessin the editor.findMinimumIdlenesshas the following parameters: String shader: a string representing the GPUs usedint switchCount: the maximum number of switches allowed Returnsint: the minimum possible idleness of the system
Example 1
Input:
shader = "aabbbbaaaa"
switchCount = 2
Output:
2
Explanation:
It is given that shader = "aabbbbaaaa" and switchCount=2. One optimal solution is:
- Switch
shader[4](1-based index) to getshader = "aababaaaa". - Switch
shader[7](1-based index) to getshader = "aabababaa". Now withshader = "aabababaa", the system has an idleness of 2.
Given an array, find the number of perfe
Constraints
n/a
Example 1
Input:
arr = [2, 5, -3]
Output:
2
Explanation: out of (2, 5) , (5, -3) and (2, -3), (2, -3) and (5, -3) satisfy both the conditions. Therefore, the output is 2.
给两个字符串 s 和 t,把 s 按空格切成词,返回那些不是 t 的子序列的单词列表,保持原顺序。
Example 1
Input:
s = "I like cheese"
t = "like"
Output:
["I", "cheese"]
Explanation:
These words are in s but not part of t.
The manager oversees a set of n servers, each with a designated upgrade capacity represented by the array element capacity[i]. The goal is to create precisely k upgrade batches, where the number of servers in the ith batch is represented by the array element numServers[i] where 0 ≤ i Function Description Complete the function getMaxEfficiencyin the editor below.getMaxEfficiency` takes the following parameters:
int capacity[n]: the upgrade capacity of each serverint numServers[k]: the number of servers in each upgrade batch Returnslong: the maximum possible sum of efficiency ofkupgrade batches
Constraints
1 ≤ n ≤ 2x10⁵1 ≤ k ≤ n1 ≤ capacity[i] ≤ 10⁹1 ≤ numServers[i] ≤ nΣ numServers[i] = n
Example 1
Input:
capacity = [3, 6, 1, 2]
numServers = [1, 3]
Output:
5
Explanation: One of the optimal ways is:
- Batch 1 takes the first server. Therefore, the efficiency of the batch = 3 - 3 = 0
- Batch 2 takes the servers at indices 1, 2, and 3. The efficiency of the batch = 6 - 1 = 5 Hence, the sum of efficiencies is 0 + 5 = 5.
Example 2
Input:
capacity = [1, 2, 3, 4]
numServers = [4]
Output:
3
Explanation: Since there is only one batch to upgrade all the servers, the efficiency of the batch is 4 - 1 = 3. Hence, the sum of efficiencies of all the batches (which is 1) is 3.
Example 3
Input:
capacity = [4, 2, 1]
numServers = [1, 1, 1]
Output:
0
Explanation: Since the size of each server upgrade batch is 1, all 3 servers are upgraded in different batches, and the efficiency of each batch is 0. Hence, the sum of efficiencies is 0.
Given an array arr that contains n integers, the following operation can be performed on it any number of times (possibly zero):
Choose any index 1 ≤ i ≤ n and swap arr[i]. Each element of the array can be swapped at most once during the whole process.
The strength of an index is defined as (arr[i] + 1) using 1-based indexing. Find the maximum possible sum of the strength of all indices after optimal swaps. Mathematically, maximize the following:
Function Description
Complete the function getMaximumSumOfStrengths in the editor below.
getMaximumSumOfStrengths has the following parameter:
int arr[n]: the initial array Returnslong int: the maximum sum of strengths
Constraints
1 ≤ n ≤ 10⁵1 ≤ arr[i] ≤ 10⁵
Example 1
Input:
arr = [1, 9, 7, 3, 2]
Output:
66
Explanation:
It is optimal to swap (arr[2], arr[3]). The final array is arr[] = [1, 9, 3, 7, 2]. The sum of strengths (1*1 + 2*9 + 3*3 + 4*7 + 5*2) = 66, which is the maximum possible.
Example 2
Input:
arr = [2, 1, 4, 3]
Output:
30
Explanation:
It is optimal to swap (arr[0], arr[1]) and (arr[2], arr[3]). The final array is arr[] = [1, 2, 3, 4]. The sum of strengths (1*1 + 2*2 + 3*3 + 4*4) = 30, which is the maximum possible.
Example 3
Input:
arr = [1, 2, 5]
Output:
20
Explanation:
No swaps are needed as the array is already in optimal order. The sum of strengths (1*1 + 2*2 + 3*5) = 20, which is the maximum possible.
A team of software developers is working on a new application with n features to implement. Each feature requires specific resources for development: they are either built from scratch or integrated using an existing library.
Given two arrays of size n, developmentTime and integrationTime, where developmentTime[i] (0 ≤ i Function Description
Complete the function getMinimumDevelopmentTime in the editor.
getMinimumDevelopmentTime has the following parameters:
-
int[] developmentTime: an array of integers representing the hours needed to develop each feature
-
int[] integrationTime: an array of integers representing the hours needed to integrate each feature Returnsint: the minimum development time
Example 1
Input:
developmentTime = [10, 12, 13, 8, 15]
integrationTime = [1, 2, 1, 1, 1]
Output:
6
Explanation: If the team lead integrates all the features using the libraries, it requires 1 + 2 + 1 + 1 + 1 = 6 units of time. Since this is less than 8, the minimum development time, there is no need to consider developing a feature. Hence, the minimum time required is 6 hours.
Given n processes that need to be executed. Among these n processes,
k are classified as high-priority processes, with their indices (1-based) represented
in the array as high_priority[i].
An OS scheduler is responsible for overseeing the execution of all processes. When a scheduler assigns
a set of processes to a processor, it has two options:
If the assigned processes are greater than 1 and even, it can divide the array of processes,
denoted as p, into two contiguous subarrays of equal length, p1 and
p2, such that p = [p1, p2]. The scheduler will then allocate p1
to one processor and p2 to another.
Alternatively, the scheduler can choose to execute the assigned array of processes, p.
The time required for process execution is determined based on the following criteria:
- If the assigned processes do not include any high-priority processes, the scheduler will take
normal_timeseconds to complete all the assigned processes. - If there are high-priority processes among the assigned tasks (denoted as
x), it will take(priority_time * x * l)seconds to complete them, wherelis the total number of assigned processes. The total time required to execute all processes is the sum of the time taken by all processors for their assigned tasks. The task is to minimize the total execution time by optimizing the assignment of processes to processors within the operating system and return this minimum possible execution time. Function Description Complete the functiongetMinimumTimein the editor below.getMinimumTimetakes the following parameters:
int n: the total number of processesint high_priority[k]: the indices of the high-priority processesint normal_time: the time factor for completing non-high-priority processesint priority_time: the time factor for completing high-priority processes Returnsint: the minimum total execution time by optimizing the assignment of processes to processors within the operating system
Constraints
1 ≤ n ≤ 10⁹nis a power of 21 ≤ k ≤ min(n, 10⁵)1 ≤ high_priority[i] ≤ n
Example 1
Input:
n = 4
high_priority = [1]
normal_time = 2
priority_time = 2
Output:
6
Explanation: One of the optimal ways is as follows:
- Assign a processor to [1, 2], which will execute the processes in (2 * 1 * 2) = 4 seconds.
- Assign a processor to [3, 4], which will execute the processes in 2 seconds. Hence, the total time taken is 6 seconds.
Implement a prototype service for malware spread control in a network.
There are g_nodes servers in a network and g_edges connections between its nodes. The i^th bidirectional connection connects g_from[i] and g_to[i]. Some of the nodes are infected with malware. They are listed in the array malware, where if malware[i] = 1 node is infected, and if malware[i] = 0, node is not infected.
Any infected node infects other non-infected nodes, which are directly connected. This process goes on until no new infected nodes are possible. Exactly 1 node can be removed from the network. Return the index of the node to remove such that the total infected nodes in the remaining network are minimized. If multiple nodes lead to the same minimum result, then return the one with the lowest index.
Function Description
Complete the function getNodeToRemove in the editor.
getNodeToRemove has the following parameter(s):
-
int g_nodes: the number of nodes
-
int g_from[]: one end of the connections
-
int g_to[]: another end of the connections
-
int malware[]: the affected nodes Returnsint: the optimal node to remove
Constraints
1 ≤ g_nodes ≤ 10³0 ≤ g_edges ≤ min(g_nodes*(g_nodes-1)/2, 10³)1 ≤ g_from[i], g_to[i] ≤ nmalware[i] = 0 or 1.
Example 1
Input:
g_nodes = 9
g_from = [1, 2, 4, 6, 7]
g_to = [2, 3, 5, 7, 8]
malware = [0, 0, 1, 0, 1, 0, 0, 0, 0]
Output:
3
Explanation: Initially, nodes [3, 5] are infected. At the end, nodes [2, 3, 4, 5] will be infected. If node 3 is removed, only nodes 4 and 5 are infected, which is the minimum possible. Return 3, the node to remove.
Example 2
Input:
g_nodes = 5
g_from = [1, 2, 3, 4]
g_to = [2, 3, 4, 5]
malware = [1, 1, 1, 1, 1]
Output:
1
Explanation:
A pair of Integers (x, y) is perfect if both of the following conditions are met:
min(|x - y|, |x + y|) ≤ min(|x|, |y|)
max(|x - y|, |x + y|) ≥ max(|x|, |y|)
Given an array arr of length n, find the number of perfect pairs
(arr[i], arr[j]) where 0 ≤ i Function Description Complete the function getPerfectPairsCountin the editor.getPerfectPairsCount` has the following parameter:
int arr[n]: an array of integers Returnsint: the number of perfect pairs
Constraints
2 ≤ n ≤ 2*10⁵-10⁹ ≤ arr[i] ≤ 10⁹
Example 1
Input:
arr = [2, 5, -3]
Output:
2
Explanation:
In this example, n = 3. The possible pairs are (2, 5), (2, -3) and (5, -3).
- (2, 5) is not perfect
- min(|2 - 5|, |2 + 5|) = 3, min(|2|, |5|) = 2
- It fails the first test: 3 > 2
- (2, -3) is perfect
- min(|5|, |-1|) = 1, min(|2|, |-3|) = 2
- It passes the first test: 1 ≤ 2
- max(|5|, |-1|) = 5, max(|2|, |-3|) = 3
- It passes the second test: 5 ≥ 3
- (5, -3) is perfect
- min(|8|, |2|) = 2, min(|5|, |-3|) = 3
- It passes the first test: 2 ≤ 3
- max(|8|, |2|) = 8, max(|5|, |-3|) = 5
- It passes the second test: 8 ≥ 5 Therefore, there are 2 perfect pairs.
There are two types of characters in a particular language: special and normal. A character is special if its value is 1 and normal if its value is 0. Given string s, return the longest substring of s that contains at most k normal characters. Whether a character is normal is determined by a 26-digit bit string named charValue. Each digit in charValue corresponds to a lowercase letter in the English alphabet.
For clarity, the alphabet is aligned with charValue below:
s = "abcde"
alphabet = abcdefghijklmnopqrstuvwxyz
charValue = 10101111111111111111111111
The only normal characters in the language (according to charValue) are b and d. The string s contains both of these characters. For k = 2, the longest substring of s that contains at most k = 2 normal characters is 5 characters long, abcde, so the return value is 5. If k = 1 instead, then the possible substrings are {'b', 'd', 'ab', 'bc', 'cd', 'de', 'abc', 'cde'}. The longest substrings are 3 characters long, which would mean a return value of 3.
Function Description
Complete the function getSpecialSubstring in the editor.
getSpecialSubstring has the following parameter(s):
-
String s: the input string
-
int k: the maximum number of normal characters allowed in a substring
-
String charValue: a string representing special or normal value of each letter of the alphabet, ascii[a-z] Returnsint: an integer that denotes the length of the longest substring ofswith at mostknormal characters
Constraints
1 ≤ length of s ≤ 10⁵1 ≤ length of k ≤ the length of s- The length of
charValue= 26 - All values in
charValuewill be either 0 or 1
Example 1
Input:
s = "giraffe"
k = 2
charValue = "01111001111111111011111111"
Output:
3
Explanation:
Align the alphabet with charValue.
abcdefghijklmnopqrstuvwxyz
01111001111111111011111111
Normal characters are in the set {a, f, g, r}. All others are special.
For the string giraffe the longest possible substrings with 2 normal characters include gir, ira and ffe.
gir: The normal characters are g and r.ira: The normal characters are r and a.ffe: The normal characters are f and f. The maximum length substring has a length of 3.
Example 2
Input:
s = "special"
k = 1
charValue = "00000000000000000000000000"
Output:
1
Explanation: In this case, there can be only 1 normal character, and all characters are normal. The maximum length of a substring can only be of length 1. The possible substrings are s, p, e, c, i, a, and l.
There are two lists of size n - developmentTime and integrationTime. Any feature can be either implemented by development or by integration. While development of multiple features can happen concurrently by multiple developers, integration of features can only be sequential and can only be done by the team lead. Return the least number of hours to implement all the n features. Assume, there are more than n developers.
Function Description
Complete the function leastHours in the editor.
leastHours has the following parameters:
-
int[] developmentTime: an array of integers representing the time to develop each feature
-
int[] integrationTime: an array of integers representing the time to integrate each feature Returns int: the least number of hours to implement all features
Constraints
n/a
Example 1
Input:
developmentTime = [3, 4, 5, 9]
integrationTime = [3, 2, 5, 5]
Output:
5
Explanation: First 3 features are developed and take 5 hours and in the meanwhile, integration of the last one takes place.
Example 2
Input:
developmentTime = [8, 10, 6, 7]
integrationTime = [1, 2, 2, 1]
Output:
6
Explanation: Sum of all integrations (1 + 2 + 2 + 1 = 6) is less than the minimum development time, so all features are integrated.
There is a weighted undirected graph with N nodes and M edges. The stress level of a path between two nodes is defined as the weight of the edge with the maximum value present in the path. Given a source node "source" and a destination node "destination", find a path with the minimum stress level. If no such path exists, report -1.
Function Description
Complete the function leastStressfulPath in the editor below.
leastStressfulPath has the following parameter(s):
int graph_nodes: number of nodesint graph_from[]: one end node for an edgeint graph_to[]: the other end node for an edgeint graph_weight[]: the weights of the edgesint source: the source nodeint destination: the destination node Returnsint: the value of the least stressful path. If no path exists, return-1. Note: Even though edge endpoints are calledgraph_from[]andgraph_to[], this is an undirected graph. Input Format for Custom Testing The first line contains two space-separated integersgraph_nodesandm, the number of nodes, and the number of edges of the graph. Each of the followingmlines contains three space-separated integersa,b, andwmeaning there is an edge connecting the nodesaandbof weightw. The next line contains a single integer, denoting the index of the"source"node. The next line contains a single integer, denoting the index of the"destination"node.
Constraints
- 1 ≤ graph_nodes ≤ 10⁵⁵
- 1 ≤ |graph_from| = |graph_to| = |graph_weight| ≤ 10⁵
- 1 ≤ graph_from[i], graph_to[i], source, destination ≤ graph_nodes
- 0 ≤ graph_weight[i] ≤ 10⁹
Example 1
Input:
graph_nodes = 4
graph_from = [2, 2, 1, 4]
graph_to = [1, 3, 4, 3]
graph_weight = [100, 200, 10, 20]
source = 1
destination = 3
Output:
20
Explanation: There are two paths, from node 1 to node 3.
- The max weighted edge/stress level in path 1 → 2 → 3 is 200.
- The max weighted edge/stress level in the path 1 → 4 → 3 is 20. Return 20, the lower stress level from the second path.
You are given two strings x and y. You need to find the length of the longest subsequence of x that is also a substring of y.
A subsequence is a sequence derived from another string by deleting some or no elements without changing the order.
A substring is a contiguous part of a string.
Function Description
Complete the function longestSubsequenceWhichIsSubstring in the editor.
longestSubsequenceWhichIsSubstring has the following parameters:
String x: the first stringString y: the second string Returns int: the length of the longest subsequence ofxthat is also a substring ofyApproach I generated all substrings ofyand checked if they are subsequences ofx. Used a helper function for checking subsequence in O(M) time using two pointers. Time complexity: O(N² * M), where N = len(y), M = len(x).
Example 1
Input:
x = "abcd"
y = "abdc"
Output:
3
Explanation:
The subsequence "abd" is present in x and also appears as a substring in y.
Given a string s, choose 3 consecut
Example 1
Input:
s = "accept"
Output:
3
Explanation: :3
Example 2
Input:
s = "aabaab"
Output:
2
Explanation: :o
Example 3
Input:
s = "aabba"
Output:
4
Explanation: :)
There is a dual-core processor with one process queue for each core. There are n processes, where the time to process the ith process is denoted by time(i) (1 ≤ i ≤ n). There is a latch that helps decide which process is processed by which core. Initially, the first core has the latch. Suppose the latch is currently with the cth core, where c is either 1 or 2, and the ith process needs to be assigned. Then one of the following operations must be performed:
The ith process is assigned to the core c, and the latch is given to the other core.
The ith process is assigned to the other core, and the latch is retained by the core c.
The aim of each core is to have a maximum sum of time of processes with them for better performance. So, while assigning the ith process, the core with the latch decides the operation to be performed such that the total sum of time of processes assigned to it is maximized after all the processes are assigned.
Find the sum of the time of processes assigned to the first and second cores if both the cores work optimally. Return an array of two integers, where the first integer is the sum of the time of processes assigned to the first core, and the second integer is the sum of the time of processes assigned to the second core.
Example 1
Input:
times = [10, 10, 10, 10]
Output:
[20, 20]
Explanation: Both cores will have processes with equal sum of times, which is 20.
Example 2
Input:
times = [1, 2, 3, 4]
Output:
[5, 5]
Explanation: Both cores will have processes with equal sum of times, which is 5.
Example 3
Input:
times = [10, 15, 20, 25, 30]
Output:
[55, 45]
Explanation: The first core will have processes with sum of times 55, and the second core will have 45.
Example 4
Input:
times = [45, 25, 35, 15, 45, 25]
Output:
[115, 75]
Explanation: The first core will have processes with sum of times 115, and the second core will have 75.
Example 5
Input:
times = [40, 20, 30, 10]
Output:
[70, 30]
Explanation: The first core will have processes with sum of times 70, and the second core will have 30.
A customer has posted several web development projects on a freelancing platform, and various web developers have put in bids for these projects. Given the bid amounts and their corresponding projects, what is the minimum amount the customer can pay to have all the projects completed?
Note: If any project has no bids, return -1.
Function Description
Complete the function minCost in the editor.
minCost has the following parameters:
-
int numProjects: the total number of projects posted by the client (labeled from 0 to n)
-
int projectId[n]: the projects that the freelancers bid on
-
int bid[n]: the bid amounts posted by the freelancers Returnslong: the minimum cost the client can spend to complete all projects, or -1 if any project has no bids.
Constraints
1 ≤ numProjects, n ≤ 5x10⁵- `0 ≤ projectId[i]
Example 1
Input:
numProjects = 3
projectId = [2, 0, 1, 2]
bid = [8, 7, 6, 9]
Output:
21
Explanation: There is only one choice of who to hire for project 0, and it will cost 7. Likewise, there is only one choice for project 1, which will cost 6. For project 2, it is optimal to hire the first web developer, instead of the fourth, and doing so will cost 8. So the final answer is 7 + 6 + 8 = 21. If instead there were n = 4 projects, the answer would be -1 since there were no bids received on the fourth project.
Example 2
Input:
numProjects = 2
projectId = [0, 1, 0, 1, 1]
bid = [4, 74, 47, 744, 7]
Output:
11
Explanation: The optimal solution is to hire the first web developer to complete project 0 (which costs 4) and to hire the fifth web developer to complete project 1 (which costs 7). So the total cost for the customer will be 4 + 7 = 11.
An array of integers is almost sorted if at most one element can be deleted from it to make it perfectly sorted, ascending. For example, arrays [2, 1, 7], [13], [9, 2] and [1, 5, 6] are almost sorted because they have 0 or 1 elements out of place. The arrays [4, 2, 1], [1, 2, 6, 4, 3] are not because they have more than one element out of place. Given an array of n unique integers, determine the minimum number of elements to remove so it becomes almost sorted.
Function Description
Complete the function minDeletions in the editor.
minDeletions has the following parameter(s):
int arr[n]: an unsorted array of integers Returns int: the minimum number of items that must be deleted to create an almost sorted array
Constraints
1 ≤ n ≤ 10⁵1 ≤ arr[i] ≤ 10⁹- All elements of
arrare distinct.
Example 1
Input:
arr = [3, 4, 2, 5, 1]
Output:
1
Explanation:
Remove 2 to get arr' = [3, 4, 5, 1] or remove 7 to get arr' = [3, 4, 2, 5], both of which are almost sorted. The minimum number of elements that must be removed in this case is 1.
An array of integers is almost sorted if at most one element can be deleted from it to make it perfectly sorted, ascending.
For example, arrays [2, 1, 7], [13, 9, 2], and [1, 5, 6] are almost sorted because they have 0 or 1 elements out of place.
The arrays [4, 2, 1] and [1, 2, 6, 4, 3] are not because they have more than one element out of place.
Given an array of n unique integers, determine the minimum number of elements to remove so that it becomes almost sorted.
Example 1
Input:
arr = [3, 4, 2, 5, 1]
Output:
1
Explanation:
Remove 2 to get arr' = [3, 4, 5, 1] or
remove 1 to get arr' = [3, 4, 2, 5], both of which are almost sorted.
The minimum number of elements that must be removed in this case is 1.
For each word in a list of words, if any two adjacent characters are equal, change one of them. Determine the minimum number of substitutions so the final string contains no adjacent equal characters.
Function Description
Complete the function minimalOperations in the editor below.
minimalOperations has the following parameter(s):
string words[n]: an array of strings Returnsint[n]: each element i is the minimum substitutions for words[i]
Constraints
- 1 ≤ n ≤ 100
- 2 ≤ length of words[i] ≤ 10⁵
- Each character of words[i] is in the range ascii[a-z]
Example 1
Input:
words = ["add", "boook", "break"]
Output:
[1, 1, 0]
Explanation:
- 'add': change one d (1 change)
- 'boook': change the middle o (1 change)
- 'break': no changes are necessary (0 changes) The return array is [1, 1, 0].
Example 2
Input:
words = ["ab", "aab", "abb", "abab", "abaaaba"]
Output:
[0, 1, 1, 0, 1]
Explanation:
"ab":长度 1 的 run,0 次操作。"aab":aa是长度 2 的 run,需 1 次替换。"abb":bb是长度 2 的 run,需 1 次替换。"abab":均为长度 1,0 次。"abaaaba":aaa是长度 3 的 run,需 1 次替换。 返回[0, 1, 1, 0, 1]。
You are given a binary string s containing only 0s and 1s.
Your task is to minimize the length of the longest consecutive substring of the same character by
performing at most k operations. In one operation, you can flip a single bit: change
a 0 to 1 or a 1 to 0.
Input:
A binary string s (length n), where 1 ≤ n ≤ 10⁵.
An integer k (the maximum number of bit flips allowed), where 0 ≤ k ≤ n.
Output:
Return the minimum possible length of the longest consecutive substring of the same character after
performing at most k flips.
Example 1
Input:
s = "00000"
k = 2
Output:
1
Explanation: n/a
Campaigns should be executed in the order they appear. Each week must contain at least one campaign.
Weekly input cost is equal to the maximum cost of any campaign in that week. The goal is to minimize
the total input cost, which is the sum of weekly input costs.
Function Description
Complete the function minimizeTotalInputCost in the editor.
minimizeTotalInputCost has the following parameters:
-
int[] campaignCosts: an array of integers representing the costs of campaigns
-
int numberOfWeeks: the number of weeks Returnsint: the minimized total input cost
Example 1
Input:
campaignCosts = [1000, 500, 2000, 8000, 1500]
numberOfWeeks = 3
Output:
9500
Explanation: The input might not be right...But it looks correct somehow... Optimal Allocation:
- Week 1: {1000} → Max Cost = 1000
- Week 2: {500} → Max Cost = 500
- Week 3: {2000, 8000, 1500} → Max Cost = 8000 Output:
- Weekly Input Costs: {1000, 500, 8000}
- Total Input Cost (TIC): 1000 + 500 + 8000 = 9500 Explanation:
- Minimized Weekly Input: The maximum cost in any week is minimized.
- Optimal Total Input Cost: The sum of all weekly maximum costs (9500) is the smallest possible.
Given a set of distinct measurements taken at different times, find the minimum possible difference between any two measurements. Print all pairs of measurements that have this minimum difference in ascending order, with the pairs' difference in ascending order, e.g., if a < b, the pair elements ordered ascending, e.g., if a < b, the pair is a b. The values should have a single space between them.
Function Description
Complete the function minimumDifference in the editor.
minimumDifference has the following parameter:
int measurements[n]: an array of integers
Example 1
Input:
measurements = [-1, 3, 6, -5, 0]
Output:
[0, 3, 3, 6]
Explanation: The minimum absolute difference is 3, and the pairs with that difference are (3,6) and (0,3). When printing element pairs (i,j), they should be ordered ascending first by i and then by j.
An automated cutting machine is used to cut rods into segments. The cutting machine can only hold a rod of minLength or more. A rod is marked with the necessary cuts and their lengths are given as an array in the order they are marked. Determine if it is possible to plan the cuts so the last cut is from a rod at least minLength units long.
Constraints
1 ≤ rodLengths.length ≤ 10^51 ≤ rodLengths[i] ≤ 10^41 ≤ minLength ≤ 10^9
Example 1
Input:
rodLengths = [3, 5, 4, 3]
minLength = 9
Output:
"Possible"
Explanation: N/A for now
Example 2
Input:
rodLengths = [4, 3, 2]
minLength = 7
Output:
"Possible"
Explanation: N/A for now
Example 3
Input:
rodLengths = [4, 2, 3]
minLength = 7
Output:
"Impossible"
Explanation: N/A for now
Example 4
Input:
rodLengths = [5, 6, 2]
minLength = 12
Output:
"Impossible"
Explanation: N/A for now
You are given a string s consisting of lowercase English letters
('a' to 'z') and the character '?'.
Each '?' can be replaced with any lowercase English letter.
Return the total number of ways to replace all '?' such that the final
string has no two adjacent identical characters.
Since the answer may be large, return it modulo 10⁹ + 7.
Constraints
1 ≤ s.length ≤ 10⁵s[i]is a lowercase English letter or'?'
Example 1
Input:
s = "??"
Output:
650
Explanation:
- First character: 26 choices
- Second character: 25 choices (cannot equal the previous character)
- Total ways = 26 * 25 = 650
Two strings, s, and t, each of length n, that contain lowercase English characters are given as well as an integer K.
The cost to change the i^th character in s from s[i] to t[i] is the absolute difference of the ASCII value of characters, i.e., abs(s[i] - t[i]).
Find the maximum length of a substring of s that can be changed to the corresponding substring of t with a total cost less than or equal to K. If there is no such substring, return 0.
Function Description
Complete the function sameSubstring in the editor.
sameSubstring has the following parameters:
String s: the string to alterString t: the string to matchint K: the maximum sum of costs Returnsint: the maximum length of a substring that can be changed
Constraints
N/A
Given n servers with their capacity, we need to schedule k batches.
Input:
n (number of servers)
Capacity array of length n
k (batches)
numServers array of length k where numServers[i] = number of servers to be included in i-th batch
Output:
For each batch calculate difference between maximum and minimum server capacity, sum it over for all k batches and return it.
Constraints
- Summation of
numServers[i]==n n≤ 1e6k≤n
Example 1
Input:
n = 4
capacity = [1, 2, 3, 4]
k = 1
numServers = [4]
Output:
3
Explanation: Heads up This and the following 2 expanations are not from the official There is only one batch, and it includes all servers. The difference between the maximum and minimum server capacity is 4 - 1 = 3.
Example 2
Input:
n = 4
capacity = [1, 2, 3, 4]
k = 4
numServers = [1, 1, 1, 1]
Output:
0
Explanation: Each batch includes only one server, so the difference between the maximum and minimum server capacity for each batch is 0. The total sum is 0.
Example 3
Input:
n = 4
capacity = [1, 2, 3, 4]
k = 2
numServers = [2, 2]
Output:
4
Explanation: The first batch can include servers with capacities 1 and 4, and the second batch can include servers with capacities 2 and 3. The difference for the first batch is 4 - 1 = 3, and for the second batch is 3 - 2 = 1. The total sum is 3 + 1 = 4.
Given an integer array nums of size n and an integer k,
split nums into k non-empty contiguous subarrays such that the sum of
maximum values of each subarray is minimized.
Function Description
Complete the function splitArray in the editor.
splitArray has the following parameters:
-
int[] nums: an integer array
-
int k: the number of subarrays to split into Returns int: the minimum sum of the maximum values of theksubarrays
Constraints
0 ≤ k ≤ 3000 ≤ n ≤ 3000 ≤ nums[i] ≤ 10⁵
Example 1
Input:
nums = [1, 2, 3, 4, 5]
k = 2
Output:
6
Explanation: The optimal split is [1], [2, 3, 4, 5]. The sum of the maximum values of each subarray is max([1]) + max([2, 3, 4, 5]) = 1 + 5 = 6.
Given a string, write a function to compress it by sh
Example 1
Input:
input = "abaasass"
Output:
"a1b1a2s1a1s2"
Explanation: :)
You are given two integers:
n: length of stringk: maximum allowed consecutive identical characters A string is invalid if it containskor more consecutive identical characters. Return the total number of strings of lengthnformed using lowercase English letters such that no character appearskor more times consecutively. Return the answer modulo10⁹ + 7.
Constraints
1 ≤ n ≤ 10⁵1 ≤ k < n
Example 1
Input:
n = 3
k = 2
Output:
16250
Explanation:
Total strings of length 3 is 26³ = 17576.
Invalid strings are those with at least one adjacent equal pair.
For this case, the valid count is 16250.
A milling machine in a manufacturing facility has a tool change system. The tool changer holds n tools and some duplicate tools may be included. The operator must move through the tools one at a time, either moving left or right. The tool changer is circular, so when the last tool in the tools array is reached in either direction, the next tool is at the other end of the array.
Given the name of the next tool needed, determine the minimum number of left or right moves to reach it.
Function Description
Complete the function toolchanger in the editor.
toolchanger has the following parameter(s):
String[] tools: an array of tool names arranged in the order they appear in the tool changerint startIndex: index of the tool currently in useString target: name of the tool needed Returns int: the minimum number of moves
Example 1
Input:
tools = ["ballendmill", "keywaycutter", "slotdrill", "facemill"]
startIndex = 1
target = "ballendmill"
Output:
1
Explanation: The tool currently in use is keywaycutter at index 1. The desired tool is ballendmill at index 0. It can be reached by moving right 3 steps or left 1 step. The minimum number of moves is 1.
There are n towers placed sequentially in the city of Hackerland. Tower x
is visible from tower y if all towers between x and y have a
height strictly less than that of x. For each tower, find the number of towers visible
from this tower, both on the left and right side.
Function Description
Complete the function visibleTowers in the editor.
visibleTowers has the following parameter:
int[] height: an array of integers representing the heights of the towers Returnsint[]: an array of integers where thei-thelement is the number of towers visible from thei-thtower.
Constraints
f
Example 1
Input:
height = [5, 2, 10, 1]
Output:
[2, 2, 3, 1]
Explanation:
From tower 1, towers 2 and 3 are visible.
From tower 2, towers 1 and 3 are visible.
From tower 3, all 3 other towers are visible.
From tower 4, tower 3 is visible.
Return [2, 2, 3, 1].
解锁全部 40 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理